recreateRoute.tsx 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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}) => path || '');
  28. let lastRootIndex: number;
  29. let routeIndex: number | undefined;
  30. // TODO(ts): typescript things
  31. if (typeof to !== 'string') {
  32. routeIndex = routes.indexOf(to) + 1;
  33. lastRootIndex = findLastIndex(paths.slice(0, routeIndex), path => path[0] === '/');
  34. } else {
  35. lastRootIndex = findLastIndex(paths, path => path[0] === '/');
  36. }
  37. let baseRoute = paths.slice(lastRootIndex, routeIndex);
  38. if (typeof stepBack !== 'undefined') {
  39. baseRoute = baseRoute.slice(0, stepBack);
  40. }
  41. const search = location?.search ?? '';
  42. const hash = location?.hash ?? '';
  43. const fullRoute = `${baseRoute.join('')}${
  44. typeof to !== 'string' ? '' : to
  45. }${search}${hash}`;
  46. return replaceRouterParams(fullRoute, params);
  47. }