clarusjs 0.9.0 → 0.10.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 (44) hide show
  1. package/dist/check/generate.js +15 -8
  2. package/dist/compiler/emit-client.js +10 -5
  3. package/dist/compiler/errors.d.ts +14 -1
  4. package/dist/compiler/html-expr.d.ts +21 -0
  5. package/dist/compiler/html-expr.js +24 -1
  6. package/dist/compiler/index.d.ts +20 -2
  7. package/dist/compiler/index.js +2 -1
  8. package/dist/compiler/ir.d.ts +6 -1
  9. package/dist/compiler/ir.js +104 -4
  10. package/dist/compiler/parse.d.ts +34 -0
  11. package/dist/compiler/parse.js +11 -0
  12. package/dist/compiler/script.js +27 -0
  13. package/dist/fetch/index.d.ts +149 -0
  14. package/dist/fetch/index.js +312 -0
  15. package/dist/forms/index.d.ts +21 -2
  16. package/dist/forms/types.d.ts +20 -3
  17. package/dist/runtime/attrs.js +10 -2
  18. package/dist/runtime/dom.d.ts +15 -7
  19. package/dist/runtime/dom.js +33 -13
  20. package/dist/runtime/env.d.ts +8 -1
  21. package/dist/runtime/env.js +8 -1
  22. package/dist/runtime/html.d.ts +9 -7
  23. package/dist/runtime/html.js +12 -7
  24. package/dist/runtime/navigate.d.ts +5 -0
  25. package/dist/runtime/navigation.d.ts +85 -13
  26. package/dist/runtime/navigation.js +77 -11
  27. package/dist/runtime/serialize.d.ts +1 -1
  28. package/dist/runtime/serialize.js +1 -1
  29. package/dist/runtime/server.d.ts +8 -1
  30. package/dist/runtime/server.js +20 -4
  31. package/dist/runtime/signals.d.ts +97 -4
  32. package/dist/runtime/signals.js +88 -4
  33. package/dist/server/handler.d.ts +14 -1
  34. package/dist/server/handler.js +2 -2
  35. package/dist/server/head.d.ts +4 -1
  36. package/dist/server/manifest.d.ts +14 -1
  37. package/dist/server/views.d.ts +64 -6
  38. package/dist/server/views.js +46 -0
  39. package/dist/vite/build.d.ts +1 -1
  40. package/dist/vite/manifest.d.ts +12 -0
  41. package/dist/vite/plugin.d.ts +30 -2
  42. package/dist/vite/plugin.js +2 -1
  43. package/dist/vite/sitemap.d.ts +1 -0
  44. 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';
@@ -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;
@@ -8,6 +8,15 @@ const browser = typeof document !== 'undefined';
8
8
  /**
9
9
  * The current page's URL, as a store: `let here = shared(currentUrl)` in an island's script. `null` on the server
10
10
  * (what the server renders), so pass the page's path as a prop when the server HTML needs it.
11
+ * @example
12
+ * ```tscl
13
+ * <script>
14
+ * import { currentUrl } from 'clarusjs/navigation'
15
+ * let here = shared(currentUrl)
16
+ * </script>
17
+ * <a href="/guide" [class]="here?.pathname === '/guide' ? 'active' : ''">Guide</a>
18
+ * ```
19
+ * @see https://clarusjs.com/reference/navigation#currenturl
11
20
  * @see https://clarusjs.com/guide/fragment-navigation
12
21
  */
13
22
  export const currentUrl = state(browser ? new URL(location.href) : null);
@@ -25,8 +34,15 @@ if (browser) {
25
34
  * Go to `to`, as a link click would: the page's navigator swaps or renders it. Resolves once the new page is shown,
26
35
  * and also when the navigation is cancelled or a newer one replaces it (so check `currentUrl` when it matters);
27
36
  * rejects when it fails.
37
+ * @example
38
+ * ```ts
39
+ * async function save() {
40
+ * await post(form)
41
+ * await navigate('/account', { replace: true })
42
+ * }
43
+ * ```
44
+ * @see https://clarusjs.com/reference/navigation#navigate
28
45
  * @see https://clarusjs.com/guide/fragment-navigation
29
- * @see https://clarusjs.com/guide/client-routes
30
46
  */
31
47
  export async function navigate(to, options = {}) {
32
48
  if (!browser)
@@ -45,13 +61,24 @@ export async function navigate(to, options = {}) {
45
61
  * Stops the navigation in progress, like the browser's stop button: its requests are cancelled and, where the URL was
46
62
  * held while loading (push and replace in browsers with precommit handlers), page and URL stay as they were. Hooks
47
63
  * 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
64
+ * @example
65
+ * ```tscl
66
+ * <button (click)="abort()">Stop loading</button>
67
+ * ```
68
+ * @see https://clarusjs.com/reference/navigation#abort
49
69
  */
50
70
  export function abort() {
51
71
  if (browser)
52
72
  stop();
53
73
  }
54
- /** Back one entry, like the browser's back button. */
74
+ /**
75
+ * Back one entry, like the browser's back button.
76
+ * @example
77
+ * ```tscl
78
+ * <button (click)="back()">Back</button>
79
+ * ```
80
+ * @see https://clarusjs.com/reference/navigation#back
81
+ */
55
82
  export function back() {
56
83
  if (browser)
57
84
  history.back();
@@ -66,21 +93,35 @@ function hook(type, listener) {
66
93
  /**
67
94
  * Before any navigation (links, forms, back/forward, `navigate()`): `nav.cancel()` stops it, for example to keep
68
95
  * unsaved work. Back/forward can only be cancelled where the browser allows it.
69
- * @see https://clarusjs.com/guide/navigation
96
+ * @example
97
+ * ```ts
98
+ * beforeNavigate((to, nav) => {
99
+ * if (dirty && !confirm('Leave without saving?')) nav.cancel()
100
+ * })
101
+ * ```
102
+ * @see https://clarusjs.com/reference/navigation#beforenavigate
70
103
  */
71
104
  export function beforeNavigate(fn) {
72
105
  hook('navigate', (e) => fn(new URL(e.destination.url), { type: e.navigationType, cancel: () => e.preventDefault() }));
73
106
  }
74
107
  /**
75
108
  * After a navigation within the page finished: the new page is in and its islands attached.
76
- * @see https://clarusjs.com/guide/navigation
109
+ * @example
110
+ * ```ts
111
+ * afterNavigate((to) => analytics.page(to.pathname))
112
+ * ```
113
+ * @see https://clarusjs.com/reference/navigation#afternavigate
77
114
  */
78
115
  export function afterNavigate(fn) {
79
116
  hook('navigatesuccess', () => fn(new URL(location.href)));
80
117
  }
81
118
  /**
82
119
  * 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
120
+ * @example
121
+ * ```ts
122
+ * onNavigateError((to, error) => report(error, { url: to.href }))
123
+ * ```
124
+ * @see https://clarusjs.com/reference/navigation#onnavigateerror
84
125
  */
85
126
  export function onNavigateError(fn) {
86
127
  // Where it was going: a navigation that failed before its URL changed (held while loading) never became current.
@@ -92,7 +133,15 @@ export function onNavigateError(fn) {
92
133
  * The navigation in progress, as a store (`let nav = shared(navigating)`): `null` when idle, else where it goes and
93
134
  * its phase, `'loading'` (the next page is fetched) or `'swapping'` (it replaces this one). For CSS alone,
94
135
  * `<html data-cl-navigating>` carries the phase.
95
- * @see https://clarusjs.com/guide/navigation
136
+ * @example
137
+ * ```tscl
138
+ * <script>
139
+ * import { navigating } from 'clarusjs/navigation'
140
+ * let nav = shared(navigating)
141
+ * </script>
142
+ * @if (nav) { <div class="progress" role="status">Loading {{ nav.to.pathname }}…</div> }
143
+ * ```
144
+ * @see https://clarusjs.com/reference/navigation#navigating
96
145
  */
97
146
  export const navigating = state(null);
98
147
  const before = [];
@@ -122,7 +171,12 @@ let done;
122
171
  * Page changes run as view transitions where the browser has them (`document.startViewTransition`), so CSS
123
172
  * `::view-transition-*` rules animate them; elsewhere they stay instant. Call it once, from any island's script.
124
173
  * `beforeSwap` hooks run before the browser's snapshot, `afterSwap` hooks once the new page is in.
125
- * @see https://clarusjs.com/guide/navigation
174
+ * @example
175
+ * ```ts
176
+ * // in the layout's island script
177
+ * viewTransitions()
178
+ * ```
179
+ * @see https://clarusjs.com/reference/navigation#viewtransitions
126
180
  */
127
181
  export function viewTransitions() {
128
182
  transitions = true;
@@ -137,7 +191,11 @@ function inBetween(hooks, fn) {
137
191
  * Runs once the next page is loaded, before it replaces this one (animate out, save state). Return a promise to
138
192
  * make the navigation wait; `t.signal` aborts when a newer navigation takes over. A hook that throws makes the page
139
193
  * load normally.
140
- * @see https://clarusjs.com/guide/navigation
194
+ * @example
195
+ * ```ts
196
+ * beforeSwap(() => document.querySelector('main')?.animate({ opacity: [1, 0] }, 150).finished)
197
+ * ```
198
+ * @see https://clarusjs.com/reference/navigation#beforeswap
141
199
  */
142
200
  export function beforeSwap(fn) {
143
201
  inBetween(before, fn);
@@ -145,7 +203,11 @@ export function beforeSwap(fn) {
145
203
  /**
146
204
  * Runs once the new page is in and its islands attached (animate in, move focus). Return a promise to make the
147
205
  * navigation wait for it.
148
- * @see https://clarusjs.com/guide/navigation
206
+ * @example
207
+ * ```ts
208
+ * afterSwap(() => document.querySelector('h1')?.focus())
209
+ * ```
210
+ * @see https://clarusjs.com/reference/navigation#afterswap
149
211
  */
150
212
  export function afterSwap(fn) {
151
213
  inBetween(after, fn);
@@ -154,7 +216,11 @@ export function afterSwap(fn) {
154
216
  * A page's URL from its route, as its file names it, with the site's base: `href('/releases/[version]',
155
217
  * { version: '0.8.0' })` is `'/releases/0.8.0'`. With .clarusjs/routes.d.ts (written by `clarusjs check`), a route
156
218
  * that doesn't exist or a missing param is a type error. Params are encoded.
157
- * @see https://clarusjs.com/guide/navigation
219
+ * @example
220
+ * ```tscl
221
+ * <a [href]="href('/releases/[version]', { version: '0.8.0' })">0.8.0</a>
222
+ * ```
223
+ * @see https://clarusjs.com/reference/navigation#href
158
224
  */
159
225
  export function href(route,
160
226
  // Without the generated routes, params are optional; with them, required exactly when the route has some.
@@ -4,5 +4,5 @@
4
4
  * path to the bad value.
5
5
  */
6
6
  export declare function stringify(value: unknown): string;
7
- /** The inverse of stringify(). */
7
+ /** The inverse of stringify(). @internal */
8
8
  export declare function parse(text: string): unknown;
@@ -62,7 +62,7 @@ function encode(value, path, seen) {
62
62
  return value; // string, boolean
63
63
  }
64
64
  }
65
- /** The inverse of stringify(). */
65
+ /** The inverse of stringify(). @internal */
66
66
  export function parse(text) {
67
67
  return decode(JSON.parse(text));
68
68
  }
@@ -3,7 +3,14 @@ export { escape, json, blockHtml, forHtml, regionHtml } from './html.ts';
3
3
  /**
4
4
  * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
5
5
  * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
6
+ * @internal Compiled components call this; apps don't.
6
7
  */
7
8
  export declare function island(name: string, src: string, props: Record<string, unknown>, html: string, state?: Record<string, unknown>, attach?: string, paths?: Record<string, unknown>): string;
8
- /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. */
9
+ /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
9
10
  export declare const attr: typeof attrHtml;
11
+ /**
12
+ * Serialize data for the browser (an island's props and state, a client route's data), refusing h() output first: it's
13
+ * HTML for server-rendered pages, and serialized it would only be a confusing "it is a function" error.
14
+ * @internal clarusjs's own server code calls this; apps don't.
15
+ */
16
+ export declare function toBrowser(value: unknown, path?: string, seen?: Set<object>): string;