clarusjs 0.9.0 → 0.11.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 (61) hide show
  1. package/dist/check/generate.js +15 -8
  2. package/dist/cli/check.d.ts +7 -0
  3. package/dist/cli/check.js +14 -6
  4. package/dist/cli/explain.js +1 -1
  5. package/dist/cli/index.js +6 -3
  6. package/dist/cli/project.d.ts +7 -2
  7. package/dist/cli/project.js +4 -3
  8. package/dist/compiler/emit-client.d.ts +2 -1
  9. package/dist/compiler/emit-client.js +19 -7
  10. package/dist/compiler/emit-server.d.ts +1 -1
  11. package/dist/compiler/emit-server.js +4 -1
  12. package/dist/compiler/errors.d.ts +14 -1
  13. package/dist/compiler/html-expr.d.ts +21 -0
  14. package/dist/compiler/html-expr.js +24 -1
  15. package/dist/compiler/index.d.ts +23 -2
  16. package/dist/compiler/index.js +5 -3
  17. package/dist/compiler/ir.d.ts +6 -1
  18. package/dist/compiler/ir.js +104 -4
  19. package/dist/compiler/lint.d.ts +82 -0
  20. package/dist/compiler/lint.js +177 -0
  21. package/dist/compiler/parse.d.ts +34 -0
  22. package/dist/compiler/parse.js +11 -0
  23. package/dist/compiler/script.js +27 -0
  24. package/dist/fetch/index.d.ts +149 -0
  25. package/dist/fetch/index.js +312 -0
  26. package/dist/forms/index.d.ts +21 -2
  27. package/dist/forms/types.d.ts +20 -3
  28. package/dist/runtime/attrs.js +10 -2
  29. package/dist/runtime/dom.d.ts +15 -7
  30. package/dist/runtime/dom.js +33 -13
  31. package/dist/runtime/env.d.ts +8 -1
  32. package/dist/runtime/env.js +8 -1
  33. package/dist/runtime/hot.d.ts +2 -0
  34. package/dist/runtime/hot.js +51 -0
  35. package/dist/runtime/html.d.ts +9 -7
  36. package/dist/runtime/html.js +12 -7
  37. package/dist/runtime/navigate.d.ts +5 -0
  38. package/dist/runtime/navigation.d.ts +85 -13
  39. package/dist/runtime/navigation.js +77 -11
  40. package/dist/runtime/serialize.d.ts +1 -1
  41. package/dist/runtime/serialize.js +1 -1
  42. package/dist/runtime/server.d.ts +18 -1
  43. package/dist/runtime/server.js +42 -4
  44. package/dist/runtime/signals.d.ts +97 -4
  45. package/dist/runtime/signals.js +88 -4
  46. package/dist/server/handler.d.ts +115 -5
  47. package/dist/server/handler.js +233 -10
  48. package/dist/server/head.d.ts +4 -1
  49. package/dist/server/manifest.d.ts +14 -1
  50. package/dist/server/views.d.ts +64 -6
  51. package/dist/server/views.js +46 -0
  52. package/dist/vite/aliases.js +3 -3
  53. package/dist/vite/build.d.ts +2 -1
  54. package/dist/vite/build.js +1 -1
  55. package/dist/vite/manifest.d.ts +15 -0
  56. package/dist/vite/manifest.js +2 -2
  57. package/dist/vite/node.js +4 -1
  58. package/dist/vite/plugin.d.ts +47 -3
  59. package/dist/vite/plugin.js +197 -106
  60. package/dist/vite/sitemap.d.ts +1 -0
  61. package/package.json +5 -1
@@ -1,7 +1,7 @@
1
1
  // Attach helpers: find markers in server HTML and keep them updated. Browser only. Never re-renders existing HTML;
2
2
  // only @if branches and @for rows that did not exist on the server are rendered here.
3
3
  import { attrValue } from './attrs.js';
4
- import { effect, onDispose, scope, state, untrack } from './signals.js';
4
+ import { batch, effect, onDispose, scope, state, untrack } from './signals.js';
5
5
  const rootOf = (ctx) => ('root' in ctx ? ctx.root : ctx);
6
6
  /** Is `node` inside `ctx` (always true for a whole island)? */
7
7
  function inside(ctx, node) {
@@ -67,11 +67,11 @@ function scan(ctx) {
67
67
  }
68
68
  return { holes, blocks, fors, regions };
69
69
  }
70
- /** Hole markers in `ctx`, by index. */
70
+ /** Hole markers in `ctx`, by index. @internal */
71
71
  export function holes(ctx) {
72
72
  return scan(ctx).holes;
73
73
  }
74
- /** @if block markers in `ctx`, by index. */
74
+ /** @if block markers in `ctx`, by index. @internal */
75
75
  export function blocks(ctx) {
76
76
  return scan(ctx).blocks;
77
77
  }
@@ -101,6 +101,7 @@ function rangeNodes(start, end) {
101
101
  /**
102
102
  * An @if block. `which()` picks the branch (-1 for none). The server-rendered branch is wired in place; a change
103
103
  * removes the old branch (disposing its effects and handlers), inserts the new branch's HTML and wires it.
104
+ * @internal Compiled components call this; apps don't.
104
105
  */
105
106
  export function block(ctx, index, which, branches) {
106
107
  const b = blocks(ctx)[index];
@@ -138,6 +139,7 @@ const onlyIsland = (nodes) => {
138
139
  const kept = nodes.filter((n) => n.nodeType !== 3 || n.textContent.trim());
139
140
  return kept.length === 1 && kept[0].localName === 'cl-island' ? kept[0] : null;
140
141
  };
142
+ /** @internal Compiled components call this; apps don't. */
141
143
  export function region(ctx, index, html, wire) {
142
144
  const r = scan(ctx).regions[index];
143
145
  if (!r)
@@ -174,6 +176,7 @@ export function region(ctx, index, html, wire) {
174
176
  * kept rows keep their DOM nodes (moved only when out of order) and get the new item and index through their
175
177
  * signals; new rows are rendered and wired; removed rows are disposed and removed. `@empty` content is shown while
176
178
  * the list is empty.
179
+ * @internal Compiled components call this; apps don't.
177
180
  */
178
181
  export function forBlock(ctx, index, list, keyOf, row, empty) {
179
182
  const f = scan(ctx).fors[index];
@@ -183,10 +186,11 @@ export function forBlock(ctx, index, list, keyOf, row, empty) {
183
186
  let rows = [];
184
187
  let emptyRange = null;
185
188
  let first = true;
189
+ const count = state(0); // the list's length, for rows using $count, $last…
186
190
  const wireRow = (range, key, item, i) => {
187
191
  const itemS = state(item);
188
192
  const indexS = state(i);
189
- const dispose = scope(() => row.wire({ root, ...range }, itemS, indexS));
193
+ const dispose = scope(() => row.wire({ root, ...range }, itemS, indexS, count));
190
194
  return { ...range, key, item: itemS, index: indexS, dispose };
191
195
  };
192
196
  const wireEmpty = (range) => ({ ...range, dispose: empty ? scope(() => empty.wire({ root, ...range })) : () => { } });
@@ -197,7 +201,8 @@ export function forBlock(ctx, index, list, keyOf, row, empty) {
197
201
  });
198
202
  effect(() => {
199
203
  const items = [...(list() ?? [])];
200
- untrack(() => {
204
+ untrack(() => batch(() => {
205
+ count.set(items.length); // with the rows' new indices below, in one batch: $last doesn't flip on the way
201
206
  // Keys, made unique: a repeated key would make two rows share one identity.
202
207
  const seen = new Set();
203
208
  const keys = items.map((item, i) => {
@@ -228,7 +233,7 @@ export function forBlock(ctx, index, list, keyOf, row, empty) {
228
233
  kept.index.set(i);
229
234
  return kept;
230
235
  }
231
- const { first: start, last: end } = insertHtml(`<!--[r-->${row.html(item, i)}<!--]-->`, f.end);
236
+ const { first: start, last: end } = insertHtml(`<!--[r-->${row.html(item, i, items)}<!--]-->`, f.end);
232
237
  return wireRow({ start: start, end: end }, keys[i], item, i);
233
238
  });
234
239
  for (const r of old.values()) {
@@ -254,10 +259,10 @@ export function forBlock(ctx, index, list, keyOf, row, empty) {
254
259
  const { first: start, last: end } = insertHtml(`<!--[e-->${empty.html()}<!--]-->`, f.end);
255
260
  emptyRange = wireEmpty({ start: start, end: end });
256
261
  }
257
- });
262
+ }));
258
263
  });
259
264
  }
260
- /** Keep exactly one text node between the hole's markers, set to `fn()`. */
265
+ /** Keep exactly one text node between the hole's markers, set to `fn()`. @internal */
261
266
  export function text(hole, fn) {
262
267
  effect(() => {
263
268
  const value = fn();
@@ -284,6 +289,7 @@ const CAPTURE = new Set([
284
289
  * One listener per island per event type; it walks from the target up to the island root, running handlers
285
290
  * innermost first and stopping when one calls `stopPropagation()`. A handler registered for a @for row only fires
286
291
  * for elements in that row.
292
+ * @internal Compiled components call this; apps don't.
287
293
  */
288
294
  export function on(ctx, index, type, fn) {
289
295
  const root = rootOf(ctx);
@@ -322,20 +328,33 @@ export function marked(ctx, selector) {
322
328
  const island = root.closest('cl-island');
323
329
  return [...root.querySelectorAll(selector)].find((e) => e.closest('cl-island') === island && inside(ctx, e));
324
330
  }
325
- /** Keep attribute `name` of the element marked `data-cl-a="index"` in `ctx` in sync with `fn()`. */
331
+ /** Keep attribute `name` of the element marked `data-cl-a="index"` in `ctx` in sync with `fn()`. @internal */
326
332
  export function attr(ctx, index, name, fn, tag) {
327
333
  const el = marked(ctx, `[data-cl-a="${index}"]`);
328
334
  if (!el)
329
335
  return;
330
336
  effect(() => {
331
- const v = attrValue(name, fn(), tag);
337
+ const raw = fn();
338
+ // <select multiple> bound to an array: each option selected when the array has its value.
339
+ if (name === 'value' && Array.isArray(raw) && el.tagName === 'SELECT' && el.multiple) {
340
+ const values = raw.map(String); // option values are text: [1, 2] selects "1" and "2"
341
+ for (const o of el.options)
342
+ o.selected = values.includes(o.value);
343
+ return;
344
+ }
345
+ const v = attrValue(name, raw, tag);
332
346
  if (v === null)
333
347
  el.removeAttribute(name);
334
348
  else
335
349
  el.setAttribute(name, v === true ? '' : v);
336
350
  // A form field shows its property once someone has typed or clicked in it, not the attribute: set both.
337
- if (name === 'value' && 'value' in el)
338
- el.value = v === null || v === true ? '' : v;
351
+ if (name === 'value' && 'value' in el) {
352
+ const field = el;
353
+ const next = v === null || v === true ? '' : v;
354
+ // A number field showing the same number keeps what was typed ("1.0" isn't rewritten to "1" mid-typing).
355
+ if (field.value !== next && !(/^(number|range)$/.test(field.type) && field.value !== '' && Number(field.value) === Number(raw)))
356
+ field.value = next;
357
+ }
339
358
  if (name === 'checked' && 'checked' in el)
340
359
  el.checked = v !== null;
341
360
  });
@@ -344,6 +363,7 @@ export function attr(ctx, index, name, fn, tag) {
344
363
  * A @model input: writing it asks the parent island to update its state (a bubbling, cancelable cl:model event from
345
364
  * the island); when no parent takes it (a top-level island), the input keeps the value itself. New props from the
346
365
  * parent set it with own().
366
+ * @internal Compiled components call this; apps don't.
347
367
  */
348
368
  export function modelInput(root, name, initial) {
349
369
  const value = state(initial);
@@ -357,7 +377,7 @@ export function modelInput(root, name, initial) {
357
377
  },
358
378
  };
359
379
  }
360
- /** [(name)]="…" on a child island in region `index`: the child's writes to its @model name arrive here. */
380
+ /** [(name)]="…" on a child island in region `index`: the child's writes to its @model name arrive here. @internal */
361
381
  export function model(ctx, index, name, set) {
362
382
  const r = scan(ctx).regions[index];
363
383
  if (!r)
@@ -2,6 +2,13 @@
2
2
  * True in the browser, false on the server. A component's script runs in both (the server renders it, the browser
3
3
  * attaches it), so code that needs the DOM, timers that keep running or listeners on `window` goes under
4
4
  * `if (browser) { … }`. A window without a document (some server runtimes define one) is the server.
5
- * @see https://clarusjs.com/guide/events
5
+ * @example
6
+ * ```ts
7
+ * if (browser) {
8
+ * const timer = setInterval(tick, 1000)
9
+ * onDispose(() => clearInterval(timer))
10
+ * }
11
+ * ```
12
+ * @see https://clarusjs.com/reference/runtime#browser
6
13
  */
7
14
  export declare const browser: boolean;
@@ -2,6 +2,13 @@
2
2
  * True in the browser, false on the server. A component's script runs in both (the server renders it, the browser
3
3
  * attaches it), so code that needs the DOM, timers that keep running or listeners on `window` goes under
4
4
  * `if (browser) { … }`. A window without a document (some server runtimes define one) is the server.
5
- * @see https://clarusjs.com/guide/events
5
+ * @example
6
+ * ```ts
7
+ * if (browser) {
8
+ * const timer = setInterval(tick, 1000)
9
+ * onDispose(() => clearInterval(timer))
10
+ * }
11
+ * ```
12
+ * @see https://clarusjs.com/reference/runtime#browser
6
13
  */
7
14
  export const browser = typeof window !== 'undefined' && typeof document !== 'undefined';
@@ -0,0 +1,2 @@
1
+ /** Swap the islands of the component at `url` (the new module's URL, `…?import&t=…`) in place. */
2
+ export declare function swap(url: string): Promise<void>;
@@ -0,0 +1,51 @@
1
+ // Island HMR (#53), dev only: a compiled island module that changed calls swap() with its new URL. The page is
2
+ // rendered again by the dev server, each of that component's islands gets its new HTML and the new module, and its
3
+ // state (and that of islands nested in it) carries over by name. Anything that doesn't line up is a full reload.
4
+ // Never part of a build: only dev client modules import it (the plugin's `hot` compile option).
5
+ import { parse, stringify } from './serialize.js';
6
+ /** Swap the islands of the component at `url` (the new module's URL, `…?import&t=…`) in place. */
7
+ export async function swap(url) {
8
+ const next = new URL(url, location.href);
9
+ const pathOf = (el) => new URL(el.getAttribute('src') ?? '', location.href).pathname;
10
+ // The outermost islands of this component: one nested in another is swapped with it.
11
+ const mine = (root) => [...root.querySelectorAll('cl-island')].filter((el) => pathOf(el) === next.pathname && !el.parentElement?.closest(`cl-island[src="${CSS.escape(el.getAttribute('src'))}"]`));
12
+ const old = mine(document);
13
+ if (!old.length)
14
+ return;
15
+ try {
16
+ const res = await fetch(location.href, { headers: { accept: 'text/html' } });
17
+ if (!res.ok)
18
+ throw new Error(`${res.status}`);
19
+ const fresh = mine(new DOMParser().parseFromString(await res.text(), 'text/html'));
20
+ if (fresh.length !== old.length)
21
+ throw new Error('the islands moved');
22
+ old.forEach((el, i) => {
23
+ // The island's own attributes (props a parent island may have changed, attach mode), the new markup and module.
24
+ const swapped = el.cloneNode(false);
25
+ swapped.removeAttribute('data-cl-ready');
26
+ swapped.removeAttribute('data-cl-error');
27
+ swapped.setAttribute('src', next.pathname + next.search);
28
+ swapped.replaceChildren(...[...fresh[i].childNodes].map((n) => document.importNode(n, true)));
29
+ swapped.setAttribute('s', fresh[i].getAttribute('s') ?? '{}');
30
+ // State: what the server rendered with, then what the running version had, island by island in page order.
31
+ const before = [el, ...el.querySelectorAll('cl-island')];
32
+ const after = [swapped, ...swapped.querySelectorAll('cl-island')];
33
+ if (before.length === after.length) {
34
+ before.forEach((b, j) => {
35
+ const state = pathOf(b) === pathOf(after[j]) ? b.__cl_hot?.() : undefined;
36
+ if (state)
37
+ after[j].setAttribute('s', stringify({ ...parse(after[j].getAttribute('s') ?? '{}'), ...state }));
38
+ });
39
+ }
40
+ el.replaceWith(swapped);
41
+ });
42
+ // The loader disposes the replaced islands (no longer in the page) and attaches the new ones.
43
+ await globalThis.__clAttach?.(document);
44
+ if (document.querySelector('cl-island[data-cl-error]'))
45
+ throw new Error('the new version failed to attach');
46
+ }
47
+ catch (err) {
48
+ console.warn('[clarusjs] reloading: the changed island could not be swapped in place', err);
49
+ location.reload();
50
+ }
51
+ }
@@ -1,12 +1,14 @@
1
- /** Escape a value for HTML text or a double-quoted attribute. null/undefined render as ''. */
1
+ /** The mark of h()'s output (clarusjs/views). Symbol.for: two copies of the module agree. @internal */
2
+ export declare const HTML: unique symbol;
3
+ /** Escape a value for HTML text or a double-quoted attribute. null/undefined render as ''. @internal */
2
4
  export declare function escape(value: unknown): string;
3
- /** A value as JSON for a <script> (JSON-LD): <, >, & and line separators escaped, so it can't end the script. */
5
+ /** A value as JSON for a <script> (JSON-LD): <, >, & and line separators escaped, so it can't end the script. @internal */
4
6
  export declare function json(value: unknown): string;
5
- /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. */
7
+ /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
6
8
  export declare function attrHtml(name: string, value: unknown, tag?: string): string;
7
- /** An @if block inside an island: markers record which branch (k, or -1 for none) was rendered. */
9
+ /** An @if block inside an island: markers record which branch (k, or -1 for none) was rendered. @internal */
8
10
  export declare function blockHtml(index: number, k: number, branches: (() => string)[]): string;
9
- /** A @for list inside an island: one marker pair around the list, one per row, one around @empty content. */
10
- export declare function forHtml(index: number, list: unknown, row: (item: any, i: number) => string, empty: (() => string) | null): string;
11
- /** A child component inside an island that the browser may re-render: markers around its HTML. */
11
+ /** A @for list inside an island: one marker pair around the list, one per row, one around @empty content. @internal */
12
+ export declare function forHtml(index: number, list: unknown, row: (item: any, i: number, list: unknown[]) => string, empty: (() => string) | null): string;
13
+ /** A child component inside an island that the browser may re-render: markers around its HTML. @internal */
12
14
  export declare function regionHtml(index: number, html: () => string): string;
@@ -1,34 +1,39 @@
1
1
  // HTML-string helpers used by compiled code on the server (render) and in the browser (branch HTML for @if).
2
2
  import { attrValue } from './attrs.js';
3
+ /** The mark of h()'s output (clarusjs/views). Symbol.for: two copies of the module agree. @internal */
4
+ export const HTML = Symbol.for('clarusjs.html');
3
5
  const ENTITIES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
4
- /** Escape a value for HTML text or a double-quoted attribute. null/undefined render as ''. */
6
+ /** Escape a value for HTML text or a double-quoted attribute. null/undefined render as ''. @internal */
5
7
  export function escape(value) {
6
8
  if (value == null)
7
9
  return '';
10
+ // h()'s output (clarusjs/views): HTML built from escaped parts, marked with a symbol data can't carry (JSON can't).
11
+ if (typeof value === 'object' && value[HTML] === true)
12
+ return value.html;
8
13
  return String(value).replace(/[&<>"']/g, (ch) => ENTITIES[ch]);
9
14
  }
10
- /** A value as JSON for a <script> (JSON-LD): <, >, & and line separators escaped, so it can't end the script. */
15
+ /** A value as JSON for a <script> (JSON-LD): <, >, & and line separators escaped, so it can't end the script. @internal */
11
16
  export function json(value) {
12
17
  return (JSON.stringify(value) ?? 'null').replace(/[<>&\u2028\u2029]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`);
13
18
  }
14
- /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. */
19
+ /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
15
20
  export function attrHtml(name, value, tag) {
16
21
  const v = attrValue(name, value, tag);
17
22
  return v === null ? '' : v === true ? ` ${name}` : ` ${name}="${escape(v)}"`;
18
23
  }
19
- /** An @if block inside an island: markers record which branch (k, or -1 for none) was rendered. */
24
+ /** An @if block inside an island: markers record which branch (k, or -1 for none) was rendered. @internal */
20
25
  export function blockHtml(index, k, branches) {
21
26
  return `<!--[b${index}:${k}-->${k >= 0 ? branches[k]() : ''}<!--]-->`;
22
27
  }
23
- /** A @for list inside an island: one marker pair around the list, one per row, one around @empty content. */
28
+ /** A @for list inside an island: one marker pair around the list, one per row, one around @empty content. @internal */
24
29
  export function forHtml(index, list, row, empty) {
25
30
  const items = [...(list ?? [])];
26
31
  const body = items.length
27
- ? items.map((item, i) => `<!--[r-->${row(item, i)}<!--]-->`).join('')
32
+ ? items.map((item, i) => `<!--[r-->${row(item, i, items)}<!--]-->`).join('')
28
33
  : empty ? `<!--[e-->${empty()}<!--]-->` : '';
29
34
  return `<!--[f${index}-->${body}<!--]-->`;
30
35
  }
31
- /** A child component inside an island that the browser may re-render: markers around its HTML. */
36
+ /** A child component inside an island that the browser may re-render: markers around its HTML. @internal */
32
37
  export function regionHtml(index, html) {
33
38
  return `<!--[c${index}-->${html()}<!--]-->`;
34
39
  }
@@ -2,6 +2,11 @@
2
2
  /** `signal`: aborts when the navigation does (pass it to the page's requests). */
3
3
  export type Render = (url: URL, gate: () => Promise<boolean> | boolean, signal?: AbortSignal) => Promise<unknown>;
4
4
  /** A navigation in progress, as the in-between hooks and the navigating store see it. */
5
+ /**
6
+ * A navigation in progress, as the `navigating` store and the swap hooks see it: where it comes from and goes, its
7
+ * type (push, replace, reload, traverse), its phase, and a signal that aborts when a newer navigation takes over.
8
+ * @see https://clarusjs.com/reference/navigation#navigating
9
+ */
5
10
  export type Transition = {
6
11
  from: URL;
7
12
  to: URL;
@@ -4,6 +4,15 @@ export type { Transition };
4
4
  /**
5
5
  * The current page's URL, as a store: `let here = shared(currentUrl)` in an island's script. `null` on the server
6
6
  * (what the server renders), so pass the page's path as a prop when the server HTML needs it.
7
+ * @example
8
+ * ```tscl
9
+ * <script>
10
+ * import { currentUrl } from 'clarusjs/navigation'
11
+ * let here = shared(currentUrl)
12
+ * </script>
13
+ * <a href="/guide" [class]="here?.pathname === '/guide' ? 'active' : ''">Guide</a>
14
+ * ```
15
+ * @see https://clarusjs.com/reference/navigation#currenturl
7
16
  * @see https://clarusjs.com/guide/fragment-navigation
8
17
  */
9
18
  export declare const currentUrl: Signal<URL | null>;
@@ -11,8 +20,15 @@ export declare const currentUrl: Signal<URL | null>;
11
20
  * Go to `to`, as a link click would: the page's navigator swaps or renders it. Resolves once the new page is shown,
12
21
  * and also when the navigation is cancelled or a newer one replaces it (so check `currentUrl` when it matters);
13
22
  * rejects when it fails.
23
+ * @example
24
+ * ```ts
25
+ * async function save() {
26
+ * await post(form)
27
+ * await navigate('/account', { replace: true })
28
+ * }
29
+ * ```
30
+ * @see https://clarusjs.com/reference/navigation#navigate
14
31
  * @see https://clarusjs.com/guide/fragment-navigation
15
- * @see https://clarusjs.com/guide/client-routes
16
32
  */
17
33
  export declare function navigate(to: string | URL, options?: {
18
34
  replace?: boolean;
@@ -22,15 +38,32 @@ export declare function navigate(to: string | URL, options?: {
22
38
  * Stops the navigation in progress, like the browser's stop button: its requests are cancelled and, where the URL was
23
39
  * held while loading (push and replace in browsers with precommit handlers), page and URL stay as they were. Hooks
24
40
  * 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
41
+ * @example
42
+ * ```tscl
43
+ * <button (click)="abort()">Stop loading</button>
44
+ * ```
45
+ * @see https://clarusjs.com/reference/navigation#abort
26
46
  */
27
47
  export declare function abort(): void;
28
- /** Back one entry, like the browser's back button. */
48
+ /**
49
+ * Back one entry, like the browser's back button.
50
+ * @example
51
+ * ```tscl
52
+ * <button (click)="back()">Back</button>
53
+ * ```
54
+ * @see https://clarusjs.com/reference/navigation#back
55
+ */
29
56
  export declare function back(): void;
30
57
  /**
31
58
  * Before any navigation (links, forms, back/forward, `navigate()`): `nav.cancel()` stops it, for example to keep
32
59
  * unsaved work. Back/forward can only be cancelled where the browser allows it.
33
- * @see https://clarusjs.com/guide/navigation
60
+ * @example
61
+ * ```ts
62
+ * beforeNavigate((to, nav) => {
63
+ * if (dirty && !confirm('Leave without saving?')) nav.cancel()
64
+ * })
65
+ * ```
66
+ * @see https://clarusjs.com/reference/navigation#beforenavigate
34
67
  */
35
68
  export declare function beforeNavigate(fn: (to: URL, nav: {
36
69
  type: string;
@@ -38,51 +71,90 @@ export declare function beforeNavigate(fn: (to: URL, nav: {
38
71
  }) => void): void;
39
72
  /**
40
73
  * After a navigation within the page finished: the new page is in and its islands attached.
41
- * @see https://clarusjs.com/guide/navigation
74
+ * @example
75
+ * ```ts
76
+ * afterNavigate((to) => analytics.page(to.pathname))
77
+ * ```
78
+ * @see https://clarusjs.com/reference/navigation#afternavigate
42
79
  */
43
80
  export declare function afterNavigate(fn: (to: URL) => void): void;
44
81
  /**
45
82
  * 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
83
+ * @example
84
+ * ```ts
85
+ * onNavigateError((to, error) => report(error, { url: to.href }))
86
+ * ```
87
+ * @see https://clarusjs.com/reference/navigation#onnavigateerror
47
88
  */
48
89
  export declare function onNavigateError(fn: (to: URL, error: unknown) => void): void;
49
90
  /**
50
91
  * The navigation in progress, as a store (`let nav = shared(navigating)`): `null` when idle, else where it goes and
51
92
  * its phase, `'loading'` (the next page is fetched) or `'swapping'` (it replaces this one). For CSS alone,
52
93
  * `<html data-cl-navigating>` carries the phase.
53
- * @see https://clarusjs.com/guide/navigation
94
+ * @example
95
+ * ```tscl
96
+ * <script>
97
+ * import { navigating } from 'clarusjs/navigation'
98
+ * let nav = shared(navigating)
99
+ * </script>
100
+ * @if (nav) { <div class="progress" role="status">Loading {{ nav.to.pathname }}…</div> }
101
+ * ```
102
+ * @see https://clarusjs.com/reference/navigation#navigating
54
103
  */
55
104
  export declare const navigating: Signal<Transition | null>;
56
105
  /**
57
106
  * Page changes run as view transitions where the browser has them (`document.startViewTransition`), so CSS
58
107
  * `::view-transition-*` rules animate them; elsewhere they stay instant. Call it once, from any island's script.
59
108
  * `beforeSwap` hooks run before the browser's snapshot, `afterSwap` hooks once the new page is in.
60
- * @see https://clarusjs.com/guide/navigation
109
+ * @example
110
+ * ```ts
111
+ * // in the layout's island script
112
+ * viewTransitions()
113
+ * ```
114
+ * @see https://clarusjs.com/reference/navigation#viewtransitions
61
115
  */
62
116
  export declare function viewTransitions(): void;
63
117
  /**
64
118
  * Runs once the next page is loaded, before it replaces this one (animate out, save state). Return a promise to
65
119
  * make the navigation wait; `t.signal` aborts when a newer navigation takes over. A hook that throws makes the page
66
120
  * load normally.
67
- * @see https://clarusjs.com/guide/navigation
121
+ * @example
122
+ * ```ts
123
+ * beforeSwap(() => document.querySelector('main')?.animate({ opacity: [1, 0] }, 150).finished)
124
+ * ```
125
+ * @see https://clarusjs.com/reference/navigation#beforeswap
68
126
  */
69
127
  export declare function beforeSwap(fn: (t: Transition) => unknown): void;
70
128
  /**
71
129
  * Runs once the new page is in and its islands attached (animate in, move focus). Return a promise to make the
72
130
  * navigation wait for it.
73
- * @see https://clarusjs.com/guide/navigation
131
+ * @example
132
+ * ```ts
133
+ * afterSwap(() => document.querySelector('h1')?.focus())
134
+ * ```
135
+ * @see https://clarusjs.com/reference/navigation#afterswap
74
136
  */
75
137
  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`). */
138
+ /**
139
+ * Route → params. Filled in by the generated .clarusjs/routes.d.ts (declaration merging; see `clarusjs check`).
140
+ * @see https://clarusjs.com/reference/navigation#href
141
+ */
77
142
  export interface Routes {
78
143
  }
79
- /** Without the generated routes any path is accepted; with them, only real routes. */
144
+ /**
145
+ * Without the generated routes any path is accepted; with them, only real routes.
146
+ * @see https://clarusjs.com/reference/navigation#href
147
+ */
80
148
  export type RouteName = [keyof Routes] extends [never] ? string : Extract<keyof Routes, string>;
81
149
  type ParamsOf<R> = R extends keyof Routes ? Routes[R] : Record<string, string>;
82
150
  /**
83
151
  * A page's URL from its route, as its file names it, with the site's base: `href('/releases/[version]',
84
152
  * { version: '0.8.0' })` is `'/releases/0.8.0'`. With .clarusjs/routes.d.ts (written by `clarusjs check`), a route
85
153
  * that doesn't exist or a missing param is a type error. Params are encoded.
86
- * @see https://clarusjs.com/guide/navigation
154
+ * @example
155
+ * ```tscl
156
+ * <a [href]="href('/releases/[version]', { version: '0.8.0' })">0.8.0</a>
157
+ * ```
158
+ * @see https://clarusjs.com/reference/navigation#href
87
159
  */
88
160
  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;