clarusjs 0.8.0 → 0.9.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.
Files changed (55) hide show
  1. package/dist/check/generate.d.ts +26 -4
  2. package/dist/check/generate.js +160 -21
  3. package/dist/cli/check.d.ts +13 -0
  4. package/dist/cli/check.js +76 -19
  5. package/dist/cli/index.js +9 -3
  6. package/dist/cli/mapper.d.ts +25 -0
  7. package/dist/cli/mapper.js +65 -0
  8. package/dist/cli/project.d.ts +5 -0
  9. package/dist/cli/project.js +21 -0
  10. package/dist/compiler/emit-client.js +23 -4
  11. package/dist/compiler/emit-server.js +3 -2
  12. package/dist/compiler/html-expr.js +5 -2
  13. package/dist/compiler/index.d.ts +8 -1
  14. package/dist/compiler/index.js +34 -23
  15. package/dist/compiler/ir.d.ts +13 -0
  16. package/dist/compiler/ir.js +157 -7
  17. package/dist/compiler/parse.d.ts +18 -1
  18. package/dist/compiler/parse.js +134 -6
  19. package/dist/compiler/script.d.ts +22 -1
  20. package/dist/compiler/script.js +81 -5
  21. package/dist/forms/index.d.ts +7 -0
  22. package/dist/forms/index.js +374 -0
  23. package/dist/forms/types.d.ts +94 -0
  24. package/dist/forms/types.js +1 -0
  25. package/dist/runtime/dom.d.ts +12 -5
  26. package/dist/runtime/dom.js +76 -5
  27. package/dist/runtime/env.d.ts +7 -0
  28. package/dist/runtime/env.js +7 -0
  29. package/dist/runtime/fragments.d.ts +1 -1
  30. package/dist/runtime/fragments.js +10 -35
  31. package/dist/runtime/index.d.ts +3 -2
  32. package/dist/runtime/index.js +3 -2
  33. package/dist/runtime/loader.d.ts +1 -1
  34. package/dist/runtime/loader.js +38 -5
  35. package/dist/runtime/navigate.d.ts +38 -0
  36. package/dist/runtime/navigate.js +88 -0
  37. package/dist/runtime/navigation.d.ts +88 -0
  38. package/dist/runtime/navigation.js +165 -0
  39. package/dist/runtime/router.d.ts +8 -1
  40. package/dist/runtime/router.js +38 -40
  41. package/dist/runtime/server.d.ts +1 -1
  42. package/dist/runtime/server.js +4 -2
  43. package/dist/runtime/signals.d.ts +2 -0
  44. package/dist/runtime/signals.js +25 -3
  45. package/dist/server/handler.d.ts +8 -0
  46. package/dist/server/handler.js +36 -9
  47. package/dist/vite/aliases.d.ts +10 -0
  48. package/dist/vite/aliases.js +42 -0
  49. package/dist/vite/build.d.ts +2 -1
  50. package/dist/vite/build.js +3 -2
  51. package/dist/vite/plugin.d.ts +6 -0
  52. package/dist/vite/plugin.js +82 -20
  53. package/dist/vite/redirects.d.ts +10 -0
  54. package/dist/vite/redirects.js +41 -0
  55. package/package.json +29 -1
@@ -2,6 +2,7 @@
2
2
  // instead of reloading. Browser only. Each page's fragment is <path>/index.frag.html; elements marked
3
3
  // data-cl-persist="key" are kept across swaps, and the island loader attaches whatever islands arrive.
4
4
  import './loader.js';
5
+ import { takeOver } from './navigate.js';
5
6
  /** '/guide/lists/' → '/guide/lists/index.frag.html', keeping the query. */
6
7
  export function fragmentUrl(url) {
7
8
  return `${url.pathname.replace(/\/+$/, '')}/index.frag.html${url.search}`;
@@ -9,15 +10,15 @@ export function fragmentUrl(url) {
9
10
  const region = (doc) => doc.querySelector('[data-cl-swap]') ?? doc.body;
10
11
  /** Fetch the page's fragment and swap it in. Throws when there is none (the caller then loads the page normally). */
11
12
  export async function swap(url, get = fetch,
12
- // False once a newer navigation has started: then this one must not touch the document.
13
+ // Awaited right before the swap (where the in-between hooks run): false once a newer navigation has started,
14
+ // then this one must not touch the document.
13
15
  isCurrent = () => true) {
14
16
  const src = fragmentUrl(url);
15
17
  const res = await get(src);
16
- if (!res.ok)
18
+ // Redirected: the page moved, and the address bar would keep the old URL. Failing loads the page normally.
19
+ if (!res.ok || res.redirected)
17
20
  throw new Error(`${res.status}: ${src}`);
18
21
  const doc = new DOMParser().parseFromString(await res.text(), 'text/html');
19
- if (!isCurrent())
20
- return;
21
22
  const next = region(doc);
22
23
  const old = region(document);
23
24
  // A body can only replace a body, and a marked region a marked region: otherwise load the page normally.
@@ -38,7 +39,7 @@ isCurrent = () => true) {
38
39
  document.head.append(added);
39
40
  }
40
41
  await Promise.all(loading);
41
- if (!isCurrent())
42
+ if (!(await isCurrent()))
42
43
  return;
43
44
  // Persisted elements move into the new page as they are, with their state and attached islands.
44
45
  for (const old of document.querySelectorAll('[data-cl-persist]')) {
@@ -46,34 +47,8 @@ isCurrent = () => true) {
46
47
  }
47
48
  document.title = doc.title;
48
49
  old.replaceWith(next);
49
- globalThis.__clAttach?.(next, 1); // 1: navigated (bytes)
50
+ // Attaches the new islands; the loader also releases those that left with the old region.
51
+ await globalThis.__clAttach?.(next, 1); // 1: navigated (bytes)
50
52
  }
51
- const navigation = typeof document !== 'undefined' ? globalThis.navigation : undefined;
52
- // Only the latest navigation may change the document; a URL that failed loads normally, never intercepted again
53
- // (the reload of a failed URL is itself a navigation to it, which the fallback check lets through).
54
- let latest = 0;
55
- let fallback = '';
56
- let swapping = false;
57
- navigation?.addEventListener('navigate', (event) => {
58
- const e = event;
59
- // A #hash, and the page's own history.pushState/replaceState (same-document, not back/forward), are never a page
60
- // load, except while a swap is still loading: they abort it, so this navigation has to show the new page instead.
61
- if (!e.canIntercept || e.hashChange || (e.destination.sameDocument && e.navigationType !== 'traverse' && !swapping) || e.downloadRequest !== null || e.formData)
62
- return;
63
- const url = new URL(e.destination.url);
64
- if (url.href === fallback)
65
- return;
66
- const id = ++latest;
67
- const isCurrent = () => latest === id && !e.signal.aborted;
68
- swapping = true;
69
- e.intercept({
70
- handler: () => swap(url, fetch, isCurrent).finally(() => { if (latest === id)
71
- swapping = false; }).catch(() => {
72
- if (!isCurrent())
73
- return;
74
- fallback = url.href;
75
- // The URL is already committed: reload it (assign() would only move within the page when it has a #hash).
76
- location.reload();
77
- }),
78
- });
79
- });
53
+ // Every navigation the shared guard takes over.
54
+ takeOver(() => (url, isCurrent, signal) => swap(url, (src) => fetch(src, { signal }), isCurrent));
@@ -1,4 +1,5 @@
1
- export { state, derived, shared, effect, scope, onDispose, untrack, type Signal, type ReadSignal } from './signals.ts';
2
- export { holes, blocks, text, on, attr, block, forBlock, region, type Hole, type Block, type Ctx } from './dom.ts';
1
+ export { state, derived, shared, effect, scope, onDispose, untrack, batch, type Signal, type ReadSignal } from './signals.ts';
2
+ export { holes, blocks, text, on, attr, block, forBlock, region, model, modelInput, type Hole, type Block, type Ctx } from './dom.ts';
3
3
  export { escape, attrHtml, blockHtml, forHtml, regionHtml } from './html.ts';
4
4
  export { parse as parseIslandData } from './serialize.ts';
5
+ export { browser } from './env.ts';
@@ -1,5 +1,6 @@
1
1
  // Browser runtime used by compiled attach() functions.
2
- export { state, derived, shared, effect, scope, onDispose, untrack } from './signals.js';
3
- export { holes, blocks, text, on, attr, block, forBlock, region } from './dom.js';
2
+ export { state, derived, shared, effect, scope, onDispose, untrack, batch } from './signals.js';
3
+ export { holes, blocks, text, on, attr, block, forBlock, region, model, modelInput } from './dom.js';
4
4
  export { escape, attrHtml, blockHtml, forHtml, regionHtml } from './html.js';
5
5
  export { parse as parseIslandData } from './serialize.js';
6
+ export { browser } from './env.js';
@@ -1,5 +1,5 @@
1
1
  type IslandModule = {
2
- attach(root: Element, props: Record<string, unknown>, state?: Record<string, unknown>): void;
2
+ attach(root: Element, props: Record<string, unknown>, state?: Record<string, unknown>): void | ((props: Record<string, unknown>) => void);
3
3
  };
4
4
  type Load = (src: string) => Promise<IslandModule>;
5
5
  /**
@@ -1,7 +1,16 @@
1
1
  // Island loader: finds <cl-island> elements, loads each one's chunk when its attach mode says so, calls attach(),
2
2
  // and replays what the visitor did before that. Browser only.
3
- var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
3
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx, extraExtensions, ignoreCase) {
4
4
  if (typeof path === "string" && /^\.\.?\//.test(path)) {
5
+ if (extraExtensions) {
6
+ for (var extension in extraExtensions) {
7
+ var suffix = path.slice(-extension.length);
8
+ if (suffix === extension || ignoreCase && suffix.toLowerCase() === extension.toLowerCase()) {
9
+ var output = extraExtensions[extension];
10
+ return output === extension ? path : path.slice(0, -extension.length) + output;
11
+ }
12
+ }
13
+ }
5
14
  return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
6
15
  return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
7
16
  });
@@ -12,6 +21,7 @@ import { parse } from './serialize.js';
12
21
  import { scope } from './signals.js';
13
22
  // Islands scheduled or loading. `data-cl-ready` is set only after attach() succeeds.
14
23
  const loading = new WeakSet();
24
+ const updates = new WeakMap();
15
25
  // Each attached island's disposer: everything its attach() wired (effects, listeners) is released by it.
16
26
  const attached = new Map();
17
27
  let lastLoad = (src) => import(__rewriteRelativeImportExtension(/* @vite-ignore */ src));
@@ -103,7 +113,12 @@ async function attachOne(el, load, recorded) {
103
113
  return;
104
114
  }
105
115
  try {
106
- attached.set(el, scope(() => mod.attach(el, props, state)));
116
+ attached.set(el, scope(() => {
117
+ // An island with inputs returns how to update them: kept for a parent island that passes new props.
118
+ const update = mod.attach(el, props, state);
119
+ if (typeof update === 'function')
120
+ updates.set(el, update);
121
+ }));
107
122
  el.setAttribute('data-cl-ready', '');
108
123
  }
109
124
  catch (err) {
@@ -175,13 +190,31 @@ function arrive() {
175
190
  region.textContent = '';
176
191
  setTimeout(() => { region.textContent = document.title; }, 50);
177
192
  }
178
- // Islands inserted later (an @if branch, a @for row, a re-rendered child) are attached through this hook. The router
179
- // and fragment navigation pass navigated = true after replacing the page.
193
+ // A parent island re-rendered this nested island with new props (`next`, not in the page): they go to it in place, so
194
+ // its DOM and state are kept. False when it can't take them (not attached yet, or another component).
180
195
  ;
196
+ globalThis.__clUpdate = (el, next) => {
197
+ const update = updates.get(el);
198
+ // The same component: the same name and the same source (two panel.tscl files share a name).
199
+ if (!update || el.getAttribute('c') !== next.getAttribute('c') || el.getAttribute('src') !== next.getAttribute('src'))
200
+ return false;
201
+ const p = next.getAttribute('p') ?? '{}';
202
+ el.setAttribute('p', p);
203
+ // Its paths for the forms engine (data-cl-path-<model>) move with it: a row removed above shifts the indexes.
204
+ for (const { name } of [...el.attributes])
205
+ if (name.startsWith('data-cl-path-'))
206
+ el.removeAttribute(name);
207
+ for (const { name, value } of [...next.attributes])
208
+ if (name.startsWith('data-cl-path-'))
209
+ el.setAttribute(name, value);
210
+ update(parse(p));
211
+ return true;
212
+ };
181
213
  globalThis.__clAttach = (root, navigated) => {
182
- void attachAll(root);
214
+ const done = attachAll(root);
183
215
  if (navigated)
184
216
  arrive();
217
+ return done;
185
218
  };
186
219
  if (typeof document !== 'undefined') {
187
220
  // Islands never affect layout. Installed on the document (not in <head>), so it survives head swaps by the client
@@ -0,0 +1,38 @@
1
+ /** `gate()` is awaited right before the page changes the document: false means stop (a newer navigation won). */
2
+ /** `signal`: aborts when the navigation does (pass it to the page's requests). */
3
+ export type Render = (url: URL, gate: () => Promise<boolean> | boolean, signal?: AbortSignal) => Promise<unknown>;
4
+ /** A navigation in progress, as the in-between hooks and the navigating store see it. */
5
+ export type Transition = {
6
+ from: URL;
7
+ to: URL;
8
+ type: string;
9
+ phase: 'loading' | 'swapping';
10
+ signal: AbortSignal;
11
+ };
12
+ type Pick = (url: URL) => Render | false | null | undefined;
13
+ type NavigateEvent = {
14
+ canIntercept: boolean;
15
+ hashChange: boolean;
16
+ downloadRequest: string | null;
17
+ formData: FormData | null;
18
+ destination: {
19
+ url: string;
20
+ sameDocument: boolean;
21
+ };
22
+ navigationType: string;
23
+ signal: AbortSignal;
24
+ intercept(options: {
25
+ handler(): Promise<void>;
26
+ precommitHandler?(): Promise<void>;
27
+ }): void;
28
+ };
29
+ /** The number of the latest navigation taken over (0 before any): only that one may change the document. */
30
+ export declare let latest: number;
31
+ /**
32
+ * Take over the navigations `pick` wants. A page loads one navigator (the router or fragments), so one picker.
33
+ * @see https://clarusjs.com/guide/client-routes
34
+ * @see https://clarusjs.com/guide/fragment-navigation
35
+ */
36
+ export declare function takeOver(pick: Pick): void;
37
+ export declare function onNavigate(e: NavigateEvent, pick: Pick): void;
38
+ export {};
@@ -0,0 +1,88 @@
1
+ // Which navigations clarusjs takes over, in one place for the fragment navigator and the client router. Browser
2
+ // only. Each passes a picker: given the URL, it returns how to render that page, or nothing to leave it alone.
3
+ /** The number of the latest navigation taken over (0 before any): only that one may change the document. */
4
+ export let latest = 0;
5
+ // A URL that failed to render loads normally, never taken over again (its reload is itself a navigation to it).
6
+ let fallback = '';
7
+ let swapping = false;
8
+ // The URL a held navigation is loading (not committed yet).
9
+ let held = '';
10
+ /**
11
+ * Take over the navigations `pick` wants. A page loads one navigator (the router or fragments), so one picker.
12
+ * @see https://clarusjs.com/guide/client-routes
13
+ * @see https://clarusjs.com/guide/fragment-navigation
14
+ */
15
+ export function takeOver(pick) {
16
+ ;
17
+ globalThis.navigation?.addEventListener('navigate', (e) => onNavigate(e, pick));
18
+ }
19
+ export function onNavigate(e, pick) {
20
+ // A #hash, and the page's own history.pushState/replaceState (same-document push or replace), are never a page
21
+ // load, except while a swap runs after its URL changed: they abort it, so this navigation shows the new page.
22
+ if (!e.canIntercept || e.hashChange || e.downloadRequest != null || e.formData)
23
+ return;
24
+ // Push and replace (same-document ones too: never reloads; back/forward is a traverse).
25
+ const hold = /^(p|rep)/.test(e.navigationType);
26
+ if (e.destination.sameDocument && hold && !swapping) {
27
+ // The page's own history change aborts a navigation whose URL is held: it goes on to its page right after.
28
+ if (held)
29
+ setTimeout(navigation.navigate.bind(navigation, held)); // it fired this event
30
+ return;
31
+ }
32
+ const url = new URL(e.destination.url);
33
+ const render = url.href != fallback && pick(url);
34
+ if (!render)
35
+ return;
36
+ const id = ++latest;
37
+ const isCurrent = () => latest == id && !e.signal.aborted;
38
+ const t = { from: new URL(location.href), to: url, type: e.navigationType, phase: 'loading', signal: e.signal };
39
+ const data = document.documentElement.dataset;
40
+ // Each step: on <html data-cl-navigating> (for CSS), then to clarusjs/navigation when an island loaded it.
41
+ const step = async (s) => {
42
+ if (s != 'swapped')
43
+ s ? (data.clNavigating = t.phase = s) : delete data.clNavigating;
44
+ await globalThis.__clNav?.(s, t);
45
+ };
46
+ step('loading');
47
+ // Push and replace hold the URL while the page loads, where the browser can (precommitHandler; others ignore it and
48
+ // only run handler): it changes once the page is ready to swap in, so an abort before that leaves page and URL as
49
+ // they were. Back/forward and reloads change it at once. Until its URL changes, a held navigation leaves the page's
50
+ // own history changes alone (see above).
51
+ swapping = !hold;
52
+ held = hold ? url.href : '';
53
+ let ready;
54
+ let commit;
55
+ const atGate = new Promise((r) => (ready = r));
56
+ const onCommit = new Promise((r) => (commit = () => { swapping = true; held = ''; r(); }));
57
+ let running;
58
+ // Ends this attempt (unless a newer one started): also when it is cancelled before its handlers ever run. `held`
59
+ // clears a task later: a page's own history change aborts this attempt just before its event reaches us, and still
60
+ // has to find it (see above).
61
+ const end = () => { if (latest == id) {
62
+ swapping = false;
63
+ step();
64
+ setTimeout(() => latest == id && (held = ''));
65
+ } };
66
+ e.signal.onabort = end;
67
+ const work = () => (running = render(url, async () => {
68
+ if (!isCurrent())
69
+ return false;
70
+ ready();
71
+ await onCommit;
72
+ await step('swapping');
73
+ return isCurrent();
74
+ }, e.signal).then(() => isCurrent() && step('swapped')).catch((err) => {
75
+ if (!isCurrent())
76
+ return;
77
+ fallback = url.href;
78
+ // Loaded normally: a reload once the URL changed (assign() would only move within the page with a #hash), else
79
+ // the new URL. After the failure is reported, so starting that load doesn't turn it into a cancellation.
80
+ setTimeout(() => (location.href == url.href ? location.reload() : location.assign(url.href)));
81
+ throw err; // reported as navigateerror (onNavigateError)
82
+ }).finally(end));
83
+ e.intercept({
84
+ // Resolves when the page is ready to swap in; rejects with a failure before that (reported, URL unchanged).
85
+ precommitHandler: hold ? () => Promise.race([atGate, work()]) : undefined,
86
+ handler: () => (commit(), running ?? work()),
87
+ });
88
+ }
@@ -0,0 +1,88 @@
1
+ import { type Signal } from './signals.ts';
2
+ import type { Transition } from './navigate.ts';
3
+ export type { Transition };
4
+ /**
5
+ * The current page's URL, as a store: `let here = shared(currentUrl)` in an island's script. `null` on the server
6
+ * (what the server renders), so pass the page's path as a prop when the server HTML needs it.
7
+ * @see https://clarusjs.com/guide/fragment-navigation
8
+ */
9
+ export declare const currentUrl: Signal<URL | null>;
10
+ /**
11
+ * Go to `to`, as a link click would: the page's navigator swaps or renders it. Resolves once the new page is shown,
12
+ * and also when the navigation is cancelled or a newer one replaces it (so check `currentUrl` when it matters);
13
+ * rejects when it fails.
14
+ * @see https://clarusjs.com/guide/fragment-navigation
15
+ * @see https://clarusjs.com/guide/client-routes
16
+ */
17
+ export declare function navigate(to: string | URL, options?: {
18
+ replace?: boolean;
19
+ state?: unknown;
20
+ }): Promise<void>;
21
+ /**
22
+ * Stops the navigation in progress, like the browser's stop button: its requests are cancelled and, where the URL was
23
+ * held while loading (push and replace in browsers with precommit handlers), page and URL stay as they were. Hooks
24
+ * see it through `t.signal`. Like the stop button, it also stops the page's own loading (images still arriving).
25
+ * @see https://clarusjs.com/guide/navigation
26
+ */
27
+ export declare function abort(): void;
28
+ /** Back one entry, like the browser's back button. */
29
+ export declare function back(): void;
30
+ /**
31
+ * Before any navigation (links, forms, back/forward, `navigate()`): `nav.cancel()` stops it, for example to keep
32
+ * unsaved work. Back/forward can only be cancelled where the browser allows it.
33
+ * @see https://clarusjs.com/guide/navigation
34
+ */
35
+ export declare function beforeNavigate(fn: (to: URL, nav: {
36
+ type: string;
37
+ cancel(): void;
38
+ }) => void): void;
39
+ /**
40
+ * After a navigation within the page finished: the new page is in and its islands attached.
41
+ * @see https://clarusjs.com/guide/navigation
42
+ */
43
+ export declare function afterNavigate(fn: (to: URL) => void): void;
44
+ /**
45
+ * A navigation failed (a fragment or a client page could not be loaded). The page then loads normally.
46
+ * @see https://clarusjs.com/guide/navigation
47
+ */
48
+ export declare function onNavigateError(fn: (to: URL, error: unknown) => void): void;
49
+ /**
50
+ * The navigation in progress, as a store (`let nav = shared(navigating)`): `null` when idle, else where it goes and
51
+ * its phase, `'loading'` (the next page is fetched) or `'swapping'` (it replaces this one). For CSS alone,
52
+ * `<html data-cl-navigating>` carries the phase.
53
+ * @see https://clarusjs.com/guide/navigation
54
+ */
55
+ export declare const navigating: Signal<Transition | null>;
56
+ /**
57
+ * Page changes run as view transitions where the browser has them (`document.startViewTransition`), so CSS
58
+ * `::view-transition-*` rules animate them; elsewhere they stay instant. Call it once, from any island's script.
59
+ * `beforeSwap` hooks run before the browser's snapshot, `afterSwap` hooks once the new page is in.
60
+ * @see https://clarusjs.com/guide/navigation
61
+ */
62
+ export declare function viewTransitions(): void;
63
+ /**
64
+ * Runs once the next page is loaded, before it replaces this one (animate out, save state). Return a promise to
65
+ * make the navigation wait; `t.signal` aborts when a newer navigation takes over. A hook that throws makes the page
66
+ * load normally.
67
+ * @see https://clarusjs.com/guide/navigation
68
+ */
69
+ export declare function beforeSwap(fn: (t: Transition) => unknown): void;
70
+ /**
71
+ * Runs once the new page is in and its islands attached (animate in, move focus). Return a promise to make the
72
+ * navigation wait for it.
73
+ * @see https://clarusjs.com/guide/navigation
74
+ */
75
+ export declare function afterSwap(fn: (t: Transition) => unknown): void;
76
+ /** Route → params. Filled in by the generated .clarusjs/routes.d.ts (declaration merging; see `clarusjs check`). */
77
+ export interface Routes {
78
+ }
79
+ /** Without the generated routes any path is accepted; with them, only real routes. */
80
+ export type RouteName = [keyof Routes] extends [never] ? string : Extract<keyof Routes, string>;
81
+ type ParamsOf<R> = R extends keyof Routes ? Routes[R] : Record<string, string>;
82
+ /**
83
+ * A page's URL from its route, as its file names it, with the site's base: `href('/releases/[version]',
84
+ * { version: '0.8.0' })` is `'/releases/0.8.0'`. With .clarusjs/routes.d.ts (written by `clarusjs check`), a route
85
+ * that doesn't exist or a missing param is a type error. Params are encoded.
86
+ * @see https://clarusjs.com/guide/navigation
87
+ */
88
+ export declare function href<R extends RouteName>(route: R, ...params: [keyof Routes] extends [never] ? [Record<string, string>?] : keyof ParamsOf<R> extends never ? [] : [ParamsOf<R>]): string;
@@ -0,0 +1,165 @@
1
+ // Moving between pages from islands: `import { navigate, back, currentUrl } from 'clarusjs/navigation'`.
2
+ // Navigations go through the Navigation API, so the page's navigator (fragments or the client router) takes them
3
+ // over exactly like a link click; without it they are normal page loads. Island scripts also run on the server,
4
+ // where this does nothing.
5
+ import { onDispose, state } from './signals.js';
6
+ const navigation = globalThis.navigation;
7
+ const browser = typeof document !== 'undefined';
8
+ /**
9
+ * The current page's URL, as a store: `let here = shared(currentUrl)` in an island's script. `null` on the server
10
+ * (what the server renders), so pass the page's path as a prop when the server HTML needs it.
11
+ * @see https://clarusjs.com/guide/fragment-navigation
12
+ */
13
+ export const currentUrl = state(browser ? new URL(location.href) : null);
14
+ if (browser) {
15
+ const update = () => currentUrl.set(new URL(location.href));
16
+ // currententrychange covers links, back/forward and the page's own pushState/replaceState; without the
17
+ // Navigation API, only back/forward and #hash changes happen within a page.
18
+ if (navigation)
19
+ navigation.addEventListener('currententrychange', update);
20
+ else
21
+ for (const type of ['popstate', 'hashchange'])
22
+ addEventListener(type, update);
23
+ }
24
+ /**
25
+ * Go to `to`, as a link click would: the page's navigator swaps or renders it. Resolves once the new page is shown,
26
+ * and also when the navigation is cancelled or a newer one replaces it (so check `currentUrl` when it matters);
27
+ * rejects when it fails.
28
+ * @see https://clarusjs.com/guide/fragment-navigation
29
+ * @see https://clarusjs.com/guide/client-routes
30
+ */
31
+ export async function navigate(to, options = {}) {
32
+ if (!browser)
33
+ return;
34
+ if (!navigation)
35
+ return options.replace ? location.replace(String(to)) : location.assign(String(to));
36
+ try {
37
+ await navigation.navigate(String(to), { history: options.replace ? 'replace' : 'auto', state: options.state }).finished;
38
+ }
39
+ catch (err) {
40
+ if (err.name != 'AbortError')
41
+ throw err;
42
+ }
43
+ }
44
+ /**
45
+ * Stops the navigation in progress, like the browser's stop button: its requests are cancelled and, where the URL was
46
+ * held while loading (push and replace in browsers with precommit handlers), page and URL stay as they were. Hooks
47
+ * see it through `t.signal`. Like the stop button, it also stops the page's own loading (images still arriving).
48
+ * @see https://clarusjs.com/guide/navigation
49
+ */
50
+ export function abort() {
51
+ if (browser)
52
+ stop();
53
+ }
54
+ /** Back one entry, like the browser's back button. */
55
+ export function back() {
56
+ if (browser)
57
+ history.back();
58
+ }
59
+ // A hook listens on the Navigation API for as long as the island that registered it (no-op without the API).
60
+ function hook(type, listener) {
61
+ if (!navigation)
62
+ return;
63
+ navigation.addEventListener(type, listener);
64
+ onDispose(() => navigation.removeEventListener(type, listener));
65
+ }
66
+ /**
67
+ * Before any navigation (links, forms, back/forward, `navigate()`): `nav.cancel()` stops it, for example to keep
68
+ * unsaved work. Back/forward can only be cancelled where the browser allows it.
69
+ * @see https://clarusjs.com/guide/navigation
70
+ */
71
+ export function beforeNavigate(fn) {
72
+ hook('navigate', (e) => fn(new URL(e.destination.url), { type: e.navigationType, cancel: () => e.preventDefault() }));
73
+ }
74
+ /**
75
+ * After a navigation within the page finished: the new page is in and its islands attached.
76
+ * @see https://clarusjs.com/guide/navigation
77
+ */
78
+ export function afterNavigate(fn) {
79
+ hook('navigatesuccess', () => fn(new URL(location.href)));
80
+ }
81
+ /**
82
+ * A navigation failed (a fragment or a client page could not be loaded). The page then loads normally.
83
+ * @see https://clarusjs.com/guide/navigation
84
+ */
85
+ export function onNavigateError(fn) {
86
+ // Where it was going: a navigation that failed before its URL changed (held while loading) never became current.
87
+ let to = '';
88
+ hook('navigate', (e) => { to = e.destination.url; });
89
+ hook('navigateerror', (e) => fn(new URL(to || location.href), e.error));
90
+ }
91
+ /**
92
+ * The navigation in progress, as a store (`let nav = shared(navigating)`): `null` when idle, else where it goes and
93
+ * its phase, `'loading'` (the next page is fetched) or `'swapping'` (it replaces this one). For CSS alone,
94
+ * `<html data-cl-navigating>` carries the phase.
95
+ * @see https://clarusjs.com/guide/navigation
96
+ */
97
+ export const navigating = state(null);
98
+ const before = [];
99
+ const after = [];
100
+ // The page's navigator (the router or fragments, a separate script) reports each step here and waits for it.
101
+ if (browser) {
102
+ ;
103
+ globalThis.__clNav = async (step, t) => {
104
+ navigating.set(step ? { ...t } : null);
105
+ if (step != 'swapping')
106
+ done?.(); // the new page is in (or the navigation ended): the transition animates
107
+ const hooks = step == 'swapping' ? before : step == 'swapped' ? after : [];
108
+ // Each hook is awaited in turn; one whose island was released meanwhile (by an earlier hook) is skipped.
109
+ for (const hook of [...hooks])
110
+ if (hooks.includes(hook))
111
+ await hook(t);
112
+ // A view transition: the browser snapshots this page, then the swap (which waits for this) runs inside it.
113
+ const start = document.startViewTransition;
114
+ if (step == 'swapping' && transitions && start) {
115
+ await new Promise((snapshot) => start.call(document, () => { snapshot(); return new Promise((r) => (done = r)); }));
116
+ }
117
+ };
118
+ }
119
+ let transitions = false;
120
+ let done;
121
+ /**
122
+ * Page changes run as view transitions where the browser has them (`document.startViewTransition`), so CSS
123
+ * `::view-transition-*` rules animate them; elsewhere they stay instant. Call it once, from any island's script.
124
+ * `beforeSwap` hooks run before the browser's snapshot, `afterSwap` hooks once the new page is in.
125
+ * @see https://clarusjs.com/guide/navigation
126
+ */
127
+ export function viewTransitions() {
128
+ transitions = true;
129
+ }
130
+ function inBetween(hooks, fn) {
131
+ if (!browser)
132
+ return;
133
+ hooks.push(fn);
134
+ onDispose(() => hooks.splice(hooks.indexOf(fn), 1));
135
+ }
136
+ /**
137
+ * Runs once the next page is loaded, before it replaces this one (animate out, save state). Return a promise to
138
+ * make the navigation wait; `t.signal` aborts when a newer navigation takes over. A hook that throws makes the page
139
+ * load normally.
140
+ * @see https://clarusjs.com/guide/navigation
141
+ */
142
+ export function beforeSwap(fn) {
143
+ inBetween(before, fn);
144
+ }
145
+ /**
146
+ * Runs once the new page is in and its islands attached (animate in, move focus). Return a promise to make the
147
+ * navigation wait for it.
148
+ * @see https://clarusjs.com/guide/navigation
149
+ */
150
+ export function afterSwap(fn) {
151
+ inBetween(after, fn);
152
+ }
153
+ /**
154
+ * A page's URL from its route, as its file names it, with the site's base: `href('/releases/[version]',
155
+ * { version: '0.8.0' })` is `'/releases/0.8.0'`. With .clarusjs/routes.d.ts (written by `clarusjs check`), a route
156
+ * that doesn't exist or a missing param is a type error. Params are encoded.
157
+ * @see https://clarusjs.com/guide/navigation
158
+ */
159
+ export function href(route,
160
+ // Without the generated routes, params are optional; with them, required exactly when the route has some.
161
+ ...params) {
162
+ const values = (params[0] ?? {});
163
+ const base = (import.meta.env?.BASE_URL ?? '/').replace(/\/$/, '');
164
+ return base + route.replace(/\[([^\]]+)\]/g, (_, key) => encodeURIComponent(values[key] ?? ''));
165
+ }
@@ -11,5 +11,12 @@ export declare function matchRoute(table: Entry[], pathname: string): {
11
11
  params: Record<string, string>;
12
12
  } | null;
13
13
  /** Render the client route at `url` into the document. False when `url` is not a client route. */
14
- export declare function show(url: URL, table: Entry[], isCurrent?: () => boolean, load?: (src: string) => Promise<Page>, get?: (url: string) => Promise<Response>): Promise<boolean>;
14
+ export declare function show(url: URL, table: Entry[], isCurrent?: () => Promise<boolean> | boolean, load?: (src: string) => Promise<Page>, get?: (url: string) => Promise<Response>): Promise<boolean>;
15
+ /**
16
+ * Puts a whole page in: its body, its own <html> attributes (lang, dir, …), its title (through `title`, else as
17
+ * written) and its inline head scripts (such as setting the theme before paint, run once as on a normal load); then
18
+ * attaches its islands (the loader also releases the old page's). The head stays. Resolves once the islands that
19
+ * attach right away are attached.
20
+ */
21
+ export declare function swapIn(html: string, title?: (title: string) => string): Promise<void>;
15
22
  export {};