fondu 0.15.0 → 0.16.0

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.
@@ -42,10 +42,11 @@ export type Rendered = ReadableStream<Uint8Array> & {
42
42
  };
43
43
  /**
44
44
  * @internal the server render of a page, streamed: the tags its components hoist (`<title>`…) first, then
45
- * `<div id="app">`, then `after` (markup of the document's, in the shell: right after the page), then what the
46
- * Suspense boundaries that were not ready add. Rejects if the shell fails to render.
45
+ * `<div id="app">`, then what the Suspense boundaries that were not ready add. Rejects if the shell fails to render.
46
+ * The tree is the browser's (`hydrateRoot(#app, <App/>)`): `<div id="app"><App/></div>` and nothing beside it, as
47
+ * `useId()` is the position in the tree (a sibling of the page forks it: every id would differ).
47
48
  */
48
- export declare function renderPage(page: Page, render: (element: ReactElement) => Promise<Rendered>, after?: ReactElement): Promise<Rendered>;
49
+ export declare function renderPage(page: Page, render: (element: ReactElement) => Promise<Rendered>): Promise<Rendered>;
49
50
  /** a form's field errors, as a page gets them (its `errors` prop): field name → message */
50
51
  export type Errors = Record<string, string>;
51
52
  /** the page on screen: its props (the shared ones, `errors`), its URL, its flash data */
@@ -1,4 +1,4 @@
1
- import { Component, createContext, createElement, Fragment, useContext, useLayoutEffect, useState, useSyncExternalStore, } from 'react';
1
+ import { Component, createContext, createElement, useContext, useLayoutEffect, useState, useSyncExternalStore, } from 'react';
2
2
  import { flushSync } from 'react-dom';
3
3
  import { createRoot, hydrateRoot } from 'react-dom/client';
4
4
  import { decoded, layoutsOf, pageId, routePatterns } from '../paths.js';
@@ -170,12 +170,13 @@ function start(settings) {
170
170
  }
171
171
  /**
172
172
  * @internal the server render of a page, streamed: the tags its components hoist (`<title>`…) first, then
173
- * `<div id="app">`, then `after` (markup of the document's, in the shell: right after the page), then what the
174
- * Suspense boundaries that were not ready add. Rejects if the shell fails to render.
173
+ * `<div id="app">`, then what the Suspense boundaries that were not ready add. Rejects if the shell fails to render.
174
+ * The tree is the browser's (`hydrateRoot(#app, <App/>)`): `<div id="app"><App/></div>` and nothing beside it, as
175
+ * `useId()` is the position in the tree (a sibling of the page forks it: every id would differ).
175
176
  */
176
- export async function renderPage(page, render, after) {
177
+ export async function renderPage(page, render) {
177
178
  const view = await load(page.component);
178
- return render(createElement(Fragment, null, createElement('div', { id: 'app' }, createElement(App, { initial: { page, view, mounts: 0 } })), after));
179
+ return render(createElement('div', { id: 'app' }, createElement(App, { initial: { page, view, mounts: 0 } })));
179
180
  }
180
181
  /** the page on screen: its props (the shared ones, `errors`), its URL, its flash data */
181
182
  export function usePage() {
@@ -44,10 +44,13 @@ export declare function startNavigation({ initial, show, prerender, pending, pre
44
44
  export declare function loadDocument(href: string): void;
45
45
  /**
46
46
  * `href` visited as a link to it would be: a page of the app in place (a new history entry, or this one's with
47
- * `replace`), anything else as a document
47
+ * `replace`), anything else as a document. `keep`: the answer is shown as `reload()` shows its own, the page keeps
48
+ * its state (a focused input, what was typed) and the scroll position, nothing is announced: a search box that
49
+ * `navigate()`s to its query as it is typed. Another page's component is shown as any navigation's.
48
50
  */
49
- export declare function navigate(href: string, { replace }?: {
51
+ export declare function navigate(href: string, { replace, keep }?: {
50
52
  replace?: boolean;
53
+ keep?: boolean;
51
54
  }): void;
52
55
  /** the page asked for again, its state and the scroll position kept */
53
56
  export declare function again(only?: string[]): void;
@@ -43,11 +43,11 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
43
43
  const headers = () => ({ 'X-Fondu': 'true', ...(version && { 'X-Fondu-Version': version }) });
44
44
  /** where a page's JSON is: its URL, or its file (a prerendered build) */
45
45
  const source = (url) => prerender ? pageDataPath(url.pathname) + url.search : url.pathname + url.search;
46
- // What a link's page answered when asked early (`prerender`), by the URL a navigation would ask: its file (a
47
- // Response, read into memory), or null (no file: 204, its data is asked for at the click, when its loader should
48
- // run). A file runs nothing, so asking early costs the app nothing. Asked once in 30 seconds (TanStack Router's
49
- // default: a deploy in between is found at the click); the click waits for an answer on its way and reads a file
50
- // once, its version checked as for any page object. The last 20
46
+ // What a link's page answered when asked early (`prerender`), by the URL a navigation would ask: its file (the
47
+ // text and the headers, read into memory), or null (no file: 204, its data is asked for at the click, when its
48
+ // loader should run). A file runs nothing, so asking early costs the app nothing. Asked once in 30 seconds
49
+ // (TanStack Router's default: a deploy in between is found at the click); the click waits for an answer on its
50
+ // way, and every click in the 30 seconds uses it, its version checked as for any page object. The last 20
51
51
  const freshFor = 30_000;
52
52
  const prefetched = new Map();
53
53
  const prefetch = (url) => {
@@ -61,7 +61,7 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
61
61
  try {
62
62
  const response = await fetch(key, { headers: { ...headers(), 'X-Fondu-Prefetch': 'true' } });
63
63
  if (response.status === 200 && response.headers.has('X-Fondu'))
64
- return new Response(await response.text(), { headers: response.headers });
64
+ return { body: await response.text(), headers: response.headers };
65
65
  }
66
66
  catch {
67
67
  // offline: asked for again
@@ -174,16 +174,14 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
174
174
  const early = entry ? await entry.answer : null;
175
175
  if (signal.aborted)
176
176
  return;
177
- // a Response is read once; a null stays, so the rests that follow ask nothing
178
- if (early && prefetched.get(from) === entry)
179
- prefetched.delete(from);
180
- const response = early ??
181
- (await fetch(from, {
177
+ const response = early
178
+ ? new Response(early.body, { headers: early.headers })
179
+ : await fetch(from, {
182
180
  method: post ? 'POST' : 'GET',
183
181
  body: options.body,
184
182
  headers: headers(),
185
183
  signal,
186
- }));
184
+ });
187
185
  if (signal.aborted)
188
186
  return;
189
187
  if (post)
@@ -241,7 +239,9 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
241
239
  const errors = Object.keys(page.props.errors ?? {}).length > 0;
242
240
  const asked = url.pathname + url.search;
243
241
  // the kept page's entry: the server's page in its place, its state kept; redirected (signed out), anew
244
- const fresh = shown ? asked !== page.url : !options.keep && !(same && errors);
242
+ // kept: the same component answers (another one mounts anew, and is scrolled to the top as a navigation's)
243
+ const stay = options.keep && page.component === on.component;
244
+ const fresh = shown ? asked !== page.url : !stay && !(same && errors);
245
245
  // the page stays (reload(), Back's, a form's answer): what it asked for isn't taken away while it is asked again
246
246
  if (!fresh && page.deferred)
247
247
  for (const name of page.deferred)
@@ -268,10 +268,10 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
268
268
  ask(page.deferred);
269
269
  if (shown && !fresh)
270
270
  return;
271
- if (!options.keep)
271
+ if (!stay)
272
272
  announce();
273
- // a page asked for again stays where it is: reload(), a form's answer at its URL
274
- if (options.keep || same)
273
+ // a page asked for again stays where it is: reload(), navigate() with `keep`, a form's answer at its URL
274
+ if (stay || same)
275
275
  return;
276
276
  // at once, the page in the DOM (show() renders it synchronously): no frame drawn where it doesn't belong
277
277
  restore(options.history === 'none' ? options.scroll : null, url.hash);
@@ -597,14 +597,16 @@ export function loadDocument(href) {
597
597
  }
598
598
  /**
599
599
  * `href` visited as a link to it would be: a page of the app in place (a new history entry, or this one's with
600
- * `replace`), anything else as a document
600
+ * `replace`), anything else as a document. `keep`: the answer is shown as `reload()` shows its own, the page keeps
601
+ * its state (a focused input, what was typed) and the scroll position, nothing is announced: a search box that
602
+ * `navigate()`s to its query as it is typed. Another page's component is shown as any navigation's.
601
603
  */
602
- export function navigate(href, { replace = false } = {}) {
604
+ export function navigate(href, { replace = false, keep = false } = {}) {
603
605
  const url = new URL(href, location.href);
604
606
  const here = url.pathname + url.search === location.pathname + location.search;
605
607
  if (!visit || url.origin !== location.origin || !isAppPage?.(url.pathname) || (here && url.hash))
606
608
  return replace ? location.replace(url.href) : location.assign(url.href); // a #fragment of this page: the browser's
607
- visit(url.href, { history: replace || url.href === location.href ? 'replace' : 'push' });
609
+ visit(url.href, { history: replace || url.href === location.href ? 'replace' : 'push', keep });
608
610
  }
609
611
  /** the page asked for again, its state and the scroll position kept */
610
612
  export function again(only) {
@@ -1,5 +1,5 @@
1
1
  import type { Context, MiddlewareHandler } from 'hono';
2
- import { type ReactElement } from 'react';
2
+ import type { ReactElement } from 'react';
3
3
  import type { Page } from '../client/navigation.js';
4
4
  /**
5
5
  * The HTML document around a page: `{head}` and `{body}` (in JSX, or `${head}` in a string) are where the page goes.
@@ -1,4 +1,3 @@
1
- import { createElement } from 'react';
2
1
  import { assetTags } from 'virtual:fondu/assets';
3
2
  import { renderMarkup, renderPage } from 'virtual:fondu/ssr';
4
3
  import { SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
@@ -42,6 +41,14 @@ async function shell(template, c, nonce) {
42
41
  return html;
43
42
  return html.replace(/<script\b(?![^>]*\s(?:src|nonce)=)/gi, `<script nonce="${nonce}"`);
44
43
  }
44
+ let shellEndReported = false;
45
+ /** once per process: every request would say the same */
46
+ function shellEndLost() {
47
+ if (shellEndReported)
48
+ return;
49
+ shellEndReported = true;
50
+ console.error("[fondu] the end of the page's shell was not found in react-dom's output (bootstrapScriptContent): the document was sent whole, without its scroll script. Is react-dom a version Fondu supports?");
51
+ }
45
52
  /**
46
53
  * The document, streamed. First: the template's start, the stylesheets and the client's tags, the tags the page hoists
47
54
  * (React writes them before the page), the page data and the page's shell. Then what React adds as the Suspense
@@ -59,6 +66,8 @@ export async function renderDocument(c, page, whole = false) {
59
66
  if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
60
67
  throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
61
68
  let ssr = null;
69
+ // per request: nothing the page renders can be it
70
+ const marker = crypto.randomUUID();
62
71
  // what fails in a boundary is for the browser to render, and is logged. The shell's failure is logged below, once:
63
72
  // React reports it to `onError` too, so what it reports is held until the shell is known to be there
64
73
  const pending = [];
@@ -68,10 +77,14 @@ export async function renderDocument(c, page, whole = false) {
68
77
  // a HEAD: Hono drops its body without cancelling it, so React would keep rendering for nothing
69
78
  if (renderPage && !browserOnly.has(c) && c.req.method !== 'HEAD') {
70
79
  // the page as the browser gets it, through JSON (a Date a string): the markup is the same on both sides
71
- const stream = await renderPage(JSON.parse(JSON.stringify(page)), { nonce, onError: (error) => (live ? late(error) : void pending.push(error)) },
72
- // the position back for a page rendered here (one rendered in the browser has nothing to scroll yet): in the
73
- // shell, right after the page, before what the boundaries add
74
- createElement('script', { nonce, dangerouslySetInnerHTML: { __html: restoreScroll } }));
80
+ const stream = await renderPage(JSON.parse(JSON.stringify(page)), {
81
+ nonce,
82
+ onError: (error) => (live ? late(error) : void pending.push(error)),
83
+ // React writes this as a script right after the shell, before what the boundaries add: where `restoreScroll`
84
+ // goes. Not as React's own script (it adds an `id`, and follows its `$RT` one), and not as a sibling of the
85
+ // page in the tree: the page alone is the browser's tree (`useId()`)
86
+ bootstrapScriptContent: marker,
87
+ });
75
88
  if (whole)
76
89
  await stream.allReady;
77
90
  ssr = stream.pipeThrough(new TextDecoderStream());
@@ -97,21 +110,59 @@ export async function renderDocument(c, page, whole = false) {
97
110
  const start = top + tags.replace(/<link rel="stylesheet"[^>]*>/g, '');
98
111
  if (!ssr)
99
112
  return start + between + data + '<div id="app"></div>' + after;
100
- // React's own: the tags the page hoists, then the page (`<div id="app"`), found across chunks
113
+ // React's own: the tags the page hoists, the page (`<div id="app"`), and the script of `marker`, the end of the
114
+ // shell (React writes the shell in as many chunks as it needs, so no chunk is its end): found across chunks.
115
+ // This relies on React writing `bootstrapScriptContent` as one inline `<script>` right after the shell. A React
116
+ // that writes it differently is reported (`shellEndLost`), not silently streamed without the scroll script.
117
+ // Only what is new is searched: from where the last search ended, less the marker's length (a marker cut between
118
+ // two chunks), so the work is linear in the shell, not quadratic
101
119
  const reader = ssr.getReader();
120
+ const closing = '</script>';
102
121
  let text = '';
103
- let at = -1;
104
- while (at < 0) {
122
+ let searchedTo = 0;
123
+ let open = -1;
124
+ let close = -1;
125
+ for (;;) {
105
126
  const { done, value } = await reader.read();
106
127
  if (done)
107
128
  break;
108
129
  text += value;
109
- at = text.indexOf('<div id="app"');
130
+ let from = Math.max(0, searchedTo - marker.length);
131
+ let hit = text.indexOf(marker, from);
132
+ while (hit >= 0) {
133
+ // `<script …>marker</script>`, and nothing else
134
+ const tagAt = text.lastIndexOf('<script', hit);
135
+ if (tagAt >= 0 && /^<script[^>]*>$/.test(text.slice(tagAt, hit))) {
136
+ const markerEnd = hit + marker.length;
137
+ // the closing tag may still be in the next chunk
138
+ if (text.length < markerEnd + closing.length)
139
+ break;
140
+ if (text.startsWith(closing, markerEnd)) {
141
+ open = tagAt;
142
+ close = markerEnd + closing.length;
143
+ }
144
+ }
145
+ if (close >= 0)
146
+ break;
147
+ from = hit + marker.length;
148
+ hit = text.indexOf(marker, from);
149
+ }
150
+ if (close >= 0)
151
+ break;
152
+ // a marker found but not complete yet is searched for again, from where it is
153
+ searchedTo = hit >= 0 ? hit : text.length;
110
154
  }
155
+ if (close < 0)
156
+ shellEndLost();
157
+ const at = Math.max(text.indexOf('<div id="app"'), 0);
158
+ const script = `<script${nonce ? ` nonce="${nonce}"` : ''}>${restoreScroll}</script>`;
159
+ // the position back for a page rendered here (one rendered in the browser has nothing to scroll yet): in the
160
+ // shell, right after the page, before what the boundaries add
161
+ const streamed = close < 0 ? text : text.slice(0, open) + script + text.slice(close);
111
162
  const out = new TextEncoder();
112
163
  return new ReadableStream({
113
164
  start(controller) {
114
- controller.enqueue(out.encode(start + text.slice(0, at) + between + data + text.slice(at)));
165
+ controller.enqueue(out.encode(start + streamed.slice(0, at) + between + data + streamed.slice(at)));
115
166
  },
116
167
  async pull(controller) {
117
168
  const { done, value } = await reader.read();
package/dist/virtual.d.ts CHANGED
@@ -12,8 +12,11 @@ declare module 'virtual:fondu/ssr' {
12
12
  export const renderPage:
13
13
  | ((
14
14
  page: import('./client/navigation.js').Page,
15
- options: { nonce?: string; onError?: (error: unknown) => void },
16
- after?: import('react').ReactElement,
15
+ options: {
16
+ nonce?: string
17
+ onError?: (error: unknown) => void
18
+ bootstrapScriptContent?: string
19
+ },
17
20
  ) => Promise<import('./client/app.js').Rendered>)
18
21
  | null
19
22
  /** React's static markup of a JSX document (`react-dom/server`'s `renderToStaticMarkup`) */
@@ -473,7 +473,7 @@ function core(options) {
473
473
  `import '${V.entry}'`,
474
474
  `import { renderToReadableStream, renderToStaticMarkup } from 'react-dom/server'`,
475
475
  `import { renderPage as render } from 'fondu/client'`,
476
- `export const renderPage = (page, options, after) => render(page, (el) => renderToReadableStream(el, options), after)`,
476
+ `export const renderPage = (page, options) => render(page, (el) => renderToReadableStream(el, options))`,
477
477
  `export { renderToStaticMarkup as renderMarkup }`,
478
478
  ].join('\n');
479
479
  if (id === resolved(V.assets))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "A small meta-framework for full-stack React apps, built on Hono and Vite. It runs on Bun, Cloudflare Workers and Node.",
5
5
  "keywords": [
6
6
  "bun",