@rsc-kit/core 0.19.0 → 0.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/apiPrerender.js +1 -1
- package/dist/apiPrerender.js.map +1 -1
- package/dist/js/Form.d.ts +2 -2
- package/dist/js/Form.js.map +1 -1
- package/dist/js/Link.d.ts +5 -5
- package/dist/js/Link.js.map +1 -1
- package/dist/js/RedirectBoundary.d.ts +11 -1
- package/dist/js/RedirectBoundary.js +10 -1
- package/dist/js/RedirectBoundary.js.map +1 -1
- package/dist/js/RouteErrorBoundary.d.ts +6 -2
- package/dist/js/RouteErrorBoundary.js +10 -0
- package/dist/js/RouteErrorBoundary.js.map +1 -1
- package/dist/js/SegmentBoundary.js +11 -4
- package/dist/js/SegmentBoundary.js.map +1 -1
- package/dist/js/SlotBoundary.d.ts +7 -1
- package/dist/js/SlotBoundary.js +9 -1
- package/dist/js/SlotBoundary.js.map +1 -1
- package/dist/js/createViteRscApp.js +20 -0
- package/dist/js/createViteRscApp.js.map +1 -1
- package/dist/js/navigate.d.ts +3 -3
- package/dist/js/navigate.js +1 -1
- package/dist/js/navigate.js.map +1 -1
- package/dist/js/nuqs.js.map +1 -1
- package/dist/js/router.d.ts +3 -3
- package/dist/js/router.js.map +1 -1
- package/dist/manifest.d.ts +6 -0
- package/dist/manifest.js.map +1 -1
- package/dist/redirect.d.ts +3 -3
- package/dist/redirect.js.map +1 -1
- package/dist/routes.d.ts +6 -9
- package/dist/routes.js.map +1 -1
- package/dist/useSsr.d.ts +11 -0
- package/dist/useSsr.js +15 -0
- package/dist/useSsr.js.map +1 -1
- package/dist/vite.js +49 -8
- package/dist/vite.js.map +1 -1
- package/package.json +1 -1
package/dist/apiPrerender.js
CHANGED
|
@@ -235,7 +235,7 @@ export async function prerenderApiRoutes(engine, manifest, write) {
|
|
|
235
235
|
const reached = answered.response.reached;
|
|
236
236
|
if (reached.length > 0) {
|
|
237
237
|
results[results.length - 1].warning =
|
|
238
|
-
`froze ${reached.join(' and ')} — a stored answer keeps whatever that returned at build time. ` +
|
|
238
|
+
`froze ${reached.join(' and ')}${route.source ? ' in ' + route.source : ''} — a stored answer keeps whatever that returned at build time. ` +
|
|
239
239
|
'If it should differ per call, read the request (await connection()) so the route runs on demand.';
|
|
240
240
|
}
|
|
241
241
|
}
|
package/dist/apiPrerender.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apiPrerender.js","sourceRoot":"","sources":["../src/apiPrerender.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAClD,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,8EAA8E;AAC9E,8EAA8E;AAC9E,+EAA+E;AAC/E,qCAAqC;AACrC,EAAE;AACF,8EAA8E;AAC9E,+EAA+E;AAC/E,QAAQ;AAER,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAA;AACxC,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AACtF,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AAEzE,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAEvC;;;;;;;GAOG;AACH,MAAM,SAAS,GAAG,KAAK,CAAA;AAiBvB,4CAA4C;AAC5C,MAAM,UAAU,MAAM,CAAC,GAAW;IAChC,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAA;AACnC,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACzB,KAAK;IACL,SAAS;IACT,MAAM;IACN,UAAU;IACV,MAAM;IACN,MAAM;IACN,UAAU;IACV,aAAa;IACb,MAAM;IACN,OAAO;IACP,QAAQ;IACR,UAAU;IACV,aAAa;CACd,CAAC,CAAA;AAEF;;;;;;GAMG;AACH,SAAS,YAAY,CAAC,GAAW,EAAE,OAAoB;IAC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BACvE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;gBACnD,IAAI;gBACJ,MAAM;aACqB,CAAC,CAC/B,CAAA;YAED,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,qDAAqD,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;YAErF,0EAA0E;YAC1E,0EAA0E;YAC1E,iBAAiB;YACjB,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAA;YAEzC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACvB,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC,OAAO;oBAClC,SAAS,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,iEAAiE;wBAC/F,kGAAkG,CAAA;YACtG,CAAC;QACH,CAAC;IACD,CAAC;YAAS,CAAC;QACT,OAAO,EAAE,CAAA;IACX,CAAC;IAED,OAAO,OAAO,CAAA;AAChB,CAAC","sourcesContent":["// Freezing an api route the way a page is frozen.\n//\n// Not as an opt-in flag, deliberately. A page is stored by default and opts\n// OUT by touching the request — connection(), cookies(), headers() all suspend\n// at build time because there is no request there, and that is what marks the\n// page dynamic. A route works the same way and for the same reason: one model\n// to learn rather than two, and the honest default in both cases is \"the build\n// tried, and here is what it found\".\n//\n// GET only. Everything else is a method a caller may not repeat, and a stored\n// answer to a POST is a stored answer to something that was supposed to happen\n// once.\n\nimport { pathKey } from './prerender.js'\nimport { UNPROBED, requestReadBy, withRequest, withResponseDraft } from './request.js'\nimport { watchNondeterminism, whileRendering } from './nondeterminism.js'\nimport type { ManifestApiRoute, RouteManifest } from './manifest.js'\nimport { allowFor } from './routing.js'\n\n/**\n * How long a route gets to answer before it is called dynamic.\n *\n * A route that reads the request does not fail here — it never settles, because\n * the accessors suspend forever with no request to read. So the budget is what\n * turns \"waiting\" into an answer, and it only has to be long enough for a route\n * that was going to finish.\n */\nconst BUDGET_MS = 2_000\n\n/** What a stored answer holds. Enough to rebuild the Response exactly. */\nexport interface FrozenApiResponse {\n status: number\n headers: [string, string][]\n body: string\n /**\n * Whether the answer depends on the query string.\n *\n * False when the handler never awaited `searchParams` and declared no schema\n * for it, which means the same answer is right for `?utm_source=anything`.\n * True and the stored answer is only good for the bare url.\n */\n varies: boolean\n}\n\n/** The file a frozen route is stored as. */\nexport function apiKey(url: string): string {\n return `${pathKey(url)}.api.json`\n}\n\n/**\n * Reading anything here means the answer depends on the caller.\n *\n * `url` is on the list although the path is the key the answer is stored\n * under, because nobody reads it for the path: a handler written the Next way\n * reads `new URL(request.url).searchParams`, which the probe cannot see the\n * way it sees the awaited `searchParams` — and a stored answer marked as\n * varying with nothing would then be served to every query, a webhook's\n * verification handshake included. Reading the url also puts the build\n * machine's origin within reach of the answer. A route that wants the bare\n * url stored awaits `searchParams` instead; the table says so.\n */\nconst PER_CALLER = new Set([\n 'url',\n 'headers',\n 'body',\n 'bodyUsed',\n 'text',\n 'json',\n 'formData',\n 'arrayBuffer',\n 'blob',\n 'bytes',\n 'signal',\n 'referrer',\n 'credentials',\n])\n\n/**\n * A Request that records what was read out of it.\n *\n * A proxy rather than a subclass because the interesting properties are\n * getters on Request.prototype, and `this` has to stay the real Request or\n * every one of them throws about an illegal invocation.\n */\nfunction probeRequest(url: string, touched: Set<string>): Request {\n const real = new Request(url, { method: 'GET' })\n\n return new Proxy(real, {\n get(target, property) {\n // The engine's own way past the probe, for the url read that resolves\n // the awaited searchParams - booked to searchParams, not to url.\n if (property === UNPROBED) return target\n if (typeof property === 'string' && PER_CALLER.has(property)) touched.add(property)\n\n const value = Reflect.get(target, property, target)\n\n return typeof value === 'function' ? value.bind(target) : value\n },\n })\n}\n\n/** The url a route with no parameters answers. */\nfunction urlFor(route: ManifestApiRoute): string | null {\n // A parameterised route has as many urls as there are values, and nothing\n // here knows them. Pages solve this with generateStaticParams; until a route\n // can say the same, one is answered per request.\n if (route.segments.some((segment) => segment.type !== 'static')) return null\n\n return '/' + route.segments.map((segment) => segment.value).join('/')\n}\n\n/**\n * What the build calls a route in its output.\n *\n * The pattern for a parameterised one, spelled the way pages already spell\n * theirs, rather than the module name — a line reading\n * \"/app/api/greet/[name]/route\" names a file on disk and the rest of the table\n * names urls.\n */\nfunction labelFor(route: ManifestApiRoute): string {\n return (\n '/' +\n route.segments\n .map((segment) => (segment.type === 'static' ? segment.value : `_${segment.value}_`))\n .join('/')\n )\n}\n\n/** Whether a body is text this can store and hand back unchanged. */\nfunction asText(bytes: Uint8Array): string | null {\n try {\n const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\n return text\n } catch {\n // Binary. Storable in principle, as base64, at the cost of a third of its\n // size on disk and a decode per request — for a route that is far more\n // likely to be streaming a file it should be serving as a file.\n return null\n }\n}\n\nexport interface ApiPrerenderResult {\n url: string\n name: string\n type: 'frozen' | 'dynamic'\n reason: string | null\n /** Stored, and worth a second look - it froze a value that will not be the same tomorrow. */\n warning?: string\n}\n\n/**\n * Try to answer every api route once, at build time, and store what can be.\n *\n * Sequential rather than parallel: there are usually few of them, each is a\n * function call rather than a React render, and the ones that are going to be\n * dynamic spend the whole budget waiting — which is time, not work.\n */\nexport async function prerenderApiRoutes(\n engine: { handleApiRoute?: (n: string, r: Request, p: Record<string, string>, a: string) => Promise<Response> },\n manifest: RouteManifest,\n write: (name: string, contents: string) => Promise<void>,\n): Promise<ApiPrerenderResult[]> {\n if (!engine.handleApiRoute || !manifest.apis?.length) return []\n\n const results: ApiPrerenderResult[] = []\n\n // Date.now() and friends are watched for the length of the loop, the way\n // the page prerender watches them; whileRendering records what each route\n // reached for while it answered.\n const unwatch = watchNondeterminism()\n\n try {\n for (const route of manifest.apis) {\n const said = (type: 'frozen' | 'dynamic', reason: string | null) => {\n results.push({ url: labelFor(route), name: route.name, type, reason })\n }\n\n if (!route.methods.includes('GET')) {\n said('dynamic', 'no GET to store')\n continue\n }\n\n // A guarded route answers differently depending on who is asking, which is\n // the whole purpose of the guard. Storing one answer and serving it to\n // everyone is how a guard is silently removed.\n if (route.middleware.length > 0) {\n said('dynamic', 'guarded by middleware')\n continue\n }\n\n const url = urlFor(route)\n\n if (!url) {\n said('dynamic', 'one url per param value, and none are listed')\n continue\n }\n\n const touched = new Set<string>()\n const request = probeRequest('https://prerender.invalid' + url, touched)\n\n // No request in scope, so headers(), cookies() and connection() suspend\n // forever rather than resolving to whatever the build machine had. The\n // budget below is what turns that into an answer.\n // Inside a response draft, because that is where the engine puts a cookie\n // a route sets - a literal Set-Cookie on its Response is moved there too\n // whenever a draft is open - and a probe with no draft reads a Response\n // the cookie may already have left. Whether it went to the draft or stayed\n // on the Response depends on what else is running in the process; the\n // question here is only whether there was one.\n const answered = await withResponseDraft(({ taken }) =>\n withRequest(null as never, async () => {\n let readBy: string[] = []\n\n const response = await Promise.race([\n whileRendering(() => engine.handleApiRoute!(route.name, request, {}, allowFor(route)))\n .then(([value, reached]) => ({ value, reached }))\n .catch((error) => ({ error })),\n new Promise<null>((resolve) =>\n setTimeout(() => {\n readBy = requestReadBy()\n resolve(null)\n }, BUDGET_MS),\n ),\n ])\n\n return { response, readBy: readBy.length ? readBy : requestReadBy(), drafted: taken() }\n }),\n )\n\n if (answered.response === null) {\n const why = answered.readBy.length\n ? 'dynamic — called ' + answered.readBy.join(', ')\n : 'did not answer within the build budget'\n\n said('dynamic', why)\n continue\n }\n\n if ('error' in answered.response) {\n // Not a build failure. A route that throws with no request may be doing\n // exactly the right thing — refusing a caller it cannot identify — and\n // refusing the build over it would make that route unbuildable.\n said('dynamic', 'threw without a request')\n continue\n }\n\n if (touched.size > 0) {\n const hint = touched.has('url') ? ' (await searchParams to read the query and keep the bare url stored)' : ''\n\n said('dynamic', 'reads the request — ' + [...touched].sort().join(', ') + hint)\n continue\n }\n\n // Awaiting the query string is not a reason to give up on the route — the\n // bare url still has one right answer. It only narrows which requests the\n // stored answer is good for.\n const varies = answered.readBy.includes('searchParams')\n\n const response = answered.response.value\n\n // A refusal is an answer to the request the build sent - none - not to\n // the ones visitors will. A route that answers 403 with nothing read is\n // usually checking something the probe cannot see, and a stored 403 was\n // once every webhook handshake's answer. Left to run, and said so.\n if (response.status >= 400) {\n said('dynamic', `answered ${response.status} to the build — a refusal is not an answer to store`)\n continue\n }\n\n // A cookie is an answer for one visitor, whatever the route read to\n // decide on it. Stored, the build's cookie would be handed to everyone.\n if (response.headers.has('set-cookie') || answered.drafted.has('set-cookie')) {\n said('dynamic', 'sets a cookie — an answer for one visitor, not one to store')\n continue\n }\n\n const body = asText(new Uint8Array(await response.arrayBuffer()))\n\n if (body === null) {\n said('dynamic', 'answers with bytes rather than text')\n continue\n }\n\n await write(\n apiKey(url),\n JSON.stringify({\n status: response.status,\n // Lower-cased and sorted, so two builds of the same route produce the\n // same bytes. Headers iteration does not promise a case or an order,\n // and a file that differs between builds for no reason defeats\n // content-addressed caching and makes a diff unreadable. Names are\n // case-insensitive, so nothing is lost by picking one.\n headers: [...response.headers]\n .map(([name, value]) => [name.toLowerCase(), value] as [string, string])\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n body,\n varies,\n } satisfies FrozenApiResponse),\n )\n\n said('frozen', varies ? 'stored for the bare url — it reads the query string' : null)\n\n // The same warning a page gets: a stored answer keeps whatever Date.now()\n // or Math.random() returned at build time, and a json body has no browser\n // to move it to.\n const reached = answered.response.reached\n\n if (reached.length > 0) {\n results[results.length - 1]!.warning =\n `froze ${reached.join(' and ')} — a stored answer keeps whatever that returned at build time. ` +\n 'If it should differ per call, read the request (await connection()) so the route runs on demand.'\n }\n }\n } finally {\n unwatch()\n }\n\n return results\n}\n"]}
|
|
1
|
+
{"version":3,"file":"apiPrerender.js","sourceRoot":"","sources":["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E,MAAM,CAAC,CAAC,CAAC,qDAAqD,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;YAErF,0EAA0E;YAC1E,0EAA0E;YAC1E,iBAAiB;YACjB,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAA;YAEzC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACvB,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC,OAAO;oBAClC,SAAS,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,iEAAiE;wBAC3I,kGAAkG,CAAA;YACtG,CAAC;QACH,CAAC;IACD,CAAC;YAAS,CAAC;QACT,OAAO,EAAE,CAAA;IACX,CAAC;IAED,OAAO,OAAO,CAAA;AAChB,CAAC","sourcesContent":["// Freezing an api route the way a page is frozen.\n//\n// Not as an opt-in flag, deliberately. A page is stored by default and opts\n// OUT by touching the request — connection(), cookies(), headers() all suspend\n// at build time because there is no request there, and that is what marks the\n// page dynamic. A route works the same way and for the same reason: one model\n// to learn rather than two, and the honest default in both cases is \"the build\n// tried, and here is what it found\".\n//\n// GET only. Everything else is a method a caller may not repeat, and a stored\n// answer to a POST is a stored answer to something that was supposed to happen\n// once.\n\nimport { pathKey } from './prerender.js'\nimport { UNPROBED, requestReadBy, withRequest, withResponseDraft } from './request.js'\nimport { watchNondeterminism, whileRendering } from './nondeterminism.js'\nimport type { ManifestApiRoute, RouteManifest } from './manifest.js'\nimport { allowFor } from './routing.js'\n\n/**\n * How long a route gets to answer before it is called dynamic.\n *\n * A route that reads the request does not fail here — it never settles, because\n * the accessors suspend forever with no request to read. So the budget is what\n * turns \"waiting\" into an answer, and it only has to be long enough for a route\n * that was going to finish.\n */\nconst BUDGET_MS = 2_000\n\n/** What a stored answer holds. Enough to rebuild the Response exactly. */\nexport interface FrozenApiResponse {\n status: number\n headers: [string, string][]\n body: string\n /**\n * Whether the answer depends on the query string.\n *\n * False when the handler never awaited `searchParams` and declared no schema\n * for it, which means the same answer is right for `?utm_source=anything`.\n * True and the stored answer is only good for the bare url.\n */\n varies: boolean\n}\n\n/** The file a frozen route is stored as. */\nexport function apiKey(url: string): string {\n return `${pathKey(url)}.api.json`\n}\n\n/**\n * Reading anything here means the answer depends on the caller.\n *\n * `url` is on the list although the path is the key the answer is stored\n * under, because nobody reads it for the path: a handler written the Next way\n * reads `new URL(request.url).searchParams`, which the probe cannot see the\n * way it sees the awaited `searchParams` — and a stored answer marked as\n * varying with nothing would then be served to every query, a webhook's\n * verification handshake included. Reading the url also puts the build\n * machine's origin within reach of the answer. A route that wants the bare\n * url stored awaits `searchParams` instead; the table says so.\n */\nconst PER_CALLER = new Set([\n 'url',\n 'headers',\n 'body',\n 'bodyUsed',\n 'text',\n 'json',\n 'formData',\n 'arrayBuffer',\n 'blob',\n 'bytes',\n 'signal',\n 'referrer',\n 'credentials',\n])\n\n/**\n * A Request that records what was read out of it.\n *\n * A proxy rather than a subclass because the interesting properties are\n * getters on Request.prototype, and `this` has to stay the real Request or\n * every one of them throws about an illegal invocation.\n */\nfunction probeRequest(url: string, touched: Set<string>): Request {\n const real = new Request(url, { method: 'GET' })\n\n return new Proxy(real, {\n get(target, property) {\n // The engine's own way past the probe, for the url read that resolves\n // the awaited searchParams - booked to searchParams, not to url.\n if (property === UNPROBED) return target\n if (typeof property === 'string' && PER_CALLER.has(property)) touched.add(property)\n\n const value = Reflect.get(target, property, target)\n\n return typeof value === 'function' ? value.bind(target) : value\n },\n })\n}\n\n/** The url a route with no parameters answers. */\nfunction urlFor(route: ManifestApiRoute): string | null {\n // A parameterised route has as many urls as there are values, and nothing\n // here knows them. Pages solve this with generateStaticParams; until a route\n // can say the same, one is answered per request.\n if (route.segments.some((segment) => segment.type !== 'static')) return null\n\n return '/' + route.segments.map((segment) => segment.value).join('/')\n}\n\n/**\n * What the build calls a route in its output.\n *\n * The pattern for a parameterised one, spelled the way pages already spell\n * theirs, rather than the module name — a line reading\n * \"/app/api/greet/[name]/route\" names a file on disk and the rest of the table\n * names urls.\n */\nfunction labelFor(route: ManifestApiRoute): string {\n return (\n '/' +\n route.segments\n .map((segment) => (segment.type === 'static' ? segment.value : `_${segment.value}_`))\n .join('/')\n )\n}\n\n/** Whether a body is text this can store and hand back unchanged. */\nfunction asText(bytes: Uint8Array): string | null {\n try {\n const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\n return text\n } catch {\n // Binary. Storable in principle, as base64, at the cost of a third of its\n // size on disk and a decode per request — for a route that is far more\n // likely to be streaming a file it should be serving as a file.\n return null\n }\n}\n\nexport interface ApiPrerenderResult {\n url: string\n name: string\n type: 'frozen' | 'dynamic'\n reason: string | null\n /** Stored, and worth a second look - it froze a value that will not be the same tomorrow. */\n warning?: string\n}\n\n/**\n * Try to answer every api route once, at build time, and store what can be.\n *\n * Sequential rather than parallel: there are usually few of them, each is a\n * function call rather than a React render, and the ones that are going to be\n * dynamic spend the whole budget waiting — which is time, not work.\n */\nexport async function prerenderApiRoutes(\n engine: { handleApiRoute?: (n: string, r: Request, p: Record<string, string>, a: string) => Promise<Response> },\n manifest: RouteManifest,\n write: (name: string, contents: string) => Promise<void>,\n): Promise<ApiPrerenderResult[]> {\n if (!engine.handleApiRoute || !manifest.apis?.length) return []\n\n const results: ApiPrerenderResult[] = []\n\n // Date.now() and friends are watched for the length of the loop, the way\n // the page prerender watches them; whileRendering records what each route\n // reached for while it answered.\n const unwatch = watchNondeterminism()\n\n try {\n for (const route of manifest.apis) {\n const said = (type: 'frozen' | 'dynamic', reason: string | null) => {\n results.push({ url: labelFor(route), name: route.name, type, reason })\n }\n\n if (!route.methods.includes('GET')) {\n said('dynamic', 'no GET to store')\n continue\n }\n\n // A guarded route answers differently depending on who is asking, which is\n // the whole purpose of the guard. Storing one answer and serving it to\n // everyone is how a guard is silently removed.\n if (route.middleware.length > 0) {\n said('dynamic', 'guarded by middleware')\n continue\n }\n\n const url = urlFor(route)\n\n if (!url) {\n said('dynamic', 'one url per param value, and none are listed')\n continue\n }\n\n const touched = new Set<string>()\n const request = probeRequest('https://prerender.invalid' + url, touched)\n\n // No request in scope, so headers(), cookies() and connection() suspend\n // forever rather than resolving to whatever the build machine had. The\n // budget below is what turns that into an answer.\n // Inside a response draft, because that is where the engine puts a cookie\n // a route sets - a literal Set-Cookie on its Response is moved there too\n // whenever a draft is open - and a probe with no draft reads a Response\n // the cookie may already have left. Whether it went to the draft or stayed\n // on the Response depends on what else is running in the process; the\n // question here is only whether there was one.\n const answered = await withResponseDraft(({ taken }) =>\n withRequest(null as never, async () => {\n let readBy: string[] = []\n\n const response = await Promise.race([\n whileRendering(() => engine.handleApiRoute!(route.name, request, {}, allowFor(route)))\n .then(([value, reached]) => ({ value, reached }))\n .catch((error) => ({ error })),\n new Promise<null>((resolve) =>\n setTimeout(() => {\n readBy = requestReadBy()\n resolve(null)\n }, BUDGET_MS),\n ),\n ])\n\n return { response, readBy: readBy.length ? readBy : requestReadBy(), drafted: taken() }\n }),\n )\n\n if (answered.response === null) {\n const why = answered.readBy.length\n ? 'dynamic — called ' + answered.readBy.join(', ')\n : 'did not answer within the build budget'\n\n said('dynamic', why)\n continue\n }\n\n if ('error' in answered.response) {\n // Not a build failure. A route that throws with no request may be doing\n // exactly the right thing — refusing a caller it cannot identify — and\n // refusing the build over it would make that route unbuildable.\n said('dynamic', 'threw without a request')\n continue\n }\n\n if (touched.size > 0) {\n const hint = touched.has('url') ? ' (await searchParams to read the query and keep the bare url stored)' : ''\n\n said('dynamic', 'reads the request — ' + [...touched].sort().join(', ') + hint)\n continue\n }\n\n // Awaiting the query string is not a reason to give up on the route — the\n // bare url still has one right answer. It only narrows which requests the\n // stored answer is good for.\n const varies = answered.readBy.includes('searchParams')\n\n const response = answered.response.value\n\n // A refusal is an answer to the request the build sent - none - not to\n // the ones visitors will. A route that answers 403 with nothing read is\n // usually checking something the probe cannot see, and a stored 403 was\n // once every webhook handshake's answer. Left to run, and said so.\n if (response.status >= 400) {\n said('dynamic', `answered ${response.status} to the build — a refusal is not an answer to store`)\n continue\n }\n\n // A cookie is an answer for one visitor, whatever the route read to\n // decide on it. Stored, the build's cookie would be handed to everyone.\n if (response.headers.has('set-cookie') || answered.drafted.has('set-cookie')) {\n said('dynamic', 'sets a cookie — an answer for one visitor, not one to store')\n continue\n }\n\n const body = asText(new Uint8Array(await response.arrayBuffer()))\n\n if (body === null) {\n said('dynamic', 'answers with bytes rather than text')\n continue\n }\n\n await write(\n apiKey(url),\n JSON.stringify({\n status: response.status,\n // Lower-cased and sorted, so two builds of the same route produce the\n // same bytes. Headers iteration does not promise a case or an order,\n // and a file that differs between builds for no reason defeats\n // content-addressed caching and makes a diff unreadable. Names are\n // case-insensitive, so nothing is lost by picking one.\n headers: [...response.headers]\n .map(([name, value]) => [name.toLowerCase(), value] as [string, string])\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n body,\n varies,\n } satisfies FrozenApiResponse),\n )\n\n said('frozen', varies ? 'stored for the bare url — it reads the query string' : null)\n\n // The same warning a page gets: a stored answer keeps whatever Date.now()\n // or Math.random() returned at build time, and a json body has no browser\n // to move it to.\n const reached = answered.response.reached\n\n if (reached.length > 0) {\n results[results.length - 1]!.warning =\n `froze ${reached.join(' and ')}${route.source ? ' in ' + route.source : ''} — a stored answer keeps whatever that returned at build time. ` +\n 'If it should differ per call, read the request (await connection()) so the route runs on demand.'\n }\n }\n } finally {\n unwatch()\n }\n\n return results\n}\n"]}
|
package/dist/js/Form.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Route } from "../routes.js";
|
|
2
2
|
import { type FormHTMLAttributes, type ReactNode, type Ref } from "react";
|
|
3
3
|
import type { FormStore } from "./formStore";
|
|
4
4
|
import type { StandardSchemaV1 } from "./standardSchema";
|
|
@@ -110,7 +110,7 @@ interface FormRenderProps<T extends Record<string, unknown> = Record<string, unk
|
|
|
110
110
|
fieldState: (name: string) => FieldState;
|
|
111
111
|
}
|
|
112
112
|
interface FormProps<T extends Record<string, unknown> = Record<string, unknown>> extends Omit<FormHTMLAttributes<HTMLFormElement>, "action" | "method" | "children" | "onSubmit" | "onError"> {
|
|
113
|
-
action:
|
|
113
|
+
action: Route | ((formData: FormData) => Promise<unknown>);
|
|
114
114
|
method?: "get" | "post";
|
|
115
115
|
/**
|
|
116
116
|
* The <form> element, for a caller that needs it - to focus, to scroll to,
|
package/dist/js/Form.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Form.js","sourceRoot":"","sources":["../../src/js/Form.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAGb,OAAO,EAKL,aAAa,EACb,WAAW,EACX,UAAU,EACV,SAAS,EACT,OAAO,EACP,MAAM,EACN,cAAc,EACd,QAAQ,EACR,oBAAoB,EACpB,aAAa,GACd,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,qBAAqB,EAAE,eAAe,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACrG,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE9C,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAGhD;;;;GAIG;AACH,MAAM,oBAAoB,GAAG,GAAG,CAAC;AA+KjC;;;;;;GAMG;AACH,SAAS,QAAQ,CACf,KAAc;IAEd,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAE7D,MAAM,MAAM,GAAG,KAId,CAAC;IAEF,IAAI,MAAM,CAAC,gBAAgB;QAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,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\"../routes.js\";\nimport {\n type FormHTMLAttributes,\n type FormEvent,\n type ReactNode,\n type Ref,\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useActionState,\n useState,\n useSyncExternalStore,\n useTransition,\n} from \"react\";\nimport { submitForm } from \"../formSubmit\";\nimport { ServerValidationError, ServerDumpError, ServerRedirectError, redirectedTo } from \"./errors\";\nimport { buildFormData, decodeFormData } from \"./formEncoding\";\nimport { createFormStore } from \"./formStore\";\nimport type { FormStore } from \"./formStore\";\nimport { validateWith } from \"./standardSchema\";\nimport type { StandardSchemaV1 } from \"./standardSchema\";\n\n/**\n * How long a blur that leaves the form waits before checking the field. A\n * dialog's exit animation is shorter than this; a form still on screen after\n * it is one somebody is looking at.\n */\nconst LEAVE_FORM_SETTLE_MS = 300;\n\ntype PrefetchStrategy = \"hover\" | \"mount\" | \"none\";\n\n/**\n * What `field(name)` hands a control, spread straight onto it.\n *\n * The same four things react-hook-form's `<Controller>` gives, because it is\n * the same job: a component with no native control behind it needs a value and\n * a way to report a new one.\n */\ninterface FieldBinding<V> {\n name: string;\n value: V;\n /**\n * Either shape: a DOM event, or the value itself.\n *\n * A native input passes the event; a Radix select or a rich editor passes\n * what was chosen. A binder understanding only one of them would work on\n * half the controls anyone actually uses.\n */\n onChange: (next: V | { target: { value: V } }) => void;\n onBlur: () => void;\n}\n\n/**\n * What is known about one field, separately from what is spread onto it.\n *\n * Two objects rather than one, which is react-hook-form's split and it is right\n * for a mechanical reason: `touched` and `invalid` are not DOM attributes, so a\n * single spreadable object would put them on the element and React would warn\n * about every one.\n */\ninterface FieldState {\n /** Whether it has been left at least once. */\n touched: boolean;\n /** Whether it currently has errors. */\n invalid: boolean;\n /** Its messages, ready for a `<FieldError>`. */\n errors: string[];\n}\n\ninterface FormRenderProps<\n T extends Record<string, unknown> = Record<string, unknown>,\n> {\n pending: boolean;\n data: T;\n /**\n * Keyed by field name, so a typo is a type error rather than undefined.\n *\n * Partial because most fields have none, and nested paths join with dots —\n * `errors['address.city']`, which is the key a Standard Schema issue for that\n * field produces.\n */\n errors: Partial<Record<keyof T & string, string[]>> &\n Record<string, string[] | undefined>;\n error: (field: keyof T & string) => string | undefined;\n clearErrors: (...fields: (keyof T & string)[]) => void;\n reset: () => void;\n /**\n * Whether anything differs from what the form started with.\n *\n * For the Save button that stays quiet until there is something to save,\n * and the Discard that appears beside it. Read from the form itself - a\n * snapshot of its FormData on mount, compared on every input - so an\n * uncontrolled field counts, which nothing outside the form can do. A\n * successful submit makes the current values the new baseline; `reset()`\n * goes back to the first one.\n */\n dirty: boolean;\n /** Whether the last submit was accepted. */\n succeeded: boolean;\n /**\n * The same thing, for two seconds.\n *\n * The \"Saved ✓\" that appears and fades. Worth having as state rather than a\n * timer in every form that wants one, because the timer has to be cleared\n * when the component goes away and that is the part people forget.\n */\n recentlySucceeded: boolean;\n /**\n * Bind one field so this component holds its value.\n *\n * Most fields need nothing: they are uncontrolled, the DOM holds the value,\n * and it is read back as FormData on submit. Reach for this when the DOM\n * cannot hold it for you — a control with no native element behind it, or a\n * value you want to read as it is typed:\n *\n * <Input {...field('title')} />\n * <span>{field('body').value.length}/100</span>\n *\n * A bound field is still an ordinary named input, so it arrives in FormData\n * with everything else. Nothing merges; there is one source of truth.\n */\n field: <K extends keyof T & string>(name: K) => FieldBinding<T[K]>;\n /**\n * What is known about a field, for deciding how to show it.\n *\n * const title = fieldState('title')\n *\n * <Field data-invalid={title.invalid}>\n * <Input {...field('title')} aria-invalid={title.invalid} />\n * <FieldError errors={title.errors.map((message) => ({ message }))} />\n * </Field>\n *\n * `touched` is what separates \"not filled in yet\" from \"filled in wrongly\" —\n * an error on a field nobody has visited is a form shouting before anyone\n * has done anything.\n */\n fieldState: (name: string) => FieldState;\n}\n\ninterface FormProps<\n T extends Record<string, unknown> = Record<string, unknown>,\n> extends Omit<\n FormHTMLAttributes<HTMLFormElement>,\n \"action\" | \"method\" | \"children\" | \"onSubmit\" | \"onError\"\n> {\n action: Href | ((formData: FormData) => Promise<unknown>);\n method?: \"get\" | \"post\";\n /**\n * The <form> element, for a caller that needs it - to focus, to scroll to,\n * to hand a library. The form keeps its own handle beside it; a caller's\n * never replaces it.\n */\n ref?: Ref<HTMLFormElement>;\n /**\n * Starting values for fields bound with `field()`.\n *\n * Uncontrolled fields do not need this — they take React's own\n * `defaultValue`, and the DOM keeps whatever is typed into them.\n */\n defaultValues?: Partial<T>;\n /**\n * A store created above this form, from `useFormStore()`.\n *\n * For the one case the context cannot reach: something that is not a\n * descendant — a top bar showing unsaved changes, a sidebar preview — needs\n * the values to exist above both of them. Create the store where they share\n * an ancestor and hand it down.\n *\n * Without it the form makes its own, which is what almost every form wants.\n */\n store?: FormStore;\n prefetch?: PrefetchStrategy;\n cacheFor?: number;\n replace?: boolean;\n preserveScroll?: boolean;\n resetOnSuccess?: boolean;\n /**\n * Check the fields before submitting, with any Standard Schema — Zod,\n * Valibot, ArkType.\n *\n * A failure fills `errors` and the action is never called, so a mistake\n * costs no round trip. It is a courtesy and not a control: the same action\n * is reachable without this form, so the server still has to check.\n */\n schema?: StandardSchemaV1;\n /** Transform form data before submitting to the server action. */\n transform?: (data: T) => Record<string, unknown>;\n /** Called inside the transition with typed form data. Use it to call your useOptimistic setter. */\n optimistic?: (data: T) => void;\n onSuccess?: (result: unknown) => void;\n /**\n * Called when a submit does not succeed.\n *\n * Validation failures arrive as field errors, with no second argument.\n * Anything else arrives as an empty error map and the thrown value — there\n * are no field errors to report, but the form still has to say so.\n */\n onError?: (errors: Record<string, string[]>, error?: unknown) => void;\n onSubmit?: (formData: FormData) => void | false;\n children: ReactNode | ((form: FormRenderProps<T>) => ReactNode);\n}\n\n/**\n * What an action built with createActionClient answers with.\n *\n * Recognised rather than thrown, because React serialises a rejected server\n * action opaquely: production strips the message and the fields it named are\n * gone. A returned object crosses intact, so a form reads it.\n */\nfunction resultOf(\n value: unknown,\n): { errors?: Record<string, string[]>; serverError?: string; redirected?: string } | null {\n if (typeof value !== \"object\" || value === null) return null;\n\n const result = value as {\n validationErrors?: Record<string, string[]>;\n serverError?: string;\n redirected?: string;\n };\n\n if (result.validationErrors) return { errors: result.validationErrors };\n if (result.serverError) return { serverError: result.serverError };\n if (typeof result.redirected === \"string\") return { redirected: result.redirected };\n\n return null;\n}\n\nconst FormStatusContext = createContext<FormRenderProps>({\n pending: false,\n data: {},\n dirty: false,\n errors: {},\n error: () => undefined,\n clearErrors: () => {},\n reset: () => {},\n succeeded: false,\n recentlySucceeded: false,\n // Outside a Form there is nothing holding a value, so a binding that reported\n // one would be lying. Name only, which is the part that is still true.\n field: ((name: string) => ({\n name,\n value: \"\",\n onChange: () => {},\n onBlur: () => {},\n })) as FormRenderProps[\"field\"],\n fieldState: () => ({ touched: false, invalid: false, errors: [] }),\n});\n\n/**\n * The store, on its own context.\n *\n * Separate from the status context because that one holds a fresh object every\n * render, so anything reading it re-renders with the form. The store is stable\n * for the life of the form, which is what lets a subscriber below it re-render\n * alone.\n */\nconst FormStoreContext = createContext<{\n store: FormStore;\n touch: (name: string) => void;\n} | null>(null);\n\n/**\n * A value store created above the form rather than by it.\n *\n * const store = useFormStore({ title: '' })\n *\n * <TopBar store={store} /> // not inside the form\n * <Form action={save} store={store}>…</Form>\n *\n * For the one case the context cannot reach. `<Form>` makes its own otherwise,\n * and almost every form should let it — this exists so that a component which\n * is not a descendant can still read the values, which is the flexibility\n * react-hook-form and TanStack Form get from `useForm()` being yours to call.\n *\n * Deliberately not reactive itself: creating the store does not subscribe to\n * it, so the component holding it does not re-render on every keystroke and\n * take the whole subtree with it. Read it with `useFormValues(store)`.\n */\nexport function useFormStore<T extends Record<string, unknown>>(\n initial: Partial<T> = {},\n): FormStore {\n const ref = useRef<FormStore | null>(null);\n\n ref.current ??= createFormStore({ ...initial });\n\n return ref.current;\n}\n\n/**\n * One field, subscribed on its own.\n *\n * The same thing `field()` gives, from a component that re-renders when this\n * field changes and at no other time. Reach for it when a form is large enough\n * that re-rendering all of it per keystroke is real:\n *\n * function Title() {\n * const { field, invalid, errors } = useField('title')\n *\n * return <Input {...field} aria-invalid={invalid} />\n * }\n *\n * Which is react-hook-form's `<Controller>` without the render prop: the\n * component you already had to write is the subscription boundary.\n */\nexport function useField(\n name: string,\n store?: FormStore,\n): FieldBinding<string> & FieldState {\n const ctx = useContext(FormStoreContext);\n const status = useContext(FormStatusContext);\n\n if (!ctx && !store) {\n throw new Error(\n \"useField() was called outside a <Form>. It reads that form's values, so there has to be one above it.\",\n );\n }\n\n const source = store ?? ctx!.store;\n const touch = ctx?.touch;\n\n const value = useSyncExternalStore(\n source.subscribe,\n () => (source.get(name) ?? \"\") as string,\n () => \"\",\n );\n\n const errors = status.errors[name] ?? [];\n\n return {\n name,\n value,\n onChange: (next) => {\n source.set(\n name,\n typeof next === \"object\" && next !== null && \"target\" in next\n ? (next as { target: { value: string } }).target.value\n : next,\n );\n },\n onBlur: () => void touch?.(name),\n touched: status.fieldState(name).touched,\n invalid: errors.length > 0,\n errors,\n };\n}\n\n/**\n * Every bound value, from anywhere inside the form.\n *\n * For a summary, a preview, a count of what has changed — something that reads\n * the form without being a field in it. Only values bound through `field()` or\n * `useField` are here: an uncontrolled input's value belongs to the DOM, and\n * this has no way to know it changed.\n */\nexport function useFormValues<T extends Record<string, unknown>>(\n store?: FormStore,\n): Partial<T> {\n const ctx = useContext(FormStoreContext);\n\n if (!ctx && !store) {\n throw new Error(\n \"useFormValues() was called outside a <Form>. It reads that form's values, so there has to be one above it.\",\n );\n }\n\n const source = store ?? ctx!.store;\n\n return useSyncExternalStore(\n source.subscribe,\n () => source.all() as Partial<T>,\n () => ({}) as Partial<T>,\n );\n}\n\nexport function useFormStatus<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(): FormRenderProps<T> {\n return useContext(FormStatusContext) as FormRenderProps<T>;\n}\n\n/**\n * submitForm bound to an action, once per action.\n *\n * Bound on every render, it was a fresh function with a fresh promise for\n * its bound arguments each time - and React, seating a posted form's state\n * during the server render, suspends on that promise until it settles, then\n * renders the component again, which bound again. A render that never\n * finished, on every page a form was posted to without javascript. One\n * bound function per action, and the promise settles once.\n */\nconst boundSubmits = new WeakMap<Function, (previous: unknown, formData: FormData) => Promise<unknown>>();\n\nfunction boundSubmit(action: (formData: FormData) => Promise<unknown>) {\n let bound = boundSubmits.get(action);\n\n if (!bound) {\n bound = submitForm.bind(null, action);\n boundSubmits.set(action, bound);\n }\n\n return bound;\n}\n\n/**\n * A form's values as one comparable string.\n *\n * FormData in document order, a file by its name and size: enough to say\n * whether anything changed, which is all `dirty` asks.\n */\nfunction serializeForm(form: HTMLFormElement): string {\n const parts: string[] = [];\n\n for (const [name, value] of new FormData(form)) {\n parts.push(\n name + \"=\" + (typeof value === \"string\" ? value : \"file:\" + value.name + \":\" + value.size),\n );\n }\n\n return parts.join(\"\\n\");\n}\n\n/**\n * Also exported by name, and re-exported below, because both spellings are in\n * use: `import Form from` and `import { Form } from`.\n */\nexport default function Form<\n T extends Record<string, unknown> = Record<string, unknown>,\n>({\n action,\n method: methodProp,\n defaultValues,\n store: providedStore,\n prefetch = \"hover\",\n cacheFor,\n replace = false,\n preserveScroll = false,\n resetOnSuccess = true,\n schema,\n transform,\n optimistic,\n onSuccess,\n onError,\n onSubmit,\n children,\n ref: callerRef,\n ...rest\n}: FormProps<T>) {\n const isGetForm = typeof action === \"string\";\n const method = methodProp ?? (isGetForm ? \"get\" : \"post\");\n\n // The answer to this form posted without a runtime, seated by React into\n // the form that posted it - which is the only way a visitor with no\n // javascript sees a refusal. Registered through submitForm, bound to the\n // action, because React hands a form-state action a (previous, formData)\n // pair and the action takes the FormData alone. On the server a plain\n // function - a closure, not a server reference - cannot be bound into a\n // form; the form falls back to the action itself, and posts nothing\n // seatable, which is all a closure could ever have done.\n const bindable =\n typeof action === \"function\" && (typeof window !== \"undefined\" || \"$$FORM_ACTION\" in action);\n const [posted, formAction] = useActionState(\n bindable ? boundSubmit(action as (formData: FormData) => Promise<unknown>) : async () => null,\n null as unknown,\n );\n const postedRefusal = resultOf(posted);\n const [errors, setErrors] = useState<Record<string, string[]>>(() => postedRefusal?.errors ?? {});\n const [touched, setTouched] = useState<Record<string, boolean>>({});\n\n /**\n * Mark a field visited, and check it.\n *\n * Checking on blur rather than on every keystroke, because an error that\n * appears while someone is halfway through typing an email address is a form\n * arguing with them. Leaving the field is the moment they have finished\n * saying what they meant.\n *\n * The whole object is validated and only this field's issues are kept: a\n * Standard Schema has no notion of one field, and filtering by path is the\n * honest way to ask it about one. Everything else's errors are left as they\n * were, so blurring an empty field does not light up the rest of the form.\n */\n const touch = useCallback(\n async (name: string) => {\n setTouched((prev) => (prev[name] ? prev : { ...prev, [name]: true }));\n\n if (!schema || !formRef.current) return;\n\n const invalid = await validateWith(\n schema,\n decodeFormData(new FormData(formRef.current), schema),\n );\n\n setErrors((prev) => {\n const next = { ...prev };\n\n if (invalid?.[name]) next[name] = invalid[name];\n else delete next[name];\n\n return next;\n });\n },\n [schema],\n );\n\n const [succeeded, setSucceeded] = useState(false);\n const [recentlySucceeded, setRecentlySucceeded] = useState(false);\n const recentTimer = useRef<ReturnType<typeof setTimeout> | undefined>(\n undefined,\n );\n\n // Cleared on unmount: a timer that fires into a component that has gone is\n // the warning nobody reads and the leak nobody finds.\n useEffect(() => () => clearTimeout(recentTimer.current), []);\n\n // Only the fields someone bound. Everything else is the DOM's.\n //\n // A store rather than state, so a component using `useField` can re-render\n // for one field while this one does not. See formStore.ts.\n const storeRef = useRef<FormStore | null>(null);\n\n storeRef.current ??= createFormStore({\n ...(defaultValues as Record<string, unknown> | undefined),\n });\n\n const store = providedStore ?? storeRef.current;\n\n // Which names the render prop read through `field()`. A change to one of\n // those has to re-render this component, because that is where the value is\n // being displayed; a change to anything else does not, which is what lets a\n // `useField` child stand on its own.\n const readHere = useRef(new Set<string>());\n const [, bump] = useState(0);\n\n useEffect(\n () =>\n store.subscribe((name) => {\n if (name === \"\" || readHere.current.has(name)) bump((n) => n + 1);\n }),\n [store],\n );\n const [currentData, setCurrentData] = useState<T>({} as T);\n const [isPending, startTransition] = useTransition();\n const formRef = useRef<HTMLFormElement>(null);\n\n // What the form started with, as its FormData reads: the baseline `dirty`\n // is measured against. Taken on mount, retaken after a successful submit.\n const baseline = useRef<string | null>(null);\n const [dirty, setDirty] = useState(false);\n // Only a form that reads `dirty` pays for it: the flip from clean to dirty\n // is a render of the whole form, and a field that subscribes for itself\n // is promised that typing in it renders it alone.\n const dirtyRead = useRef(false);\n\n const snapshot = useCallback(() => {\n if (!formRef.current) return;\n\n baseline.current = serializeForm(formRef.current);\n setDirty(false);\n }, []);\n\n const measureDirty = useCallback(() => {\n if (!dirtyRead.current || !formRef.current || baseline.current === null) return;\n\n const now = serializeForm(formRef.current) !== baseline.current;\n\n setDirty((was) => (was === now ? was : now));\n }, []);\n\n useEffect(snapshot, [snapshot]);\n\n // A bound control with no native element behind it changes through the\n // store, not through an input event - a Radix select - so the store is\n // watched too. Its input, if it has one, is read back with the rest.\n useEffect(() => store.subscribe(() => queueMicrotask(measureDirty)), [store, measureDirty]);\n\n // Both handles, one element. React 19 hands a function component its ref\n // as a prop, and spread after the form's own it replaced it - every\n // FormData read then found null. A caller's ref is filled beside ours.\n const attachForm = useCallback(\n (element: HTMLFormElement | null) => {\n formRef.current = element;\n\n if (typeof callerRef === \"function\") callerRef(element);\n else if (callerRef) callerRef.current = element;\n },\n [callerRef],\n );\n\n const error = useCallback(\n (field: keyof T & string): string | undefined => errors[field]?.[0],\n [errors],\n );\n\n const clearErrors = useCallback((...fields: (keyof T & string)[]) => {\n if (fields.length === 0) {\n setErrors({});\n } else {\n setErrors((prev) => {\n const next = { ...prev };\n for (const f of fields) {\n delete next[f];\n }\n return next;\n });\n }\n }, []);\n\n const resetForm = useCallback(() => {\n formRef.current?.reset();\n setErrors({});\n setCurrentData({} as T);\n queueMicrotask(measureDirty);\n }, [measureDirty]);\n\n useEffect(() => {\n if (isGetForm && prefetch === \"mount\") {\n const fn = (window as any).__rsc_prefetch;\n fn?.(action, cacheFor);\n }\n }, [isGetForm, prefetch, action, cacheFor]);\n\n const doPrefetch = useCallback(() => {\n if (!isGetForm) return;\n const fn = (window as any).__rsc_prefetch;\n fn?.(action as string, cacheFor);\n }, [isGetForm, action, cacheFor]);\n\n const handleSubmit = useCallback(\n async (e: FormEvent<HTMLFormElement>) => {\n e.preventDefault();\n const formData = new FormData(e.currentTarget);\n const data = decodeFormData<T>(formData, schema);\n setCurrentData(data);\n\n if (onSubmit?.(formData) === false) {\n return;\n }\n\n if (isGetForm && method === \"get\") {\n const url = new URL(action as string, window.location.origin);\n for (const [key, value] of formData.entries()) {\n if (typeof value === \"string\" && value !== \"\") {\n url.searchParams.set(key, value);\n }\n }\n\n const path = url.pathname + url.search;\n const shell = action as string;\n const nav = (window as any).__rsc_navigate;\n const prefetched = (window as any).__rsc_is_prefetched;\n\n // The route without its query is that route's shell: the layout, the\n // chrome, and whatever it renders with nothing to show yet. Prefetching\n // on hover put it in the cache, so going there first costs no request\n // and puts the page on screen while the real query is still running.\n //\n // The query itself is never prefetched. It is the expensive half, and\n // hovering a search button is not a reason to run someone's search.\n if (path !== shell && prefetched?.(shell)) {\n // Awaited rather than raced: navigate() aborts whatever is in flight,\n // so starting the real one first would cancel the shell before it\n // could render. It is a cache hit, so this is a render, not a wait.\n Promise.resolve(nav?.(shell, { replace, preserveScroll })).then(() =>\n // Replaces, so the shell does not become a back-button stop of its\n // own — the pair leaves exactly one entry behind.\n nav?.(path, { replace: true, preserveScroll }),\n );\n\n return;\n }\n\n nav?.(path, { replace, preserveScroll });\n return;\n }\n\n const serverAction = action as (formData: FormData) => Promise<unknown>;\n\n // Rebuilt rather than edited: transform returns the values to send, so\n // whatever was in the form and is not in the result should not go.\n if (transform) {\n for (const key of [...formData.keys()]) formData.delete(key);\n\n for (const [key, value] of buildFormData(transform(data))) {\n formData.append(key, value);\n }\n }\n\n setErrors({});\n\n // Before the transition, so a failure neither runs the optimistic\n // update nor leaves the form looking like it is submitting.\n const invalid = await validateWith(schema, data);\n\n if (invalid) {\n setErrors(invalid);\n onError?.(invalid);\n\n return;\n }\n\n startTransition(async () => {\n try {\n // Call optimistic updater inside the transition so React's\n // useOptimistic picks it up and auto-reverts on settle.\n optimistic?.(data);\n\n const result = await serverAction(formData);\n const refused = resultOf(result);\n\n // The action answered with somewhere to go, and callServer has\n // already started the navigation. Not an error for a form to\n // show, and not a save to announce either: signing in and going\n // to the dashboard is the whole success.\n if (refused?.redirected !== undefined || redirectedTo() !== null) return;\n\n if (refused) {\n if (refused.errors) {\n setErrors(refused.errors);\n onError?.(refused.errors);\n } else {\n onError?.({}, new Error(refused.serverError));\n }\n\n return;\n }\n\n if (resetOnSuccess) {\n formRef.current?.reset();\n setTouched({});\n setCurrentData({} as T);\n }\n\n // Saved: what is in the form now is what the server has.\n snapshot();\n\n setErrors({});\n setSucceeded(true);\n setRecentlySucceeded(true);\n\n clearTimeout(recentTimer.current);\n recentTimer.current = setTimeout(\n () => setRecentlySucceeded(false),\n 2_000,\n );\n\n onSuccess?.(result);\n } catch (err) {\n // A redirect no longer arrives here - callServer resolves after\n // performing it - but an action called through something older\n // than that still may.\n if (err instanceof ServerRedirectError) return;\n\n if (err instanceof ServerValidationError) {\n setErrors(err.errors);\n onError?.(err.errors);\n } else if (err instanceof ServerDumpError) {\n // Dump overlay is already shown — silently swallow\n } else if (onError) {\n // Not rethrown. A rejected action never settles, and until it\n // settles React keeps the optimistic update on screen — so an\n // unexpected failure left the row showing as though the write had\n // worked. Settling is what takes it back.\n onError({}, err);\n } else {\n // Nothing is handling it, and swallowing here would lose it\n // entirely — the reason this used to rethrow.\n console.error(\"[rsc-kit] form submit failed\", err);\n }\n }\n });\n },\n [\n action,\n isGetForm,\n method,\n replace,\n preserveScroll,\n resetOnSuccess,\n schema,\n transform,\n optimistic,\n onSubmit,\n onSuccess,\n onError,\n ],\n );\n\n const field = useCallback(\n <K extends keyof T & string>(name: K): FieldBinding<T[K]> => {\n // Recorded during render, deliberately: this is how the form knows which\n // values it is the one displaying. Idempotent, so a double render in\n // development records the same name twice and means the same thing.\n readHere.current.add(name);\n\n return {\n name,\n value: (store.get(name) ?? \"\") as T[K],\n onChange: (next: unknown) => {\n const value =\n typeof next === \"object\" && next !== null && \"target\" in next\n ? (next as { target: { value: string } }).target.value\n : next;\n\n store.set(name, value);\n },\n onBlur: () => void touch(name),\n };\n },\n [store, touch],\n );\n\n const fieldState = useCallback(\n (name: string): FieldState => ({\n touched: touched[name] === true,\n invalid: (errors[name]?.length ?? 0) > 0,\n errors: errors[name] ?? [],\n }),\n [touched, errors],\n );\n\n // Stable, so a subscriber below does not re-render because this one did.\n const storeContext = useMemo(() => ({ store, touch }), [store, touch]);\n\n const formStatus: FormRenderProps<T> = {\n pending: isPending,\n data: currentData,\n get dirty() {\n dirtyRead.current = true;\n\n return dirty;\n },\n succeeded,\n recentlySucceeded,\n field,\n fieldState,\n errors: errors as FormRenderProps<T>[\"errors\"],\n error,\n clearErrors,\n reset: resetForm,\n };\n\n return (\n <FormStoreContext.Provider value={storeContext}>\n <FormStatusContext.Provider value={formStatus as FormRenderProps}>\n <form\n ref={attachForm}\n // On the element as well as in the handler, which is what makes this\n // work before hydration. React emits a form a browser can submit on its\n // own for a server action, and an ordinary action/method pair for a\n // url — so a submit that happens before the javascript arrives still\n // reaches the server.\n //\n // The two do not fight: handleSubmit calls preventDefault() first, and\n // React does not run a form action when the submit event was cancelled.\n // So the enhanced path wins whenever there is one, and the native path\n // is what is left when there is not.\n action={(bindable ? formAction : action) as never}\n // Only for a url. React sets the method itself for a server action, and\n // passing one alongside is what it warns about.\n method={isGetForm ? method : undefined}\n onSubmit={handleSubmit}\n // Every keystroke and every toggle, from any control in the form,\n // uncontrolled ones included: React's onInput here is the bubbling\n // `input` event. A caller's own handler still runs.\n onInput={(event) => {\n rest.onInput?.(event);\n measureDirty();\n }}\n onChange={(event) => {\n rest.onChange?.(event);\n measureDirty();\n }}\n // On the form, not only on the bound fields. `focusout` bubbles where\n // `blur` does not, so React's onBlur here sees every control that was\n // left — including the uncontrolled ones, which are most of them and\n // would otherwise never be marked touched at all.\n onBlur={(event) => {\n const target = event.target as unknown as {\n name?: string;\n value?: string;\n };\n const name = target.name;\n\n if (!name) return;\n\n // Leaving a field is the moment to check it; leaving the form is\n // not the same moment. Focus going to nothing, or to something\n // outside the form, is a click on the page - most often a dialog\n // closing - and an error painted into a dialog as it animates out\n // reads as a submit that nobody made. An empty field left that way\n // is not checked at all. One with something in it is, but only\n // once the dust settles: if the form is gone or hidden by then, it\n // was a dialog closing, and nobody is there to read the error.\n const left = event.relatedTarget as Node | null;\n const stillInForm = !!left && !!formRef.current?.contains(left);\n\n if (stillInForm) {\n void touch(name);\n\n return;\n }\n\n if (!target.value) return;\n\n setTimeout(() => {\n const form = formRef.current;\n\n if (\n !form ||\n !form.isConnected ||\n form.getClientRects().length === 0\n )\n return;\n if (\n form.closest(\n \"[hidden], [aria-hidden='true'], [data-ending-style], [data-closed]\",\n )\n )\n return;\n\n void touch(name);\n }, LEAVE_FORM_SETTLE_MS);\n }}\n onMouseEnter={prefetch === \"hover\" ? doPrefetch : undefined}\n data-pending={isPending ? \"\" : undefined}\n {...rest}\n >\n {typeof children === \"function\" ? children(formStatus) : children}\n </form>\n </FormStatusContext.Provider>\n </FormStoreContext.Provider>\n );\n}\n\n// Also by name, because both spellings are in use: `import Form` and\n// `import { Form }`. This was a re-export of \"./Form\" — from inside Form.tsx,\n// so the module named itself. It survived on the bundler tolerating a circular\n// self-reference, left over from when a separate barrel re-exported a\n// FormComponent.tsx that a case-insensitive filesystem would not let be called\n// Form.ts. There is one file now, and it can just export what it declares.\nexport { Form };\n"]}
|
|
1
|
+
{"version":3,"file":"Form.js","sourceRoot":"","sources":["../../src/js/Form.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAGb,OAAO,EAKL,aAAa,EACb,WAAW,EACX,UAAU,EACV,SAAS,EACT,OAAO,EACP,MAAM,EACN,cAAc,EACd,QAAQ,EACR,oBAAoB,EACpB,aAAa,GACd,MAAM,OAAO,CAAC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I,CAAC,OAAO,CACV,oEAAoE,CACrE;4BAED,OAAO;wBAET,KAAK,KAAK,CAAC,IAAI,CAAC,CAAC;oBACnB,CAAC,EAAE,oBAAoB,CAAC,CAAC;gBAC3B,CAAC,EACD,YAAY,EAAE,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,kBAC7C,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,KACpC,IAAI,YAEP,OAAO,QAAQ,KAAK,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,GAC5D,GACoB,GACH,CAC7B,CAAC;AACJ,CAAC;AAED,qEAAqE;AACrE,8EAA8E;AAC9E,+EAA+E;AAC/E,sEAAsE;AACtE,+EAA+E;AAC/E,2EAA2E;AAC3E,OAAO,EAAE,IAAI,EAAE,CAAC","sourcesContent":["\"use client\";\n\nimport type { Route } from \"../routes.js\";\nimport {\n type FormHTMLAttributes,\n type FormEvent,\n type ReactNode,\n type Ref,\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useActionState,\n useState,\n useSyncExternalStore,\n useTransition,\n} from \"react\";\nimport { submitForm } from \"../formSubmit\";\nimport { ServerValidationError, ServerDumpError, ServerRedirectError, redirectedTo } from \"./errors\";\nimport { buildFormData, decodeFormData } from \"./formEncoding\";\nimport { createFormStore } from \"./formStore\";\nimport type { FormStore } from \"./formStore\";\nimport { validateWith } from \"./standardSchema\";\nimport type { StandardSchemaV1 } from \"./standardSchema\";\n\n/**\n * How long a blur that leaves the form waits before checking the field. A\n * dialog's exit animation is shorter than this; a form still on screen after\n * it is one somebody is looking at.\n */\nconst LEAVE_FORM_SETTLE_MS = 300;\n\ntype PrefetchStrategy = \"hover\" | \"mount\" | \"none\";\n\n/**\n * What `field(name)` hands a control, spread straight onto it.\n *\n * The same four things react-hook-form's `<Controller>` gives, because it is\n * the same job: a component with no native control behind it needs a value and\n * a way to report a new one.\n */\ninterface FieldBinding<V> {\n name: string;\n value: V;\n /**\n * Either shape: a DOM event, or the value itself.\n *\n * A native input passes the event; a Radix select or a rich editor passes\n * what was chosen. A binder understanding only one of them would work on\n * half the controls anyone actually uses.\n */\n onChange: (next: V | { target: { value: V } }) => void;\n onBlur: () => void;\n}\n\n/**\n * What is known about one field, separately from what is spread onto it.\n *\n * Two objects rather than one, which is react-hook-form's split and it is right\n * for a mechanical reason: `touched` and `invalid` are not DOM attributes, so a\n * single spreadable object would put them on the element and React would warn\n * about every one.\n */\ninterface FieldState {\n /** Whether it has been left at least once. */\n touched: boolean;\n /** Whether it currently has errors. */\n invalid: boolean;\n /** Its messages, ready for a `<FieldError>`. */\n errors: string[];\n}\n\ninterface FormRenderProps<\n T extends Record<string, unknown> = Record<string, unknown>,\n> {\n pending: boolean;\n data: T;\n /**\n * Keyed by field name, so a typo is a type error rather than undefined.\n *\n * Partial because most fields have none, and nested paths join with dots —\n * `errors['address.city']`, which is the key a Standard Schema issue for that\n * field produces.\n */\n errors: Partial<Record<keyof T & string, string[]>> &\n Record<string, string[] | undefined>;\n error: (field: keyof T & string) => string | undefined;\n clearErrors: (...fields: (keyof T & string)[]) => void;\n reset: () => void;\n /**\n * Whether anything differs from what the form started with.\n *\n * For the Save button that stays quiet until there is something to save,\n * and the Discard that appears beside it. Read from the form itself - a\n * snapshot of its FormData on mount, compared on every input - so an\n * uncontrolled field counts, which nothing outside the form can do. A\n * successful submit makes the current values the new baseline; `reset()`\n * goes back to the first one.\n */\n dirty: boolean;\n /** Whether the last submit was accepted. */\n succeeded: boolean;\n /**\n * The same thing, for two seconds.\n *\n * The \"Saved ✓\" that appears and fades. Worth having as state rather than a\n * timer in every form that wants one, because the timer has to be cleared\n * when the component goes away and that is the part people forget.\n */\n recentlySucceeded: boolean;\n /**\n * Bind one field so this component holds its value.\n *\n * Most fields need nothing: they are uncontrolled, the DOM holds the value,\n * and it is read back as FormData on submit. Reach for this when the DOM\n * cannot hold it for you — a control with no native element behind it, or a\n * value you want to read as it is typed:\n *\n * <Input {...field('title')} />\n * <span>{field('body').value.length}/100</span>\n *\n * A bound field is still an ordinary named input, so it arrives in FormData\n * with everything else. Nothing merges; there is one source of truth.\n */\n field: <K extends keyof T & string>(name: K) => FieldBinding<T[K]>;\n /**\n * What is known about a field, for deciding how to show it.\n *\n * const title = fieldState('title')\n *\n * <Field data-invalid={title.invalid}>\n * <Input {...field('title')} aria-invalid={title.invalid} />\n * <FieldError errors={title.errors.map((message) => ({ message }))} />\n * </Field>\n *\n * `touched` is what separates \"not filled in yet\" from \"filled in wrongly\" —\n * an error on a field nobody has visited is a form shouting before anyone\n * has done anything.\n */\n fieldState: (name: string) => FieldState;\n}\n\ninterface FormProps<\n T extends Record<string, unknown> = Record<string, unknown>,\n> extends Omit<\n FormHTMLAttributes<HTMLFormElement>,\n \"action\" | \"method\" | \"children\" | \"onSubmit\" | \"onError\"\n> {\n action: Route | ((formData: FormData) => Promise<unknown>);\n method?: \"get\" | \"post\";\n /**\n * The <form> element, for a caller that needs it - to focus, to scroll to,\n * to hand a library. The form keeps its own handle beside it; a caller's\n * never replaces it.\n */\n ref?: Ref<HTMLFormElement>;\n /**\n * Starting values for fields bound with `field()`.\n *\n * Uncontrolled fields do not need this — they take React's own\n * `defaultValue`, and the DOM keeps whatever is typed into them.\n */\n defaultValues?: Partial<T>;\n /**\n * A store created above this form, from `useFormStore()`.\n *\n * For the one case the context cannot reach: something that is not a\n * descendant — a top bar showing unsaved changes, a sidebar preview — needs\n * the values to exist above both of them. Create the store where they share\n * an ancestor and hand it down.\n *\n * Without it the form makes its own, which is what almost every form wants.\n */\n store?: FormStore;\n prefetch?: PrefetchStrategy;\n cacheFor?: number;\n replace?: boolean;\n preserveScroll?: boolean;\n resetOnSuccess?: boolean;\n /**\n * Check the fields before submitting, with any Standard Schema — Zod,\n * Valibot, ArkType.\n *\n * A failure fills `errors` and the action is never called, so a mistake\n * costs no round trip. It is a courtesy and not a control: the same action\n * is reachable without this form, so the server still has to check.\n */\n schema?: StandardSchemaV1;\n /** Transform form data before submitting to the server action. */\n transform?: (data: T) => Record<string, unknown>;\n /** Called inside the transition with typed form data. Use it to call your useOptimistic setter. */\n optimistic?: (data: T) => void;\n onSuccess?: (result: unknown) => void;\n /**\n * Called when a submit does not succeed.\n *\n * Validation failures arrive as field errors, with no second argument.\n * Anything else arrives as an empty error map and the thrown value — there\n * are no field errors to report, but the form still has to say so.\n */\n onError?: (errors: Record<string, string[]>, error?: unknown) => void;\n onSubmit?: (formData: FormData) => void | false;\n children: ReactNode | ((form: FormRenderProps<T>) => ReactNode);\n}\n\n/**\n * What an action built with createActionClient answers with.\n *\n * Recognised rather than thrown, because React serialises a rejected server\n * action opaquely: production strips the message and the fields it named are\n * gone. A returned object crosses intact, so a form reads it.\n */\nfunction resultOf(\n value: unknown,\n): { errors?: Record<string, string[]>; serverError?: string; redirected?: string } | null {\n if (typeof value !== \"object\" || value === null) return null;\n\n const result = value as {\n validationErrors?: Record<string, string[]>;\n serverError?: string;\n redirected?: string;\n };\n\n if (result.validationErrors) return { errors: result.validationErrors };\n if (result.serverError) return { serverError: result.serverError };\n if (typeof result.redirected === \"string\") return { redirected: result.redirected };\n\n return null;\n}\n\nconst FormStatusContext = createContext<FormRenderProps>({\n pending: false,\n data: {},\n dirty: false,\n errors: {},\n error: () => undefined,\n clearErrors: () => {},\n reset: () => {},\n succeeded: false,\n recentlySucceeded: false,\n // Outside a Form there is nothing holding a value, so a binding that reported\n // one would be lying. Name only, which is the part that is still true.\n field: ((name: string) => ({\n name,\n value: \"\",\n onChange: () => {},\n onBlur: () => {},\n })) as FormRenderProps[\"field\"],\n fieldState: () => ({ touched: false, invalid: false, errors: [] }),\n});\n\n/**\n * The store, on its own context.\n *\n * Separate from the status context because that one holds a fresh object every\n * render, so anything reading it re-renders with the form. The store is stable\n * for the life of the form, which is what lets a subscriber below it re-render\n * alone.\n */\nconst FormStoreContext = createContext<{\n store: FormStore;\n touch: (name: string) => void;\n} | null>(null);\n\n/**\n * A value store created above the form rather than by it.\n *\n * const store = useFormStore({ title: '' })\n *\n * <TopBar store={store} /> // not inside the form\n * <Form action={save} store={store}>…</Form>\n *\n * For the one case the context cannot reach. `<Form>` makes its own otherwise,\n * and almost every form should let it — this exists so that a component which\n * is not a descendant can still read the values, which is the flexibility\n * react-hook-form and TanStack Form get from `useForm()` being yours to call.\n *\n * Deliberately not reactive itself: creating the store does not subscribe to\n * it, so the component holding it does not re-render on every keystroke and\n * take the whole subtree with it. Read it with `useFormValues(store)`.\n */\nexport function useFormStore<T extends Record<string, unknown>>(\n initial: Partial<T> = {},\n): FormStore {\n const ref = useRef<FormStore | null>(null);\n\n ref.current ??= createFormStore({ ...initial });\n\n return ref.current;\n}\n\n/**\n * One field, subscribed on its own.\n *\n * The same thing `field()` gives, from a component that re-renders when this\n * field changes and at no other time. Reach for it when a form is large enough\n * that re-rendering all of it per keystroke is real:\n *\n * function Title() {\n * const { field, invalid, errors } = useField('title')\n *\n * return <Input {...field} aria-invalid={invalid} />\n * }\n *\n * Which is react-hook-form's `<Controller>` without the render prop: the\n * component you already had to write is the subscription boundary.\n */\nexport function useField(\n name: string,\n store?: FormStore,\n): FieldBinding<string> & FieldState {\n const ctx = useContext(FormStoreContext);\n const status = useContext(FormStatusContext);\n\n if (!ctx && !store) {\n throw new Error(\n \"useField() was called outside a <Form>. It reads that form's values, so there has to be one above it.\",\n );\n }\n\n const source = store ?? ctx!.store;\n const touch = ctx?.touch;\n\n const value = useSyncExternalStore(\n source.subscribe,\n () => (source.get(name) ?? \"\") as string,\n () => \"\",\n );\n\n const errors = status.errors[name] ?? [];\n\n return {\n name,\n value,\n onChange: (next) => {\n source.set(\n name,\n typeof next === \"object\" && next !== null && \"target\" in next\n ? (next as { target: { value: string } }).target.value\n : next,\n );\n },\n onBlur: () => void touch?.(name),\n touched: status.fieldState(name).touched,\n invalid: errors.length > 0,\n errors,\n };\n}\n\n/**\n * Every bound value, from anywhere inside the form.\n *\n * For a summary, a preview, a count of what has changed — something that reads\n * the form without being a field in it. Only values bound through `field()` or\n * `useField` are here: an uncontrolled input's value belongs to the DOM, and\n * this has no way to know it changed.\n */\nexport function useFormValues<T extends Record<string, unknown>>(\n store?: FormStore,\n): Partial<T> {\n const ctx = useContext(FormStoreContext);\n\n if (!ctx && !store) {\n throw new Error(\n \"useFormValues() was called outside a <Form>. It reads that form's values, so there has to be one above it.\",\n );\n }\n\n const source = store ?? ctx!.store;\n\n return useSyncExternalStore(\n source.subscribe,\n () => source.all() as Partial<T>,\n () => ({}) as Partial<T>,\n );\n}\n\nexport function useFormStatus<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(): FormRenderProps<T> {\n return useContext(FormStatusContext) as FormRenderProps<T>;\n}\n\n/**\n * submitForm bound to an action, once per action.\n *\n * Bound on every render, it was a fresh function with a fresh promise for\n * its bound arguments each time - and React, seating a posted form's state\n * during the server render, suspends on that promise until it settles, then\n * renders the component again, which bound again. A render that never\n * finished, on every page a form was posted to without javascript. One\n * bound function per action, and the promise settles once.\n */\nconst boundSubmits = new WeakMap<Function, (previous: unknown, formData: FormData) => Promise<unknown>>();\n\nfunction boundSubmit(action: (formData: FormData) => Promise<unknown>) {\n let bound = boundSubmits.get(action);\n\n if (!bound) {\n bound = submitForm.bind(null, action);\n boundSubmits.set(action, bound);\n }\n\n return bound;\n}\n\n/**\n * A form's values as one comparable string.\n *\n * FormData in document order, a file by its name and size: enough to say\n * whether anything changed, which is all `dirty` asks.\n */\nfunction serializeForm(form: HTMLFormElement): string {\n const parts: string[] = [];\n\n for (const [name, value] of new FormData(form)) {\n parts.push(\n name + \"=\" + (typeof value === \"string\" ? value : \"file:\" + value.name + \":\" + value.size),\n );\n }\n\n return parts.join(\"\\n\");\n}\n\n/**\n * Also exported by name, and re-exported below, because both spellings are in\n * use: `import Form from` and `import { Form } from`.\n */\nexport default function Form<\n T extends Record<string, unknown> = Record<string, unknown>,\n>({\n action,\n method: methodProp,\n defaultValues,\n store: providedStore,\n prefetch = \"hover\",\n cacheFor,\n replace = false,\n preserveScroll = false,\n resetOnSuccess = true,\n schema,\n transform,\n optimistic,\n onSuccess,\n onError,\n onSubmit,\n children,\n ref: callerRef,\n ...rest\n}: FormProps<T>) {\n const isGetForm = typeof action === \"string\";\n const method = methodProp ?? (isGetForm ? \"get\" : \"post\");\n\n // The answer to this form posted without a runtime, seated by React into\n // the form that posted it - which is the only way a visitor with no\n // javascript sees a refusal. Registered through submitForm, bound to the\n // action, because React hands a form-state action a (previous, formData)\n // pair and the action takes the FormData alone. On the server a plain\n // function - a closure, not a server reference - cannot be bound into a\n // form; the form falls back to the action itself, and posts nothing\n // seatable, which is all a closure could ever have done.\n const bindable =\n typeof action === \"function\" && (typeof window !== \"undefined\" || \"$$FORM_ACTION\" in action);\n const [posted, formAction] = useActionState(\n bindable ? boundSubmit(action as (formData: FormData) => Promise<unknown>) : async () => null,\n null as unknown,\n );\n const postedRefusal = resultOf(posted);\n const [errors, setErrors] = useState<Record<string, string[]>>(() => postedRefusal?.errors ?? {});\n const [touched, setTouched] = useState<Record<string, boolean>>({});\n\n /**\n * Mark a field visited, and check it.\n *\n * Checking on blur rather than on every keystroke, because an error that\n * appears while someone is halfway through typing an email address is a form\n * arguing with them. Leaving the field is the moment they have finished\n * saying what they meant.\n *\n * The whole object is validated and only this field's issues are kept: a\n * Standard Schema has no notion of one field, and filtering by path is the\n * honest way to ask it about one. Everything else's errors are left as they\n * were, so blurring an empty field does not light up the rest of the form.\n */\n const touch = useCallback(\n async (name: string) => {\n setTouched((prev) => (prev[name] ? prev : { ...prev, [name]: true }));\n\n if (!schema || !formRef.current) return;\n\n const invalid = await validateWith(\n schema,\n decodeFormData(new FormData(formRef.current), schema),\n );\n\n setErrors((prev) => {\n const next = { ...prev };\n\n if (invalid?.[name]) next[name] = invalid[name];\n else delete next[name];\n\n return next;\n });\n },\n [schema],\n );\n\n const [succeeded, setSucceeded] = useState(false);\n const [recentlySucceeded, setRecentlySucceeded] = useState(false);\n const recentTimer = useRef<ReturnType<typeof setTimeout> | undefined>(\n undefined,\n );\n\n // Cleared on unmount: a timer that fires into a component that has gone is\n // the warning nobody reads and the leak nobody finds.\n useEffect(() => () => clearTimeout(recentTimer.current), []);\n\n // Only the fields someone bound. Everything else is the DOM's.\n //\n // A store rather than state, so a component using `useField` can re-render\n // for one field while this one does not. See formStore.ts.\n const storeRef = useRef<FormStore | null>(null);\n\n storeRef.current ??= createFormStore({\n ...(defaultValues as Record<string, unknown> | undefined),\n });\n\n const store = providedStore ?? storeRef.current;\n\n // Which names the render prop read through `field()`. A change to one of\n // those has to re-render this component, because that is where the value is\n // being displayed; a change to anything else does not, which is what lets a\n // `useField` child stand on its own.\n const readHere = useRef(new Set<string>());\n const [, bump] = useState(0);\n\n useEffect(\n () =>\n store.subscribe((name) => {\n if (name === \"\" || readHere.current.has(name)) bump((n) => n + 1);\n }),\n [store],\n );\n const [currentData, setCurrentData] = useState<T>({} as T);\n const [isPending, startTransition] = useTransition();\n const formRef = useRef<HTMLFormElement>(null);\n\n // What the form started with, as its FormData reads: the baseline `dirty`\n // is measured against. Taken on mount, retaken after a successful submit.\n const baseline = useRef<string | null>(null);\n const [dirty, setDirty] = useState(false);\n // Only a form that reads `dirty` pays for it: the flip from clean to dirty\n // is a render of the whole form, and a field that subscribes for itself\n // is promised that typing in it renders it alone.\n const dirtyRead = useRef(false);\n\n const snapshot = useCallback(() => {\n if (!formRef.current) return;\n\n baseline.current = serializeForm(formRef.current);\n setDirty(false);\n }, []);\n\n const measureDirty = useCallback(() => {\n if (!dirtyRead.current || !formRef.current || baseline.current === null) return;\n\n const now = serializeForm(formRef.current) !== baseline.current;\n\n setDirty((was) => (was === now ? was : now));\n }, []);\n\n useEffect(snapshot, [snapshot]);\n\n // A bound control with no native element behind it changes through the\n // store, not through an input event - a Radix select - so the store is\n // watched too. Its input, if it has one, is read back with the rest.\n useEffect(() => store.subscribe(() => queueMicrotask(measureDirty)), [store, measureDirty]);\n\n // Both handles, one element. React 19 hands a function component its ref\n // as a prop, and spread after the form's own it replaced it - every\n // FormData read then found null. A caller's ref is filled beside ours.\n const attachForm = useCallback(\n (element: HTMLFormElement | null) => {\n formRef.current = element;\n\n if (typeof callerRef === \"function\") callerRef(element);\n else if (callerRef) callerRef.current = element;\n },\n [callerRef],\n );\n\n const error = useCallback(\n (field: keyof T & string): string | undefined => errors[field]?.[0],\n [errors],\n );\n\n const clearErrors = useCallback((...fields: (keyof T & string)[]) => {\n if (fields.length === 0) {\n setErrors({});\n } else {\n setErrors((prev) => {\n const next = { ...prev };\n for (const f of fields) {\n delete next[f];\n }\n return next;\n });\n }\n }, []);\n\n const resetForm = useCallback(() => {\n formRef.current?.reset();\n setErrors({});\n setCurrentData({} as T);\n queueMicrotask(measureDirty);\n }, [measureDirty]);\n\n useEffect(() => {\n if (isGetForm && prefetch === \"mount\") {\n const fn = (window as any).__rsc_prefetch;\n fn?.(action, cacheFor);\n }\n }, [isGetForm, prefetch, action, cacheFor]);\n\n const doPrefetch = useCallback(() => {\n if (!isGetForm) return;\n const fn = (window as any).__rsc_prefetch;\n fn?.(action as string, cacheFor);\n }, [isGetForm, action, cacheFor]);\n\n const handleSubmit = useCallback(\n async (e: FormEvent<HTMLFormElement>) => {\n e.preventDefault();\n const formData = new FormData(e.currentTarget);\n const data = decodeFormData<T>(formData, schema);\n setCurrentData(data);\n\n if (onSubmit?.(formData) === false) {\n return;\n }\n\n if (isGetForm && method === \"get\") {\n const url = new URL(action as string, window.location.origin);\n for (const [key, value] of formData.entries()) {\n if (typeof value === \"string\" && value !== \"\") {\n url.searchParams.set(key, value);\n }\n }\n\n const path = url.pathname + url.search;\n const shell = action as string;\n const nav = (window as any).__rsc_navigate;\n const prefetched = (window as any).__rsc_is_prefetched;\n\n // The route without its query is that route's shell: the layout, the\n // chrome, and whatever it renders with nothing to show yet. Prefetching\n // on hover put it in the cache, so going there first costs no request\n // and puts the page on screen while the real query is still running.\n //\n // The query itself is never prefetched. It is the expensive half, and\n // hovering a search button is not a reason to run someone's search.\n if (path !== shell && prefetched?.(shell)) {\n // Awaited rather than raced: navigate() aborts whatever is in flight,\n // so starting the real one first would cancel the shell before it\n // could render. It is a cache hit, so this is a render, not a wait.\n Promise.resolve(nav?.(shell, { replace, preserveScroll })).then(() =>\n // Replaces, so the shell does not become a back-button stop of its\n // own — the pair leaves exactly one entry behind.\n nav?.(path, { replace: true, preserveScroll }),\n );\n\n return;\n }\n\n nav?.(path, { replace, preserveScroll });\n return;\n }\n\n const serverAction = action as (formData: FormData) => Promise<unknown>;\n\n // Rebuilt rather than edited: transform returns the values to send, so\n // whatever was in the form and is not in the result should not go.\n if (transform) {\n for (const key of [...formData.keys()]) formData.delete(key);\n\n for (const [key, value] of buildFormData(transform(data))) {\n formData.append(key, value);\n }\n }\n\n setErrors({});\n\n // Before the transition, so a failure neither runs the optimistic\n // update nor leaves the form looking like it is submitting.\n const invalid = await validateWith(schema, data);\n\n if (invalid) {\n setErrors(invalid);\n onError?.(invalid);\n\n return;\n }\n\n startTransition(async () => {\n try {\n // Call optimistic updater inside the transition so React's\n // useOptimistic picks it up and auto-reverts on settle.\n optimistic?.(data);\n\n const result = await serverAction(formData);\n const refused = resultOf(result);\n\n // The action answered with somewhere to go, and callServer has\n // already started the navigation. Not an error for a form to\n // show, and not a save to announce either: signing in and going\n // to the dashboard is the whole success.\n if (refused?.redirected !== undefined || redirectedTo() !== null) return;\n\n if (refused) {\n if (refused.errors) {\n setErrors(refused.errors);\n onError?.(refused.errors);\n } else {\n onError?.({}, new Error(refused.serverError));\n }\n\n return;\n }\n\n if (resetOnSuccess) {\n formRef.current?.reset();\n setTouched({});\n setCurrentData({} as T);\n }\n\n // Saved: what is in the form now is what the server has.\n snapshot();\n\n setErrors({});\n setSucceeded(true);\n setRecentlySucceeded(true);\n\n clearTimeout(recentTimer.current);\n recentTimer.current = setTimeout(\n () => setRecentlySucceeded(false),\n 2_000,\n );\n\n onSuccess?.(result);\n } catch (err) {\n // A redirect no longer arrives here - callServer resolves after\n // performing it - but an action called through something older\n // than that still may.\n if (err instanceof ServerRedirectError) return;\n\n if (err instanceof ServerValidationError) {\n setErrors(err.errors);\n onError?.(err.errors);\n } else if (err instanceof ServerDumpError) {\n // Dump overlay is already shown — silently swallow\n } else if (onError) {\n // Not rethrown. A rejected action never settles, and until it\n // settles React keeps the optimistic update on screen — so an\n // unexpected failure left the row showing as though the write had\n // worked. Settling is what takes it back.\n onError({}, err);\n } else {\n // Nothing is handling it, and swallowing here would lose it\n // entirely — the reason this used to rethrow.\n console.error(\"[rsc-kit] form submit failed\", err);\n }\n }\n });\n },\n [\n action,\n isGetForm,\n method,\n replace,\n preserveScroll,\n resetOnSuccess,\n schema,\n transform,\n optimistic,\n onSubmit,\n onSuccess,\n onError,\n ],\n );\n\n const field = useCallback(\n <K extends keyof T & string>(name: K): FieldBinding<T[K]> => {\n // Recorded during render, deliberately: this is how the form knows which\n // values it is the one displaying. Idempotent, so a double render in\n // development records the same name twice and means the same thing.\n readHere.current.add(name);\n\n return {\n name,\n value: (store.get(name) ?? \"\") as T[K],\n onChange: (next: unknown) => {\n const value =\n typeof next === \"object\" && next !== null && \"target\" in next\n ? (next as { target: { value: string } }).target.value\n : next;\n\n store.set(name, value);\n },\n onBlur: () => void touch(name),\n };\n },\n [store, touch],\n );\n\n const fieldState = useCallback(\n (name: string): FieldState => ({\n touched: touched[name] === true,\n invalid: (errors[name]?.length ?? 0) > 0,\n errors: errors[name] ?? [],\n }),\n [touched, errors],\n );\n\n // Stable, so a subscriber below does not re-render because this one did.\n const storeContext = useMemo(() => ({ store, touch }), [store, touch]);\n\n const formStatus: FormRenderProps<T> = {\n pending: isPending,\n data: currentData,\n get dirty() {\n dirtyRead.current = true;\n\n return dirty;\n },\n succeeded,\n recentlySucceeded,\n field,\n fieldState,\n errors: errors as FormRenderProps<T>[\"errors\"],\n error,\n clearErrors,\n reset: resetForm,\n };\n\n return (\n <FormStoreContext.Provider value={storeContext}>\n <FormStatusContext.Provider value={formStatus as FormRenderProps}>\n <form\n ref={attachForm}\n // On the element as well as in the handler, which is what makes this\n // work before hydration. React emits a form a browser can submit on its\n // own for a server action, and an ordinary action/method pair for a\n // url — so a submit that happens before the javascript arrives still\n // reaches the server.\n //\n // The two do not fight: handleSubmit calls preventDefault() first, and\n // React does not run a form action when the submit event was cancelled.\n // So the enhanced path wins whenever there is one, and the native path\n // is what is left when there is not.\n action={(bindable ? formAction : action) as never}\n // Only for a url. React sets the method itself for a server action, and\n // passing one alongside is what it warns about.\n method={isGetForm ? method : undefined}\n onSubmit={handleSubmit}\n // Every keystroke and every toggle, from any control in the form,\n // uncontrolled ones included: React's onInput here is the bubbling\n // `input` event. A caller's own handler still runs.\n onInput={(event) => {\n rest.onInput?.(event);\n measureDirty();\n }}\n onChange={(event) => {\n rest.onChange?.(event);\n measureDirty();\n }}\n // On the form, not only on the bound fields. `focusout` bubbles where\n // `blur` does not, so React's onBlur here sees every control that was\n // left — including the uncontrolled ones, which are most of them and\n // would otherwise never be marked touched at all.\n onBlur={(event) => {\n const target = event.target as unknown as {\n name?: string;\n value?: string;\n };\n const name = target.name;\n\n if (!name) return;\n\n // Leaving a field is the moment to check it; leaving the form is\n // not the same moment. Focus going to nothing, or to something\n // outside the form, is a click on the page - most often a dialog\n // closing - and an error painted into a dialog as it animates out\n // reads as a submit that nobody made. An empty field left that way\n // is not checked at all. One with something in it is, but only\n // once the dust settles: if the form is gone or hidden by then, it\n // was a dialog closing, and nobody is there to read the error.\n const left = event.relatedTarget as Node | null;\n const stillInForm = !!left && !!formRef.current?.contains(left);\n\n if (stillInForm) {\n void touch(name);\n\n return;\n }\n\n if (!target.value) return;\n\n setTimeout(() => {\n const form = formRef.current;\n\n if (\n !form ||\n !form.isConnected ||\n form.getClientRects().length === 0\n )\n return;\n if (\n form.closest(\n \"[hidden], [aria-hidden='true'], [data-ending-style], [data-closed]\",\n )\n )\n return;\n\n void touch(name);\n }, LEAVE_FORM_SETTLE_MS);\n }}\n onMouseEnter={prefetch === \"hover\" ? doPrefetch : undefined}\n data-pending={isPending ? \"\" : undefined}\n {...rest}\n >\n {typeof children === \"function\" ? children(formStatus) : children}\n </form>\n </FormStatusContext.Provider>\n </FormStoreContext.Provider>\n );\n}\n\n// Also by name, because both spellings are in use: `import Form` and\n// `import { Form }`. This was a re-export of \"./Form\" — from inside Form.tsx,\n// so the module named itself. It survived on the bundler tolerating a circular\n// self-reference, left over from when a separate barrel re-exported a\n// FormComponent.tsx that a case-insensitive filesystem would not let be called\n// Form.ts. There is one file now, and it can just export what it declares.\nexport { Form };\n"]}
|
package/dist/js/Link.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type Route, type SearchProp } from "../routes.js";
|
|
2
2
|
import { type AnchorHTMLAttributes, type Ref } from "react";
|
|
3
3
|
type PrefetchStrategy = "hover" | "mount" | "click" | "none" | boolean;
|
|
4
|
-
interface LinkBaseProps<H extends
|
|
4
|
+
interface LinkBaseProps<H extends Route> extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
|
|
5
5
|
/**
|
|
6
6
|
* Where this goes. Typed to the routes the build found, so a link to a page
|
|
7
|
-
* that does not exist stops compiling; `path as
|
|
7
|
+
* that does not exist stops compiling; `path as Route` when it is computed.
|
|
8
8
|
*/
|
|
9
9
|
href: H;
|
|
10
10
|
/**
|
|
@@ -27,6 +27,6 @@ interface LinkBaseProps<H extends Href> extends Omit<AnchorHTMLAttributes<HTMLAn
|
|
|
27
27
|
* number written as text does not compile, and a key it requires is required
|
|
28
28
|
* here. With no schema, any scalars. See SearchFor in routes.ts.
|
|
29
29
|
*/
|
|
30
|
-
type LinkProps<H extends
|
|
31
|
-
export default function Link<H extends
|
|
30
|
+
type LinkProps<H extends Route> = LinkBaseProps<H> & SearchProp<H>;
|
|
31
|
+
export default function Link<H extends Route>({ href: path, search, prefetch: prefetchProp, cacheFor, replace, preserveScroll, children, onClick, onMouseEnter, onMouseLeave, ...rest }: LinkProps<H>): import("react").JSX.Element;
|
|
32
32
|
export {};
|
package/dist/js/Link.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Link.js","sourceRoot":"","sources":["../../src/js/Link.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAA8B,UAAU,EAAE,MAAM,cAAc,CAAC;AACtE,OAAO,EAIL,WAAW,EACX,SAAS,EACT,MAAM,EACN,QAAQ,GACT,MAAM,OAAO,CAAC;AAoCf,SAAS,aAAa,CAAC,GAAW;IAChC,IAAI,CAAC;QACH,OAAO,CACL,IAAI,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,QAAQ,CAAC,MAAM,CACvE,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED,SAAS,oBAAoB,CAAC,CAAgC;IAC5D,OAAO,CACL,CAAC,CAAC,CAAC,gBAAgB;QACnB,CAAC,CAAC,MAAM,KAAK,CAAC;QACd,CAAC,CAAC,CAAC,OAAO;QACV,CAAC,CAAC,CAAC,OAAO;QACV,CAAC,CAAC,CAAC,QAAQ;QACX,CAAC,CAAC,CAAC,MAAM,CACV,CAAC;AACJ,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC,MAAM,CAAC,OAAO,UAAU,IAAI,CAAiB,EAC3C,IAAI,EAAE,IAAI,EACV,MAAM,EACN,QAAQ,EAAE,YAAY,GAAG,OAAO,EAChC,QAAQ,EACR,OAAO,GAAG,KAAK,EACf,cAAc,GAAG,KAAK,EACtB,QAAQ,EACR,OAAO,EACP,YAAY,EACZ,YAAY,EACZ,GAAG,IAAI,EACM;IACb,0EAA0E;IAC1E,oCAAoC;IACpC,MAAM,IAA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C,UAAU,CAAC,OAAO,GAAG,IAAI,CAAC;QAC5B,CAAC;QAED,yEAAyE;QACzE,wEAAwE;QACxE,IAAI,aAAa,CAAC,IAAI,CAAC;YAAE,OAAO;QAC/B,MAAc,CAAC,qBAAqB,EAAE,CAAC,IAAI,CAAC,CAAC;IAChD,CAAC,EACD,CAAC,IAAI,EAAE,YAAY,CAAC,CACrB,CAAC;IAEF,yEAAyE;IACzE,wEAAwE;IACxE,qEAAqE;IACrE,MAAM,gBAAgB,GAAG,WAAW,CAAC,GAAG,EAAE;QACxC,IAAI,gBAAgB,KAAK,OAAO,IAAI,gBAAgB,KAAK,OAAO,EAAE,CAAC;YACjE,UAAU,EAAE,CAAC;QACf,CAAC;IACH,CAAC,EAAE,CAAC,gBAAgB,EAAE,UAAU,CAAC,CAAC,CAAC;IAEnC,6EAA6E;IAC7E,SAAS,CACP,GAAG,EAAE,CAAC,GAAG,EAAE;QACT,IAAI,UAAU,CAAC,OAAO,KAAK,IAAI;YAAE,YAAY,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACpE,CAAC,EACD,EAAE,CACH,CAAC;IAEF,OAAO,CACL,KAAC,iBAAiB,CAAC,QAAQ,IAAC,KAAK,EAAE,EAAE,OAAO,EAAE,YAC5C,YACE,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,WAAW,EACpB,YAAY,EAAE,gBAAgB,EAC9B,YAAY,EAAE,gBAAgB,EAC9B,YAAY,EAAE,gBAAgB,kBAChB,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,KAClC,IAAI,YAEP,QAAQ,GACP,GACuB,CAC9B,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport { LinkStatusContext } from \"./useLinkStatus\";\nimport { type Href, type SearchProp, withSearch } from \"../routes.js\";\nimport {\n type AnchorHTMLAttributes,\n type MouseEvent,\n type Ref,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from \"react\";\n\ntype PrefetchStrategy = \"hover\" | \"mount\" | \"click\" | \"none\" | boolean;\n\ninterface LinkBaseProps<H extends Href> extends Omit<\n AnchorHTMLAttributes<HTMLAnchorElement>,\n \"href\"\n> {\n /**\n * Where this goes. Typed to the routes the build found, so a link to a page\n * that does not exist stops compiling; `path as Href` when it is computed.\n */\n href: H;\n /**\n * The underlying anchor.\n *\n * Spread onto it like any other prop — React 19 passes ref through a\n * function component without forwardRef — but declared here because it is\n * not part of AnchorHTMLAttributes. A link that cannot be focused is a link\n * a dialog cannot move focus to when it opens.\n */\n ref?: Ref<HTMLAnchorElement>;\n prefetch?: PrefetchStrategy;\n cacheFor?: number;\n replace?: boolean;\n preserveScroll?: boolean;\n}\n\n/**\n * `search` is typed to the page's own `searchParams` schema when it exports\n * one — the same schema the page parses with, so a key it never reads or a\n * number written as text does not compile, and a key it requires is required\n * here. With no schema, any scalars. See SearchFor in routes.ts.\n */\ntype LinkProps<H extends Href> = LinkBaseProps<H> & SearchProp<H>;\n\nfunction isExternalUrl(url: string): boolean {\n try {\n return (\n new URL(url, window.location.origin).origin !== window.location.origin\n );\n } catch {\n return false;\n }\n}\n\nfunction shouldInterceptClick(e: MouseEvent<HTMLAnchorElement>): boolean {\n return (\n !e.defaultPrevented &&\n e.button === 0 &&\n !e.metaKey &&\n !e.ctrlKey &&\n !e.shiftKey &&\n !e.altKey\n );\n}\n\n/**\n * How long a pointer has to settle on a link before it prefetches.\n *\n * A pointer crossing a nav bar enters every link on the way, and each one used\n * to fire a request immediately — enough to fill the browser's per-origin\n * connection limit with pages the user never meant to visit. Waiting is close\n * to free: the prefetch only has to beat the click, and a click that follows a\n * hover this short would not have had its payload back anyway.\n */\nconst HOVER_PREFETCH_DELAY_MS = 100;\n\nexport default function Link<H extends Href>({\n href: path,\n search,\n prefetch: prefetchProp = \"hover\",\n cacheFor,\n replace = false,\n preserveScroll = false,\n children,\n onClick,\n onMouseEnter,\n onMouseLeave,\n ...rest\n}: LinkProps<H>) {\n // The string the anchor and the router both use: the path, with the typed\n // search params serialised onto it.\n const href = (search ? withSearch(path, search as object) : path) as Href;\n const [pending, setPending] = useState(false);\n const hoverTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const prefetchStrategy =\n prefetchProp === true\n ? \"hover\"\n : prefetchProp === false\n ? \"none\"\n : prefetchProp;\n\n const doPrefetch = useCallback(() => {\n if (isExternalUrl(href)) return;\n const fn = (window as any).__rsc_prefetch;\n fn?.(href, cacheFor);\n }, [href, cacheFor]);\n\n // Only useEffect needed: prefetch on mount strategy\n useEffect(() => {\n if (prefetchStrategy === \"mount\") {\n doPrefetch();\n }\n }, [prefetchStrategy, doPrefetch]);\n\n const handleClick = useCallback(\n (e: MouseEvent<HTMLAnchorElement>) => {\n onClick?.(e);\n\n if (e.defaultPrevented) return;\n\n const target = (e.currentTarget as HTMLAnchorElement).target;\n if (target && target !== \"_self\") return;\n if (!shouldInterceptClick(e) || isExternalUrl(href)) return;\n\n // Hash-only links (#section) — let the browser scroll natively\n if (href.startsWith(\"#\")) return;\n\n e.preventDefault();\n setPending(true);\n\n // navigate() returns a Promise — clear pending when it resolves or rejects\n const nav = (window as any).__rsc_navigate;\n const promise = nav?.(href, { replace, preserveScroll });\n promise?.then(\n () => setPending(false),\n () => setPending(false),\n );\n },\n [href, replace, preserveScroll, onClick],\n );\n\n const handleMouseEnter = useCallback(\n (e: MouseEvent<HTMLAnchorElement>) => {\n onMouseEnter?.(e);\n\n if (prefetchStrategy !== \"hover\" && prefetchStrategy !== \"click\") return;\n\n if (hoverTimer.current !== null) clearTimeout(hoverTimer.current);\n\n hoverTimer.current = setTimeout(() => {\n hoverTimer.current = null;\n doPrefetch();\n }, HOVER_PREFETCH_DELAY_MS);\n },\n [prefetchStrategy, doPrefetch, onMouseEnter],\n );\n\n const handleMouseLeave = useCallback(\n (e: MouseEvent<HTMLAnchorElement>) => {\n onMouseLeave?.(e);\n\n // Never fired: the pointer passed over on its way somewhere else.\n if (hoverTimer.current !== null) {\n clearTimeout(hoverTimer.current);\n hoverTimer.current = null;\n }\n\n // Already in flight: give the connection back to whatever the pointer is\n // heading for. A prefetch that has landed is kept — see cancelPrefetch.\n if (isExternalUrl(href)) return;\n (window as any).__rsc_cancel_prefetch?.(href);\n },\n [href, onMouseLeave],\n );\n\n // Touch gets no delay. There is no hovering to disambiguate — a touch is\n // already the start of a tap — and touchstart leads the click by little\n // enough that spending any of it waiting would waste the head start.\n const handleTouchStart = useCallback(() => {\n if (prefetchStrategy === \"hover\" || prefetchStrategy === \"click\") {\n doPrefetch();\n }\n }, [prefetchStrategy, doPrefetch]);\n\n // A link unmounted mid-hover (navigating away) must not prefetch afterwards.\n useEffect(\n () => () => {\n if (hoverTimer.current !== null) clearTimeout(hoverTimer.current);\n },\n [],\n );\n\n return (\n <LinkStatusContext.Provider value={{ pending }}>\n <a\n href={href}\n onClick={handleClick}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n onTouchStart={handleTouchStart}\n data-pending={pending ? \"\" : undefined}\n {...rest}\n >\n {children}\n </a>\n </LinkStatusContext.Provider>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Link.js","sourceRoot":"","sources":["../../src/js/Link.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAA+B,UAAU,EAAE,MAAM,cAAc,CAAC;AACvE,OAAO,EAIL,WAAW,EACX,SAAS,EACT,MAAM,EACN,QAAQ,GACT,MAAM,OAAO,CAAC;AAoCf,SAAS,aAAa,CAAC,GAAW;IAChC,IAAI,CAAC;QACH,OAAO,CACL,IAAI,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,QAAQ,CAAC,MAAM,CACvE,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED,SAAS,oBAAoB,CA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AC;IACpE,CAAC,EACD,EAAE,CACH,CAAC;IAEF,OAAO,CACL,KAAC,iBAAiB,CAAC,QAAQ,IAAC,KAAK,EAAE,EAAE,OAAO,EAAE,YAC5C,YACE,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,WAAW,EACpB,YAAY,EAAE,gBAAgB,EAC9B,YAAY,EAAE,gBAAgB,EAC9B,YAAY,EAAE,gBAAgB,kBAChB,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,KAClC,IAAI,YAEP,QAAQ,GACP,GACuB,CAC9B,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport { LinkStatusContext } from \"./useLinkStatus\";\nimport { type Route, type SearchProp, withSearch } from \"../routes.js\";\nimport {\n type AnchorHTMLAttributes,\n type MouseEvent,\n type Ref,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from \"react\";\n\ntype PrefetchStrategy = \"hover\" | \"mount\" | \"click\" | \"none\" | boolean;\n\ninterface LinkBaseProps<H extends Route> extends Omit<\n AnchorHTMLAttributes<HTMLAnchorElement>,\n \"href\"\n> {\n /**\n * Where this goes. Typed to the routes the build found, so a link to a page\n * that does not exist stops compiling; `path as Route` when it is computed.\n */\n href: H;\n /**\n * The underlying anchor.\n *\n * Spread onto it like any other prop — React 19 passes ref through a\n * function component without forwardRef — but declared here because it is\n * not part of AnchorHTMLAttributes. A link that cannot be focused is a link\n * a dialog cannot move focus to when it opens.\n */\n ref?: Ref<HTMLAnchorElement>;\n prefetch?: PrefetchStrategy;\n cacheFor?: number;\n replace?: boolean;\n preserveScroll?: boolean;\n}\n\n/**\n * `search` is typed to the page's own `searchParams` schema when it exports\n * one — the same schema the page parses with, so a key it never reads or a\n * number written as text does not compile, and a key it requires is required\n * here. With no schema, any scalars. See SearchFor in routes.ts.\n */\ntype LinkProps<H extends Route> = LinkBaseProps<H> & SearchProp<H>;\n\nfunction isExternalUrl(url: string): boolean {\n try {\n return (\n new URL(url, window.location.origin).origin !== window.location.origin\n );\n } catch {\n return false;\n }\n}\n\nfunction shouldInterceptClick(e: MouseEvent<HTMLAnchorElement>): boolean {\n return (\n !e.defaultPrevented &&\n e.button === 0 &&\n !e.metaKey &&\n !e.ctrlKey &&\n !e.shiftKey &&\n !e.altKey\n );\n}\n\n/**\n * How long a pointer has to settle on a link before it prefetches.\n *\n * A pointer crossing a nav bar enters every link on the way, and each one used\n * to fire a request immediately — enough to fill the browser's per-origin\n * connection limit with pages the user never meant to visit. Waiting is close\n * to free: the prefetch only has to beat the click, and a click that follows a\n * hover this short would not have had its payload back anyway.\n */\nconst HOVER_PREFETCH_DELAY_MS = 100;\n\nexport default function Link<H extends Route>({\n href: path,\n search,\n prefetch: prefetchProp = \"hover\",\n cacheFor,\n replace = false,\n preserveScroll = false,\n children,\n onClick,\n onMouseEnter,\n onMouseLeave,\n ...rest\n}: LinkProps<H>) {\n // The string the anchor and the router both use: the path, with the typed\n // search params serialised onto it.\n const href = (search ? withSearch(path, search as object) : path) as Route;\n const [pending, setPending] = useState(false);\n const hoverTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const prefetchStrategy =\n prefetchProp === true\n ? \"hover\"\n : prefetchProp === false\n ? \"none\"\n : prefetchProp;\n\n const doPrefetch = useCallback(() => {\n if (isExternalUrl(href)) return;\n const fn = (window as any).__rsc_prefetch;\n fn?.(href, cacheFor);\n }, [href, cacheFor]);\n\n // Only useEffect needed: prefetch on mount strategy\n useEffect(() => {\n if (prefetchStrategy === \"mount\") {\n doPrefetch();\n }\n }, [prefetchStrategy, doPrefetch]);\n\n const handleClick = useCallback(\n (e: MouseEvent<HTMLAnchorElement>) => {\n onClick?.(e);\n\n if (e.defaultPrevented) return;\n\n const target = (e.currentTarget as HTMLAnchorElement).target;\n if (target && target !== \"_self\") return;\n if (!shouldInterceptClick(e) || isExternalUrl(href)) return;\n\n // Hash-only links (#section) — let the browser scroll natively\n if (href.startsWith(\"#\")) return;\n\n e.preventDefault();\n setPending(true);\n\n // navigate() returns a Promise — clear pending when it resolves or rejects\n const nav = (window as any).__rsc_navigate;\n const promise = nav?.(href, { replace, preserveScroll });\n promise?.then(\n () => setPending(false),\n () => setPending(false),\n );\n },\n [href, replace, preserveScroll, onClick],\n );\n\n const handleMouseEnter = useCallback(\n (e: MouseEvent<HTMLAnchorElement>) => {\n onMouseEnter?.(e);\n\n if (prefetchStrategy !== \"hover\" && prefetchStrategy !== \"click\") return;\n\n if (hoverTimer.current !== null) clearTimeout(hoverTimer.current);\n\n hoverTimer.current = setTimeout(() => {\n hoverTimer.current = null;\n doPrefetch();\n }, HOVER_PREFETCH_DELAY_MS);\n },\n [prefetchStrategy, doPrefetch, onMouseEnter],\n );\n\n const handleMouseLeave = useCallback(\n (e: MouseEvent<HTMLAnchorElement>) => {\n onMouseLeave?.(e);\n\n // Never fired: the pointer passed over on its way somewhere else.\n if (hoverTimer.current !== null) {\n clearTimeout(hoverTimer.current);\n hoverTimer.current = null;\n }\n\n // Already in flight: give the connection back to whatever the pointer is\n // heading for. A prefetch that has landed is kept — see cancelPrefetch.\n if (isExternalUrl(href)) return;\n (window as any).__rsc_cancel_prefetch?.(href);\n },\n [href, onMouseLeave],\n );\n\n // Touch gets no delay. There is no hovering to disambiguate — a touch is\n // already the start of a tap — and touchstart leads the click by little\n // enough that spending any of it waiting would waste the head start.\n const handleTouchStart = useCallback(() => {\n if (prefetchStrategy === \"hover\" || prefetchStrategy === \"click\") {\n doPrefetch();\n }\n }, [prefetchStrategy, doPrefetch]);\n\n // A link unmounted mid-hover (navigating away) must not prefetch afterwards.\n useEffect(\n () => () => {\n if (hoverTimer.current !== null) clearTimeout(hoverTimer.current);\n },\n [],\n );\n\n return (\n <LinkStatusContext.Provider value={{ pending }}>\n <a\n href={href}\n onClick={handleClick}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n onTouchStart={handleTouchStart}\n data-pending={pending ? \"\" : undefined}\n {...rest}\n >\n {children}\n </a>\n </LinkStatusContext.Provider>\n );\n}\n"]}
|
|
@@ -4,13 +4,23 @@ interface Props {
|
|
|
4
4
|
children: ReactNode;
|
|
5
5
|
/** Shown while the navigation is in flight. Null keeps the space empty. */
|
|
6
6
|
fallback?: ReactNode;
|
|
7
|
+
/**
|
|
8
|
+
* Whether what this boundary wraps is the page on screen. A segment keeps
|
|
9
|
+
* pages alive behind the active one, each under its own boundary, and a
|
|
10
|
+
* redirect caught on a page that is not showing is not performed — it was
|
|
11
|
+
* already performed when it was. Shown again, the boundary renders the
|
|
12
|
+
* page afresh, and a refusal that still stands redirects again.
|
|
13
|
+
*/
|
|
14
|
+
active?: boolean;
|
|
7
15
|
}
|
|
8
16
|
interface State {
|
|
9
17
|
redirecting: boolean;
|
|
18
|
+
wasActive: boolean;
|
|
10
19
|
}
|
|
11
20
|
export declare class RedirectBoundary extends Component<Props, State> {
|
|
12
21
|
state: State;
|
|
13
|
-
static getDerivedStateFromError(error: unknown): State | null;
|
|
22
|
+
static getDerivedStateFromError(error: unknown): Partial<State> | null;
|
|
23
|
+
static getDerivedStateFromProps(props: Props, state: State): Partial<State> | null;
|
|
14
24
|
componentDidCatch(error: unknown, _info: ErrorInfo): void;
|
|
15
25
|
render(): ReactNode;
|
|
16
26
|
}
|
|
@@ -3,7 +3,7 @@ import { Component } from "react";
|
|
|
3
3
|
import { parseRedirectDigest } from "../redirectDigest.js";
|
|
4
4
|
import { visit } from "./router";
|
|
5
5
|
export class RedirectBoundary extends Component {
|
|
6
|
-
state = { redirecting: false };
|
|
6
|
+
state = { redirecting: false, wasActive: this.props.active !== false };
|
|
7
7
|
static getDerivedStateFromError(error) {
|
|
8
8
|
// Reading `digest` rather than the message: React replaces a server
|
|
9
9
|
// error's message in production and transmits the digest either way.
|
|
@@ -11,10 +11,19 @@ export class RedirectBoundary extends Component {
|
|
|
11
11
|
? { redirecting: true }
|
|
12
12
|
: null;
|
|
13
13
|
}
|
|
14
|
+
static getDerivedStateFromProps(props, state) {
|
|
15
|
+
const active = props.active !== false;
|
|
16
|
+
if (active === state.wasActive)
|
|
17
|
+
return null;
|
|
18
|
+
// Revealed again: render the page, not the space left by its redirect.
|
|
19
|
+
return { wasActive: active, redirecting: active ? false : state.redirecting };
|
|
20
|
+
}
|
|
14
21
|
componentDidCatch(error, _info) {
|
|
15
22
|
const target = parseRedirectDigest(error?.digest);
|
|
16
23
|
if (!target)
|
|
17
24
|
throw error;
|
|
25
|
+
if (this.props.active === false)
|
|
26
|
+
return;
|
|
18
27
|
// An SPA navigation, not a location assignment: the layouts above this
|
|
19
28
|
// boundary are already mounted and correct, so replacing the document
|
|
20
29
|
// would throw away state the user can see — including whatever they had
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RedirectBoundary.js","sourceRoot":"","sources":["../../src/js/RedirectBoundary.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAqBb,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"RedirectBoundary.js","sourceRoot":"","sources":["../../src/js/RedirectBoundary.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAqBb,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AAqBjC,MAAM,OAAO,gBAAiB,SAAQ,SAAuB;IAC3D,KAAK,GAAU,EAAE,WAAW,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,KAAK,EAAE,CAAC;IAE9E,MAAM,CAAC,wBAAwB,CAAC,KAAc;QAC5C,oEAAoE;QACpE,qEAAqE;QACrE,OAAO,mBAAmB,CAAE,KAA8B,EAAE,MAAM,CAAC;YACjE,CAAC,CAAC,EAAE,WAAW,EAAE,IAAI,EAAE;YACvB,CAAC,CAAC,IAAI,CAAC;IACX,CAAC;IAED,MAAM,CAAC,wBAAwB,CAAC,KAAY,EAAE,KAAY;QACxD,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,KAAK,KAAK,CAAC;QAEtC,IAAI,MAAM,KAAK,KAAK,CAAC,SAAS;YAAE,OAAO,IAAI,CAAC;QAE5C,uEAAuE;QACvE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;IAChF,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,KAAgB;QAChD,MAAM,MAAM,GAAG,mBAAmB,CAAE,KAA8B,EAAE,MAAM,CAAC,CAAC;QAE5E,IAAI,CAAC,MAAM;YAAE,MAAM,KAAK,CAAC;QACzB,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,KAAK;YAAE,OAAO;QAExC,uEAAuE;QACvE,sEAAsE;QACtE,wEAAwE;QACxE,wDAAwD;QACxD,EAAE;QACF,uEAAuE;QACvE,uEAAuE;QACvE,uEAAuE;QACvE,KAAK,KAAK,CAAC,MAAM,CAAC,QAAiB,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1D,CAAC;IAED,MAAM;QACJ,IAAI,IAAI,CAAC,KAAK,CAAC,WAAW;YAAE,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,IAAI,IAAI,CAAC;QAE/D,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;IAC7B,CAAC;CACF","sourcesContent":["\"use client\";\n\n/**\n * Performs a redirect that was decided too late to be a status code.\n *\n * A redirect thrown above every Suspense boundary is answered by the host\n * before anything is written — the browser never sees this page, and this\n * component is never involved. One thrown inside a boundary arrives after the\n * shell, as an error carrying the destination in its digest, and this is what\n * turns that back into a navigation.\n *\n * An error boundary rather than a hook because that is the only thing React\n * offers for \"a child threw\": the throw happens in a server component whose\n * error is serialised into the payload, and it surfaces here when the client\n * renders it.\n *\n * Anything that is not a redirect is rethrown untouched, so an app's own error\n * boundaries still see the errors they exist for.\n */\n\nimport type { Route } from \"../routes.js\";\nimport { Component } from \"react\";\nimport type { ErrorInfo, ReactNode } from \"react\";\nimport { parseRedirectDigest } from \"../redirectDigest.js\";\nimport { visit } from \"./router\";\n\ninterface Props {\n children: ReactNode;\n /** Shown while the navigation is in flight. Null keeps the space empty. */\n fallback?: ReactNode;\n /**\n * Whether what this boundary wraps is the page on screen. A segment keeps\n * pages alive behind the active one, each under its own boundary, and a\n * redirect caught on a page that is not showing is not performed — it was\n * already performed when it was. Shown again, the boundary renders the\n * page afresh, and a refusal that still stands redirects again.\n */\n active?: boolean;\n}\n\ninterface State {\n redirecting: boolean;\n wasActive: boolean;\n}\n\nexport class RedirectBoundary extends Component<Props, State> {\n state: State = { redirecting: false, wasActive: this.props.active !== false };\n\n static getDerivedStateFromError(error: unknown): Partial<State> | null {\n // Reading `digest` rather than the message: React replaces a server\n // error's message in production and transmits the digest either way.\n return parseRedirectDigest((error as { digest?: unknown })?.digest)\n ? { redirecting: true }\n : null;\n }\n\n static getDerivedStateFromProps(props: Props, state: State): Partial<State> | null {\n const active = props.active !== false;\n\n if (active === state.wasActive) return null;\n\n // Revealed again: render the page, not the space left by its redirect.\n return { wasActive: active, redirecting: active ? false : state.redirecting };\n }\n\n componentDidCatch(error: unknown, _info: ErrorInfo): void {\n const target = parseRedirectDigest((error as { digest?: unknown })?.digest);\n\n if (!target) throw error;\n if (this.props.active === false) return;\n\n // An SPA navigation, not a location assignment: the layouts above this\n // boundary are already mounted and correct, so replacing the document\n // would throw away state the user can see — including whatever they had\n // typed into a page that is only being redirected past.\n //\n // replace, because the url being left never became a page the user was\n // on; leaving a history entry for it means Back returns to a redirect.\n // The server chose this, so it is not one of the app's authored hrefs.\n void visit(target.location as Route, { replace: true });\n }\n\n render(): ReactNode {\n if (this.state.redirecting) return this.props.fallback ?? null;\n\n return this.props.children;\n }\n}\n"]}
|
|
@@ -28,9 +28,13 @@ interface State {
|
|
|
28
28
|
}
|
|
29
29
|
export declare class RouteErrorBoundary extends Component<Props, State> {
|
|
30
30
|
state: State;
|
|
31
|
-
static getDerivedStateFromError(error: Error
|
|
31
|
+
static getDerivedStateFromError(error: Error & {
|
|
32
|
+
digest?: string;
|
|
33
|
+
}): Partial<State> | null;
|
|
32
34
|
static getDerivedStateFromProps(props: Props, state: State): Partial<State> | null;
|
|
33
|
-
componentDidCatch(error: Error
|
|
35
|
+
componentDidCatch(error: Error & {
|
|
36
|
+
digest?: string;
|
|
37
|
+
}): void;
|
|
34
38
|
render(): ReactNode;
|
|
35
39
|
}
|
|
36
40
|
export {};
|
|
@@ -10,9 +10,16 @@
|
|
|
10
10
|
// first, so the nearest file to the failure is the one that answers — the same
|
|
11
11
|
// rule loading.tsx follows.
|
|
12
12
|
import { Component, createElement } from 'react';
|
|
13
|
+
import { parseRedirectDigest } from '../redirectDigest.js';
|
|
13
14
|
export class RouteErrorBoundary extends Component {
|
|
14
15
|
state = { error: null, from: '' };
|
|
15
16
|
static getDerivedStateFromError(error) {
|
|
17
|
+
// A redirect decided inside a Suspense boundary arrives as an error with
|
|
18
|
+
// the destination in its digest. It is not a failure for an error.tsx to
|
|
19
|
+
// show - it is the page's answer - and the boundary that performs it sits
|
|
20
|
+
// above this one. Left alone here; componentDidCatch hands it up.
|
|
21
|
+
if (parseRedirectDigest(error?.digest))
|
|
22
|
+
return null;
|
|
16
23
|
return { error };
|
|
17
24
|
}
|
|
18
25
|
static getDerivedStateFromProps(props, state) {
|
|
@@ -26,6 +33,9 @@ export class RouteErrorBoundary extends Component {
|
|
|
26
33
|
return null;
|
|
27
34
|
}
|
|
28
35
|
componentDidCatch(error) {
|
|
36
|
+
// Rethrown so the RedirectBoundary above turns it back into a navigation.
|
|
37
|
+
if (parseRedirectDigest(error?.digest))
|
|
38
|
+
throw error;
|
|
29
39
|
// Reported as well as rendered. A boundary that swallows the error leaves
|
|
30
40
|
// nothing in the console for whoever has to find the cause.
|
|
31
41
|
console.error(error);
|