recreateRoute.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import {PlainRoute} from 'react-router';
  2. import {Location} from 'history';
  3. import findLastIndex from 'lodash/findLastIndex';
  4. import replaceRouterParams from 'sentry/utils/replaceRouterParams';
  5. type Options = {
  6. // parameters to replace any route string parameters (e.g. if route is `:orgId`,
  7. // params should have `{orgId: slug}`
  8. params: {[key: string]: string | undefined};
  9. routes: PlainRoute[];
  10. location?: Location;
  11. /**
  12. * The number of routes to to pop off of `routes
  13. * Must be < 0
  14. *
  15. * There's no ts type for negative numbers so we are arbitrarily specifying -1-9
  16. */
  17. stepBack?: -1 | -2 | -3 | -4 | -5 | -6 | -7 | -8 | -9;
  18. };
  19. /**
  20. * Given a route object or a string and a list of routes + params from router, this will attempt to recreate a location string while replacing url params.
  21. * Can additionally specify the number of routes to move back
  22. *
  23. * See tests for examples
  24. */
  25. export default function recreateRoute(to: string | PlainRoute, options: Options): string {
  26. const {routes, params, location, stepBack} = options;
  27. const paths = routes.map(({path}) => {
  28. path = path || '';
  29. if (path.length > 0 && !path.endsWith('/')) {
  30. path = `${path}/`;
  31. }
  32. return path;
  33. });
  34. let lastRootIndex: number;
  35. let routeIndex: number | undefined;
  36. // TODO(ts): typescript things
  37. if (typeof to !== 'string') {
  38. routeIndex = routes.indexOf(to) + 1;
  39. lastRootIndex = findLastIndex(paths.slice(0, routeIndex), path => path[0] === '/');
  40. } else {
  41. lastRootIndex = findLastIndex(paths, path => path[0] === '/');
  42. }
  43. let baseRoute = paths.slice(lastRootIndex, routeIndex);
  44. if (typeof stepBack !== 'undefined') {
  45. baseRoute = baseRoute.slice(0, stepBack);
  46. }
  47. const search = location?.search ?? '';
  48. const hash = location?.hash ?? '';
  49. const fullRoute = `${baseRoute.join('')}${
  50. typeof to !== 'string' ? '' : to
  51. }${search}${hash}`;
  52. return replaceRouterParams(fullRoute, params);
  53. }