fondu 0.16.2 → 0.17.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.
@@ -49,7 +49,10 @@ export type Rendered = ReadableStream<Uint8Array> & {
49
49
  export declare function renderPage(page: Page, render: (element: ReactElement) => Promise<Rendered>): Promise<Rendered>;
50
50
  /** a form's field errors, as a page gets them (its `errors` prop): field name → message */
51
51
  export type Errors = Record<string, string>;
52
- /** the page on screen: its props (the shared ones, `errors`), its URL, its flash data */
52
+ /**
53
+ * The page on screen: its props (the shared ones, `errors`), its URL (path and query: it follows a shallow
54
+ * navigation, and the props do not), its flash data
55
+ */
53
56
  export declare function usePage<P = Shared>(): {
54
57
  component: string;
55
58
  props: P & {
@@ -198,7 +198,10 @@ export async function renderPage(page, render) {
198
198
  const view = await load(page.component);
199
199
  return render(createElement('div', { id: 'app' }, createElement(App, { initial: { page, view, mounts: 0 } })));
200
200
  }
201
- /** the page on screen: its props (the shared ones, `errors`), its URL, its flash data */
201
+ /**
202
+ * The page on screen: its props (the shared ones, `errors`), its URL (path and query: it follows a shallow
203
+ * navigation, and the props do not), its flash data
204
+ */
202
205
  export function usePage() {
203
206
  const page = useContext(PageContext);
204
207
  if (!page)
@@ -47,11 +47,30 @@ export declare function loadDocument(href: string): void;
47
47
  * `replace`), anything else as a document. `keep`: the answer is shown as `reload()` shows its own, the page keeps
48
48
  * its state (a focused input, what was typed) and the scroll position, nothing is announced: a search box that
49
49
  * `navigate()`s to its query as it is typed. Another page's component is shown as any navigation's.
50
+ *
51
+ * `shallow`: the query and #fragment of the page on the screen change, and nothing is asked for: the page keeps its
52
+ * props, its state and the scroll position, `usePage().url` follows, and a changed #fragment fires `hashchange` (the
53
+ * browser doesn't scroll to it, and `:target` stays as it was). Only this page's own pathname; another page throws.
54
+ * Not with `keep`: a shallow navigation keeps the page anyway. Before the app has started, a document load. While a
55
+ * visit is being put on the screen (its URL is in the history, its page is not there yet), a normal navigation.
50
56
  */
51
- export declare function navigate(href: string, { replace, keep }?: {
57
+ export declare function navigate(href: string, options?: {
52
58
  replace?: boolean;
53
59
  keep?: boolean;
60
+ shallow?: false;
61
+ } | {
62
+ replace?: boolean;
63
+ keep?: never;
64
+ shallow: true;
54
65
  }): void;
66
+ /**
67
+ * Closes what `navigate(…, { shallow: true })` or a `data-shallow` link opened (a dialog, a drawer), one step. An
68
+ * entry that was pushed by a shallow navigation, from the entry below it: Back, to the page as it was. Any other (a
69
+ * document loaded at this URL, a reload, an entry replaced…): `to` in its place, a shallow navigation with `replace`
70
+ * (`to` is a URL of this page, as that takes it). Never leaves the page, and never adds an entry. A second call before
71
+ * the first one's Back has landed does nothing: a double click closes one level.
72
+ */
73
+ export declare function closeShallow(to: string): void;
55
74
  /** the page asked for again, its state and the scroll position kept */
56
75
  export declare function again(only?: string[]): void;
57
76
  export {};
@@ -1,6 +1,10 @@
1
1
  import { crlf } from '../form.js';
2
2
  import { pageDataPath, SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
3
3
  let visit;
4
+ /** the page on the screen at another URL of its own, nothing asked for (`navigate(url, { shallow: true })`) */
5
+ let shallowTo;
6
+ /** the URL of the page on the screen (its path and query): not `location`'s while a visit is being put on the screen */
7
+ let shownUrl;
4
8
  /** the props of the page on the screen asked for, quietly (`defer()`, `reload({ only })`) */
5
9
  let ask;
6
10
  /** a URL path is one of the app's pages (the client's, once it has started) */
@@ -29,6 +33,12 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
29
33
  // the page on the screen, and how many were put there (an answer for another is dropped)
30
34
  let on = initial;
31
35
  let shows = 0;
36
+ // The history entries (their keys) that show the page on the screen, at URLs of their own: the one that got it, the
37
+ // ones shallow navigations added, the browser's own #fragment entries. Back and Forward between them ask for
38
+ // nothing. A page put on the screen is its entry's alone: the others are normal entries again (Back asks)
39
+ let group = new Set();
40
+ // the URL the page's props are the loader's answer for: `on.url` changes with a shallow navigation, this does not
41
+ let answered = initial.url;
32
42
  const asking = new Set();
33
43
  const put = async (page, fresh, stale) => {
34
44
  await show(page, fresh, stale);
@@ -36,10 +46,13 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
36
46
  return;
37
47
  on = page;
38
48
  shows++;
49
+ group = new Set([scroll.key()]);
50
+ answered = page.url;
39
51
  // the page they were for is gone
40
52
  for (const quiet of asking)
41
53
  quiet.abort();
42
54
  };
55
+ shownUrl = () => new URL(on.url, location.href);
43
56
  const headers = () => ({ 'X-Fondu': 'true', ...(version && { 'X-Fondu-Version': version }) });
44
57
  /** where a page's JSON is: its URL, or its file (a prerendered build) */
45
58
  const source = (url) => prerender ? pageDataPath(url.pathname) + url.search : url.pathname + url.search;
@@ -90,7 +103,7 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
90
103
  const absent = names.filter((n) => !Object.hasOwn(page.props, n) && !page.deferred?.includes(n));
91
104
  if (absent.length)
92
105
  void show((on = { ...page, deferred: [...(page.deferred ?? []), ...absent] }), false, () => shows !== at);
93
- let got = {};
106
+ let got;
94
107
  try {
95
108
  const response = await fetch(source(new URL(page.url, location.href)), {
96
109
  headers: {
@@ -108,12 +121,21 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
108
121
  asking.delete(controller);
109
122
  if (controller.signal.aborted || shows !== at)
110
123
  return;
124
+ // asked at the URL of a shallow entry, which the page has left since: not its answer
125
+ if (page.url !== answered && page.url !== on.url)
126
+ return;
111
127
  const next = {
112
128
  ...on,
113
129
  props: { ...on.props, ...got },
114
130
  deferred: on.deferred?.filter((n) => !names.includes(n)),
115
131
  };
116
132
  on = next; // before the module is awaited: another answer merges into this one
133
+ // asked at the URL of a shallow entry, not at the one the page was loaded at: an answer of its own, and this
134
+ // entry's alone (those asked before the shallow navigation are the loader's answer still)
135
+ if (got && page.url !== answered) {
136
+ group = new Set([scroll.key()]);
137
+ answered = page.url;
138
+ }
117
139
  await show(next, false, () => shows !== at);
118
140
  if (shows === at)
119
141
  keep(next);
@@ -238,6 +260,9 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
238
260
  const same = post && page.url === here;
239
261
  const errors = Object.keys(page.props.errors ?? {}).length > 0;
240
262
  const asked = url.pathname + url.search;
263
+ // asked for the entry on the screen, which a shallow navigation has since left for another URL: not its answer
264
+ if (options.history === 'none' && location.pathname + location.search !== asked)
265
+ return;
241
266
  // the kept page's entry: the server's page in its place, its state kept; redirected (signed out), anew
242
267
  // kept: the same component answers (another one mounts anew, and is scrolled to the top as a navigation's)
243
268
  const stay = options.keep && page.component === on.component;
@@ -297,7 +322,46 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
297
322
  }
298
323
  })();
299
324
  };
300
- /** the URL of a link the client may follow itself: same origin, this window, no download */
325
+ /**
326
+ * The page on the screen at a URL of its own (its query, its #fragment), nothing asked for: a new history entry, or
327
+ * this one's. The props stay the loader's answer for the URL that got the page; its `url` follows the address bar.
328
+ */
329
+ shallowTo = (url, replace) => {
330
+ // A visit whose URL is in the history already, its page not on the screen yet (its modules load): no URL of the
331
+ // page on the screen to change. A normal navigation, which supersedes that visit as any does
332
+ if (location.pathname + location.search !== on.url)
333
+ return navigate(url.href, { replace });
334
+ current?.abort(); // a visit still waiting for its answer: given up, as any newer navigation does
335
+ const was = location.href;
336
+ scroll.save();
337
+ const before = scroll.key();
338
+ replace ||= url.href === location.href;
339
+ scroll.write(url.href, replace, true);
340
+ scroll.commit();
341
+ scroll.save(); // the new entry starts where the page is
342
+ if (replace)
343
+ group.delete(before);
344
+ group.add(scroll.key());
345
+ settle(true);
346
+ // the browser fires no `hashchange` for pushState
347
+ if (new URL(was).hash !== url.hash)
348
+ dispatchEvent(new HashChangeEvent('hashchange', { oldURL: was, newURL: url.href }));
349
+ };
350
+ /**
351
+ * The page on the screen follows the address bar (its `url`; a shallow navigation also drops its flash and errors,
352
+ * which belonged to the answer before it), and is kept for the entry
353
+ */
354
+ const settle = (fresh) => {
355
+ const at = shows;
356
+ on = {
357
+ ...on,
358
+ url: location.pathname + location.search,
359
+ ...(fresh && { flash: {}, props: { ...on.props, errors: {} } }),
360
+ };
361
+ void show(on, false, () => shows !== at);
362
+ keep(on);
363
+ };
364
+ /** a link the client may follow itself (same origin, this window, no download): its URL; `soft`, a shallow one */
301
365
  const linkOf = (target) => {
302
366
  const link = target?.closest?.('a[href]');
303
367
  if (!(link instanceof HTMLAnchorElement))
@@ -307,7 +371,11 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
307
371
  const url = new URL(link.href);
308
372
  if (url.origin !== location.origin || !isWebUrl(url.href))
309
373
  return;
310
- return url;
374
+ // `data-shallow`: for the page on the screen's own URL (its query, its #fragment) a shallow navigation
375
+ return {
376
+ url,
377
+ soft: link.hasAttribute('data-shallow') && url.pathname === shownUrl().pathname,
378
+ };
311
379
  };
312
380
  // links: a plain click on a same-origin <a href>, which the page let through
313
381
  document.addEventListener('click', (event) => {
@@ -315,9 +383,14 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
315
383
  return;
316
384
  if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
317
385
  return;
318
- const url = linkOf(event.target);
319
- if (!url)
386
+ const link = linkOf(event.target);
387
+ if (!link)
320
388
  return;
389
+ const { url } = link;
390
+ if (link.soft) {
391
+ event.preventDefault();
392
+ return shallowTo(url, false);
393
+ }
321
394
  // a #fragment of this page: the browser scrolls to it (the position left saved for Back)
322
395
  if (url.pathname + url.search === location.pathname + location.search && url.hash) {
323
396
  scroll.save();
@@ -337,21 +410,21 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
337
410
  const RESTING = 80; // milliseconds the pointer rests
338
411
  let timer;
339
412
  document.addEventListener('mouseover', (event) => {
340
- const url = linkOf(event.target);
413
+ const link = linkOf(event.target);
341
414
  clearTimeout(timer);
342
- if (url && isPage(url.pathname))
415
+ if (link && !link.soft && isPage(link.url.pathname))
343
416
  timer = setTimeout(() => {
344
- preload(url.pathname);
345
- void prefetch(url);
417
+ preload(link.url.pathname);
418
+ void prefetch(link.url);
346
419
  }, RESTING);
347
420
  });
348
421
  document.addEventListener('mouseout', () => clearTimeout(timer));
349
422
  document.addEventListener('touchstart', (event) => {
350
- const url = linkOf(event.target);
351
- if (!url || !isPage(url.pathname))
423
+ const link = linkOf(event.target);
424
+ if (!link || link.soft || !isPage(link.url.pathname))
352
425
  return;
353
- preload(url.pathname);
354
- void prefetch(url);
426
+ preload(link.url.pathname);
427
+ void prefetch(link.url);
355
428
  }, { passive: true });
356
429
  }
357
430
  // forms: GET and POST to this origin, in this window, which the page let through
@@ -388,8 +461,19 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
388
461
  });
389
462
  // Back and Forward: the entry's page, where it was scrolled
390
463
  window.addEventListener('popstate', (event) => {
464
+ closing = false;
391
465
  const popped = scroll.pop(event.state);
466
+ // an entry that shows the page on the screen, at a URL of its own: its URL, nothing asked for, the scroll where it
467
+ // is. A visit on its way is given up, as any Back does
468
+ if (!popped.fragment && popped.key && group.has(popped.key)) {
469
+ current?.abort();
470
+ pending(null);
471
+ scroll.commit();
472
+ return settle(false);
473
+ }
392
474
  if (popped.fragment) {
475
+ if (!popped.key)
476
+ group.add(scroll.key()); // an entry the browser made (no key yet): of this page
393
477
  // a #fragment that names no element (a dialog's `#settings/account`) leaves the page where it is, as the browser does
394
478
  if (!popped.position && location.hash && !fragmentTarget(location.hash.slice(1)))
395
479
  return;
@@ -406,20 +490,40 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
406
490
  // manual; Firefox, a #fragment), and over the page's own (Firefox, at load, a page rendered in the browser at 0)
407
491
  window.addEventListener('pagehide', scroll.save);
408
492
  // the browser's own #fragment navigations: the entry gets its key
409
- window.addEventListener('hashchange', scroll.commit);
493
+ window.addEventListener('hashchange', () => {
494
+ // an entry the browser made (no key yet; a popstate may have given it one): of the page on the screen
495
+ if (scroll.commit())
496
+ group.add(scroll.key());
497
+ });
498
+ addEventListener('pageshow', () => (closing = false));
410
499
  // a page rendered on the server is where it belongs already, before its first paint: at its entry's position (its
411
500
  // document's script: a reload, Back from another site), else at its #fragment (the browser). One rendered here has
412
501
  // its content only now: its entry's position, or its #fragment's target
413
502
  const position = scroll.start();
503
+ group.add(scroll.key());
414
504
  if (!hydrated) {
415
505
  restore(position, location.hash, true);
416
506
  if (position)
417
507
  holdUntilLoaded(position);
418
508
  }
419
509
  keep(initial);
510
+ // A prerendered page's file is made without a query, and the document it hydrates is too: once it is hydrated, its URL
511
+ // is the browser's (a state the query holds works at a direct load; its loader never saw the query). A page
512
+ // rendered per request has its query in its URL already
513
+ if (location.pathname + location.search !== on.url)
514
+ settle(false);
420
515
  if (initial.deferred?.length)
421
516
  ask(initial.deferred);
422
517
  }
518
+ /**
519
+ * What this client adds to `history.state` (beside the scroll key, `paths.ts`), and what outlives a deploy: an entry's
520
+ * own state, read by the build that is running when the browser comes back to it.
521
+ * `__fondu_shallow: true`: the entry was pushed by a shallow navigation, from the entry below it, which showed the
522
+ * same page. `closeShallow()` goes back (one step) from such an entry; any other it replaces in place.
523
+ */
524
+ const SHALLOW = '__fondu_shallow';
525
+ /** `closeShallow()` has gone back, and the browser has not landed yet: a second call waits (until the entry is there) */
526
+ let closing = false;
423
527
  /**
424
528
  * Scroll positions, per history entry (a key in `history.state`), in memory and in sessionStorage (a reload, a page
425
529
  * of another site and back): the browser's restoration is off. Each belongs to the entry on the screen, even once
@@ -474,13 +578,15 @@ function scrollPositions() {
474
578
  positions.set(key, { x: scrollX, y: scrollY });
475
579
  });
476
580
  }, { passive: true });
477
- /** this entry's key, given one if it has none (a first visit, a #fragment the browser navigated to) */
581
+ /** this entry's key, given one if it has none (a first visit, a #fragment the browser navigated to): true if so */
478
582
  const commit = () => {
479
583
  let key = keyOf(history.state);
584
+ const added = !key;
480
585
  if (!key)
481
586
  history.replaceState({ ...history.state, [KEY]: (key = newKey()) }, '');
482
587
  rendered = key;
483
588
  renderedUrl = location.pathname + location.search;
589
+ return added;
484
590
  };
485
591
  return {
486
592
  save,
@@ -496,9 +602,26 @@ function scrollPositions() {
496
602
  commit();
497
603
  return read(rendered);
498
604
  },
499
- /** the page on the screen, at `url`: a new entry or this one */
500
- write(url, replace) {
501
- const state = { ...(replace ? history.state : {}), [KEY]: newKey() };
605
+ /**
606
+ * The page on the screen, at `url`: a new entry or this one. `shallow`: by a shallow navigation, which marks a
607
+ * new entry (SHALLOW); a replaced entry keeps its state, but another URL, by a navigation that is not
608
+ * shallow, takes the mark away: `closeShallow()` there must not go Back off it.
609
+ */
610
+ write(url, replace, shallow = false) {
611
+ const state = {
612
+ ...(replace ? history.state : {}),
613
+ [KEY]: newKey(),
614
+ };
615
+ if (shallow) {
616
+ if (!replace)
617
+ state[SHALLOW] = true;
618
+ }
619
+ else {
620
+ // the same URL (a form's answer, reload()): the same overlay. Another page: not a shallow entry
621
+ const to = new URL(url, location.href);
622
+ if (to.pathname + to.search !== location.pathname + location.search)
623
+ delete state[SHALLOW];
624
+ }
502
625
  if (replace)
503
626
  history.replaceState(state, '', url);
504
627
  else
@@ -600,14 +723,52 @@ export function loadDocument(href) {
600
723
  * `replace`), anything else as a document. `keep`: the answer is shown as `reload()` shows its own, the page keeps
601
724
  * its state (a focused input, what was typed) and the scroll position, nothing is announced: a search box that
602
725
  * `navigate()`s to its query as it is typed. Another page's component is shown as any navigation's.
726
+ *
727
+ * `shallow`: the query and #fragment of the page on the screen change, and nothing is asked for: the page keeps its
728
+ * props, its state and the scroll position, `usePage().url` follows, and a changed #fragment fires `hashchange` (the
729
+ * browser doesn't scroll to it, and `:target` stays as it was). Only this page's own pathname; another page throws.
730
+ * Not with `keep`: a shallow navigation keeps the page anyway. Before the app has started, a document load. While a
731
+ * visit is being put on the screen (its URL is in the history, its page is not there yet), a normal navigation.
603
732
  */
604
- export function navigate(href, { replace = false, keep = false } = {}) {
605
- const url = new URL(href, location.href);
733
+ export function navigate(href, options = {}) {
734
+ const { replace = false, keep = false, shallow = false } = options;
735
+ if (shallow && keep)
736
+ throw new Error('fondu: a shallow navigation takes no `keep`: the page stays as it is');
737
+ const shown = shownUrl?.();
738
+ // a shallow navigation is relative to the page on the screen, whose URL `location` may have left
739
+ const url = new URL(href, shallow ? (shown ?? location.href) : location.href);
740
+ if (shallow) {
741
+ if (url.origin !== location.origin || url.pathname !== (shown ?? location).pathname)
742
+ throw new Error(`fondu: a shallow navigation stays on this page (its query, its #fragment); ${url.origin === location.origin ? url.pathname : url.href} is another page: leave out \`shallow\``);
743
+ if (shallowTo)
744
+ return shallowTo(url, replace);
745
+ }
606
746
  const here = url.pathname + url.search === location.pathname + location.search;
607
- if (!visit || url.origin !== location.origin || !isAppPage?.(url.pathname) || (here && url.hash))
608
- return replace ? location.replace(url.href) : location.assign(url.href); // a #fragment of this page: the browser's
747
+ if (shallow ||
748
+ !visit ||
749
+ url.origin !== location.origin ||
750
+ !isAppPage?.(url.pathname) ||
751
+ (here && url.hash))
752
+ return replace ? location.replace(url.href) : location.assign(url.href); // a #fragment of this page: the browser's; shallow: the app has not started
609
753
  visit(url.href, { history: replace || url.href === location.href ? 'replace' : 'push', keep });
610
754
  }
755
+ /**
756
+ * Closes what `navigate(…, { shallow: true })` or a `data-shallow` link opened (a dialog, a drawer), one step. An
757
+ * entry that was pushed by a shallow navigation, from the entry below it: Back, to the page as it was. Any other (a
758
+ * document loaded at this URL, a reload, an entry replaced…): `to` in its place, a shallow navigation with `replace`
759
+ * (`to` is a URL of this page, as that takes it). Never leaves the page, and never adds an entry. A second call before
760
+ * the first one's Back has landed does nothing: a double click closes one level.
761
+ */
762
+ export function closeShallow(to) {
763
+ if (closing)
764
+ return;
765
+ if (history.state?.[SHALLOW] === true) {
766
+ closing = true;
767
+ history.back();
768
+ }
769
+ else
770
+ navigate(to, { shallow: true, replace: true });
771
+ }
611
772
  /** the page asked for again, its state and the scroll position kept */
612
773
  export function again(only) {
613
774
  if (!visit)
package/dist/client.d.ts CHANGED
@@ -63,7 +63,7 @@ type Args<P extends string> = [ParamNames<P>] extends [never] ? {} extends Query
63
63
  export declare function href<P extends Href>(path: P, ...[options]: Args<P>): string;
64
64
  export { usePage, useNavigation, reload, Deferred, __entry, renderPage, type Errors, type Navigation, } from './client/app.js';
65
65
  export { useForm } from './client/form.js';
66
- export { loadDocument, navigate, type Page } from './client/navigation.js';
66
+ export { closeShallow, loadDocument, navigate, type Page } from './client/navigation.js';
67
67
  export type { ProgressOptions } from './client/progress.js';
68
68
  type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
69
69
  /** no generated types (or none of routes): everything is loose, as `Href` is */
package/dist/client.js CHANGED
@@ -25,7 +25,7 @@ function buildUrl(path, params, query, hash) {
25
25
  }
26
26
  export { usePage, useNavigation, reload, Deferred, __entry, renderPage, } from './client/app.js';
27
27
  export { useForm } from './client/form.js';
28
- export { loadDocument, navigate } from './client/navigation.js';
28
+ export { closeShallow, loadDocument, navigate } from './client/navigation.js';
29
29
  /** a non-2xx answer: `status`, `data` (the parsed body: a 422's `{ errors }`) and the `response` */
30
30
  export class FetchError extends Error {
31
31
  status;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.16.2",
3
+ "version": "0.17.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",