All files / src/routes legacyRedirect.tsx

100% Statements 10/10
83.33% Branches 5/6
100% Functions 2/2
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44                                                86x 5x 5x 5x 5x 4x       5x 5x   86x              
import React from "react";
import { Navigate, useLocation, useParams } from "react-router-dom";
 
/** A page that only redirects. `redirectsTo` marks it as one: it is checked
 *  by the route tests, which otherwise require every page to be lazy and to
 *  render something. */
export interface RedirectPage extends React.FC {
  redirectsTo: string;
}
 
/**
 * A page that sends an old path to where the thing now lives.
 *
 * URLs outlive layouts. When a resource moves under the page that owns it —
 * a tool from `/user/tools/id/…` to `/user/inference/tools/id/…` — the old
 * path is in somebody's bookmarks, in a Slack message, in a runbook. Leaving
 * it to fall through to the not-found page makes a resource that still exists
 * look deleted.
 *
 * Route params are carried across by name, so `:toolId` in the old path fills
 * `:toolId` in the new one, and the query string comes with it — an old link
 * that already carried `?version=3` still lands on version 3.
 */
export function legacyRedirect(template: string): RedirectPage {
  const LegacyRedirect: React.FC = () => {
    const params = useParams();
    const { search, hash } = useLocation();
    let to = template;
    for (const [name, value] of Object.entries(params)) {
      Eif (value) to = to.replace(`:${name}`, value);
    }
    // A target that already has a query (`?section=mcp`) takes the old
    // link's parameters after its own, rather than a second `?`.
    const query = to.includes("?") && search ? `&${search.slice(1)}` : search;
    return <Navigate to={`${to}${query}${hash}`} replace />;
  };
  return Object.assign(LegacyRedirect, {
    displayName: "LegacyRedirect",
    redirectsTo: template,
  });
}
 
export default legacyRedirect;