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
@@ -0,0 +1,150 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx, extraExtensions, ignoreCase) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ if (extraExtensions) {
4
+ for (var extension in extraExtensions) {
5
+ var suffix = path.slice(-extension.length);
6
+ if (suffix === extension || ignoreCase && suffix.toLowerCase() === extension.toLowerCase()) {
7
+ var output = extraExtensions[extension];
8
+ return output === extension ? path : path.slice(0, -extension.length) + output;
9
+ }
10
+ }
11
+ }
12
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
13
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
14
+ });
15
+ }
16
+ return path;
17
+ };
18
+ import { createReadStream, existsSync, statSync } from 'node:fs';
19
+ import { createServer } from 'node:http';
20
+ import { extname, resolve, sep } from 'node:path';
21
+ import { pathToFileURL } from 'node:url';
22
+ import { basePath } from '../server/head.js';
23
+ import { canonical, headersFor, readHeaders } from '../vite/headers.js';
24
+ import { acceptsEncoding, sendResponse, toRequest } from '../vite/node.js';
25
+ const TEXT = 'charset=utf-8';
26
+ const TYPES = {
27
+ '.html': `text/html; ${TEXT}`, '.js': `text/javascript; ${TEXT}`, '.mjs': `text/javascript; ${TEXT}`, '.css': `text/css; ${TEXT}`,
28
+ '.json': `application/json; ${TEXT}`, '.map': `application/json; ${TEXT}`, '.webmanifest': `application/manifest+json; ${TEXT}`,
29
+ '.txt': `text/plain; ${TEXT}`, '.md': `text/markdown; ${TEXT}`, '.xml': `application/xml; ${TEXT}`, '.svg': `image/svg+xml; ${TEXT}`,
30
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.avif': 'image/avif',
31
+ '.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.otf': 'font/otf',
32
+ '.wasm': 'application/wasm', '.pdf': 'application/pdf', '.mp4': 'video/mp4', '.webm': 'video/webm', '.mp3': 'audio/mpeg',
33
+ };
34
+ const HIDDEN = new Set(['_headers', '_redirects', '_routes.json', '.assetsignore', '_worker.js']);
35
+ export async function createListener(root = '.') {
36
+ const client = resolve(root, 'dist/client');
37
+ const entry = resolve(root, 'dist/server/index.mjs');
38
+ if (!existsSync(client))
39
+ throw new Error(`clarusjs serve: no ${client}; run vite build first`);
40
+ const app = existsSync(entry) ? (await import(__rewriteRelativeImportExtension(pathToFileURL(entry).href))).default : undefined;
41
+ const base = basePath(app?.base ?? '/');
42
+ const rules = readHeaders(client);
43
+ const fileFor = (path) => {
44
+ for (const candidate of [path, `${path.replace(/\/?$/, '/')}index.html`]) {
45
+ const file = resolve(client, `.${candidate}`);
46
+ if (!file.startsWith(client + sep) || HIDDEN.has(file.slice(client.length + 1).split(sep)[0].toLowerCase()))
47
+ continue;
48
+ if (existsSync(file) && statSync(file).isFile())
49
+ return file;
50
+ }
51
+ return undefined;
52
+ };
53
+ const withRules = (res, pathname) => {
54
+ for (const [name, value] of headersFor(rules, pathname))
55
+ if (!res.hasHeader(name))
56
+ res.setHeader(name, value);
57
+ };
58
+ function sendFile(req, res, file, pathname, status = 200) {
59
+ const stat = statSync(file);
60
+ const etag = `W/"${stat.size.toString(36)}-${stat.mtimeMs.toString(36)}"`;
61
+ res.setHeader('content-type', TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream');
62
+ withRules(res, pathname);
63
+ if (!res.hasHeader('cache-control'))
64
+ res.setHeader('cache-control', 'no-cache');
65
+ if (status === 200) {
66
+ res.setHeader('etag', etag);
67
+ if (req.headers['if-none-match'] === etag) {
68
+ res.statusCode = 304;
69
+ return void res.end();
70
+ }
71
+ }
72
+ let body = file;
73
+ const copies = ['br', 'gzip'].filter((enc) => existsSync(file + (enc === 'br' ? '.br' : '.gz')));
74
+ if (copies.length) {
75
+ res.setHeader('vary', 'Accept-Encoding');
76
+ const pick = copies.find((enc) => acceptsEncoding(String(req.headers['accept-encoding'] ?? ''), enc));
77
+ if (pick) {
78
+ res.setHeader('content-encoding', pick);
79
+ body = file + (pick === 'br' ? '.br' : '.gz');
80
+ }
81
+ }
82
+ res.statusCode = status;
83
+ res.setHeader('content-length', statSync(body).size);
84
+ if (req.method === 'HEAD')
85
+ return void res.end();
86
+ const stream = createReadStream(body);
87
+ stream.on('error', (err) => {
88
+ if (res.headersSent)
89
+ return void res.destroy(err);
90
+ res.statusCode = 500;
91
+ res.removeHeader('content-length');
92
+ res.removeHeader('content-encoding');
93
+ res.end();
94
+ });
95
+ stream.once('open', () => stream.pipe(res));
96
+ res.once('close', () => stream.destroy());
97
+ }
98
+ return async (req, res) => {
99
+ const bad = () => {
100
+ res.statusCode = 400;
101
+ res.setHeader('content-type', `text/plain; ${TEXT}`);
102
+ res.end('Bad Request: malformed URL');
103
+ };
104
+ const [raw, query] = (req.url ?? '/').split(/\?(.*)/s);
105
+ let encoded;
106
+ let pathname;
107
+ try {
108
+ encoded = new URL(raw.startsWith('/') ? `http://x${raw}` : raw).pathname.replace(/\/{2,}/g, '/');
109
+ pathname = decodeURIComponent(encoded);
110
+ }
111
+ catch {
112
+ return bad();
113
+ }
114
+ if (canonical(pathname) !== pathname)
115
+ return bad();
116
+ const inBaseEncoded = encoded === base.slice(0, -1) ? '/' : encoded.startsWith(base) ? '/' + encoded.slice(base.length) : undefined;
117
+ const inBase = inBaseEncoded === undefined ? undefined : decodeURIComponent(inBaseEncoded);
118
+ const readable = req.method === 'GET' || req.method === 'HEAD';
119
+ const file = inBase !== undefined && readable ? fileFor(inBase) : undefined;
120
+ if (file)
121
+ return sendFile(req, res, file, pathname);
122
+ if (app && inBase !== undefined && app.isServerPath(inBase)) {
123
+ try {
124
+ req.url = inBaseEncoded + (query === undefined ? '' : `?${query}`);
125
+ const response = await app.fetch(toRequest(req));
126
+ withRules(res, pathname);
127
+ return await sendResponse(res, response);
128
+ }
129
+ catch (err) {
130
+ console.error(err);
131
+ res.statusCode = 500;
132
+ return void res.end();
133
+ }
134
+ }
135
+ const notFound = fileFor('/404.html');
136
+ if (notFound && readable)
137
+ return sendFile(req, res, notFound, pathname, 404);
138
+ res.statusCode = 404;
139
+ res.setHeader('content-type', `text/plain; ${TEXT}`);
140
+ res.end('Not Found');
141
+ };
142
+ }
143
+ export async function serve(options = {}) {
144
+ const listener = await createListener(options.root);
145
+ const server = createServer((req, res) => void listener(req, res));
146
+ const port = options.port ?? Number(process.env.PORT ?? 3000);
147
+ const host = options.host ?? process.env.HOST ?? '0.0.0.0';
148
+ await new Promise((done, fail) => server.once('error', fail).listen(port, host, done));
149
+ return server;
150
+ }
@@ -1,3 +1,9 @@
1
+ /**
2
+ * What `attrValue()` puts in place of a URL it refuses (a `javascript:` link, say): an address that goes nowhere.
3
+ * @example
4
+ * attrValue('href', 'javascript:alert(1)') === UNSAFE_URL // true
5
+ * @see https://clarusjs.com/reference/runtime#attrvalue
6
+ */
1
7
  export declare const UNSAFE_URL = "about:invalid#unsafe";
2
8
  /**
3
9
  * A class from a string (as written), an object (its truthy keys) or an array (flattened, falsy entries dropped), like
@@ -18,6 +24,13 @@ export declare function classValue(value: unknown): string;
18
24
  export declare function styleValue(value: unknown): string;
19
25
  /**
20
26
  * What an attribute should become: `null` removes it, `true` makes it a bare boolean attribute, a string is its value.
27
+ * URL attributes (`href`, `src`…) are checked: a relative URL or a safe scheme passes, anything else becomes
28
+ * `UNSAFE_URL`. The same check templates use, for packages that write attributes themselves (`@clarusjs/editor`).
29
+ * @example
30
+ * attrValue('href', '/docs') // '/docs'
31
+ * attrValue('href', 'javascript:alert(1)') // UNSAFE_URL
32
+ * attrValue('disabled', true) // true
33
+ * @see https://clarusjs.com/reference/runtime#attrvalue
21
34
  */
22
35
  export declare function attrValue(name: string, value: unknown, tag?: string): string | true | null;
23
36
  /**
@@ -13,6 +13,12 @@ const ANIMATION_ELEMENTS = new Set(['animate', 'set', 'animatemotion', 'animatet
13
13
  const IMAGE_ATTRS = new Set(['src', 'srcset', 'poster']);
14
14
  const SAFE_SCHEMES = new Set(['http', 'https', 'mailto', 'tel']);
15
15
  const RASTER_DATA = /^data:image\/(png|gif|jpe?g|webp|avif|bmp);/i;
16
+ /**
17
+ * What `attrValue()` puts in place of a URL it refuses (a `javascript:` link, say): an address that goes nowhere.
18
+ * @example
19
+ * attrValue('href', 'javascript:alert(1)') === UNSAFE_URL // true
20
+ * @see https://clarusjs.com/reference/runtime#attrvalue
21
+ */
16
22
  export const UNSAFE_URL = 'about:invalid#unsafe';
17
23
  /**
18
24
  * Allowlist: a relative URL, a safe scheme, or (for image attributes) a raster data: image or an object URL.
@@ -60,6 +66,13 @@ export function styleValue(value) {
60
66
  }
61
67
  /**
62
68
  * What an attribute should become: `null` removes it, `true` makes it a bare boolean attribute, a string is its value.
69
+ * URL attributes (`href`, `src`…) are checked: a relative URL or a safe scheme passes, anything else becomes
70
+ * `UNSAFE_URL`. The same check templates use, for packages that write attributes themselves (`@clarusjs/editor`).
71
+ * @example
72
+ * attrValue('href', '/docs') // '/docs'
73
+ * attrValue('href', 'javascript:alert(1)') // UNSAFE_URL
74
+ * attrValue('disabled', true) // true
75
+ * @see https://clarusjs.com/reference/runtime#attrvalue
63
76
  */
64
77
  export function attrValue(name, value, tag) {
65
78
  if (value == null)
@@ -39,10 +39,23 @@ export declare function owner(node: Node): Element | null;
39
39
  export declare function provideOn(root: Element, cx: object): void;
40
40
  /** Slot ranges still open at `n`, among the siblings before it (#465). @internal */
41
41
  export declare function openSlots(n: Node): number;
42
+ /** The DOM's shape changed: counts kept so far may be wrong. */
43
+ /** @internal Nodes were added or removed: cached slot ranges are stale. */
44
+ export declare const reshaped: () => void;
45
+ /**
46
+ * Run `fn` with openSlots() counts kept between calls; nothing outside this file may add or remove nodes meanwhile.
47
+ * @internal The loader (attach) and the forms engine (refresh) call this.
48
+ */
49
+ export declare function keepSlots<T>(fn: () => T): T;
42
50
  /** Hole markers in `ctx`, by index. @internal */
43
51
  export declare function holes(ctx: Ctx): Hole[];
44
52
  /** @if block markers in `ctx`, by index. @internal */
45
53
  export declare function blocks(ctx: Ctx): Block[];
54
+ /** Turn HTML into nodes and put them before `end`; returns the first and last inserted node. @internal */
55
+ export declare function insertHtml(html: string, end: Node): {
56
+ first: Node | null;
57
+ last: Node | null;
58
+ };
46
59
  /**
47
60
  * An @if block. `which()` picks the branch (-1 for none). The server-rendered branch is wired in place; a change
48
61
  * removes the old branch (disposing its effects and handlers), inserts the new branch's HTML and wires it.
@@ -63,6 +76,17 @@ export declare function awaited(fn: () => unknown): {
63
76
  };
64
77
  /** @internal Compiled components call this; apps don't. */
65
78
  export declare function region(ctx: Ctx, index: number, html: (cx?: object) => string, wire: () => void, cx?: object): void;
79
+ /**
80
+ * @transition around a @for (clarusjs/motion): `in` gets each new row's nodes (`initial` for the server's rows on
81
+ * attach), `out` a removed row's (instead of removing them), and the update runs inside `frame` so moves can be
82
+ * measured before and after.
83
+ * @internal
84
+ */
85
+ export type ForTransition = {
86
+ in(nodes: Node[], initial?: boolean): void;
87
+ out(nodes: Node[]): void;
88
+ frame(start: Node, end: Node, run: () => void): void;
89
+ };
66
90
  /**
67
91
  * A @for list. Rows the server rendered are adopted in place. When the list changes, rows are matched by key:
68
92
  * kept rows keep their DOM nodes (moved only when out of order) and get the new item and index through their
@@ -76,7 +100,7 @@ export declare function forBlock(ctx: Ctx, index: number, list: () => unknown, k
76
100
  }, empty: {
77
101
  html: () => string;
78
102
  wire: (ctx: Ctx) => void;
79
- } | null): void;
103
+ } | null, t?: ForTransition): void;
80
104
  /** Keep exactly one text node between the hole's markers, set to `fn()`. @internal */
81
105
  export declare function text(hole: Hole, fn: () => unknown): void;
82
106
  /**
@@ -86,7 +110,13 @@ export declare function text(hole: Hole, fn: () => unknown): void;
86
110
  * for elements in that row.
87
111
  * @internal Compiled components call this; apps don't.
88
112
  */
89
- export declare function on(ctx: Ctx, index: number, type: string, fn: (e: Event) => void): void;
113
+ export declare function on(ctx: Ctx, index: number, type: string, fn: (e: Event, el: Element) => void): void;
114
+ /**
115
+ * $values (#444): el's form's fields (el's, or its form's) as an object; a repeated name gives a list, and a
116
+ * submit's button counts.
117
+ * @internal Compiled handlers call this.
118
+ */
119
+ export declare function values(el: Element, e?: Event): Record<string, unknown>;
90
120
  /**
91
121
  * [use]="behaviour" (#464): call each behaviour (one, or a list) with the element marked data-cl-u="index", once; a
92
122
  * function it returns runs when the branch, row or island goes.
@@ -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, spreadAttrs } from './attrs.js';
4
- import { batch, effect, onDispose, scope, state, untrack } from './signals.js';
4
+ import { afterWiring, 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) {
@@ -46,6 +46,23 @@ function contextAt(node, root, own) {
46
46
  }
47
47
  /** Slot ranges still open at `n`, among the siblings before it (#465). @internal */
48
48
  export function openSlots(n) {
49
+ if (slots) {
50
+ // While keepSlots() runs: from the nearest sibling on the left already counted, then rightwards, keeping each count. A list's
51
+ // rows then cost one pass, not one walk back per row. Left to right it's a depth: [s opens, ]s closes an open one.
52
+ const todo = [];
53
+ let s = n.previousSibling;
54
+ while (s && !slots.has(s)) {
55
+ todo.push(s);
56
+ s = s.previousSibling;
57
+ }
58
+ let depth = s ? step(slots.get(s), s) : 0;
59
+ for (let i = todo.length - 1; i >= 0; i--) {
60
+ slots.set(todo[i], depth);
61
+ depth = step(depth, todo[i]);
62
+ }
63
+ slots.set(n, depth);
64
+ return depth;
65
+ }
49
66
  let open = 0;
50
67
  let closed = 0;
51
68
  for (let s = n.previousSibling; s; s = s.previousSibling) {
@@ -59,6 +76,28 @@ export function openSlots(n) {
59
76
  }
60
77
  return open;
61
78
  }
79
+ // The slot ranges open before each node (#589 review), kept while keepSlots() runs: an island’s attach, a forms refresh.
80
+ let slots = null;
81
+ const step = (depth, n) => (n.nodeType !== 8 ? depth : n.data === '[s' ? depth + 1 : n.data === ']s' && depth ? depth - 1 : depth);
82
+ /** The DOM's shape changed: counts kept so far may be wrong. */
83
+ /** @internal Nodes were added or removed: cached slot ranges are stale. */
84
+ export const reshaped = () => { if (slots)
85
+ slots = new WeakMap(); };
86
+ /**
87
+ * Run `fn` with openSlots() counts kept between calls; nothing outside this file may add or remove nodes meanwhile.
88
+ * @internal The loader (attach) and the forms engine (refresh) call this.
89
+ */
90
+ export function keepSlots(fn) {
91
+ if (slots)
92
+ return fn();
93
+ slots = new WeakMap();
94
+ try {
95
+ return fn();
96
+ }
97
+ finally {
98
+ slots = null;
99
+ }
100
+ }
62
101
  /** The island a context's root stands for: itself when it is one, else the island it is in (null: none). */
63
102
  const islandOf = (root) => (root.localName === 'cl-island' ? root : owner(root));
64
103
  /**
@@ -110,11 +149,12 @@ function scan(ctx) {
110
149
  };
111
150
  // One pass (#465): `level` counts the islands entered below this one, minus the slot ranges entered (each moves its
112
151
  // content one island out), so the island's own comments are at 0 and nothing below 0 is (as owner() says, linearly).
113
- const visit = (parent, level) => {
152
+ // The siblings from `first` up to `stop` (not included), and what they hold.
153
+ const visit = (first, stop, level) => {
114
154
  let ranges = 0;
115
- for (let n = parent.firstChild; n; n = n.nextSibling) {
155
+ for (let n = first; n && n !== stop; n = n.nextSibling) {
116
156
  if (n.nodeType === 1)
117
- level < 0 || visit(n, level + (n.localName === 'cl-island' ? 1 : 0));
157
+ level < 0 || visit(n.firstChild, null, level + (n.localName === 'cl-island' ? 1 : 0));
118
158
  else if (n.nodeType !== 8)
119
159
  continue;
120
160
  else if (n.data === '[s') {
@@ -127,11 +167,17 @@ function scan(ctx) {
127
167
  level++;
128
168
  }
129
169
  }
130
- else if (!level && inside(ctx, n))
170
+ else if (!level && (near || inside(ctx, n)))
131
171
  take(n);
132
172
  }
133
173
  };
134
- visit(root, 0);
174
+ // A row whose markers are siblings: only between them, not the whole island once per row. Otherwise (a <tr> row
175
+ // straight in a <table>: the parser puts a <tbody> between them) the whole island, kept to the row's range.
176
+ const near = 'root' in ctx && ctx.start.parentNode === ctx.end.parentNode;
177
+ if (near)
178
+ visit(ctx.start.nextSibling, ctx.end, 0);
179
+ else
180
+ visit(root.firstChild, null, 0);
135
181
  return { holes, blocks, fors, regions };
136
182
  }
137
183
  /** Hole markers in `ctx`, by index. @internal */
@@ -142,13 +188,14 @@ export function holes(ctx) {
142
188
  export function blocks(ctx) {
143
189
  return scan(ctx).blocks;
144
190
  }
145
- /** Turn HTML into nodes and put them before `end`; returns the first and last inserted node. */
146
- function insertHtml(html, end) {
191
+ /** Turn HTML into nodes and put them before `end`; returns the first and last inserted node. @internal */
192
+ export function insertHtml(html, end) {
147
193
  const t = document.createElement('template');
148
194
  t.innerHTML = html;
149
195
  const first = t.content.firstChild;
150
196
  const last = t.content.lastChild;
151
197
  end.parentNode.insertBefore(t.content, end);
198
+ reshaped();
152
199
  // Child islands in the new HTML attach like the ones on the page (the loader registers this hook).
153
200
  const attachIslands = globalThis.__clAttach;
154
201
  if (attachIslands && end.parentNode)
@@ -187,6 +234,7 @@ export function block(ctx, index, which, branches) {
187
234
  dispose?.();
188
235
  while (b.start.nextSibling && b.start.nextSibling !== b.end)
189
236
  b.start.nextSibling.remove();
237
+ reshaped();
190
238
  if (k >= 0)
191
239
  insertHtml(branches[k].html(), b.end);
192
240
  current = k;
@@ -255,6 +303,7 @@ export function region(ctx, index, html, wire, cx) {
255
303
  dispose?.();
256
304
  while (r.start.nextSibling && r.start.nextSibling !== r.end)
257
305
  r.start.nextSibling.remove();
306
+ reshaped();
258
307
  insertHtml(next, r.end);
259
308
  }
260
309
  first = false;
@@ -269,7 +318,7 @@ export function region(ctx, index, html, wire, cx) {
269
318
  * the list is empty.
270
319
  * @internal Compiled components call this; apps don't.
271
320
  */
272
- export function forBlock(ctx, index, list, keyOf, row, empty) {
321
+ export function forBlock(ctx, index, list, keyOf, row, empty, t) {
273
322
  const f = scan(ctx).fors[index];
274
323
  if (!f)
275
324
  return;
@@ -310,40 +359,79 @@ export function forBlock(ctx, index, list, keyOf, row, empty) {
310
359
  });
311
360
  if (first) {
312
361
  first = false;
313
- rows = f.rows.map((range, i) => wireRow(range, keys[i], items[i], i));
362
+ if (f.rows.length === items.length) {
363
+ rows = f.rows.map((range, i) => wireRow(range, keys[i], items[i], i));
364
+ if (f.empty)
365
+ emptyRange = wireEmpty(f.empty);
366
+ if (t)
367
+ for (const r of rows)
368
+ t.in(rangeNodes(r.start, r.end), true);
369
+ return;
370
+ }
371
+ // The browser's list isn't the one the server rendered (it read something the server couldn't: the URL,
372
+ // storage): drop the server's rows and render the browser's below, as for any change.
373
+ for (const range of f.rows)
374
+ for (const node of rangeNodes(range.start, range.end))
375
+ node.parentNode?.removeChild(node);
314
376
  if (f.empty)
315
377
  emptyRange = wireEmpty(f.empty);
316
- return;
378
+ reshaped();
317
379
  }
318
- const old = new Map(rows.map((r) => [r.key, r]));
319
- const next = items.map((item, i) => {
320
- const kept = old.get(keys[i]);
321
- if (kept) {
322
- old.delete(keys[i]);
323
- kept.item.set(item);
324
- kept.index.set(i);
325
- return kept;
380
+ // With @transition, the update runs inside t.frame (clarusjs/motion measures rows before and after it).
381
+ const update = () => {
382
+ const added = [];
383
+ const old = new Map(rows.map((r) => [r.key, r]));
384
+ const next = items.map((item, i) => {
385
+ const kept = old.get(keys[i]);
386
+ if (kept) {
387
+ old.delete(keys[i]);
388
+ kept.item.set(item);
389
+ kept.index.set(i);
390
+ return kept;
391
+ }
392
+ const { first: start, last: end } = insertHtml(`<!--[r-->${row.html(item, i, items)}<!--]-->`, f.end);
393
+ const r = wireRow({ start: start, end: end }, keys[i], item, i);
394
+ added.push(r);
395
+ return r;
396
+ });
397
+ for (const r of old.values()) {
398
+ r.dispose();
399
+ // With @transition, a removed row leaves first (clarusjs/motion), else it goes now.
400
+ if (t)
401
+ t.out(rangeNodes(r.start, r.end));
402
+ else
403
+ for (const n of rangeNodes(r.start, r.end))
404
+ n.parentNode?.removeChild(n);
326
405
  }
327
- const { first: start, last: end } = insertHtml(`<!--[r-->${row.html(item, i, items)}<!--]-->`, f.end);
328
- return wireRow({ start: start, end: end }, keys[i], item, i);
329
- });
330
- for (const r of old.values()) {
331
- r.dispose();
332
- for (const n of rangeNodes(r.start, r.end))
333
- n.parentNode?.removeChild(n);
334
- }
335
- // Put rows in order, moving only those that are not already right after the previous one.
336
- let anchor = f.start;
337
- for (const r of next) {
338
- if (anchor.nextSibling !== r.start)
339
- anchor.after(...rangeNodes(r.start, r.end));
340
- anchor = r.end;
341
- }
342
- rows = next;
406
+ reshaped();
407
+ // Put rows in order, moving only those that are not already right after the previous one.
408
+ let anchor = f.start;
409
+ for (const r of next) {
410
+ // With @transition, leaving rows (no markers left) sit between live ones: stepped over, they keep their place.
411
+ let at = anchor.nextSibling;
412
+ if (t)
413
+ while (at && at.nodeType !== 8)
414
+ at = at.nextSibling;
415
+ if (at !== r.start) {
416
+ anchor.after(...rangeNodes(r.start, r.end));
417
+ reshaped();
418
+ }
419
+ anchor = r.end;
420
+ }
421
+ rows = next;
422
+ if (t)
423
+ for (const r of added)
424
+ t.in(rangeNodes(r.start, r.end));
425
+ };
426
+ if (t)
427
+ t.frame(f.start, f.end, update);
428
+ else
429
+ update();
343
430
  if (items.length && emptyRange) {
344
431
  emptyRange.dispose();
345
432
  for (const n of rangeNodes(emptyRange.start, emptyRange.end))
346
433
  n.parentNode?.removeChild(n);
434
+ reshaped();
347
435
  emptyRange = null;
348
436
  }
349
437
  else if (!items.length && !emptyRange && empty) {
@@ -399,7 +487,7 @@ export function on(ctx, index, type, fn) {
399
487
  continue;
400
488
  for (const h of [...(own.get(Number(i)) ?? [])])
401
489
  if (inside(h.ctx, el))
402
- h.fn(e);
490
+ h.fn(e, el);
403
491
  if (e.cancelBubble)
404
492
  break;
405
493
  }
@@ -413,6 +501,22 @@ export function on(ctx, index, type, fn) {
413
501
  onDispose(() => { const at = list.indexOf(handler); if (at !== -1)
414
502
  list.splice(at, 1); }); // a removed branch or row stops listening
415
503
  }
504
+ /**
505
+ * $values (#444): el's form's fields (el's, or its form's) as an object; a repeated name gives a list, and a
506
+ * submit's button counts.
507
+ * @internal Compiled handlers call this.
508
+ */
509
+ export function values(el, e) {
510
+ const form = el instanceof HTMLFormElement ? el : el.form ?? el.closest('form');
511
+ if (!form)
512
+ return {};
513
+ const data = new FormData(form, e?.submitter);
514
+ // own properties: a field named __proto__ stays a field
515
+ return Object.fromEntries([...new Set(data.keys())].map((k) => {
516
+ const all = data.getAll(k);
517
+ return [k, all.length > 1 ? all : all[0]];
518
+ }));
519
+ }
416
520
  /**
417
521
  * [use]="behaviour" (#464): call each behaviour (one, or a list) with the element marked data-cl-u="index", once; a
418
522
  * function it returns runs when the branch, row or island goes.
@@ -422,19 +526,35 @@ export function use(ctx, index, get) {
422
526
  const el = marked(ctx, `[data-cl-u="${index}"]`);
423
527
  if (!el)
424
528
  return;
425
- for (const fn of [untrack(get)].flat()) {
426
- if (typeof fn !== 'function')
427
- continue;
428
- const dispose = fn(el);
429
- if (typeof dispose === 'function')
430
- onDispose(dispose);
431
- }
529
+ // After the wiring around it (#550), if its element is still there.
530
+ afterWiring(() => {
531
+ if (!el.isConnected)
532
+ return;
533
+ for (const fn of [untrack(get)].flat()) {
534
+ if (typeof fn !== 'function')
535
+ continue;
536
+ const dispose = fn(el);
537
+ if (typeof dispose === 'function')
538
+ onDispose(dispose);
539
+ }
540
+ });
432
541
  }
433
542
  /** The element matching `selector` in `ctx`: this island's (not a nested island's), and in a row, that row's. */
434
543
  export function marked(ctx, selector) {
435
544
  const root = rootOf(ctx);
436
545
  const island = islandOf(root);
437
- return [...root.querySelectorAll(selector)].find((e) => owner(e) === island && inside(ctx, e));
546
+ const mine = (e) => owner(e) === island;
547
+ if (!('root' in ctx) || ctx.start.parentNode !== ctx.end.parentNode)
548
+ return [...root.querySelectorAll(selector)].find((e) => mine(e) && inside(ctx, e));
549
+ // A row with sibling markers: the elements between them, not the whole island's once per row.
550
+ for (let n = ctx.start.nextSibling; n && n !== ctx.end; n = n.nextSibling) {
551
+ if (n.nodeType !== 1)
552
+ continue;
553
+ const found = (n.matches(selector) ? [n] : []).concat([...n.querySelectorAll(selector)]).find(mine);
554
+ if (found)
555
+ return found;
556
+ }
557
+ return undefined;
438
558
  }
439
559
  /**
440
560
  * A reactive spread (#405): sets the attributes the object has, removes the ones it no longer has (only those it set:
@@ -466,8 +586,13 @@ export function attr(ctx, index, name, fn, tag) {
466
586
  const el = marked(ctx, `[data-cl-a="${index}"]`);
467
587
  if (!el)
468
588
  return;
589
+ let first = true;
469
590
  effect(() => {
470
591
  const raw = fn();
592
+ // At attach, a field already typed in (before the island's code loaded) keeps what was typed: the loader's
593
+ // replayed input event then writes it to state. Its value differs from the one the server rendered.
594
+ const typed = first && name === 'value' && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') && el.value !== el.defaultValue;
595
+ first = false;
471
596
  // <select multiple> bound to an array: each option selected when the array has its value.
472
597
  if (name === 'value' && Array.isArray(raw) && el.tagName === 'SELECT' && el.multiple) {
473
598
  const values = raw.map(String); // option values are text: [1, 2] selects "1" and "2"
@@ -481,7 +606,7 @@ export function attr(ctx, index, name, fn, tag) {
481
606
  else
482
607
  el.setAttribute(name, v === true ? '' : v);
483
608
  // A form field shows its property once someone has typed or clicked in it, not the attribute: set both.
484
- if (name === 'value' && 'value' in el) {
609
+ if (name === 'value' && 'value' in el && !typed) {
485
610
  const field = el;
486
611
  const next = v === null || v === true ? '' : v;
487
612
  // A number field showing the same number keeps what was typed ("1.0" isn't rewritten to "1" mid-typing).
@@ -8,7 +8,8 @@ export async function swap(url) {
8
8
  const next = new URL(url, location.href);
9
9
  const pathOf = (el) => new URL(el.getAttribute('src') ?? '', location.href).pathname;
10
10
  // The outermost islands of this component: one nested in another is swapped with it.
11
- const mine = (root) => [...root.querySelectorAll('cl-island')].filter((el) => pathOf(el) === next.pathname && !el.parentElement?.closest(`cl-island[src="${CSS.escape(el.getAttribute('src'))}"]`));
11
+ // A copy still leaving (@transition: inert) isn't the page's any more: not counted.
12
+ const mine = (root) => [...root.querySelectorAll('cl-island')].filter((el) => pathOf(el) === next.pathname && !el.closest('[inert]') && !el.parentElement?.closest(`cl-island[src="${CSS.escape(el.getAttribute('src'))}"]`));
12
13
  const old = mine(document);
13
14
  if (!old.length)
14
15
  return;
@@ -28,7 +29,7 @@ export async function swap(url) {
28
29
  swapped.replaceChildren(...[...fresh[i].childNodes].map((n) => document.importNode(n, true)));
29
30
  swapped.setAttribute('s', fresh[i].getAttribute('s') ?? '{}');
30
31
  // State: what the server rendered with, then what the running version had, island by island in page order.
31
- const before = [el, ...el.querySelectorAll('cl-island')];
32
+ const before = [el, ...[...el.querySelectorAll('cl-island')].filter((x) => !x.closest('[inert]'))];
32
33
  const after = [swapped, ...swapped.querySelectorAll('cl-island')];
33
34
  if (before.length === after.length) {
34
35
  before.forEach((b, j) => {
@@ -1,6 +1,6 @@
1
1
  export { state, derived, shared, effect, scope, onDispose, untrack, batch, type Signal, type ReadSignal } from './signals.ts';
2
- export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, declare, use, provideOn, type Hole, type Block, type Ctx } from './dom.ts';
2
+ export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, declare, use, values, provideOn, type Hole, type Block, type Ctx } from './dom.ts';
3
3
  export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.ts';
4
4
  export { parse as parseIslandData } from './serialize.ts';
5
- export { classValue, styleValue } from './attrs.ts';
5
+ export { attrValue, classValue, styleValue, UNSAFE_URL } from './attrs.ts';
6
6
  export { browser } from './env.ts';
@@ -1,7 +1,7 @@
1
1
  // Browser runtime used by compiled attach() functions.
2
2
  export { state, derived, shared, effect, scope, onDispose, untrack, batch } from './signals.js';
3
- export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, declare, use, provideOn } from './dom.js';
3
+ export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, declare, use, values, provideOn } from './dom.js';
4
4
  export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.js';
5
5
  export { parse as parseIslandData } from './serialize.js';
6
- export { classValue, styleValue } from './attrs.js';
6
+ export { attrValue, classValue, styleValue, UNSAFE_URL } from './attrs.js';
7
7
  export { browser } from './env.js';