clarusjs 0.16.0 → 0.18.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 (64) 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 +14 -7
  12. package/dist/compiler/index.js +32 -5
  13. package/dist/compiler/ir.d.ts +15 -0
  14. package/dist/compiler/ir.js +87 -11
  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/attrs.d.ts +13 -0
  28. package/dist/runtime/attrs.js +13 -0
  29. package/dist/runtime/dom.d.ts +32 -2
  30. package/dist/runtime/dom.js +170 -45
  31. package/dist/runtime/hot.js +3 -2
  32. package/dist/runtime/index.d.ts +2 -2
  33. package/dist/runtime/index.js +2 -2
  34. package/dist/runtime/loader.js +26 -7
  35. package/dist/runtime/motion.d.ts +59 -0
  36. package/dist/runtime/motion.js +339 -0
  37. package/dist/runtime/navigate.d.ts +2 -0
  38. package/dist/runtime/navigate.js +7 -1
  39. package/dist/runtime/navigation.d.ts +44 -0
  40. package/dist/runtime/navigation.js +69 -3
  41. package/dist/runtime/signals.d.ts +2 -0
  42. package/dist/runtime/signals.js +31 -0
  43. package/dist/seo.d.ts +140 -0
  44. package/dist/seo.js +64 -0
  45. package/dist/server/handler.d.ts +1 -0
  46. package/dist/server/handler.js +1 -0
  47. package/dist/server/head.js +5 -0
  48. package/dist/vite/cloudflare.d.ts +3 -0
  49. package/dist/vite/cloudflare.js +55 -0
  50. package/dist/vite/env.d.ts +19 -0
  51. package/dist/vite/env.js +34 -0
  52. package/dist/vite/headers.d.ts +27 -0
  53. package/dist/vite/headers.js +70 -0
  54. package/dist/vite/manifest.d.ts +11 -1
  55. package/dist/vite/manifest.js +10 -1
  56. package/dist/vite/netlify.d.ts +5 -2
  57. package/dist/vite/netlify.js +4 -2
  58. package/dist/vite/node.d.ts +4 -0
  59. package/dist/vite/node.js +9 -2
  60. package/dist/vite/plugin.d.ts +25 -2
  61. package/dist/vite/plugin.js +84 -9
  62. package/dist/vite/vercel.d.ts +3 -0
  63. package/dist/vite/vercel.js +53 -0
  64. package/package.json +14 -1
@@ -17,7 +17,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
17
17
  }
18
18
  return path;
19
19
  };
20
- import { owner } from './dom.js';
20
+ import { keepSlots, owner } from './dom.js';
21
21
  import { parse } from './serialize.js';
22
22
  import { scope } from './signals.js';
23
23
  // Islands scheduled or loading. `data-cl-ready` is set only after attach() succeeds.
@@ -120,9 +120,9 @@ async function attachOne(el, load, recorded) {
120
120
  let state;
121
121
  try {
122
122
  mod = await load(el.getAttribute('src'));
123
- props = parse(el.getAttribute('p') ?? '{}');
124
- const s = el.getAttribute('s');
125
- state = s === null ? undefined : parse(s);
123
+ // Waiting (idle, visible, interaction) or loading while it started leaving (@transition: inert): it's going.
124
+ if (el.closest('[inert]'))
125
+ return;
126
126
  // Islands in it holding its content attach first (#465): content it re-renders there reads what they provide. One
127
127
  // failing to load fails this one too (both retry). ponytail: later ones (idle, visible, interaction) aren't waited for.
128
128
  for (const inner of el.querySelectorAll('cl-island')) {
@@ -132,6 +132,10 @@ async function attachOne(el, load, recorded) {
132
132
  if (!pending.has(inner))
133
133
  throw 0;
134
134
  }
135
+ // Read last: a parent may have passed new props meanwhile (#524).
136
+ props = parse(el.getAttribute('p') ?? '{}');
137
+ const s = el.getAttribute('s');
138
+ state = s === null ? undefined : parse(s);
135
139
  }
136
140
  catch (err) {
137
141
  recorded.stop();
@@ -144,7 +148,7 @@ async function attachOne(el, load, recorded) {
144
148
  rendered.set(el, rootAttrs(el));
145
149
  attached.set(el, scope(() => {
146
150
  // An island with inputs returns how to update them: kept for a parent island that passes new props.
147
- const update = mod.attach(el, props, state);
151
+ const update = keepSlots(() => mod.attach(el, props, state)); // openSlots counts kept while it wires (dom.ts)
148
152
  if (typeof update === 'function')
149
153
  updates.set(el, update);
150
154
  }));
@@ -158,8 +162,15 @@ async function attachOne(el, load, recorded) {
158
162
  loading.delete(el);
159
163
  }
160
164
  recorded.stop();
161
- if (el.hasAttribute('data-cl-ready'))
165
+ if (el.hasAttribute('data-cl-ready')) {
166
+ // Fields filled before attach with no input to replay (form restore, autofill: the value differs from the
167
+ // server's) send one now, before a replayed submit reads state; a field typed in gets its recorded input, once.
168
+ for (const f of el.querySelectorAll('input,textarea'))
169
+ // the value check first: owner() walks siblings, too slow to run for every row's field
170
+ if (f.value !== f.defaultValue && owner(f) === el && !recorded.events.some((e) => e.target === f && e.type === 'input'))
171
+ f.dispatchEvent(new Event('input', { bubbles: true }));
162
172
  replay(recorded.events);
173
+ }
163
174
  }
164
175
  /**
165
176
  * Attach every island under `root` that isn't attached yet. Resolves once the islands that attach right away
@@ -230,7 +241,10 @@ globalThis.__clUpdate = (el, next) => {
230
241
  // The same component: the same name and the same source (two panel.tscl files share a name). An attached island
231
242
  // without inputs has nothing to update (#465: re-rendered because the content it holds changed, which its parent
232
243
  // wires in place).
233
- if (!attached.has(el) || el.getAttribute('c') !== next.getAttribute('c') || el.getAttribute('src') !== next.getAttribute('src'))
244
+ if (el.getAttribute('c') !== next.getAttribute('c') || el.getAttribute('src') !== next.getAttribute('src'))
245
+ return false;
246
+ // Not attached yet but on its way: it takes the new props and attaches with them (#524).
247
+ if (!attached.has(el) && !loading.has(el))
234
248
  return false;
235
249
  const p = next.getAttribute('p') ?? '{}';
236
250
  el.setAttribute('p', p);
@@ -241,6 +255,11 @@ globalThis.__clUpdate = (el, next) => {
241
255
  for (const { name, value } of [...next.attributes])
242
256
  if (name.startsWith('data-cl-path-'))
243
257
  el.setAttribute(name, value);
258
+ if (!attached.has(el)) {
259
+ // And the markup rendered for them, which it adopts.
260
+ el.replaceChildren(...next.childNodes);
261
+ return true;
262
+ }
244
263
  const root = el.firstElementChild;
245
264
  const before = rendered.get(el);
246
265
  const after = rootAttrs(next);
@@ -0,0 +1,59 @@
1
+ import { type Ctx } from './dom.ts';
2
+ import type { Signal } from './signals.ts';
3
+ /**
4
+ * What `@transition (name, options)` takes after the name.
5
+ * @example
6
+ * <script>
7
+ * const slide = { mode: 'out-in', duration: { enter: 200, leave: 150 } }
8
+ * </script>
9
+ * @transition ('slide', slide) { @if (step === 1) { <p>One</p> } @else { <p>Two</p> } }
10
+ * @see https://clarusjs.com/guide/animations#transition
11
+ */
12
+ export type TransitionOptions = {
13
+ /** Default: the old branch leaves while the new one enters. `out-in`: the new one comes once the old one is gone. `in-out`: the new one enters first, then the old one leaves. */
14
+ mode?: 'out-in' | 'in-out';
15
+ /** Run enter on the branch the server rendered, when the island attaches. */
16
+ appear?: boolean;
17
+ /** Milliseconds to wait instead of the element's animations (Vue's `:duration`). Not waited under reduced motion. */
18
+ duration?: number | {
19
+ enter?: number;
20
+ leave?: number;
21
+ };
22
+ /** `false`: no classes, only the hooks. */
23
+ css?: false;
24
+ onBeforeEnter?(el: Element): void;
25
+ /** With a second parameter, the enter waits until `done()` is called. */
26
+ onEnter?(el: Element, done: () => void): void;
27
+ onAfterEnter?(el: Element): void;
28
+ /** The branch changed while this element was still entering: it leaves from where it is. */
29
+ onEnterCancelled?(el: Element): void;
30
+ onBeforeLeave?(el: Element): void;
31
+ /** With a second parameter, the leave waits until `done()` is called. */
32
+ onLeave?(el: Element, done: () => void): void;
33
+ onAfterLeave?(el: Element): void;
34
+ };
35
+ type Branch = {
36
+ html: () => string;
37
+ wire: () => void;
38
+ };
39
+ /**
40
+ * The @if block of `@transition (name, options) { @if … }`: as dom.ts's block(), with enter and leave transitions.
41
+ * @internal Compiled components call this; apps don't.
42
+ */
43
+ export declare function transitionBlock(ctx: Ctx, index: number, which: () => number, branches: Branch[], name: string, options?: TransitionOptions): void;
44
+ /** A row's template, as the compiler passes it to forBlock. */
45
+ type RowParts = {
46
+ html: (item: any, i: number, list: unknown[]) => string;
47
+ wire: (ctx: Ctx, item: Signal<any>, index: Signal<number>, count: Signal<number>) => void;
48
+ };
49
+ /**
50
+ * The @for block of `@transition (name, options) { @for … }`: dom.ts's forBlock(), with rows entering and leaving
51
+ * with the classes, and rows that move sliding into place (FLIP: measured before and after the update, put back with
52
+ * an inverse transform, then `<name>-move` and the transform off, so its CSS transition animates the move).
53
+ * @internal Compiled components call this; apps don't.
54
+ */
55
+ export declare function transitionFor(ctx: Ctx, index: number, list: () => unknown, keyOf: (item: any, i: number) => unknown, row: RowParts, empty: {
56
+ html: () => string;
57
+ wire: (ctx: Ctx) => void;
58
+ } | null, name: string, options?: TransitionOptions): void;
59
+ export {};
@@ -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