react-router-dom#generatePath TypeScript Examples

The following examples show how to use react-router-dom#generatePath. 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: watching.tsx    From kinopub.webos with MIT License 6 votes vote down vote up
WatchingView: React.FC = () => {
  const { watchingType = 'serials' } = useParams<RouteParams>();
  const { data, isLoading } = useApi(`watching${capitalize(watchingType) as Capitalize<WatchingTypes>}`, [Bool.True]);
  const total = useMemo(() => sumBy(data?.items, (item) => +(item.new || 0)), [data?.items]);
  const seoTitle = watchingType === 'serials' ? 'Новые эпизоды' : 'Недосмотренные фильмы';
  const title = total ? `${seoTitle} (${total})` : seoTitle;

  return (
    <>
      <Seo title={seoTitle} />
      <ItemsList
        title={
          <>
            <Text>{title}</Text>

            <div className="flex">
              {map(WATCHING_TYPES_MAP, (watchingTypeName, watchingTypeKey) => (
                <Link
                  key={watchingTypeKey}
                  className="mr-2"
                  replace
                  active={watchingType === watchingTypeKey}
                  href={generatePath(PATHS.Watching, { watchingType: watchingTypeKey })}
                >
                  {watchingTypeName}
                </Link>
              ))}
            </div>
          </>
        }
        items={data?.items}
        loading={isLoading}
      />
    </>
  );
}
Example #2
Source File: LegendStudioRouter.ts    From legend-studio with Apache License 2.0 6 votes vote down vote up
generateViewProjectByGAVRoute = (
  groupId: string,
  artifactId: string,
  versionId: string,
  entityPath?: string | undefined,
): string =>
  !entityPath
    ? generatePath(LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_GAV, {
        gav: generateGAVCoordinates(groupId, artifactId, versionId),
      })
    : generatePath(LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_GAV_ENTITY, {
        gav: generateGAVCoordinates(groupId, artifactId, versionId),
        entityPath,
      })
Example #3
Source File: index.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
AuditLinkList = ({ audits = [], selectedId }: AuditLinkListProps) => (
  <List
    data-testid="audit-sidebar"
    component="nav"
    aria-label="lighthouse audit history"
  >
    {audits.map(audit => (
      <ListItem
        key={audit.id}
        selected={audit.id === selectedId}
        button
        component={Link}
        replace
        to={resolvePath(generatePath('audit/:id', { id: audit.id }), '../../')}
      >
        <ListItemIcon>
          <AuditStatusIcon audit={audit} />
        </ListItemIcon>
        <ListItemText primary={formatTime(audit.timeCreated)} />
      </ListItem>
    ))}
  </List>
)
Example #4
Source File: LegendStudioRouter.ts    From legend-studio with Apache License 2.0 6 votes vote down vote up
generateViewVersionRoute = (
  projectId: string,
  versionId: string,
  entityPath?: string | undefined,
): string =>
  !entityPath
    ? generatePath(LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_VERSION, {
        projectId,
        versionId,
      })
    : generatePath(LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_VERSION_ENTITY, {
        projectId,
        versionId,
        entityPath,
      })
Example #5
Source File: LegendStudioRouter.ts    From legend-studio with Apache License 2.0 6 votes vote down vote up
generateViewRevisionRoute = (
  projectId: string,
  revisionId: string,
  entityPath?: string | undefined,
): string =>
  !entityPath
    ? generatePath(LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_REVISION, {
        projectId,
        revisionId,
      })
    : generatePath(LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_REVISION_ENTITY, {
        projectId,
        revisionId,
        entityPath,
      })
Example #6
Source File: Host.tsx    From fishbowl with MIT License 6 votes vote down vote up
function HostRedirect(props: { gameId: Games["id"] }) {
  const { data } = useGameByIdSubscription({
    variables: {
      id: props.gameId,
    },
  })
  const joinCode = data?.games_by_pk?.join_code
  if (joinCode) {
    return (
      <Redirect
        push
        to={generatePath(routes.game.lobby, {
          joinCode: joinCode,
        })}
      />
    )
  } else {
    return null
  }
}
Example #7
Source File: GameStateRedirects.tsx    From fishbowl with MIT License 6 votes vote down vote up
function GameStateRedirects(props: { joinCode: string }) {
  const location = useLocation()
  const currentGame = React.useContext(CurrentGameContext)

  if (
    matchPath(location.pathname, { path: routes.game.pending, exact: true }) ||
    matchPath(location.pathname, { path: routes.game.settings, exact: true })
  ) {
    return null
  }

  const pair = stateRoutePairs.find((pair) => pair.state === currentGame.state)
  if (
    pair?.state &&
    !matchPath(location.pathname, {
      path: pair.route,
      exact: true,
    })
  ) {
    return (
      <Redirect
        to={generatePath(pair.route, {
          joinCode: props.joinCode,
        })}
      ></Redirect>
    )
  } else {
    return null
  }
}
Example #8
Source File: LegendQueryRouter.ts    From legend-studio with Apache License 2.0 6 votes vote down vote up
generateCreateQueryRoute = (
  groupId: string,
  artifactId: string,
  versionId: string,
  mappingPath: string,
  runtimePath: string,
  classPath: string | undefined,
): string =>
  classPath
    ? generatePath(LEGEND_QUERY_ROUTE_PATTERN.CREATE_QUERY_WITH_CLASS, {
        [LEGEND_QUERY_PATH_PARAM_TOKEN.GROUP_ID]: groupId,
        [LEGEND_QUERY_PATH_PARAM_TOKEN.ARTIFACT_ID]: artifactId,
        [LEGEND_QUERY_PATH_PARAM_TOKEN.VERSION_ID]: versionId,
        [LEGEND_QUERY_PATH_PARAM_TOKEN.MAPPING_PATH]: mappingPath,
        [LEGEND_QUERY_PATH_PARAM_TOKEN.RUNTIME_PATH]: runtimePath,
        [LEGEND_QUERY_PATH_PARAM_TOKEN.CLASS_PATH]: classPath,
      })
    : generatePath(LEGEND_QUERY_ROUTE_PATTERN.CREATE_QUERY, {
        [LEGEND_QUERY_PATH_PARAM_TOKEN.GROUP_ID]: groupId,
        [LEGEND_QUERY_PATH_PARAM_TOKEN.ARTIFACT_ID]: artifactId,
        [LEGEND_QUERY_PATH_PARAM_TOKEN.VERSION_ID]: versionId,
        [LEGEND_QUERY_PATH_PARAM_TOKEN.MAPPING_PATH]: mappingPath,
        [LEGEND_QUERY_PATH_PARAM_TOKEN.RUNTIME_PATH]: runtimePath,
      })
Example #9
Source File: routes.ts    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
routes: Routes = {
  ...baseRoutes,
  editProject: id =>
    id ? generatePath(baseRoutes.editProject, { id }) : baseRoutes.editProject,
  editEmployee: id =>
    id
      ? generatePath(baseRoutes.editEmployee, { id })
      : baseRoutes.editEmployee,
}
Example #10
Source File: LegendTaxonomyRouter.ts    From legend-studio with Apache License 2.0 6 votes vote down vote up
generateExploreTaxonomyTreeNodeDataSpaceRoute = (
  taxonomyTreeKey: string,
  taxonomyNodePath: string,
  GAVCoordinates: string,
  dataSpacePath: string,
): string =>
  generatePath(
    LEGEND_TAXONOMY_ROUTE_PATTERN.EXPLORE_TAXONOMY_TREE_NODE_DATA_SPACE,
    {
      [LEGEND_TAXONOMY_PARAM_TOKEN.TAXONOMY_TREE_KEY]: taxonomyTreeKey,
      [LEGEND_TAXONOMY_PARAM_TOKEN.TAXONOMY_PATH]: taxonomyNodePath,
      [LEGEND_TAXONOMY_PARAM_TOKEN.GAV]: GAVCoordinates,
      [LEGEND_TAXONOMY_PARAM_TOKEN.DATA_SPACE_PATH]: dataSpacePath,
    },
  )
Example #11
Source File: LegendQueryRouter.ts    From legend-studio with Apache License 2.0 6 votes vote down vote up
generateServiceQueryRoute = (
  groupId: string,
  artifactId: string,
  versionId: string,
  servicePath: string,
  key?: string,
): string =>
  `${generatePath(LEGEND_QUERY_ROUTE_PATTERN.SERVICE_QUERY, {
    [LEGEND_QUERY_PATH_PARAM_TOKEN.GROUP_ID]: groupId,
    [LEGEND_QUERY_PATH_PARAM_TOKEN.ARTIFACT_ID]: artifactId,
    [LEGEND_QUERY_PATH_PARAM_TOKEN.VERSION_ID]: versionId,
    [LEGEND_QUERY_PATH_PARAM_TOKEN.SERVICE_PATH]: servicePath,
  })}${key ? `?${LEGEND_QUERY_QUERY_PARAM_TOKEN.SERVICE_KEY}=${key}` : ''}`
Example #12
Source File: LegendStudioRouter.ts    From legend-studio with Apache License 2.0 6 votes vote down vote up
generateGroupWorkspaceSetupRoute = (
  projectId: string | undefined,
  groupWorkspaceId: string,
): string =>
  generatePath(LEGEND_STUDIO_ROUTE_PATTERN.SETUP_GROUP, {
    // FIXME: due to some problem with typings, we will need to cast like this
    // we will fix this when upgrading react-router
    // See https://github.com/finos/legend-studio/issues/688
    projectId: projectId as string,
    groupWorkspaceId,
  })
Example #13
Source File: LegendStudioRouter.ts    From legend-studio with Apache License 2.0 6 votes vote down vote up
generateWorkspaceSetupRoute = (
  projectId: string | undefined,
  workspaceId?: string,
): string =>
  generatePath(LEGEND_STUDIO_ROUTE_PATTERN.SETUP, {
    // FIXME: due to some problem with typings, we will need to cast like this
    // we will fix this when upgrading react-router
    // See https://github.com/finos/legend-studio/issues/688
    projectId: projectId as string,
    // FIXME: due to some problem with typings, we will need to cast like this
    // we will fix this when upgrading react-router
    // See https://github.com/finos/legend-studio/issues/688
    workspaceId: workspaceId as string,
  })
Example #14
Source File: LegendStudioRouter.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
generateReviewRoute = (
  projectId: string,
  reviewId: string,
): string =>
  generatePath(LEGEND_STUDIO_ROUTE_PATTERN.REVIEW, {
    projectId,
    reviewId,
  })
Example #15
Source File: LegendStudioRouter.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
generateViewEntityRoute = (
  projectId: string,
  entityPath: string,
): string =>
  generatePath(LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_ENTITY, {
    projectId,
    entityPath,
  })
Example #16
Source File: LegendStudioRouter.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
generateViewProjectRoute = (projectId: string): string =>
  generatePath(LEGEND_STUDIO_ROUTE_PATTERN.VIEW, {
    projectId,
  })
Example #17
Source File: Site.tsx    From mirrorz with MIT License 5 votes vote down vote up
siteUrl = (path: string, site: Site) => generatePath(path, { siteSlug: site.abbr.replace(/\s/g, '') })
Example #18
Source File: LegendStudioRouter.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
generateViewProjectEntityByGAVRoute = (
  groupId: string,
  artifactId: string,
  versionId: string,
): string =>
  generatePath(LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_GAV, {
    gav: generateGAVCoordinates(groupId, artifactId, versionId),
  })
Example #19
Source File: LegendTaxonomyRouter.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
generateExploreTaxonomyTreeRoute = (
  taxonomyTreeKey: string,
): string =>
  generatePath(LEGEND_TAXONOMY_ROUTE_PATTERN.EXPLORE_TAXONOMY_TREE, {
    [LEGEND_TAXONOMY_PARAM_TOKEN.TAXONOMY_TREE_KEY]: taxonomyTreeKey,
  })
Example #20
Source File: LegendTaxonomyRouter.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
generateExploreTaxonomyTreeNodeRoute = (
  taxonomyTreeKey: string,
  taxonomyNodePath: string,
): string =>
  generatePath(LEGEND_TAXONOMY_ROUTE_PATTERN.EXPLORE_TAXONOMY_TREE_NODE, {
    [LEGEND_TAXONOMY_PARAM_TOKEN.TAXONOMY_TREE_KEY]: taxonomyTreeKey,
    [LEGEND_TAXONOMY_PARAM_TOKEN.TAXONOMY_PATH]: taxonomyNodePath,
  })
Example #21
Source File: LegendTaxonomyRouter.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
generateStandaloneDataSpaceViewerRoute = (
  GAVCoordinates: string,
  dataSpacePath: string,
): string =>
  generatePath(LEGEND_TAXONOMY_ROUTE_PATTERN.VIEW_DATA_SPACE, {
    [LEGEND_TAXONOMY_PARAM_TOKEN.GAV]: GAVCoordinates,
    [LEGEND_TAXONOMY_PARAM_TOKEN.DATA_SPACE_PATH]: dataSpacePath,
  })
Example #22
Source File: UserProgram.tsx    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
UserProgram = (props: Props) => {
  const alert = useAlert();

  const { program, isMetaLinkActive = true } = props;

  return (
    <div className={styles.programsListItem} key={program.id}>
      <div className={styles.programWrapper}>
        <span
          className={clsx(
            styles.programsListIndicator,
            program.initStatus === ProgramStatus.Success && styles['program-item-success'],
            program.initStatus === ProgramStatus.Failed && styles['program-item-failure'],
            program.initStatus === ProgramStatus.InProgress && styles['program-item-loading']
          )}
        />
        <div className={styles.programWrapperName}>
          <div className={styles.programsListName}>
            <Link className={styles.programLink} to={`/program/${program.id}`}>
              {program.name && fileNameHandler(program.name)}
            </Link>
          </div>
        </div>
        <div className={styles.programsCopyId}>
          <button type="button" onClick={() => copyToClipboard(program.id, alert, 'Program ID copied')}>
            <img src={Copy} alt="copy program ID" />
          </button>
        </div>
      </div>
      <div className={styles.programWrapperData}>
        <div className={styles.programsListInfo}>
          Timestamp:
          <span className={styles.programsListInfoData}>{program.timestamp && formatDate(program.timestamp)}</span>
        </div>
      </div>

      <div className={styles.programsListBtns}>
        <Link to={`/send/message/${program.id}`} className={styles.allProgramsItemSendMessage}>
          <img src={MessageIllustration} alt="Send message to program" />
        </Link>
        <Link
          to={generatePath(routes.meta, { programId: program.id })}
          tabIndex={Number(isMetaLinkActive)}
          className={clsx(styles.allProgramsItemUpload, !isMetaLinkActive && styles.linkInactive)}
        >
          <img src={UploadIcon} alt="Upload metadata" />
        </Link>
      </div>
    </div>
  );
}
Example #23
Source File: ApiKeyCard.tsx    From jitsu with MIT License 5 votes vote down vote up
export function ApiKeyCard({ apiKey: key, showDocumentation }: ApiKeyCardProps) {
  const services = useServices()
  const [loading, setLoading] = useState(false)
  const rotateKey = async (key: ApiKey, type: "jsAuth" | "serverAuth"): Promise<string> => {
    let newKey = apiKeysStore.generateApiToken(type === "jsAuth" ? "js" : "s2s")
    await flowResult(apiKeysStore.patch(key.uid, { [type]: newKey }))
    actionNotification.info("New key has been generated and saved")
    return newKey
  }

  let deleteAction = async () => {
    confirmDelete({
      entityName: "api key",
      action: async () => {
        setLoading(true)
        try {
          await flowResult(apiKeysStore.delete(key.uid))
        } catch (error) {
          handleError(error, "Unable to delete API key at this moment, please try later.")
        } finally {
          setLoading(false)
        }
      },
    })
  }
  let editLink = generatePath(apiKeysRoutes.editExact, {
    projectId: services.activeProject.id,
    id: key.uid.replace(".", "-"),
  })
  return (
    <ConnectionCard
      loading={loading}
      title={APIKeyUtil.getDisplayName(key)}
      icon={apiKeysReferenceMap.js.icon}
      deleteAction={deleteAction}
      editAction={editLink}
      menuOverlay={
        <Menu>
          <Menu.Item icon={<EditOutlined />}>
            <NavLink to={editLink}>Edit</NavLink>
          </Menu.Item>
          <Menu.Item icon={<DeleteOutlined />} onClick={deleteAction}>
            Delete
          </Menu.Item>
        </Menu>
      }
      rename={async newName => {
        await flowResult(apiKeysStore.patch(key.uid, { comment: newName }))
      }}
      subtitle={<a onClick={showDocumentation}>Show connection instructions→</a>}
      status={
        <>
          <div className="text-xs">
            <div className="flex flex-nowrap items-center">
              <span className="inline-block whitespace-nowrap w-16 text-xxs">Server Key</span>{" "}
              <SecretKey rotateKey={() => rotateKey(key, "serverAuth")}>{key.serverAuth}</SecretKey>
            </div>
            <div className="flex flex-nowrap items-center pt-2">
              <span className="inline-block whitespace-nowrap w-16 text-xxs">JS Key</span>
              <SecretKey rotateKey={() => rotateKey(key, "jsAuth")}>{key.jsAuth}</SecretKey>
            </div>
          </div>
        </>
      }
    />
  )
}
Example #24
Source File: ProjectLink.tsx    From jitsu with MIT License 5 votes vote down vote up
export function projectRoute(pattern: string, params: ExtractRouteParams<string> = {}): string {
  return generatePath(pattern, { projectId: ApplicationServices.get().activeProject.id, ...params })
}
Example #25
Source File: Mirrors.tsx    From mirrorz with MIT License 5 votes vote down vote up
Group = React.memo((
  { group, entries, filtered, defaultCollapse = true }:
    { group: string, entries: ParsedMirror[], filtered: boolean, defaultCollapse?: boolean }) => {
  const match = useRouteMatch();
  const [collapse, setCollapse] = useState(defaultCollapse);
  const toggleCollapse = useCallback(() => setCollapse(c => !c), []);

  const summary = useMemo(() =>
    <Summary sum={statusSum(entries.map(({ status }) => statusMapper(status)))} />,
    [entries]);

  return (
    <div className={"group" + (filtered ? " filtered" : "") + (collapse ? "" : " group-expanded")}>
      <Link to={generatePath(match.path, { filter: encodeURIComponent(group) })}>
        <div className="group-header" id={group} onClick={toggleCollapse}>
          <h2 className="heading">
            {collapse ?
              (<Icon>add</Icon>) :
              (<Icon>remove</Icon>)
            }
            {group}
          </h2>
          <div>
            {summary}
          </div>
        </div>
      </Link>
      <div className="group-items">
        {collapse == false && entries.sort((a, b) => a.source.localeCompare(b.source)).map(({ full, help, upstream, desc, status, source, size, note }, idx) => (
          <div key={idx}>
            <h3>
              <a href={full} target="_blank">
                {source}
              </a>
              {help && (
                <a className="help" href={help} target="_blank">
                  <Icon title="Help">help</Icon>
                </a>
              )}
            </h3>
            {upstream && (
              <div className="upstream">
                <Icon>outbound</Icon>
                {upstream}
              </div>
            )}
            {status && (
              <StatusList mapper={statusMapper(status)} />
            )}
            {size && (
              <div className="size">
                <Icon>save</Icon>
                {size}
              </div>
            )}
            {note && (
              <div className="note">
                <Icon>note</Icon>
                {note}
              </div>
            )}
            {desc && (
              <div className="desc">{desc}</div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
})
Example #26
Source File: LegendStudioRouter.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
generateGroupWorkspaceEditorRoute = (
  projectId: string,
  groupWorkspaceId: string,
): string =>
  generatePath(LEGEND_STUDIO_ROUTE_PATTERN.EDIT_GROUP, {
    projectId,
    groupWorkspaceId,
  })
Example #27
Source File: list.tsx    From master-frontend-lemoncode with MIT License 5 votes vote down vote up
ListPage: React.FC = () => {
  const [members, setMembers] = React.useState<MemberEntity[]>([]);

  React.useEffect(() => {
    fetch(`https://api.github.com/orgs/lemoncode/members`)
      .then((response) => response.json())
      .then((json) => setMembers(json));
  }, []);

  return (
    <>
      <h2>Hello from List page</h2>
      <table className="table">
        <thead>
          <tr>
            <th>Avatar</th>
            <th>Id</th>
            <th>Name</th>
          </tr>
        </thead>
        <tbody>
          {members.map((member) => (
            <tr>
              <td>
                <img src={member.avatar_url} style={{ width: "5rem" }} />
              </td>
              <td>
                <span>{member.id}</span>
              </td>
              <td>
                <Link to={generatePath("/detail/:id", { id: member.login })}>
                  {member.login}
                </Link>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </>
  );
}
Example #28
Source File: list.tsx    From master-frontend-lemoncode with MIT License 5 votes vote down vote up
ListPage: React.FC = () => {
  const [members, setMembers] = React.useState<MemberEntity[]>([]);

  React.useEffect(() => {
    fetch(`https://api.github.com/orgs/lemoncode/members`)
      .then((response) => response.json())
      .then((json) => setMembers(json));
  }, []);

  return (
    <>
      <TableContainer component={Paper}>
        <Table aria-label="list table">
          <TableHead>
            <TableRow>
              <TableCell align="right">Avatar</TableCell>
              <TableCell align="right">Id</TableCell>
              <TableCell align="right">Name</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {members.map((member) => (
              <TableRow key={member.login}>
                <TableCell>
                  <img src={member.avatar_url} style={{ width: "2rem" }} />
                </TableCell>
                <TableCell align="right">{member.id}</TableCell>
                <TableCell align="right">
                  <Link to={generatePath("/detail/:id", { id: member.login })}>
                    {member.login}
                  </Link>{" "}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </>
  );
}
Example #29
Source File: routes.ts    From master-frontend-lemoncode with MIT License 5 votes vote down vote up
routes: Routes = {
  ...switchRoutes,
  editEmployee: id => generatePath(switchRoutes.editEmployee, { id }),
}