clarusjs 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/check/generate.js +97 -8
  2. package/dist/cli/check.d.ts +3 -0
  3. package/dist/cli/check.js +55 -3
  4. package/dist/cli/explain.js +3 -0
  5. package/dist/cli/index.js +21 -3
  6. package/dist/cli/project.d.ts +5 -0
  7. package/dist/cli/project.js +1 -1
  8. package/dist/compiler/emit-client.js +33 -8
  9. package/dist/compiler/events.d.ts +9 -0
  10. package/dist/compiler/events.js +46 -0
  11. package/dist/compiler/html-expr.js +12 -7
  12. package/dist/compiler/index.js +32 -5
  13. package/dist/compiler/ir.d.ts +14 -0
  14. package/dist/compiler/ir.js +76 -10
  15. package/dist/compiler/lint.d.ts +6 -2
  16. package/dist/compiler/lint.js +114 -5
  17. package/dist/compiler/loops.d.ts +13 -0
  18. package/dist/compiler/loops.js +49 -0
  19. package/dist/compiler/parse.d.ts +23 -0
  20. package/dist/compiler/parse.js +149 -1
  21. package/dist/compiler/script.d.ts +2 -0
  22. package/dist/compiler/script.js +78 -1
  23. package/dist/forms/index.js +35 -15
  24. package/dist/forms/types.d.ts +7 -0
  25. package/dist/node/serve.d.ts +26 -0
  26. package/dist/node/serve.js +150 -0
  27. package/dist/runtime/dom.d.ts +32 -2
  28. package/dist/runtime/dom.js +164 -44
  29. package/dist/runtime/hot.js +3 -2
  30. package/dist/runtime/index.d.ts +1 -1
  31. package/dist/runtime/index.js +1 -1
  32. package/dist/runtime/loader.js +18 -6
  33. package/dist/runtime/motion.d.ts +59 -0
  34. package/dist/runtime/motion.js +339 -0
  35. package/dist/runtime/navigate.d.ts +2 -0
  36. package/dist/runtime/navigate.js +7 -1
  37. package/dist/runtime/navigation.d.ts +44 -0
  38. package/dist/runtime/navigation.js +69 -3
  39. package/dist/runtime/signals.d.ts +2 -0
  40. package/dist/runtime/signals.js +31 -0
  41. package/dist/seo.d.ts +140 -0
  42. package/dist/seo.js +64 -0
  43. package/dist/server/handler.d.ts +1 -0
  44. package/dist/server/handler.js +1 -0
  45. package/dist/server/head.js +5 -0
  46. package/dist/vite/cloudflare.d.ts +3 -0
  47. package/dist/vite/cloudflare.js +55 -0
  48. package/dist/vite/env.d.ts +19 -0
  49. package/dist/vite/env.js +34 -0
  50. package/dist/vite/headers.d.ts +27 -0
  51. package/dist/vite/headers.js +70 -0
  52. package/dist/vite/manifest.d.ts +11 -1
  53. package/dist/vite/manifest.js +10 -1
  54. package/dist/vite/netlify.d.ts +5 -2
  55. package/dist/vite/netlify.js +4 -2
  56. package/dist/vite/node.d.ts +4 -0
  57. package/dist/vite/node.js +9 -2
  58. package/dist/vite/plugin.d.ts +25 -2
  59. package/dist/vite/plugin.js +84 -9
  60. package/dist/vite/vercel.d.ts +3 -0
  61. package/dist/vite/vercel.js +53 -0
  62. package/package.json +14 -1
@@ -0,0 +1,339 @@
1
+ // clarusjs/motion: the browser side of `@transition (name, options) { @if … }` (motion phase 2). An @if block of its
2
+ // own, so only islands that use @transition load this: dom.ts's block() stays as it is. Vue's contract (classes
3
+ // `<name>-enter-from/-active/-to`, `-leave-…`, modes, appear, duration, hooks); the end of a transition is read from
4
+ // the element's animations (getAnimations), capped by a timeout.
5
+ import { blocks, forBlock, insertHtml, owner, reshaped } from './dom.js';
6
+ import { effect, onDispose, scope, untrack } from './signals.js';
7
+ const failed = (err) => console.error('[clarusjs] a @transition hook failed', err);
8
+ const reduced = () => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
9
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
10
+ /** `wait`, or `ms` if that comes first; the timer is cleared either way, so none is left pending. */
11
+ const capped = async (wait, ms) => {
12
+ let timer;
13
+ try {
14
+ await Promise.race([wait, new Promise((done) => (timer = setTimeout(done, ms)))]);
15
+ }
16
+ finally {
17
+ clearTimeout(timer);
18
+ }
19
+ };
20
+ // Vue's timing: the -from class is in place for one painted frame before -to replaces it.
21
+ const nextFrame = () => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(() => done())));
22
+ /** The elements a branch's top-level nodes animate: a <cl-island> (display: contents) stands for its element children. */
23
+ function targets(nodes) {
24
+ return nodes.flatMap((n) => (n.nodeType !== 1 ? [] : n.localName === 'cl-island' ? targets([...n.children]) : [n]));
25
+ }
26
+ /** The nodes between `start` and `end`, both excluded. */
27
+ function between(start, end) {
28
+ const out = [];
29
+ for (let n = start.nextSibling; n && n !== end; n = n.nextSibling)
30
+ out.push(n);
31
+ return out;
32
+ }
33
+ /**
34
+ * One element's enter or leave. Resolves when it's done; `cancel()` (an enter interrupted) ends it early, with the
35
+ * classes taken off.
36
+ */
37
+ function run(el, dir, name, o) {
38
+ const css = o.css !== false;
39
+ const cls = (s) => `${name}-${dir}-${s}`;
40
+ const hook = (what) => o[`on${what}`];
41
+ let cancelled = false;
42
+ const clear = () => { if (css)
43
+ el.classList.remove(cls('from'), cls('active'), cls('to')); };
44
+ hook(dir === 'enter' ? 'BeforeEnter' : 'BeforeLeave')?.(el, () => { });
45
+ if (css)
46
+ el.classList.add(cls('from'), cls('active'));
47
+ // A reflow, so the leave starts from the element's current style (Vue forces one too).
48
+ if (dir === 'leave')
49
+ void el.offsetHeight;
50
+ const done = (async () => {
51
+ await nextFrame();
52
+ if (cancelled)
53
+ return;
54
+ if (css) {
55
+ el.classList.remove(cls('from'));
56
+ el.classList.add(cls('to'));
57
+ }
58
+ const on = hook(dir === 'enter' ? 'Enter' : 'Leave');
59
+ const ms = typeof o.duration === 'number' ? o.duration : o.duration?.[dir];
60
+ let wait;
61
+ if (on && on.length >= 2)
62
+ wait = new Promise((resolve) => on(el, resolve));
63
+ else {
64
+ on?.(el, () => { });
65
+ // An explicit duration replaces the animations; under reduced motion there is nothing the user wants to wait for.
66
+ wait = ms !== undefined ? (reduced() ? Promise.resolve() : sleep(ms))
67
+ : css ? Promise.allSettled((el.getAnimations?.({ subtree: true }) ?? []).map((a) => a.finished)) : Promise.resolve();
68
+ }
69
+ // The safety net: an animation that never ends (infinite, or never started) can't hold the element.
70
+ await capped(wait, Math.max(5000, 2 * (ms ?? 0)));
71
+ if (cancelled)
72
+ return;
73
+ clear();
74
+ hook(dir === 'enter' ? 'AfterEnter' : 'AfterLeave')?.(el, () => { });
75
+ })();
76
+ return {
77
+ done,
78
+ cancel() {
79
+ if (cancelled)
80
+ return;
81
+ cancelled = true;
82
+ clear();
83
+ if (dir === 'enter')
84
+ hook('EnterCancelled')?.(el, () => { });
85
+ },
86
+ };
87
+ }
88
+ /**
89
+ * Make leaving nodes no longer the island's: their markers and data-cl-* attributes go (so the island's scans and a
90
+ * re-wire can't find them), they can't be focused or clicked, and child islands that never attached stay unattached.
91
+ */
92
+ function neutralise(nodes, island) {
93
+ for (const node of nodes) {
94
+ if (node.nodeType !== 1)
95
+ continue;
96
+ const el = node;
97
+ // Only what the outer island owns (owner(): a child island's own markers are its, and a running child still
98
+ // updates its blocks during the leave; content the outer island passed into a child's slot is the outer's).
99
+ // The slot markers themselves ([s, ]s) are the child's structure: kept.
100
+ const comments = [];
101
+ const elements = [el];
102
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT);
103
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
104
+ if (n.nodeType === 8) {
105
+ if (n.data !== '[s' && n.data !== ']s' && owner(n) === island)
106
+ comments.push(n);
107
+ }
108
+ else
109
+ elements.push(n);
110
+ }
111
+ for (const c of comments)
112
+ c.parentNode.removeChild(c);
113
+ for (const e of elements) {
114
+ if (owner(e) === island)
115
+ for (const a of [...e.attributes])
116
+ if (a.name.startsWith('data-cl-') && a.name !== 'data-cl-ready' && a.name !== 'data-cl-error')
117
+ e.removeAttribute(a.name);
118
+ // The next insert would attach an island that hasn't yet (idle, visible, interaction): it's leaving.
119
+ if (e.localName === 'cl-island' && !e.hasAttribute('data-cl-error'))
120
+ e.setAttribute('data-cl-ready', '');
121
+ }
122
+ el.setAttribute('inert', '');
123
+ el.setAttribute('aria-hidden', 'true');
124
+ }
125
+ reshaped();
126
+ }
127
+ /**
128
+ * The @if block of `@transition (name, options) { @if … }`: as dom.ts's block(), with enter and leave transitions.
129
+ * @internal Compiled components call this; apps don't.
130
+ */
131
+ export function transitionBlock(ctx, index, which, branches, name, options) {
132
+ const b = blocks(ctx)[index];
133
+ if (!b)
134
+ return;
135
+ const o = options ?? {};
136
+ let current = b.k;
137
+ let live = between(b.start, b.end);
138
+ let dispose = null;
139
+ let alive = true;
140
+ let first = true;
141
+ let holding = false; // out-in: an insert waits for the leave to end
142
+ const entering = new Map();
143
+ onDispose(() => { alive = false; dispose?.(); });
144
+ const enter = (nodes) => Promise.all(targets(nodes).map(async (el) => {
145
+ try {
146
+ const r = run(el, 'enter', name, o);
147
+ entering.set(el, r.cancel);
148
+ await r.done;
149
+ }
150
+ catch (err) {
151
+ failed(err);
152
+ }
153
+ finally {
154
+ entering.delete(el);
155
+ }
156
+ }));
157
+ const leave = (nodes) => {
158
+ // Text goes at once; elements leave, then go.
159
+ for (const n of nodes)
160
+ if (n.nodeType !== 1)
161
+ n.parentNode?.removeChild(n);
162
+ const elements = nodes.filter((n) => n.nodeType === 1);
163
+ const parent = elements[0]?.parentNode;
164
+ return Promise.all(elements.map(async (top) => {
165
+ const els = targets([top]);
166
+ for (const el of els)
167
+ entering.get(el)?.();
168
+ // A hook that throws is reported; the element still goes, and out-in still inserts what comes next.
169
+ try {
170
+ await Promise.all(els.map((el) => run(el, 'leave', name, o).done));
171
+ }
172
+ catch (err) {
173
+ failed(err);
174
+ }
175
+ top.remove();
176
+ })).then(() => {
177
+ // Child islands that left are disposed by the loader's next pass over the page: one pass for them all.
178
+ const attach = globalThis.__clAttach;
179
+ if (attach && parent)
180
+ attach(parent);
181
+ });
182
+ };
183
+ const insert = (k, animate = true) => {
184
+ if (!alive || k < 0)
185
+ return Promise.resolve();
186
+ const { first: from, last } = insertHtml(branches[k].html(), b.end);
187
+ live = from && last ? between(from.previousSibling ?? b.start, last.nextSibling ?? b.end) : [];
188
+ dispose = scope(() => branches[k].wire());
189
+ return animate ? enter(live) : Promise.resolve();
190
+ };
191
+ effect(() => {
192
+ const k = which();
193
+ untrack(() => {
194
+ if (first) {
195
+ first = false;
196
+ // The browser's state picks another branch than the server rendered (HMR carrying state over, a state restored
197
+ // in the browser): swapped at once, as block() does, then entered only with appear.
198
+ if (k !== current) {
199
+ for (const n of live)
200
+ n.parentNode?.removeChild(n);
201
+ reshaped();
202
+ live = [];
203
+ current = k;
204
+ void insert(k, o.appear === true);
205
+ return;
206
+ }
207
+ if (k >= 0) {
208
+ dispose = scope(() => branches[k].wire());
209
+ if (o.appear)
210
+ void enter(live);
211
+ }
212
+ return;
213
+ }
214
+ if (k === current)
215
+ return;
216
+ current = k;
217
+ // The old branch: unwired and neutralised now (two live copies would share marker numbers), animated out.
218
+ dispose?.();
219
+ dispose = null;
220
+ const old = live;
221
+ live = [];
222
+ neutralise(old, 'root' in ctx ? ctx.root : ctx);
223
+ // Now, whatever the mode: its text goes, and an enter it was still running stops (in-out leaves it only later).
224
+ for (const n of old)
225
+ if (n.nodeType !== 1)
226
+ n.parentNode?.removeChild(n);
227
+ for (const el of targets(old))
228
+ entering.get(el)?.();
229
+ if (o.mode === 'out-in') {
230
+ const leaving = leave(old);
231
+ if (holding)
232
+ return;
233
+ holding = true;
234
+ void leaving.then(() => { holding = false; void insert(current); });
235
+ }
236
+ else if (o.mode === 'in-out') {
237
+ void insert(k).then(() => leave(old));
238
+ }
239
+ else {
240
+ void leave(old);
241
+ void insert(k);
242
+ }
243
+ });
244
+ });
245
+ }
246
+ /**
247
+ * The @for block of `@transition (name, options) { @for … }`: dom.ts's forBlock(), with rows entering and leaving
248
+ * with the classes, and rows that move sliding into place (FLIP: measured before and after the update, put back with
249
+ * an inverse transform, then `<name>-move` and the transform off, so its CSS transition animates the move).
250
+ * @internal Compiled components call this; apps don't.
251
+ */
252
+ export function transitionFor(ctx, index, list, keyOf, row, empty, name, options) {
253
+ const o = options ?? {};
254
+ const island = 'root' in ctx ? ctx.root : ctx;
255
+ const entering = new Map();
256
+ const enter = (el) => {
257
+ try {
258
+ const r = run(el, 'enter', name, o);
259
+ entering.set(el, r.cancel);
260
+ r.done.catch(failed).finally(() => entering.delete(el));
261
+ }
262
+ catch (err) {
263
+ failed(err);
264
+ }
265
+ };
266
+ forBlock(ctx, index, list, keyOf, row, empty, {
267
+ in(nodes, initial) {
268
+ if (initial && !o.appear)
269
+ return;
270
+ for (const el of targets(nodes))
271
+ enter(el);
272
+ },
273
+ out(nodes) {
274
+ neutralise(nodes, island);
275
+ // The row's markers and text go now; its elements leave, then go.
276
+ for (const n of nodes)
277
+ if (n.nodeType !== 1)
278
+ n.parentNode?.removeChild(n);
279
+ for (const top of nodes.filter((n) => n.nodeType === 1)) {
280
+ const els = targets([top]);
281
+ for (const el of els)
282
+ entering.get(el)?.();
283
+ void (async () => {
284
+ try {
285
+ await Promise.all(els.map((el) => run(el, 'leave', name, o).done));
286
+ }
287
+ catch (err) {
288
+ failed(err);
289
+ }
290
+ const parent = top.parentNode;
291
+ top.remove();
292
+ const attach = globalThis.__clAttach;
293
+ if (attach && parent)
294
+ attach(parent);
295
+ })();
296
+ }
297
+ reshaped();
298
+ },
299
+ frame(start, end, update) {
300
+ // Nothing slides under reduced motion: the rows take their places at once.
301
+ if (reduced() || o.css === false)
302
+ return update();
303
+ const before = new Map();
304
+ for (const n of between(start, end))
305
+ if (n.nodeType === 1 && !n.hasAttribute('inert'))
306
+ for (const el of targets([n]))
307
+ before.set(el, el.getBoundingClientRect());
308
+ update();
309
+ const moved = [];
310
+ for (const [el, was] of before) {
311
+ if (!el.isConnected || el.closest('[inert]'))
312
+ continue;
313
+ const now = el.getBoundingClientRect();
314
+ const dx = was.left - now.left;
315
+ const dy = was.top - now.top;
316
+ if (!dx && !dy)
317
+ continue;
318
+ const s = el.style;
319
+ s.transform = `translate(${dx}px, ${dy}px)`;
320
+ s.transitionDuration = '0s';
321
+ moved.push(el);
322
+ }
323
+ if (!moved.length)
324
+ return;
325
+ void document.body.offsetHeight; // the inverse transforms take effect before the move starts
326
+ const cls = `${name}-move`;
327
+ for (const el of moved) {
328
+ el.classList.add(cls);
329
+ el.style.transform = '';
330
+ el.style.transitionDuration = '';
331
+ void (async () => {
332
+ await nextFrame();
333
+ await capped(Promise.allSettled((el.getAnimations?.() ?? []).map((a) => a.finished)), 5000);
334
+ el.classList.remove(cls);
335
+ })();
336
+ }
337
+ },
338
+ });
339
+ }
@@ -29,7 +29,9 @@ type NavigateEvent = {
29
29
  intercept(options: {
30
30
  handler(): Promise<void>;
31
31
  precommitHandler?(): Promise<void>;
32
+ scroll?: 'after-transition' | 'manual';
32
33
  }): void;
34
+ info?: unknown;
33
35
  };
34
36
  /** The number of the latest navigation taken over (0 before any): only that one may change the document. */
35
37
  export declare let latest: number;
@@ -34,6 +34,9 @@ export function onNavigate(e, pick) {
34
34
  if (!render)
35
35
  return;
36
36
  const id = ++latest;
37
+ // scroll: false (navigate()'s option): where the visitor is, put back after the swap (replacing the content can
38
+ // briefly shorten the page, and the browser then clamps the position).
39
+ const keep = e.info?.scroll === false && [scrollX, scrollY];
37
40
  const isCurrent = () => latest == id && !e.signal.aborted;
38
41
  const t = { from: new URL(location.href), to: url, type: e.navigationType, phase: 'loading', signal: e.signal };
39
42
  const data = document.documentElement.dataset;
@@ -71,7 +74,7 @@ export function onNavigate(e, pick) {
71
74
  await onCommit;
72
75
  await step('swapping');
73
76
  return isCurrent();
74
- }, e.signal).then(() => isCurrent() && step('swapped')).catch((err) => {
77
+ }, e.signal).then(() => isCurrent() && (keep && scrollTo(...keep), step('swapped'))).catch((err) => {
75
78
  if (!isCurrent())
76
79
  return;
77
80
  fallback = url.href;
@@ -81,6 +84,9 @@ export function onNavigate(e, pick) {
81
84
  throw err; // reported as navigateerror (onNavigateError)
82
85
  }).finally(end));
83
86
  e.intercept({
87
+ // Scroll: the browser's (Back/Forward restore the position, a new page starts at the top, a #hash scrolls to it),
88
+ // unless navigate(…, { scroll: false }) asked to stay where the visitor is.
89
+ scroll: keep ? 'manual' : undefined, // undefined: the browser's own ('after-transition')
84
90
  // Resolves when the page is ready to swap in; rejects with a failure before that (reported, URL unchanged).
85
91
  precommitHandler: hold ? () => Promise.race([atGate, work()]) : undefined,
86
92
  handler: () => (commit(), running ?? work()),
@@ -16,6 +16,49 @@ export type { Transition };
16
16
  * @see https://clarusjs.com/guide/fragment-navigation
17
17
  */
18
18
  export declare const currentUrl: Signal<URL | null>;
19
+ /**
20
+ * The current page's query, as a store kept in step with `currentUrl`: `let query = shared(searchParams)`, then
21
+ * `query?.get('q')`. `null` on the server, like `currentUrl`. Change it with `setSearch()`.
22
+ * @example
23
+ * ```tscl
24
+ * <script>
25
+ * import { searchParams } from 'clarusjs/navigation'
26
+ * let query = shared(searchParams)
27
+ * </script>
28
+ * <p>Results for {{ query?.get('q') ?? 'everything' }}</p>
29
+ * ```
30
+ * @see https://clarusjs.com/guide/navigation#query-strings
31
+ */
32
+ export declare const searchParams: Signal<URLSearchParams | null>;
33
+ /**
34
+ * Change the current URL's query and go there: each key is set (a string or number), repeated (an array) or removed
35
+ * (`null`); the path, hash and other params stay. Replaces the history entry by default, as a search box or filter
36
+ * should (so Back leaves the page, not each keystroke); `{ replace: false }` adds one. Keeps the scroll position by
37
+ * default (`{ scroll: true }` goes to the top, as a new page does).
38
+ * @example
39
+ * ```ts
40
+ * setSearch({ q: input.value, page: null }) // a new search starts at page 1
41
+ * setSearch({ page: 3 }, { replace: false }) // pages are worth a Back step
42
+ * ```
43
+ * @see https://clarusjs.com/guide/navigation#query-strings
44
+ */
45
+ export declare function setSearch(changes: Record<string, string | number | null | readonly (string | number)[]>, options?: {
46
+ replace?: boolean;
47
+ state?: unknown;
48
+ scroll?: boolean;
49
+ }): Promise<void>;
50
+ /**
51
+ * What `navigate(url, { state })` stored with the current history entry (`undefined` if nothing, or on the server).
52
+ * Kept by the browser for Back and Forward, not in the URL: for things like where the visitor came from.
53
+ * @example
54
+ * ```ts
55
+ * await navigate('/results', { state: { from: 'search' } })
56
+ * // later, on /results:
57
+ * const from = (navigationState() as { from?: string } | undefined)?.from
58
+ * ```
59
+ * @see https://clarusjs.com/guide/navigation#history-state
60
+ */
61
+ export declare function navigationState<T = unknown>(): T | undefined;
19
62
  /**
20
63
  * Go to `to`, as a link click would: the page's navigator swaps or renders it. Resolves once the new page is shown,
21
64
  * and also when the navigation is cancelled or a newer one replaces it (so check `currentUrl` when it matters);
@@ -33,6 +76,7 @@ export declare const currentUrl: Signal<URL | null>;
33
76
  export declare function navigate(to: string | URL, options?: {
34
77
  replace?: boolean;
35
78
  state?: unknown;
79
+ scroll?: boolean;
36
80
  }): Promise<void>;
37
81
  /**
38
82
  * Stops the navigation in progress, like the browser's stop button: its requests are cancelled and, where the URL was
@@ -2,7 +2,7 @@
2
2
  // Navigations go through the Navigation API, so the page's navigator (fragments or the client router) takes them
3
3
  // over exactly like a link click; without it they are normal page loads. Island scripts also run on the server,
4
4
  // where this does nothing.
5
- import { onDispose, state } from './signals.js';
5
+ import { effect, onDispose, state } from './signals.js';
6
6
  const navigation = globalThis.navigation;
7
7
  const browser = typeof document !== 'undefined';
8
8
  /**
@@ -30,6 +30,70 @@ if (browser) {
30
30
  for (const type of ['popstate', 'hashchange'])
31
31
  addEventListener(type, update);
32
32
  }
33
+ /**
34
+ * The current page's query, as a store kept in step with `currentUrl`: `let query = shared(searchParams)`, then
35
+ * `query?.get('q')`. `null` on the server, like `currentUrl`. Change it with `setSearch()`.
36
+ * @example
37
+ * ```tscl
38
+ * <script>
39
+ * import { searchParams } from 'clarusjs/navigation'
40
+ * let query = shared(searchParams)
41
+ * </script>
42
+ * <p>Results for {{ query?.get('q') ?? 'everything' }}</p>
43
+ * ```
44
+ * @see https://clarusjs.com/guide/navigation#query-strings
45
+ */
46
+ export const searchParams = state(currentUrl.get() ? new URLSearchParams(currentUrl.get().search) : null);
47
+ effect(() => {
48
+ const url = currentUrl.get();
49
+ searchParams.set(url ? new URLSearchParams(url.search) : null);
50
+ });
51
+ /**
52
+ * Change the current URL's query and go there: each key is set (a string or number), repeated (an array) or removed
53
+ * (`null`); the path, hash and other params stay. Replaces the history entry by default, as a search box or filter
54
+ * should (so Back leaves the page, not each keystroke); `{ replace: false }` adds one. Keeps the scroll position by
55
+ * default (`{ scroll: true }` goes to the top, as a new page does).
56
+ * @example
57
+ * ```ts
58
+ * setSearch({ q: input.value, page: null }) // a new search starts at page 1
59
+ * setSearch({ page: 3 }, { replace: false }) // pages are worth a Back step
60
+ * ```
61
+ * @see https://clarusjs.com/guide/navigation#query-strings
62
+ */
63
+ export function setSearch(changes, options = {}) {
64
+ if (!browser)
65
+ return Promise.resolve();
66
+ const url = new URL(location.href);
67
+ for (const [key, value] of Object.entries(changes)) {
68
+ if (value === null)
69
+ url.searchParams.delete(key);
70
+ else if (!Array.isArray(value))
71
+ url.searchParams.set(key, String(value)); // keeps its place
72
+ else {
73
+ url.searchParams.delete(key);
74
+ for (const v of value)
75
+ url.searchParams.append(key, String(v));
76
+ }
77
+ }
78
+ return navigate(url, { replace: options.replace ?? true, state: options.state, scroll: options.scroll ?? false });
79
+ }
80
+ /**
81
+ * What `navigate(url, { state })` stored with the current history entry (`undefined` if nothing, or on the server).
82
+ * Kept by the browser for Back and Forward, not in the URL: for things like where the visitor came from.
83
+ * @example
84
+ * ```ts
85
+ * await navigate('/results', { state: { from: 'search' } })
86
+ * // later, on /results:
87
+ * const from = (navigationState() as { from?: string } | undefined)?.from
88
+ * ```
89
+ * @see https://clarusjs.com/guide/navigation#history-state
90
+ */
91
+ export function navigationState() {
92
+ if (!browser)
93
+ return undefined;
94
+ const entry = navigation?.currentEntry;
95
+ return (entry ? entry.getState() : history.state);
96
+ }
33
97
  /**
34
98
  * Go to `to`, as a link click would: the page's navigator swaps or renders it. Resolves once the new page is shown,
35
99
  * and also when the navigation is cancelled or a newer one replaces it (so check `currentUrl` when it matters);
@@ -50,7 +114,8 @@ export async function navigate(to, options = {}) {
50
114
  if (!navigation)
51
115
  return options.replace ? location.replace(String(to)) : location.assign(String(to));
52
116
  try {
53
- await navigation.navigate(String(to), { history: options.replace ? 'replace' : 'auto', state: options.state }).finished;
117
+ // scroll: false reaches the navigator (navigate.ts) as info: it keeps the scroll position for this navigation.
118
+ await navigation.navigate(String(to), { history: options.replace ? 'replace' : 'auto', state: options.state, info: { scroll: options.scroll ?? true } }).finished;
54
119
  }
55
120
  catch (err) {
56
121
  if (err.name != 'AbortError')
@@ -161,7 +226,8 @@ if (browser) {
161
226
  // A view transition: the browser snapshots this page, then the swap (which waits for this) runs inside it.
162
227
  const start = document.startViewTransition;
163
228
  if (step == 'swapping' && transitions && start) {
164
- await new Promise((snapshot) => start.call(document, () => { snapshot(); return new Promise((r) => (done = r)); }));
229
+ // A newer page change (Back before this one swapped) skips this transition: its ready rejects, as expected.
230
+ await new Promise((snapshot) => start.call(document, () => { snapshot(); return new Promise((r) => (done = r)); }).ready.catch(() => { }));
165
231
  }
166
232
  };
167
233
  }
@@ -28,6 +28,8 @@ export type ReadSignal<T> = {
28
28
  * @see https://clarusjs.com/reference/runtime#scope
29
29
  */
30
30
  export declare function scope(fn: () => void): () => void;
31
+ /** Run `fn` when the wiring pass ends (now if none), in the scope it was asked from (#550). @internal */
32
+ export declare function afterWiring(fn: () => void): void;
31
33
  /**
32
34
  * Run `fn` when the enclosing scope is disposed (an island leaving the page, an @if branch or @for row going away).
33
35
  * Outside a scope it does nothing.
@@ -18,17 +18,48 @@ export function scope(fn) {
18
18
  const prev = currentScope;
19
19
  const cleanups = [];
20
20
  currentScope = cleanups;
21
+ // The outermost scope is a wiring pass: what waits for it runs at its end.
22
+ const outer = !after;
23
+ if (outer)
24
+ after = [];
25
+ let wired = false;
21
26
  try {
22
27
  fn();
28
+ wired = true;
23
29
  }
24
30
  finally {
25
31
  currentScope = prev;
32
+ if (outer) {
33
+ const waiting = after;
34
+ after = null;
35
+ if (wired)
36
+ for (const run of waiting)
37
+ run();
38
+ }
26
39
  }
27
40
  const dispose = () => { for (const c of cleanups.splice(0).reverse())
28
41
  c(); };
29
42
  onDispose(dispose);
30
43
  return dispose;
31
44
  }
45
+ // What waits for the wiring pass that's running (null when none is).
46
+ let after = null;
47
+ /** Run `fn` when the wiring pass ends (now if none), in the scope it was asked from (#550). @internal */
48
+ export function afterWiring(fn) {
49
+ if (!after)
50
+ return fn();
51
+ const owner = currentScope;
52
+ after.push(() => {
53
+ const prev = currentScope;
54
+ currentScope = owner;
55
+ try {
56
+ fn();
57
+ }
58
+ finally {
59
+ currentScope = prev;
60
+ }
61
+ });
62
+ }
32
63
  /**
33
64
  * Run `fn` when the enclosing scope is disposed (an island leaving the page, an @if branch or @for row going away).
34
65
  * Outside a scope it does nothing.