lodash#toString JavaScript Examples

The following examples show how to use lodash#toString. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js    From gutenberg-forms with GNU General Public License v2.0 6 votes vote down vote up
// will get post url from the post id from the cwpGlobal variable

export function getPostUrl(id) {
	const posts = get(window, "cwpGlobal.cwp-cpt-forms");
	const filteredPost = isArray(posts)
		? posts.filter((post) => isEqual(toString(post.ID), id))
		: false;

	const requiredPost = isArray(filteredPost) ? filteredPost[0] : false;

	if (!requiredPost) {
		return "";
	} else {
		const url = get(requiredPost, "post_edit_url");
		const editUrl = url.concat("&action=edit");
		return editUrl;
	}
}
Example #2
Source File: index.js    From strapi-molecules with MIT License 4 votes vote down vote up
Header = ({
  allowedActions: { canUpdate, canCreate, canPublish },
  componentLayouts,
  initialData,
  isCreatingEntry,
  isSingleType,
  hasDraftAndPublish,
  layout,
  modifiedData,
  onPublish,
  onUnpublish,
  status,
}) => {
  const { previewHeaderActions } = usePreview();
  const [showWarningUnpublish, setWarningUnpublish] = useState(false);
  const { formatMessage } = useIntl();
  const formatMessageRef = useRef(formatMessage);
  const [draftRelationsCount, setDraftRelationsCount] = useState(0);
  const [showWarningDraftRelation, setShowWarningDraftRelation] = useState(
    false,
  );
  const [shouldUnpublish, setShouldUnpublish] = useState(false);
  const [shouldPublish, setShouldPublish] = useState(false);

  const currentContentTypeMainField = useMemo(
    () => get(layout, ['settings', 'mainField'], 'id'),
    [layout],
  );

  const currentContentTypeName = useMemo(() => get(layout, ['info', 'name']), [
    layout,
  ]);

  const didChangeData = useMemo(() => {
    return (
      !isEqual(initialData, modifiedData) ||
      (isCreatingEntry && !isEmpty(modifiedData))
    );
  }, [initialData, isCreatingEntry, modifiedData]);
  const apiID = useMemo(() => layout.apiID, [layout.apiID]);

  /* eslint-disable indent */
  const entryHeaderTitle = isCreatingEntry
    ? formatMessage({
        id: getTrad('containers.Edit.pluginHeader.title.new'),
      })
    : templateObject({ mainField: currentContentTypeMainField }, initialData)
        .mainField;
  /* eslint-enable indent */

  const headerTitle = useMemo(() => {
    const title = isSingleType ? currentContentTypeName : entryHeaderTitle;

    return title || currentContentTypeName;
  }, [currentContentTypeName, entryHeaderTitle, isSingleType]);

  const checkIfHasDraftRelations = useCallback(() => {
    const count = getDraftRelations(modifiedData, layout, componentLayouts);

    setDraftRelationsCount(count);

    return count > 0;
  }, [modifiedData, layout, componentLayouts]);

  const headerActions = useMemo(() => {
    let headerActions = [];

    if ((isCreatingEntry && canCreate) || (!isCreatingEntry && canUpdate)) {
      headerActions = [
        {
          disabled: !didChangeData,
          color: 'success',
          label: formatMessage({
            id: getTrad('containers.Edit.submit'),
          }),
          isLoading: status === 'submit-pending',
          type: 'submit',
          style: {
            minWidth: 150,
            fontWeight: 600,
          },
        },
      ];
    }
    if (hasDraftAndPublish && canPublish) {
      const isPublished = !isEmpty(initialData.published_at);
      const isLoading = isPublished
        ? status === 'unpublish-pending'
        : status === 'publish-pending';
      const labelID = isPublished ? 'app.utils.unpublish' : 'app.utils.publish';
      /* eslint-disable indent */
      const onClick = isPublished
        ? () => setWarningUnpublish(true)
        : (e) => {
            if (!checkIfHasDraftRelations()) {
              onPublish(e);
            } else {
              setShowWarningDraftRelation(true);
            }
          };
      /* eslint-enable indent */

      const action = {
        ...primaryButtonObject,
        disabled: isCreatingEntry || didChangeData,
        isLoading,
        label: formatMessage({ id: labelID }),
        onClick,
      };

      headerActions.unshift(action);
    }

    return [...previewHeaderActions, ...headerActions];
  }, [
    isCreatingEntry,
    canCreate,
    canUpdate,
    hasDraftAndPublish,
    canPublish,
    didChangeData,
    formatMessage,
    status,
    initialData,
    onPublish,
    checkIfHasDraftRelations,
    previewHeaderActions,
  ]);

  const headerProps = useMemo(() => {
    return {
      title: {
        label: toString(headerTitle),
      },
      content: `${formatMessageRef.current({
        id: getTrad('api.id'),
      })} : ${apiID}`,
      actions: headerActions,
    };
  }, [headerActions, headerTitle, apiID]);

  const toggleWarningPublish = () =>
    setWarningUnpublish((prevState) => !prevState);

  const toggleWarningDraftRelation = useCallback(() => {
    setShowWarningDraftRelation((prev) => !prev);
  }, []);

  const handleConfirmPublish = useCallback(() => {
    setShouldPublish(true);
    setShowWarningDraftRelation(false);
  }, []);

  const handleConfirmUnpublish = useCallback(() => {
    setShouldUnpublish(true);
    setWarningUnpublish(false);
  }, []);

  const handleCloseModalPublish = useCallback(
    (e) => {
      if (shouldPublish) {
        onPublish(e);
      }

      setShouldUnpublish(false);
    },
    [onPublish, shouldPublish],
  );

  const handleCloseModalUnpublish = useCallback(
    (e) => {
      if (shouldUnpublish) {
        onUnpublish(e);
      }

      setShouldUnpublish(false);
    },
    [onUnpublish, shouldUnpublish],
  );

  const contentIdSuffix = draftRelationsCount > 1 ? 'plural' : 'singular';

  return (
    <>
      <PluginHeader {...headerProps} />
      {hasDraftAndPublish && (
        <>
          <ModalConfirm
            isOpen={showWarningUnpublish}
            toggle={toggleWarningPublish}
            content={{
              id: getTrad('popUpWarning.warning.unpublish'),
              values: {
                br: () => <br />,
              },
            }}
            type="xwarning"
            onConfirm={handleConfirmUnpublish}
            onClosed={handleCloseModalUnpublish}
          >
            <Text>
              {formatMessage({
                id: getTrad('popUpWarning.warning.unpublish-question'),
              })}
            </Text>
          </ModalConfirm>
          <ModalConfirm
            confirmButtonLabel={{
              id: getTrad(
                'popUpwarning.warning.has-draft-relations.button-confirm',
              ),
            }}
            isOpen={showWarningDraftRelation}
            toggle={toggleWarningDraftRelation}
            onClosed={handleCloseModalPublish}
            onConfirm={handleConfirmPublish}
            type="success"
            content={{
              id: getTrad(
                `popUpwarning.warning.has-draft-relations.message.${contentIdSuffix}`,
              ),
              values: {
                count: draftRelationsCount,
                b: (chunks) => (
                  <Text as="span" fontWeight="bold">
                    {chunks}
                  </Text>
                ),
                br: () => <br />,
              },
            }}
          >
            <Text>
              {formatMessage({
                id: getTrad('popUpWarning.warning.publish-question'),
              })}
            </Text>
          </ModalConfirm>
        </>
      )}
    </>
  );
}
Example #3
Source File: PostFilterBar.jsx    From frontend-app-discussions with GNU Affero General Public License v3.0 4 votes vote down vote up
function PostFilterBar({
  filterSelfPosts,
  intl,
}) {
  const dispatch = useDispatch();
  const { courseId } = useParams();
  const userIsPrivileged = useSelector(selectUserIsPrivileged);
  const currentSorting = useSelector(selectThreadSorting());
  const currentFilters = useSelector(selectThreadFilters());
  const { status } = useSelector(state => state.cohorts);
  const cohorts = useSelector(selectCourseCohorts);
  const userIsStaff = useSelector(selectUserIsStaff);

  const [isOpen, setOpen] = useState(false);

  const selectedCohort = useMemo(() => cohorts.find(cohort => (
    toString(cohort.id) === currentFilters.cohort)),
  [currentFilters.cohort]);

  const handleSortFilterChange = (event) => {
    const currentType = currentFilters.postType;
    const currentStatus = currentFilters.status;
    const {
      name,
      value,
    } = event.currentTarget;
    if (name === 'type') {
      dispatch(setPostsTypeFilter(value));
      if (
        value === ThreadType.DISCUSSION && currentStatus === PostsStatusFilter.UNANSWERED
      ) {
        // You can't filter discussions by unanswered
        dispatch(setStatusFilter(PostsStatusFilter.ALL));
      }
    }
    if (name === 'status') {
      dispatch(setStatusFilter(value));
      if (value === PostsStatusFilter.UNANSWERED && currentType !== ThreadType.QUESTION) {
        // You can't filter discussions by unanswered so switch type to questions
        dispatch(setPostsTypeFilter(ThreadType.QUESTION));
      }
    }
    if (name === 'sort') {
      dispatch(setSortedBy(value));
    }
    if (name === 'cohort') {
      dispatch(setCohortFilter(value));
    }
    setOpen(false);
  };

  useEffect(() => {
    if (userIsPrivileged && isEmpty(cohorts)) {
      dispatch(fetchCourseCohorts(courseId));
    }
  }, [courseId, userIsPrivileged]);

  return (
    <Collapsible.Advanced
      open={isOpen}
      onToggle={() => setOpen(!isOpen)}
      className="collapsible-card-lg border-right-0"
    >
      <Collapsible.Trigger className="collapsible-trigger border-0">
        <span className="text-primary-700 pr-4">
          {intl.formatMessage(messages.sortFilterStatus, {
            own: filterSelfPosts,
            type: currentFilters.postType,
            sort: currentSorting,
            status: currentFilters.status,
            cohortType: selectedCohort?.name ? 'group' : 'all',
            cohort: capitalize(selectedCohort?.name),
          })}
        </span>
        <Collapsible.Visible whenClosed>
          <Icon src={Tune} />
        </Collapsible.Visible>
        <Collapsible.Visible whenOpen>
          <Icon src={Tune} />
        </Collapsible.Visible>
      </Collapsible.Trigger>
      <Collapsible.Body className="collapsible-body px-4 pb-3 pt-0">
        <Form>
          <div className="d-flex flex-row py-2 justify-content-between">
            <Form.RadioSet
              name="type"
              className="d-flex flex-column list-group list-group-flush"
              value={currentFilters.postType}
              onChange={handleSortFilterChange}
            >
              <ActionItem
                id="type-all"
                label={intl.formatMessage(messages.allPosts)}
                value={ThreadType.ALL}
                selected={currentFilters.postType}
              />
              <ActionItem
                id="type-discussions"
                label={intl.formatMessage(messages.filterDiscussions)}
                value={ThreadType.DISCUSSION}
                selected={currentFilters.postType}
              />
              <ActionItem
                id="type-questions"
                label={intl.formatMessage(messages.filterQuestions)}
                value={ThreadType.QUESTION}
                selected={currentFilters.postType}
              />
            </Form.RadioSet>
            <Form.RadioSet
              name="status"
              className="d-flex flex-column list-group list-group-flush"
              value={currentFilters.status}
              onChange={handleSortFilterChange}
            >
              <ActionItem
                id="status-any"
                label={intl.formatMessage(messages.filterAnyStatus)}
                value={PostsStatusFilter.ALL}
                selected={currentFilters.status}
              />
              <ActionItem
                id="status-unread"
                label={intl.formatMessage(messages.filterUnread)}
                value={PostsStatusFilter.UNREAD}
                selected={currentFilters.status}
              />
              <ActionItem
                id="status-following"
                label={intl.formatMessage(messages.filterFollowing)}
                value={PostsStatusFilter.FOLLOWING}
                selected={currentFilters.status}
              />
              {(userIsPrivileged || userIsStaff) && (
                <ActionItem
                  id="status-reported"
                  label={intl.formatMessage(messages.filterReported)}
                  value={PostsStatusFilter.REPORTED}
                  selected={currentFilters.status}
                />
              )}
              <ActionItem
                id="status-unanswered"
                label={intl.formatMessage(messages.filterUnanswered)}
                value={PostsStatusFilter.UNANSWERED}
                selected={currentFilters.status}
              />
            </Form.RadioSet>
            <Form.RadioSet
              name="sort"
              className="d-flex flex-column list-group list-group-flush"
              value={currentSorting}
              onChange={handleSortFilterChange}
            >
              <ActionItem
                id="sort-activity"
                label={intl.formatMessage(messages.lastActivityAt)}
                value={ThreadOrdering.BY_LAST_ACTIVITY}
                selected={currentSorting}
              />
              <ActionItem
                id="sort-comments"
                label={intl.formatMessage(messages.commentCount)}
                value={ThreadOrdering.BY_COMMENT_COUNT}
                selected={currentSorting}
              />
              <ActionItem
                id="sort-votes"
                label={intl.formatMessage(messages.voteCount)}
                value={ThreadOrdering.BY_VOTE_COUNT}
                selected={currentSorting}
              />
            </Form.RadioSet>
          </div>
          {userIsPrivileged && (
            <>
              <div className="border-bottom my-2" />
              {status === RequestStatus.IN_PROGRESS ? (
                <div className="d-flex justify-content-center p-4">
                  <Spinner animation="border" variant="primary" size="lg" />
                </div>
              ) : (
                <div className="d-flex flex-row pt-2">
                  <Form.RadioSet
                    name="cohort"
                    className="d-flex flex-column list-group list-group-flush w-100"
                    value={currentFilters.cohort}
                    onChange={handleSortFilterChange}
                  >
                    <ActionItem
                      id="all-groups"
                      label="All groups"
                      value=""
                      selected={currentFilters.cohort}
                    />
                    {cohorts.map(cohort => (
                      <ActionItem
                        key={cohort.id}
                        id={cohort.id}
                        label={capitalize(cohort.name)}
                        value={toString(cohort.id)}
                        selected={currentFilters.cohort}
                      />
                    ))}
                  </Form.RadioSet>
                </div>
              )}
            </>
          )}
        </Form>
      </Collapsible.Body>
    </Collapsible.Advanced>
  );
}