<html lang="en">
<head></head>
<body>

<form id="mainForm" method="post" action="https://stackblitz.com/run" target="_self">
<input type="hidden" name="project[files][.gitignore]" value="node_modules
.DS_Store
dist
dist-ssr
*.local
">
<input type="hidden" name="project[files][README.md]" value="# TanStack Router - Kitchen Sink Example

A comprehensive example demonstrating many TanStack Router features.

- [TanStack Router Docs](https://tanstack.com/router)

## Start a new project based on this example

To start a new project based on this example, run:

```sh
npx gitpick TanStack/router/tree/main/examples/react/kitchen-sink kitchen-sink
```

## Getting Started

Install dependencies:

```sh
pnpm install
```

Start the development server:

```sh
pnpm dev
```

## Build

Build for production:

```sh
pnpm build
```

## About This Example

This &quot;kitchen sink&quot; example demonstrates:

- Advanced routing patterns
- Nested routes
- Route parameters and search params
- Data loading
- Error handling
- Route guards
- And many more TanStack Router features
">
<input type="hidden" name="project[files][index.html]" value="&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot; /&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;
    &lt;title&gt;Vite App&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id=&quot;app&quot;&gt;&lt;/div&gt;
    &lt;script type=&quot;module&quot; src=&quot;/src/main.tsx&quot;&gt;&lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
">
<input type="hidden" name="project[files][package.json]" value="{&quot;name&quot;:&quot;tanstack-router-react-example-kitchen-sink&quot;,&quot;private&quot;:true,&quot;type&quot;:&quot;module&quot;,&quot;scripts&quot;:{&quot;dev&quot;:&quot;vite --port 3000&quot;,&quot;build&quot;:&quot;vite build &amp;&amp; tsc --noEmit&quot;,&quot;preview&quot;:&quot;vite preview&quot;,&quot;start&quot;:&quot;vite&quot;},&quot;dependencies&quot;:{&quot;@tailwindcss/vite&quot;:&quot;^4.1.18&quot;,&quot;@tanstack/react-router&quot;:&quot;https://pkg.pr.new/TanStack/router/@tanstack/react-router@a8b8021139e1f21e979e462e14ed8c15d4ce0f92&quot;,&quot;@tanstack/react-router-devtools&quot;:&quot;https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@a8b8021139e1f21e979e462e14ed8c15d4ce0f92&quot;,&quot;immer&quot;:&quot;^10.1.1&quot;,&quot;react&quot;:&quot;^19.0.0&quot;,&quot;react-dom&quot;:&quot;^19.0.0&quot;,&quot;redaxios&quot;:&quot;^0.5.1&quot;,&quot;tailwindcss&quot;:&quot;^4.1.18&quot;,&quot;zod&quot;:&quot;^3.24.2&quot;},&quot;devDependencies&quot;:{&quot;@types/react&quot;:&quot;^19.0.8&quot;,&quot;@types/react-dom&quot;:&quot;^19.0.3&quot;,&quot;@vitejs/plugin-react&quot;:&quot;^4.3.4&quot;,&quot;typescript&quot;:&quot;^5.7.2&quot;,&quot;vite&quot;:&quot;^7.1.7&quot;}}">
<input type="hidden" name="project[files][tsconfig.json]" value="{
  &quot;compilerOptions&quot;: {
    &quot;strict&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;jsx&quot;: &quot;react-jsx&quot;,
    &quot;target&quot;: &quot;ESNext&quot;,
    &quot;moduleResolution&quot;: &quot;Bundler&quot;,
    &quot;module&quot;: &quot;ESNext&quot;,
    &quot;lib&quot;: [&quot;DOM&quot;, &quot;DOM.Iterable&quot;, &quot;ES2022&quot;],
    &quot;skipLibCheck&quot;: true
  }
}
">
<input type="hidden" name="project[files][vite.config.js]" value="import { defineConfig } from &#39;vite&#39;
import react from &#39;@vitejs/plugin-react&#39;
import tailwindcss from &#39;@tailwindcss/vite&#39;

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [tailwindcss(), react()],
})
">
<input type="hidden" name="project[files][.vscode/settings.json]" value="{
  &quot;files.watcherExclude&quot;: {
    &quot;**/routeTree.gen.ts&quot;: true
  },
  &quot;search.exclude&quot;: {
    &quot;**/routeTree.gen.ts&quot;: true
  },
  &quot;files.readonlyInclude&quot;: {
    &quot;**/routeTree.gen.ts&quot;: true
  }
}
">
<input type="hidden" name="project[files][src/Expensive.tsx]" value="import * as React from &#39;react&#39;

export default function Expensive() {
  return (
    &lt;div className={`p-2`}&gt;
      I am an &quot;expensive&quot; component... which really just means that I was
      code-split 😉
    &lt;/div&gt;
  )
}
">
<input type="hidden" name="project[files][src/main.tsx]" value="/* eslint-disable @typescript-eslint/no-unnecessary-condition */
import * as React from &#39;react&#39;
import ReactDOM from &#39;react-dom/client&#39;
import {
  ErrorComponent,
  Link,
  MatchRoute,
  Outlet,
  RouterProvider,
  createRootRouteWithContext,
  createRoute,
  createRouter,
  lazyRouteComponent,
  notFound,
  redirect,
  retainSearchParams,
  useNavigate,
  useRouter,
  useRouterState,
  useSearch,
} from &#39;@tanstack/react-router&#39;
import { TanStackRouterDevtools } from &#39;@tanstack/react-router-devtools&#39;
import { z } from &#39;zod&#39;
import {
  fetchInvoiceById,
  fetchInvoices,
  fetchUserById,
  fetchUsers,
  patchInvoice,
  postInvoice,
} from &#39;./mockTodos&#39;
import { useMutation } from &#39;./useMutation&#39;
import type { NotFoundRouteProps } from &#39;@tanstack/react-router&#39;
import type { Invoice } from &#39;./mockTodos&#39;
import &#39;./styles.css&#39;

//

type UsersViewSortBy = &#39;name&#39; | &#39;id&#39; | &#39;email&#39;

type MissingUserData = {
  userId: number
}

function isMissingUserData(data: unknown): data is MissingUserData {
  return (
    typeof data === &#39;object&#39; &amp;&amp;
    data !== null &amp;&amp;
    typeof (data as { userId?: unknown }).userId === &#39;number&#39;
  )
}

function UsersNotFoundComponent({ data, routeId }: NotFoundRouteProps) {
  const userId = isMissingUserData(data) ? data.userId : undefined

  return (
    &lt;div className=&quot;p-4 space-y-2&quot;&gt;
      &lt;h4 className=&quot;text-lg font-bold&quot;&gt;User not found&lt;/h4&gt;
      &lt;p&gt;
        {typeof userId === &#39;number&#39;
          ? `We couldn&#39;t find a user with ID ${userId}.`
          : &quot;We couldn&#39;t find the requested user.&quot;}
      &lt;/p&gt;
      &lt;p className=&quot;text-xs text-gray-500&quot;&gt;
        Rendered by the &quot;{routeId}&quot; route.
      &lt;/p&gt;
      &lt;p className=&quot;text-sm text-gray-500&quot;&gt;
        Pick another user from the list on the left to continue.
      &lt;/p&gt;
    &lt;/div&gt;
  )
}

const rootRoute = createRootRouteWithContext&lt;{
  auth: Auth
}&gt;()({
  component: RootComponent,
})

function RouterSpinner() {
  const isLoading = useRouterState({ select: (s) =&gt; s.status === &#39;pending&#39; })
  return &lt;Spinner show={isLoading} /&gt;
}

function RootComponent() {
  return (
    &lt;&gt;
      &lt;div className={`min-h-screen flex flex-col`}&gt;
        &lt;div className={`flex items-center border-b gap-2`}&gt;
          &lt;h1 className={`text-3xl p-2`}&gt;Kitchen Sink&lt;/h1&gt;
          {/* Show a global spinner when the router is transitioning */}
          &lt;div className={`text-3xl`}&gt;
            &lt;RouterSpinner /&gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div className={`flex-1 flex`}&gt;
          &lt;div className={`divide-y w-56`}&gt;
            {(
              [
                [&#39;/&#39;, &#39;Home&#39;],
                [&#39;/dashboard&#39;, &#39;Dashboard&#39;],
                [&#39;/expensive&#39;, &#39;Expensive&#39;],
                [&#39;/route-a&#39;, &#39;Pathless Layout A&#39;],
                [&#39;/route-b&#39;, &#39;Pathless Layout B&#39;],
                [&#39;/profile&#39;, &#39;Profile&#39;],
                ...(auth.status === &#39;loggedOut&#39; ? [[&#39;/login&#39;, &#39;Login&#39;]] : []),
              ] as const
            ).map(([to, label]) =&gt; {
              return (
                &lt;div key={to}&gt;
                  &lt;Link
                    to={to}
                    activeOptions={
                      {
                        // If the route points to the root of it&#39;s parent,
                        // make sure it&#39;s only active if it&#39;s exact
                        // exact: to === &#39;.&#39;,
                      }
                    }
                    preload=&quot;intent&quot;
                    className={`block py-2 px-3 text-blue-700`}
                    // Make &quot;active&quot; links bold
                    activeProps={{ className: `font-bold` }}
                  &gt;
                    {label}
                  &lt;/Link&gt;
                &lt;/div&gt;
              )
            })}
          &lt;/div&gt;
          &lt;div className={`flex-1 border-l`}&gt;
            {/* Render our first route match */}
            &lt;Outlet /&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;TanStackRouterDevtools position=&quot;bottom-right&quot; /&gt;
    &lt;/&gt;
  )
}

const indexRoute = createRoute({
  getParentRoute: () =&gt; rootRoute,
  path: &#39;/&#39;,
  component: IndexComponent,
})

function IndexComponent() {
  return (
    &lt;div className={`p-2`}&gt;
      &lt;div className={`text-lg`}&gt;Welcome Home!&lt;/div&gt;
      &lt;hr className={`my-2`} /&gt;
      &lt;Link
        to={invoiceRoute.to}
        params={{
          invoiceId: 3,
        }}
        className={`py-1 px-2 text-xs bg-blue-500 text-white rounded-full`}
      &gt;
        1 New Invoice
      &lt;/Link&gt;
      &lt;hr className={`my-2`} /&gt;
      &lt;div className={`max-w-xl`}&gt;
        As you navigate around take note of the UX. It should feel
        suspense-like, where routes are only rendered once all of their data and
        elements are ready.
        &lt;hr className={`my-2`} /&gt;
        To exaggerate async effects, play with the artificial request delay
        slider in the bottom-left corner.
        &lt;hr className={`my-2`} /&gt;
        The last 2 sliders determine if link-hover preloading is enabled (and
        how long those preloads stick around) and also whether to cache rendered
        route data (and for how long). Both of these default to 0 (or off).
      &lt;/div&gt;
    &lt;/div&gt;
  )
}

const dashboardLayoutRoute = createRoute({
  getParentRoute: () =&gt; rootRoute,
  path: &#39;dashboard&#39;,
  component: DashboardLayoutComponent,
})

function DashboardLayoutComponent() {
  return (
    &lt;&gt;
      &lt;div className=&quot;flex items-center border-b&quot;&gt;
        &lt;h2 className=&quot;text-xl p-2&quot;&gt;Dashboard&lt;/h2&gt;
      &lt;/div&gt;
      &lt;div className=&quot;flex flex-wrap divide-x&quot;&gt;
        {(
          [
            [&#39;/dashboard&#39;, &#39;Summary&#39;, true],
            [&#39;/dashboard/invoices&#39;, &#39;Invoices&#39;],
            [&#39;/dashboard/users&#39;, &#39;Users&#39;],
          ] as const
        ).map(([to, label, exact]) =&gt; {
          return (
            &lt;Link
              key={to}
              to={to}
              activeOptions={{ exact }}
              activeProps={{ className: `font-bold` }}
              className=&quot;p-2&quot;
            &gt;
              {label}
            &lt;/Link&gt;
          )
        })}
      &lt;/div&gt;
      &lt;hr /&gt;
      &lt;Outlet /&gt;
    &lt;/&gt;
  )
}

const dashboardIndexRoute = createRoute({
  getParentRoute: () =&gt; dashboardLayoutRoute,
  path: &#39;/&#39;,
  loader: () =&gt; fetchInvoices(),
  component: DashboardIndexComponent,
})

function DashboardIndexComponent() {
  const invoices = dashboardIndexRoute.useLoaderData()

  return (
    &lt;div className=&quot;p-2&quot;&gt;
      &lt;div className=&quot;p-2&quot;&gt;
        Welcome to the dashboard! You have{&#39; &#39;}
        &lt;strong&gt;{invoices.length} total invoices&lt;/strong&gt;.
      &lt;/div&gt;
    &lt;/div&gt;
  )
}

const invoicesLayoutRoute = createRoute({
  getParentRoute: () =&gt; dashboardLayoutRoute,
  path: &#39;invoices&#39;,
  loader: () =&gt; fetchInvoices(),
  component: InvoicesLayoutComponent,
})

function InvoicesLayoutComponent() {
  const invoices = invoicesLayoutRoute.useLoaderData()

  return (
    &lt;div className=&quot;flex-1 flex&quot;&gt;
      &lt;div className=&quot;divide-y w-48&quot;&gt;
        {invoices.map((invoice) =&gt; {
          return (
            &lt;div key={invoice.id}&gt;
              &lt;Link
                to=&quot;/dashboard/invoices/$invoiceId&quot;
                params={{
                  invoiceId: invoice.id,
                }}
                preload=&quot;intent&quot;
                className=&quot;block py-2 px-3 text-blue-700&quot;
                activeProps={{ className: `font-bold ` }}
              &gt;
                &lt;pre className=&quot;text-sm&quot;&gt;
                  #{invoice.id} - {invoice.title.slice(0, 10)}{&#39; &#39;}
                  {/* {updateSubmission ? (
                      &lt;Spinner /&gt;
                    ) : ( */}
                  &lt;MatchRoute
                    to={invoiceRoute.to}
                    params={{
                      invoiceId: invoice.id,
                    }}
                    pending
                  &gt;
                    {(match) =&gt; &lt;Spinner show={!!match} wait=&quot;delay-50&quot; /&gt;}
                  &lt;/MatchRoute&gt;
                  {/* )} */}
                &lt;/pre&gt;
              &lt;/Link&gt;
            &lt;/div&gt;
          )
        })}
      &lt;/div&gt;
      &lt;div className=&quot;flex-1 border-l&quot;&gt;
        &lt;Outlet /&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  )
}

const invoicesIndexRoute = createRoute({
  getParentRoute: () =&gt; invoicesLayoutRoute,
  path: &#39;/&#39;,
  component: InvoicesIndexComponent,
})

function InvoicesIndexComponent() {
  const createInvoiceMutation = useMutation({
    fn: postInvoice,
    onSuccess: () =&gt; router.invalidate(),
  })

  return (
    &lt;&gt;
      &lt;div className=&quot;p-2&quot;&gt;
        &lt;form
          onSubmit={(event) =&gt; {
            event.preventDefault()
            event.stopPropagation()
            const formData = new FormData(event.target as HTMLFormElement)
            createInvoiceMutation.mutate({
              title: formData.get(&#39;title&#39;) as string,
              body: formData.get(&#39;body&#39;) as string,
            })
          }}
          className=&quot;space-y-2&quot;
        &gt;
          &lt;div&gt;Create a new Invoice:&lt;/div&gt;
          &lt;InvoiceFields invoice={{} as Invoice} /&gt;
          &lt;div&gt;
            &lt;button
              className=&quot;bg-blue-500 rounded-sm p-2 uppercase text-white font-black disabled:opacity-50&quot;
              disabled={createInvoiceMutation.status === &#39;pending&#39;}
            &gt;
              {createInvoiceMutation.status === &#39;pending&#39; ? (
                &lt;&gt;
                  Creating &lt;Spinner /&gt;
                &lt;/&gt;
              ) : (
                &#39;Create&#39;
              )}
            &lt;/button&gt;
          &lt;/div&gt;
          {createInvoiceMutation.status === &#39;success&#39; ? (
            &lt;div className=&quot;inline-block px-2 py-1 rounded-sm bg-green-500 text-white animate-bounce [animation-iteration-count:2.5] [animation-duration:.3s]&quot;&gt;
              Created!
            &lt;/div&gt;
          ) : createInvoiceMutation.status === &#39;error&#39; ? (
            &lt;div className=&quot;inline-block px-2 py-1 rounded-sm bg-red-500 text-white animate-bounce [animation-iteration-count:2.5] [animation-duration:.3s]&quot;&gt;
              Failed to create.
            &lt;/div&gt;
          ) : null}
        &lt;/form&gt;
      &lt;/div&gt;
    &lt;/&gt;
  )
}

const invoiceRoute = createRoute({
  getParentRoute: () =&gt; invoicesLayoutRoute,
  path: &#39;$invoiceId&#39;,
  params: {
    parse: (params) =&gt; ({
      invoiceId: z.number().int().parse(Number(params.invoiceId)),
    }),
    stringify: ({ invoiceId }) =&gt; ({ invoiceId: `${invoiceId}` }),
  },
  validateSearch: (search) =&gt;
    z
      .object({
        showNotes: z.boolean().optional(),
        notes: z.string().optional(),
      })
      .parse(search),
  loader: ({ params: { invoiceId } }) =&gt; fetchInvoiceById(invoiceId),
  component: InvoiceComponent,
  pendingComponent: () =&gt; &lt;Spinner /&gt;,
})

function InvoiceComponent() {
  const search = invoiceRoute.useSearch()
  const navigate = useNavigate({ from: invoiceRoute.fullPath })
  const invoice = invoiceRoute.useLoaderData()
  const updateInvoiceMutation = useMutation({
    fn: patchInvoice,
    onSuccess: () =&gt; router.invalidate(),
  })
  const [notes, setNotes] = React.useState(search.notes ?? &#39;&#39;)
  React.useEffect(() =&gt; {
    navigate({
      search: (old) =&gt; ({
        ...old,
        notes: notes ? notes : undefined,
      }),
      params: true,
      replace: true,
    })
  }, [notes])

  return (
    &lt;form
      key={invoice.id}
      onSubmit={(event) =&gt; {
        event.preventDefault()
        event.stopPropagation()
        const formData = new FormData(event.target as HTMLFormElement)
        updateInvoiceMutation.mutate({
          id: invoice.id,
          title: formData.get(&#39;title&#39;) as string,
          body: formData.get(&#39;body&#39;) as string,
        })
      }}
      className=&quot;p-2 space-y-2&quot;
    &gt;
      &lt;InvoiceFields
        invoice={invoice}
        disabled={updateInvoiceMutation.status === &#39;pending&#39;}
      /&gt;
      &lt;div&gt;
        &lt;Link
          search={(old) =&gt; ({
            ...old,
            showNotes: old.showNotes ? undefined : true,
          })}
          className=&quot;text-blue-700&quot;
          from={invoiceRoute.fullPath}
          params={true}
        &gt;
          {search.showNotes ? &#39;Close Notes&#39; : &#39;Show Notes&#39;}{&#39; &#39;}
        &lt;/Link&gt;
        {search.showNotes ? (
          &lt;&gt;
            &lt;div&gt;
              &lt;div className=&quot;h-2&quot; /&gt;
              &lt;textarea
                value={notes}
                onChange={(e) =&gt; {
                  setNotes(e.target.value)
                }}
                rows={5}
                className=&quot;shadow-sm w-full p-2 rounded-sm&quot;
                placeholder=&quot;Write some notes here...&quot;
              /&gt;
              &lt;div className=&quot;italic text-xs&quot;&gt;
                Notes are stored in the URL. Try copying the URL into a new tab!
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/&gt;
        ) : null}
      &lt;/div&gt;
      &lt;div&gt;
        &lt;button
          className=&quot;bg-blue-500 rounded-sm p-2 uppercase text-white font-black disabled:opacity-50&quot;
          disabled={updateInvoiceMutation.status === &#39;pending&#39;}
        &gt;
          Save
        &lt;/button&gt;
      &lt;/div&gt;
      {updateInvoiceMutation.variables?.id === invoice.id ? (
        &lt;div key={updateInvoiceMutation.submittedAt}&gt;
          {updateInvoiceMutation.status === &#39;success&#39; ? (
            &lt;div className=&quot;inline-block px-2 py-1 rounded-sm bg-green-500 text-white animate-bounce [animation-iteration-count:2.5] [animation-duration:.3s]&quot;&gt;
              Saved!
            &lt;/div&gt;
          ) : updateInvoiceMutation.status === &#39;error&#39; ? (
            &lt;div className=&quot;inline-block px-2 py-1 rounded-sm bg-red-500 text-white animate-bounce [animation-iteration-count:2.5] [animation-duration:.3s]&quot;&gt;
              Failed to save.
            &lt;/div&gt;
          ) : null}
        &lt;/div&gt;
      ) : null}
    &lt;/form&gt;
  )
}

const usersLayoutRoute = createRoute({
  getParentRoute: () =&gt; dashboardLayoutRoute,
  path: &#39;users&#39;,
  validateSearch: z.object({
    usersView: z
      .object({
        sortBy: z.enum([&#39;name&#39;, &#39;id&#39;, &#39;email&#39;]).optional(),
        filterBy: z.string().optional(),
      })
      .optional(),
  }).parse,
  search: {
    // Retain the usersView search param while navigating
    // within or to this route (or it&#39;s children!)
    middlewares: [retainSearchParams([&#39;usersView&#39;])],
  },
  loaderDeps: ({ search: { usersView } }) =&gt; ({
    filterBy: usersView?.filterBy,
    sortBy: usersView?.sortBy ?? &#39;name&#39;,
  }),
  loader: ({ deps }) =&gt; fetchUsers(deps),
  notFoundComponent: UsersNotFoundComponent,
  component: UsersLayoutComponent,
})

function UsersLayoutComponent() {
  const navigate = useNavigate({ from: usersLayoutRoute.fullPath })
  const { usersView } = usersLayoutRoute.useSearch()
  const users = usersLayoutRoute.useLoaderData()
  const sortBy = usersView?.sortBy ?? &#39;name&#39;
  const filterBy = usersView?.filterBy

  const [filterDraft, setFilterDraft] = React.useState(filterBy ?? &#39;&#39;)

  React.useEffect(() =&gt; {
    setFilterDraft(filterBy ?? &#39;&#39;)
  }, [filterBy])

  const sortedUsers = React.useMemo(() =&gt; {
    if (!users) return []

    return !sortBy
      ? users
      : [...users].sort((a, b) =&gt; {
          return a[sortBy] &gt; b[sortBy] ? 1 : -1
        })
  }, [users, sortBy])

  const filteredUsers = React.useMemo(() =&gt; {
    if (!filterBy) return sortedUsers

    return sortedUsers.filter((user) =&gt;
      user.name.toLowerCase().includes(filterBy.toLowerCase()),
    )
  }, [sortedUsers, filterBy])

  const setSortBy = (sortBy: UsersViewSortBy) =&gt;
    navigate({
      search: (old) =&gt; {
        return {
          ...old,
          usersView: {
            ...(old.usersView ?? {}),
            sortBy,
          },
        }
      },
      replace: true,
    })

  React.useEffect(() =&gt; {
    navigate({
      search: (old) =&gt; {
        return {
          ...old,
          usersView: {
            ...old.usersView,
            filterBy: filterDraft || undefined,
          },
        }
      },
      replace: true,
    })
  }, [filterDraft])

  return (
    &lt;div className=&quot;flex-1 flex&quot;&gt;
      &lt;div className=&quot;divide-y&quot;&gt;
        &lt;div className=&quot;py-2 px-3 flex gap-2 items-center bg-gray-100 dark:bg-gray-800&quot;&gt;
          &lt;div&gt;Sort By:&lt;/div&gt;
          &lt;select
            value={sortBy}
            onChange={(e) =&gt; setSortBy(e.target.value as UsersViewSortBy)}
            className=&quot;flex-1 border p-1 px-2 rounded-sm&quot;
          &gt;
            {[&#39;name&#39;, &#39;id&#39;, &#39;email&#39;].map((d) =&gt; {
              return &lt;option key={d} value={d} children={d} /&gt;
            })}
          &lt;/select&gt;
        &lt;/div&gt;
        &lt;div className=&quot;py-2 px-3 flex gap-2 items-center bg-gray-100 dark:bg-gray-800&quot;&gt;
          &lt;div&gt;Filter By:&lt;/div&gt;
          &lt;input
            value={filterDraft}
            onChange={(e) =&gt; setFilterDraft(e.target.value)}
            placeholder=&quot;Search Names...&quot;
            className=&quot;min-w-0 flex-1 border p-1 px-2 rounded-sm&quot;
          /&gt;
        &lt;/div&gt;
        {filteredUsers.map((user) =&gt; {
          return (
            &lt;div key={user.id}&gt;
              &lt;Link
                to=&quot;/dashboard/users/user&quot;
                search={{
                  userId: user.id,
                }}
                className=&quot;block py-2 px-3 text-blue-700&quot;
                activeProps={{ className: `font-bold` }}
              &gt;
                &lt;pre className=&quot;text-sm&quot;&gt;
                  {user.name}{&#39; &#39;}
                  &lt;MatchRoute
                    to={userRoute.to}
                    search={{
                      userId: user.id,
                    }}
                    pending
                  &gt;
                    {(match) =&gt; &lt;Spinner show={!!match} wait=&quot;delay-50&quot; /&gt;}
                  &lt;/MatchRoute&gt;
                &lt;/pre&gt;
              &lt;/Link&gt;
            &lt;/div&gt;
          )
        })}
        &lt;div className=&quot;px-3 py-2 text-xs text-gray-500 bg-gray-100 dark:bg-gray-800/60&quot;&gt;
          Need to see how not-found errors look?{&#39; &#39;}
          &lt;Link
            to={userRoute.to}
            search={{
              userId: 404,
            }}
            className=&quot;text-blue-700&quot;
          &gt;
            Try loading user 404
          &lt;/Link&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div className=&quot;flex-initial border-l&quot;&gt;
        &lt;Outlet /&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  )
}

const usersIndexRoute = createRoute({
  getParentRoute: () =&gt; usersLayoutRoute,
  path: &#39;/&#39;,
  component: UsersIndexComponent,
})

function UsersIndexComponent() {
  return (
    &lt;div className=&quot;p-2 space-y-2&quot;&gt;
      &lt;p&gt;
        Normally, setting default search parameters would either need to be done
        manually in every link to a page, or as a side-effect (not a great
        experience).
      &lt;/p&gt;
      &lt;p&gt;
        Instead, we can use &lt;strong&gt;search filters&lt;/strong&gt; to provide defaults
        or even persist search params for links to routes (and child routes).
      &lt;/p&gt;
      &lt;p&gt;
        A good example of this is the sorting and filtering of the users list.
        In a traditional router, both would be lost while navigating around
        individual users or even changing each sort/filter option unless each
        state was manually passed from the current route into each new link we
        created (that&#39;s a lot of tedious and error-prone work). With TanStack
        router and search filters, they are persisted with little effort.
      &lt;/p&gt;
    &lt;/div&gt;
  )
}

const userRoute = createRoute({
  getParentRoute: () =&gt; usersLayoutRoute,
  path: &#39;user&#39;,
  validateSearch: z.object({
    userId: z.number(),
  }),
  loaderDeps: ({ search: { userId } }) =&gt; ({
    userId,
  }),
  loader: async ({ deps: { userId } }) =&gt; {
    const user = await fetchUserById(userId)

    if (!user) {
      throw notFound({
        data: {
          userId,
        },
      })
    }

    return user
  },
  component: UserComponent,
})

function UserComponent() {
  const user = userRoute.useLoaderData()

  return (
    &lt;&gt;
      &lt;h4 className=&quot;p-2 font-bold&quot;&gt;{user?.name}&lt;/h4&gt;
      &lt;pre className=&quot;text-sm whitespace-pre-wrap&quot;&gt;
        {JSON.stringify(user, null, 2)}
      &lt;/pre&gt;
    &lt;/&gt;
  )
}

const expensiveRoute = createRoute({
  getParentRoute: () =&gt; rootRoute,
  // Your elements can be asynchronous, which means you can code-split!
  path: &#39;expensive&#39;,
  component: lazyRouteComponent(() =&gt; import(&#39;./Expensive&#39;)),
})

const authPathlessLayoutRoute = createRoute({
  getParentRoute: () =&gt; rootRoute,
  id: &#39;auth&#39;,
  // Before loading, authenticate the user via our auth context
  // This will also happen during prefetching (e.g. hovering over links, etc)
  beforeLoad: ({ context, location }) =&gt; {
    // If the user is logged out, redirect them to the login page
    if (context.auth.status === &#39;loggedOut&#39;) {
      console.log(location)
      throw redirect({
        to: loginRoute.to,
        search: {
          // Use the current location to power a redirect after login
          // (Do not use `router.state.resolvedLocation` as it can
          // potentially lag behind the actual current location)
          redirect: location.href,
        },
      })
    }

    // Otherwise, return the user in context
    return {
      username: auth.username,
    }
  },
})

const profileRoute = createRoute({
  getParentRoute: () =&gt; authPathlessLayoutRoute,
  path: &#39;profile&#39;,
  component: ProfileComponent,
})

function ProfileComponent() {
  const { username } = profileRoute.useRouteContext()

  return (
    &lt;div className=&quot;p-2 space-y-2&quot;&gt;
      &lt;div&gt;
        Username:&lt;strong&gt;{username}&lt;/strong&gt;
      &lt;/div&gt;
      &lt;button
        className=&quot;text-sm bg-blue-500 text-white border inline-block py-1 px-2 rounded-sm&quot;
        onClick={() =&gt; {
          auth.logout()
          router.invalidate()
        }}
      &gt;
        Log out
      &lt;/button&gt;
    &lt;/div&gt;
  )
}

const loginRoute = createRoute({
  getParentRoute: () =&gt; rootRoute,
  path: &#39;login&#39;,
  validateSearch: z.object({
    redirect: z.string().optional(),
  }),
}).update({
  component: LoginComponent,
})

function LoginComponent() {
  const router = useRouter()
  const { auth, status } = loginRoute.useRouteContext({
    select: ({ auth }) =&gt; ({ auth, status: auth.status }),
  })
  const search = useSearch({ from: loginRoute.fullPath })
  const [username, setUsername] = React.useState(&#39;&#39;)

  const onSubmit = (e: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {
    e.preventDefault()
    auth.login(username)
    router.invalidate()
  }

  // Ah, the subtle nuances of client side auth. 🙄
  React.useLayoutEffect(() =&gt; {
    if (status === &#39;loggedIn&#39; &amp;&amp; search.redirect) {
      router.history.push(search.redirect)
    }
  }, [status, search.redirect])

  return status === &#39;loggedIn&#39; ? (
    &lt;div&gt;
      Logged in as &lt;strong&gt;{auth.username}&lt;/strong&gt;
      &lt;div className=&quot;h-2&quot; /&gt;
      &lt;button
        onClick={() =&gt; {
          auth.logout()
          router.invalidate()
        }}
        className=&quot;text-sm bg-blue-500 text-white border inline-block py-1 px-2 rounded-sm&quot;
      &gt;
        Log out
      &lt;/button&gt;
      &lt;div className=&quot;h-2&quot; /&gt;
    &lt;/div&gt;
  ) : (
    &lt;div className=&quot;p-2&quot;&gt;
      &lt;div&gt;You must log in!&lt;/div&gt;
      &lt;div className=&quot;h-2&quot; /&gt;
      &lt;form onSubmit={onSubmit} className=&quot;flex gap-2&quot;&gt;
        &lt;input
          value={username}
          onChange={(e) =&gt; setUsername(e.target.value)}
          placeholder=&quot;Username&quot;
          className=&quot;border p-1 px-2 rounded-sm&quot;
        /&gt;
        &lt;button className=&quot;text-sm bg-blue-500 text-white border inline-block py-1 px-2 rounded-sm&quot;&gt;
          Login
        &lt;/button&gt;
      &lt;/form&gt;
    &lt;/div&gt;
  )
}

const pathlessLayoutRoute = createRoute({
  getParentRoute: () =&gt; rootRoute,
  id: &#39;pathless-layout&#39;,
  component: PathlessLayoutComponent,
})

function PathlessLayoutComponent() {
  return (
    &lt;div&gt;
      &lt;div&gt;Pathless Layout&lt;/div&gt;
      &lt;hr /&gt;
      &lt;Outlet /&gt;
    &lt;/div&gt;
  )
}

const pathlessLayoutARoute = createRoute({
  getParentRoute: () =&gt; pathlessLayoutRoute,
  path: &#39;route-a&#39;,
  component: PathlessLayoutAComponent,
})

function PathlessLayoutAComponent() {
  return (
    &lt;div&gt;
      &lt;div&gt;I&#39;m A&lt;/div&gt;
    &lt;/div&gt;
  )
}

const pathlessLayoutBRoute = createRoute({
  getParentRoute: () =&gt; pathlessLayoutRoute,
  path: &#39;route-b&#39;,
  component: PathlessLayoutBComponent,
})

function PathlessLayoutBComponent() {
  return (
    &lt;div&gt;
      &lt;div&gt;I&#39;m B&lt;/div&gt;
    &lt;/div&gt;
  )
}

const routeTree = rootRoute.addChildren([
  indexRoute,
  dashboardLayoutRoute.addChildren([
    dashboardIndexRoute,
    invoicesLayoutRoute.addChildren([invoicesIndexRoute, invoiceRoute]),
    usersLayoutRoute.addChildren([usersIndexRoute, userRoute]),
  ]),
  expensiveRoute,
  authPathlessLayoutRoute.addChildren([profileRoute]),
  loginRoute,
  pathlessLayoutRoute.addChildren([pathlessLayoutARoute, pathlessLayoutBRoute]),
])

const router = createRouter({
  routeTree,
  defaultPendingComponent: () =&gt; (
    &lt;div className={`p-2 text-2xl`}&gt;
      &lt;Spinner /&gt;
    &lt;/div&gt;
  ),
  defaultErrorComponent: ({ error }) =&gt; &lt;ErrorComponent error={error} /&gt;,
  context: {
    auth: undefined!, // We&#39;ll inject this when we render
  },
  defaultPreload: &#39;intent&#39;,
  scrollRestoration: true,
})

declare module &#39;@tanstack/react-router&#39; {
  interface Register {
    router: typeof router
  }
}

const auth: Auth = {
  status: &#39;loggedOut&#39;,
  username: undefined,
  login: (username: string) =&gt; {
    auth.username = username
    auth.status = &#39;loggedIn&#39;
  },
  logout: () =&gt; {
    auth.status = &#39;loggedOut&#39;
    auth.username = undefined
  },
}

function App() {
  // This stuff is just to tweak our sandbox setup in real-time
  const [loaderDelay, setLoaderDelay] = useSessionStorage(&#39;loaderDelay&#39;, 500)
  const [pendingMs, setPendingMs] = useSessionStorage(&#39;pendingMs&#39;, 1000)
  const [pendingMinMs, setPendingMinMs] = useSessionStorage(&#39;pendingMinMs&#39;, 500)

  return (
    &lt;&gt;
      &lt;div className=&quot;text-xs fixed w-52 shadow-md shadow-black/20 rounded-sm bottom-2 left-2 bg-white dark:bg-gray-800 bg-opacity-75 border-b flex flex-col gap-1 flex-wrap items-left divide-y&quot;&gt;
        &lt;div className=&quot;p-2 space-y-2&quot;&gt;
          &lt;div className=&quot;flex gap-2&quot;&gt;
            &lt;button
              className=&quot;bg-blue-500 text-white rounded-sm p-1 px-2&quot;
              onClick={() =&gt; {
                setLoaderDelay(150)
              }}
            &gt;
              Fast
            &lt;/button&gt;
            &lt;button
              className=&quot;bg-blue-500 text-white rounded-sm p-1 px-2&quot;
              onClick={() =&gt; {
                setLoaderDelay(500)
              }}
            &gt;
              Fast 3G
            &lt;/button&gt;
            &lt;button
              className=&quot;bg-blue-500 text-white rounded-sm p-1 px-2&quot;
              onClick={() =&gt; {
                setLoaderDelay(2000)
              }}
            &gt;
              Slow 3G
            &lt;/button&gt;
          &lt;/div&gt;
          &lt;div&gt;
            &lt;div&gt;Loader Delay: {loaderDelay}ms&lt;/div&gt;
            &lt;input
              type=&quot;range&quot;
              min=&quot;0&quot;
              max=&quot;5000&quot;
              step=&quot;100&quot;
              value={loaderDelay}
              onChange={(e) =&gt; setLoaderDelay(e.target.valueAsNumber)}
              className=&quot;w-full&quot;
            /&gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div className=&quot;p-2 space-y-2&quot;&gt;
          &lt;div className=&quot;flex gap-2&quot;&gt;
            &lt;button
              className=&quot;bg-blue-500 text-white rounded-sm p-1 px-2&quot;
              onClick={() =&gt; {
                setPendingMs(1000)
                setPendingMinMs(500)
              }}
            &gt;
              Reset to Default
            &lt;/button&gt;
          &lt;/div&gt;
          &lt;div&gt;
            &lt;div&gt;defaultPendingMs: {pendingMs}ms&lt;/div&gt;
            &lt;input
              type=&quot;range&quot;
              min=&quot;0&quot;
              max=&quot;5000&quot;
              step=&quot;100&quot;
              value={pendingMs}
              onChange={(e) =&gt; setPendingMs(e.target.valueAsNumber)}
              className=&quot;w-full&quot;
            /&gt;
          &lt;/div&gt;
          &lt;div&gt;
            &lt;div&gt;defaultPendingMinMs: {pendingMinMs}ms&lt;/div&gt;
            &lt;input
              type=&quot;range&quot;
              min=&quot;0&quot;
              max=&quot;5000&quot;
              step=&quot;100&quot;
              value={pendingMinMs}
              onChange={(e) =&gt; setPendingMinMs(e.target.valueAsNumber)}
              className=&quot;w-full&quot;
            /&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;RouterProvider
        router={router}
        defaultPreload=&quot;intent&quot;
        defaultPendingMs={pendingMs}
        defaultPendingMinMs={pendingMinMs}
        context={{
          auth,
        }}
      /&gt;
    &lt;/&gt;
  )
}

function InvoiceFields({
  invoice,
  disabled,
}: {
  invoice: Invoice
  disabled?: boolean
}) {
  return (
    &lt;div className=&quot;space-y-2&quot;&gt;
      &lt;h2 className=&quot;font-bold text-lg&quot;&gt;
        &lt;input
          name=&quot;title&quot;
          defaultValue={invoice.title}
          placeholder=&quot;Invoice Title&quot;
          className=&quot;border border-opacity-50 rounded-sm p-2 w-full&quot;
          disabled={disabled}
        /&gt;
      &lt;/h2&gt;
      &lt;div&gt;
        &lt;textarea
          name=&quot;body&quot;
          defaultValue={invoice.body}
          rows={6}
          placeholder=&quot;Invoice Body...&quot;
          className=&quot;border border-opacity-50 p-2 rounded-sm w-full&quot;
          disabled={disabled}
        /&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  )
}

type Auth = {
  login: (username: string) =&gt; void
  logout: () =&gt; void
  status: &#39;loggedOut&#39; | &#39;loggedIn&#39;
  username?: string
}

function Spinner({ show, wait }: { show?: boolean; wait?: `delay-${number}` }) {
  return (
    &lt;div
      className={`inline-block animate-spin px-3 transition ${
        (show ?? true)
          ? `opacity-1 duration-500 ${wait ?? &#39;delay-300&#39;}`
          : &#39;duration-500 opacity-0 delay-0&#39;
      }`}
    &gt;
      ⍥
    &lt;/div&gt;
  )
}

function useSessionStorage&lt;T&gt;(key: string, initialValue: T) {
  const state = React.useState&lt;T&gt;(() =&gt; {
    const stored = sessionStorage.getItem(key)
    return stored ? JSON.parse(stored) : initialValue
  })

  React.useEffect(() =&gt; {
    sessionStorage.setItem(key, JSON.stringify(state[0]))
  }, [state[0]])

  return state
}

const rootElement = document.getElementById(&#39;app&#39;)!
if (!rootElement.innerHTML) {
  const root = ReactDOM.createRoot(rootElement)
  root.render(
    &lt;React.StrictMode&gt;
      &lt;App /&gt;
    &lt;/React.StrictMode&gt;,
  )
}
">
<input type="hidden" name="project[files][src/mockTodos.ts]" value="import axios from &#39;redaxios&#39;
import { produce } from &#39;immer&#39;
import { actionDelayFn, loaderDelayFn, shuffle } from &#39;./utils&#39;

type PickAsRequired&lt;TValue, TKey extends keyof TValue&gt; = Omit&lt;TValue, TKey&gt; &amp;
  Required&lt;Pick&lt;TValue, TKey&gt;&gt;

export type Invoice = {
  id: number
  title: string
  body: string
}

export interface User {
  id: number
  name: string
  username: string
  email: string
  address: Address
  phone: string
  website: string
  company: Company
}

export interface Address {
  street: string
  suite: string
  city: string
  zipcode: string
  geo: Geo
}

export interface Geo {
  lat: string
  lng: string
}

export interface Company {
  name: string
  catchPhrase: string
  bs: string
}

let invoices: Array&lt;Invoice&gt; = null!
let users: Array&lt;User&gt; = null!

let invoicesPromise: Promise&lt;void&gt; | undefined = undefined
let usersPromise: Promise&lt;void&gt; | undefined = undefined

const ensureInvoices = async () =&gt; {
  if (!invoicesPromise) {
    invoicesPromise = Promise.resolve().then(async () =&gt; {
      const { data } = await axios.get(
        &#39;https://jsonplaceholder.typicode.com/posts&#39;,
      )
      invoices = data.slice(0, 10)
    })
  }

  await invoicesPromise
}

const ensureUsers = async () =&gt; {
  if (!usersPromise) {
    usersPromise = Promise.resolve().then(async () =&gt; {
      const { data } = await axios.get(
        &#39;https://jsonplaceholder.typicode.com/users&#39;,
      )
      users = data.slice(0, 10)
    })
  }

  await usersPromise
}

export async function fetchInvoices() {
  return loaderDelayFn(() =&gt; ensureInvoices().then(() =&gt; invoices))
}

export async function fetchInvoiceById(id: number) {
  return loaderDelayFn(() =&gt;
    ensureInvoices().then(() =&gt; {
      const invoice = invoices.find((d) =&gt; d.id === id)
      if (!invoice) {
        throw new Error(&#39;Invoice not found&#39;)
      }
      return invoice
    }),
  )
}

export async function postInvoice(partialInvoice: Partial&lt;Invoice&gt;) {
  return actionDelayFn(() =&gt; {
    if (partialInvoice.title?.includes(&#39;error&#39;)) {
      console.error(&#39;error&#39;)
      throw new Error(&#39;Ouch!&#39;)
    }
    const invoice = {
      id: invoices.length + 1,
      title:
        partialInvoice.title ?? `New Invoice ${String(Date.now()).slice(0, 5)}`,
      body:
        partialInvoice.body ??
        shuffle(
          `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
      Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. 
      Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna.  Integer id quam. Morbi mi. Quisque nisl felis, venenatis tristique, dignissim in, ultrices sit amet, augue. Proin sodales libero eget ante.
      `.split(&#39; &#39;),
        ).join(&#39; &#39;),
    }
    invoices = [...invoices, invoice]
    return invoice
  })
}

export async function patchInvoice({
  id,
  ...updatedInvoice
}: PickAsRequired&lt;Partial&lt;Invoice&gt;, &#39;id&#39;&gt;) {
  return actionDelayFn(() =&gt; {
    invoices = produce(invoices, (draft) =&gt; {
      const invoice = draft.find((d) =&gt; d.id === id)
      if (!invoice) {
        throw new Error(&#39;Invoice not found.&#39;)
      }
      // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
      if (updatedInvoice.title?.toLocaleLowerCase()?.includes(&#39;error&#39;)) {
        throw new Error(&#39;Ouch!&#39;)
      }
      Object.assign(invoice, updatedInvoice)
    })

    return invoices.find((d) =&gt; d.id === id)
  })
}

export type UsersSortBy = &#39;name&#39; | &#39;id&#39; | &#39;email&#39;

export async function fetchUsers({
  filterBy,
  sortBy,
}: { filterBy?: string; sortBy?: UsersSortBy } = {}) {
  return loaderDelayFn(() =&gt;
    ensureUsers().then(() =&gt; {
      let usersDraft = users

      if (filterBy) {
        usersDraft = usersDraft.filter((d) =&gt;
          d.name.toLowerCase().includes(filterBy.toLowerCase()),
        )
      }

      if (sortBy) {
        usersDraft = [...usersDraft].sort((a, b) =&gt; {
          return a[sortBy] &gt; b[sortBy] ? 1 : -1
        })
      }

      return usersDraft
    }),
  )
}

export async function fetchUserById(id: number) {
  return loaderDelayFn(() =&gt;
    ensureUsers().then(() =&gt; users.find((d) =&gt; d.id === id)),
  )
}

export async function fetchRandomNumber() {
  return loaderDelayFn(() =&gt; {
    return Math.random()
  })
}
">
<input type="hidden" name="project[files][src/styles.css]" value="@import &#39;tailwindcss&#39;;

@layer base {
  *,
  ::after,
  ::before,
  ::backdrop,
  ::file-selector-button {
    border-color: var(--color-gray-200, currentcolor);
  }
}

html {
  color-scheme: light dark;
}
* {
  @apply border-gray-200 dark:border-gray-800;
}
body {
  @apply bg-gray-50 text-gray-950 dark:bg-gray-900 dark:text-gray-200;
}
">
<input type="hidden" name="project[files][src/useMutation.tsx]" value="import * as React from &#39;react&#39;

export function useMutation&lt;TVariables, TData, TError = Error&gt;(opts: {
  fn: (variables: TVariables) =&gt; Promise&lt;TData&gt;
  onSuccess?: (ctx: { data: TData }) =&gt; void | Promise&lt;void&gt;
}) {
  const [submittedAt, setSubmittedAt] = React.useState&lt;number | undefined&gt;()
  const [variables, setVariables] = React.useState&lt;TVariables | undefined&gt;()
  const [error, setError] = React.useState&lt;TError | undefined&gt;()
  const [data, setData] = React.useState&lt;TData | undefined&gt;()
  const [status, setStatus] = React.useState&lt;
    &#39;idle&#39; | &#39;pending&#39; | &#39;success&#39; | &#39;error&#39;
  &gt;(&#39;idle&#39;)

  const mutate = React.useCallback(
    async (variables: TVariables): Promise&lt;TData | undefined&gt; =&gt; {
      setStatus(&#39;pending&#39;)
      setSubmittedAt(Date.now())
      setVariables(variables)
      //
      try {
        const data = await opts.fn(variables)
        await opts.onSuccess?.({ data })
        setStatus(&#39;success&#39;)
        setError(undefined)
        setData(data)
        return data
      } catch (err: any) {
        setStatus(&#39;error&#39;)
        setError(err)
      }
    },
    [opts.fn],
  )

  return {
    status,
    variables,
    submittedAt,
    mutate,
    error,
    data,
  }
}
">
<input type="hidden" name="project[files][src/utils.tsx]" value="export async function loaderDelayFn&lt;T&gt;(
  fn: (...args: Array&lt;any&gt;) =&gt; Promise&lt;T&gt; | T,
) {
  const delay = Number(sessionStorage.getItem(&#39;loaderDelay&#39;) ?? 0)
  const delayPromise = new Promise((r) =&gt; setTimeout(r, delay))

  await delayPromise
  const res = await fn()

  return res
}

export async function actionDelayFn&lt;T&gt;(
  fn: (...args: Array&lt;any&gt;) =&gt; Promise&lt;T&gt; | T,
) {
  const delay = Number(sessionStorage.getItem(&#39;actionDelay&#39;) ?? 0)
  await new Promise((r) =&gt; setTimeout(r, delay))
  return fn()
}

export function shuffle&lt;T&gt;(arr: Array&lt;T&gt;): Array&lt;T&gt; {
  let i = arr.length
  if (i == 0) return arr
  const copy = [...arr]
  while (--i) {
    const j = Math.floor(Math.random() * (i + 1))
    const a = copy[i]
    const b = copy[j]
    copy[i] = b!
    copy[j] = a!
  }
  return copy
}
">
<input type="hidden" name="project[description]" value="generated by https://pkg.pr.new">
<input type="hidden" name="project[template]" value="node">
<input type="hidden" name="project[title]" value="tanstack-router-react-example-kitchen-sink">
</form>
<script>document.getElementById("mainForm").submit();</script>

</body></html>