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
@@ -42,6 +42,17 @@ export type AwaitBranch = {
42
42
  nameStart: number;
43
43
  children: TemplateNode[];
44
44
  };
45
+ /**
46
+ * `@transition (name, options) { … }` around an @if or a @for: its argument expressions as written (null: none).
47
+ * @see https://clarusjs.com/guide/animations#transition
48
+ */
49
+ export type Transition = {
50
+ name: string | null;
51
+ nameStart: number;
52
+ options: string | null;
53
+ optionsStart: number;
54
+ start: number;
55
+ };
45
56
  /**
46
57
  * A node of a template's syntax tree: an element, text, a `{{ }}` hole, an `@if`, an `@for`, a slot fill…
47
58
  * @see https://clarusjs.com/reference/compiler#parse
@@ -73,6 +84,8 @@ export type TemplateNode = {
73
84
  children: TemplateNode[];
74
85
  }[];
75
86
  start: number;
87
+ /** `@transition (name, options) { @if … }` around it: the argument expressions as written (null: none). */
88
+ transition?: Transition;
76
89
  } | {
77
90
  type: 'await';
78
91
  expr: string;
@@ -97,9 +110,11 @@ export type TemplateNode = {
97
110
  itemStart: number;
98
111
  listStart: number;
99
112
  trackStart: number;
113
+ aliases: ForAlias[];
100
114
  children: TemplateNode[];
101
115
  empty: TemplateNode[] | null;
102
116
  start: number;
117
+ transition?: Transition;
103
118
  };
104
119
  /**
105
120
  * An `@input` (or `@model`) declaration: its name, type text, default, and offsets.
@@ -200,6 +215,12 @@ export type ParsedFile = {
200
215
  };
201
216
  nodes: TemplateNode[];
202
217
  };
218
+ /** `let name = $index` in a @for header: another name for a row's implicit value, for a nested loop to reach. */
219
+ export type ForAlias = {
220
+ name: string;
221
+ of: string;
222
+ start: number;
223
+ };
203
224
  /** The names a @for row has besides its item: $index, $count, $first, $last, $even, $odd. */
204
225
  export declare const FOR_IMPLICIT: string[];
205
226
  /**
@@ -228,3 +249,5 @@ export declare function fragmentRoot(nodes: TemplateNode[]): boolean;
228
249
  export declare function parse(source: string, file: string): ParsedFile;
229
250
  /** Local names an import clause binds: `{ a, b as c, type T }` → a, c; `x` → x. */
230
251
  export declare function importNames(clause: string): string[];
252
+ /** A component name in kebab case, as a tag: uiButton and UiButton → ui-button, XMLViewer → xml-viewer. */
253
+ export declare function kebabOf(name: string): string;
@@ -359,6 +359,95 @@ export function parse(source, file) {
359
359
  }
360
360
  return { type: 'await', expr, exprStart, pending, then, catch: caught, start };
361
361
  }
362
+ function transitionBlock() {
363
+ const start = i;
364
+ i += '@transition'.length;
365
+ while (/\s/.test(source[i] ?? ''))
366
+ i++;
367
+ let args = { name: null, nameStart: i, options: null, optionsStart: i };
368
+ if (source[i] === '(') {
369
+ const { condStart } = condition('@transition');
370
+ const raw = source.slice(condStart, i - 1);
371
+ const comma = topLevelComma(raw);
372
+ const part = (from, to) => {
373
+ const text = raw.slice(from, to);
374
+ const lead = text.length - text.trimStart().length;
375
+ return { text: text.trim() || null, at: condStart + from + lead };
376
+ };
377
+ const name = part(0, comma === -1 ? raw.length : comma);
378
+ const options = comma === -1 ? { text: null, at: condStart + raw.length } : part(comma + 1, raw.length);
379
+ args = { name: name.text, nameStart: name.at, options: options.text, optionsStart: options.at };
380
+ while (/\s/.test(source[i] ?? ''))
381
+ i++;
382
+ }
383
+ if (source[i] !== '{')
384
+ fail('expected { to open the block', i);
385
+ i++;
386
+ const kids = children({ tag: '@transition', start, block: true });
387
+ const wrapped = kids.filter((n) => !(n.type === 'text' && !n.value.trim()));
388
+ const only = wrapped[0];
389
+ const blockish = (n) => n.type === 'if' || n.type === 'for';
390
+ if (wrapped.length !== 1 || !blockish(only))
391
+ fail('@transition wraps one @if or @for', (wrapped.find((n) => !blockish(n)) ?? wrapped[1] ?? { start }).start);
392
+ const node = only;
393
+ node.transition = { ...args, start };
394
+ return node;
395
+ }
396
+ function topLevelComma(text) {
397
+ let depth = 0;
398
+ const template = (j) => {
399
+ for (j++; j < text.length; j++) {
400
+ if (text[j] === '\\')
401
+ j++;
402
+ else if (text[j] === '`')
403
+ return j;
404
+ else if (text[j] === '$' && text[j + 1] === '{') {
405
+ let inner = 1;
406
+ for (j += 2; j < text.length && inner; j++) {
407
+ const c = text[j];
408
+ if (c === '`')
409
+ j = template(j);
410
+ else if (c === '"' || c === "'") {
411
+ for (j++; j < text.length && text[j] !== c; j++)
412
+ if (text[j] === '\\')
413
+ j++;
414
+ }
415
+ else if (c === '{')
416
+ inner++;
417
+ else if (c === '}')
418
+ inner--;
419
+ }
420
+ j--;
421
+ }
422
+ }
423
+ return j;
424
+ };
425
+ for (let j = 0; j < text.length; j++) {
426
+ const c = text[j];
427
+ if (c === '"' || c === "'") {
428
+ for (j++; j < text.length && text[j] !== c; j++)
429
+ if (text[j] === '\\')
430
+ j++;
431
+ }
432
+ else if (c === '`')
433
+ j = template(j);
434
+ else if (c === '/' && text[j + 1] === '/') {
435
+ const nl = text.indexOf('\n', j);
436
+ j = nl === -1 ? text.length : nl;
437
+ }
438
+ else if (c === '/' && text[j + 1] === '*') {
439
+ const close = text.indexOf('*/', j + 2);
440
+ j = close === -1 ? text.length : close + 1;
441
+ }
442
+ else if (c === '(' || c === '[' || c === '{')
443
+ depth++;
444
+ else if (c === ')' || c === ']' || c === '}')
445
+ depth--;
446
+ else if (c === ',' && depth === 0)
447
+ return j;
448
+ }
449
+ return -1;
450
+ }
362
451
  function ifBlock() {
363
452
  const start = i;
364
453
  i += 3;
@@ -439,7 +528,30 @@ export function parse(source, file) {
439
528
  const listStart = at + first.start + m.indices[2][0];
440
529
  let track = null;
441
530
  let trackStart = -1;
531
+ const aliases = [];
442
532
  for (const clause of rest) {
533
+ if (/^let\s/.test(clause.text)) {
534
+ let from = at + clause.start + 4;
535
+ for (const part of clause.text.slice(4).split(',')) {
536
+ const lead = part.length - part.trimStart().length;
537
+ const a = /^([A-Za-z_$][\w$]*)\s*=\s*(\S+)$/.exec(part.trim());
538
+ const start = from + lead;
539
+ from += part.length + 1;
540
+ if (!a)
541
+ fail('let takes name = $index (or $count, $first, $last, $even, $odd), separated by commas', start);
542
+ const [, name, of] = a;
543
+ if (!FOR_IMPLICIT.includes(of))
544
+ fail(`let takes the row's $index, $count, $first, $last, $even or $odd: ${name} = ${of}`, start);
545
+ if (FOR_IMPLICIT.includes(name))
546
+ fail(`"${name}" is an implicit @for variable: name the alias something else`, start);
547
+ if (name === m[1].trim())
548
+ fail(`"${name}" is this @for's item: name the alias something else`, start);
549
+ if (aliases.some((x) => x.name === name))
550
+ fail(`"${name}" is named twice in this @for`, start);
551
+ aliases.push({ name: name, of: of, start });
552
+ }
553
+ continue;
554
+ }
443
555
  const t = /^track\s+([\s\S]+)$/d.exec(clause.text);
444
556
  if (!t)
445
557
  fail(`unknown @for clause "${clause.text}"`, headStart);
@@ -475,7 +587,7 @@ export function parse(source, file) {
475
587
  }
476
588
  else
477
589
  i = save;
478
- return { type: 'for', item: m[1], list: m[2].trim(), track, headStart, itemStart, listStart, trackStart, children: body, empty, start };
590
+ return { type: 'for', item: m[1], list: m[2].trim(), track, headStart, itemStart, listStart, trackStart, aliases, children: body, empty, start };
479
591
  }
480
592
  function fillBlock() {
481
593
  const start = i;
@@ -523,6 +635,11 @@ export function parse(source, file) {
523
635
  nodes.push(ifBlock());
524
636
  textStart = i;
525
637
  }
638
+ else if (/^@transition[\s({]/.test(source.slice(i, i + 12))) {
639
+ flush();
640
+ nodes.push(transitionBlock());
641
+ textStart = i;
642
+ }
526
643
  else if (/^@await[\s(]/.test(source.slice(i, i + 7))) {
527
644
  flush();
528
645
  nodes.push(awaitBlock());
@@ -677,6 +794,9 @@ export function parse(source, file) {
677
794
  return nodes;
678
795
  }
679
796
  out.nodes = children();
797
+ const kebab = new Map(out.imports.map((imp) => [kebabOf(imp.name), imp.name]).filter(([k, name]) => k !== name && k.includes('-')));
798
+ if (kebab.size)
799
+ renameTags(out.nodes, kebab);
680
800
  return out;
681
801
  }
682
802
  export function importNames(clause) {
@@ -685,3 +805,31 @@ export function importNames(clause) {
685
805
  return clause.slice(1, -1).split(',').map((p) => p.trim()).filter((p) => p && !p.startsWith('type '))
686
806
  .map((p) => p.split(/\s+as\s+/).pop().trim());
687
807
  }
808
+ function renameTags(nodes, names) {
809
+ for (const n of nodes) {
810
+ if (n.type === 'element') {
811
+ n.tag = names.get(n.tag) ?? n.tag;
812
+ renameTags(n.children, names);
813
+ }
814
+ else if (n.type === 'fill')
815
+ renameTags(n.children, names);
816
+ else if (n.type === 'if')
817
+ for (const b of n.branches)
818
+ renameTags(b.children, names);
819
+ else if (n.type === 'for') {
820
+ renameTags(n.children, names);
821
+ if (n.empty)
822
+ renameTags(n.empty, names);
823
+ }
824
+ else if (n.type === 'await') {
825
+ renameTags(n.pending, names);
826
+ if (n.then)
827
+ renameTags(n.then.children, names);
828
+ if (n.catch)
829
+ renameTags(n.catch.children, names);
830
+ }
831
+ }
832
+ }
833
+ export function kebabOf(name) {
834
+ return name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/([A-Z])([A-Z][a-z])/g, '$1-$2').toLowerCase();
835
+ }
@@ -1,4 +1,6 @@
1
1
  export type Signals = Map<string, 'state' | 'derived' | 'shared' | 'input' | 'model'>;
2
+ /** Throw a located ClarusError for a script that isn't JavaScript (#432): what clarusjs check runs before reading it. */
3
+ export declare function checkScript(code: string, file: string, source: string, offset: number): void;
2
4
  /** Throw a located ClarusError unless `expr` is exactly one JS expression. */
3
5
  export declare function checkExpr(expr: string, file: string, source: string, offset: number): void;
4
6
  /** Throw a located ClarusError unless `code` parses as statements (event handlers may hold several). */
@@ -1,4 +1,4 @@
1
- import { parse as acornParse, parseExpressionAt } from 'acorn';
1
+ import { tokenizer, parse as acornParse, parseExpressionAt } from 'acorn';
2
2
  import { FOR_IMPLICIT } from './parse.js';
3
3
  import { ClarusError } from './errors.js';
4
4
  const OPTS = { ecmaVersion: 'latest', sourceType: 'module' };
@@ -51,15 +51,92 @@ function print(node, code, hook, parent = null, key = '') {
51
51
  }
52
52
  return out + code.slice(pos, node.end);
53
53
  }
54
+ const TS = 'TypeScript syntax in a <script> (scripts are JavaScript): ';
55
+ const TS_WHERE = '. Types come from @input, inference, and the .ts modules a script imports';
56
+ function typescriptAt(code, pos) {
57
+ const before = code.slice(0, pos).trimEnd();
58
+ const at = code.slice(pos);
59
+ if (/^as\s/.test(at) && /[\w$)\]]$/.test(before))
60
+ return 'an as cast';
61
+ if (/^satisfies\s/.test(at))
62
+ return 'a satisfies check';
63
+ if (/^!(?!=)/.test(at) && /[\w$)\]]$/.test(before))
64
+ return 'a non-null assertion (!)';
65
+ if (/^:/.test(at) && /[\w$)\]]$/.test(before))
66
+ return 'a type annotation';
67
+ if (/(^|[\n;{}])\s*(interface|enum)\s*$/.test(before) || /(^|[\n;{}])\s*(interface|enum|type\s+[\w$]+\s*[=<])/.test(code.slice(code.lastIndexOf('\n', pos - 1) + 1, pos + 40)))
68
+ return 'a type declaration';
69
+ if (/^</.test(at) && /\bfunction\s+[\w$]+$|[\w$]$/.test(before))
70
+ return 'type parameters (<T>)';
71
+ if (/<[^<>]*>\s*\(?$/.test(before))
72
+ return 'a type argument (<…>)';
73
+ return null;
74
+ }
75
+ const TYPE_TOKENS = new Set(['name', 'string', 'num', ',', '.', '[', ']', '{', '}', ':', '?', '|', '&', '=>', '(', ')', 'true', 'false', 'null', 'void', 'typeof', 'new', '...']);
76
+ function typeArgumentIn(code) {
77
+ let tokens;
78
+ try {
79
+ tokens = [...tokenizer(code, OPTS)];
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ for (let i = 1; i < tokens.length; i++) {
85
+ const lt = tokens[i];
86
+ const name = tokens[i - 1];
87
+ if (lt.value !== '<' || name.type.label !== 'name' || name.end !== lt.start)
88
+ continue;
89
+ let depth = 1;
90
+ let j = i + 1;
91
+ for (; j < tokens.length && depth > 0; j++) {
92
+ const t = tokens[j];
93
+ if (t.value === '<')
94
+ depth++;
95
+ else if (t.value === '>')
96
+ depth--;
97
+ else if (t.value === '>>')
98
+ depth -= 2;
99
+ else if (t.value === '>>>')
100
+ depth -= 3;
101
+ else if (!TYPE_TOKENS.has(t.type.label) && t.type.label !== 'keyof')
102
+ break;
103
+ if (depth < 0)
104
+ break;
105
+ }
106
+ if (depth !== 0 || tokens[j]?.type.label !== '(')
107
+ continue;
108
+ let k = i - 1;
109
+ while (k >= 2 && tokens[k - 1].type.label === '.' && tokens[k - 2].type.label === 'name')
110
+ k -= 2;
111
+ const what = tokens[k - 1]?.type.label === 'function' ? 'type parameters' : 'a type argument';
112
+ const between = code.slice(lt.end, tokens[j - 1].start).trim();
113
+ let p = j + 1;
114
+ for (let open = 1; p < tokens.length && open; p++)
115
+ open += tokens[p].type.label === '(' ? 1 : tokens[p].type.label === ')' ? -1 : 0;
116
+ const inside = code.slice(tokens[j].end, tokens[p - 1].start).trim();
117
+ const comparison = /^[\w$.]+$/.test(between) && tokens[j - 1].value === '>' ? `(${code.slice(tokens[k].start, lt.start)} < ${between}) > ${inside.includes(',') ? `(${inside})` : inside}` : '';
118
+ return { start: tokens[k].start, text: `${code.slice(tokens[k].start, tokens[j - 1].end)}(…)`, what, comparison };
119
+ }
120
+ return null;
121
+ }
54
122
  function parseScript(code, file = '<script>', source = code, offset = 0) {
123
+ const arg = typeArgumentIn(code);
124
+ if (arg)
125
+ throw new ClarusError(`${TS}${arg.what}, ${arg.text}${TS_WHERE}${arg.comparison ? ` (for a comparison, add parentheses: ${arg.comparison})` : ''}`, file, source, offset + arg.start);
55
126
  try {
56
127
  return acornParse(code, OPTS);
57
128
  }
58
129
  catch (e) {
59
130
  const pos = e.pos ?? 0;
131
+ const ts = typescriptAt(code, pos);
132
+ if (ts)
133
+ throw new ClarusError(TS + ts + TS_WHERE, file, source, offset + pos);
60
134
  throw new ClarusError(`script: ${e.message.replace(/ \(\d+:\d+\)$/, '')}`, file, source, offset + pos);
61
135
  }
62
136
  }
137
+ export function checkScript(code, file, source, offset) {
138
+ parseScript(code, file, source, offset);
139
+ }
63
140
  function parseExpr(expr) {
64
141
  const ast = parseExpressionAt(expr, 0, OPTS);
65
142
  const open = (expr.slice(0, ast.start).match(/\(/g) ?? []).length;
@@ -1,5 +1,5 @@
1
1
  import { effect, onDispose, state, untrack } from '../runtime/index.js';
2
- import { marked, openSlots, owner } from '../runtime/dom.js';
2
+ import { keepSlots, marked, openSlots, owner } from '../runtime/dom.js';
3
3
  import { browser } from '../runtime/env.js';
4
4
  const CONTAINERS = 'label, [data-cl-field], fieldset, cl-island';
5
5
  const FIELDS = 'input[data-cl-path],select[data-cl-path],textarea[data-cl-path]';
@@ -7,6 +7,9 @@ const FLAGS = ['valueMissing', 'typeMismatch', 'patternMismatch', 'tooLong', 'to
7
7
  let ids = 0;
8
8
  const read = (value, path) => path.split('.').reduce((v, k) => (v == null ? v : v[k]), value);
9
9
  const dotted = (path = []) => path.map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
10
+ const same = (a, b) => a === b || (!!a && !!b && typeof a === 'object' && typeof b === 'object' && Array.isArray(a) === Array.isArray(b) &&
11
+ Object.keys(a).length === Object.keys(b).length && a.length === b.length &&
12
+ Object.keys(a).every((k) => same(a[k], b[k])));
10
13
  function pathOf(field, root) {
11
14
  const parts = [];
12
15
  let through = 0;
@@ -53,23 +56,26 @@ export function form(values, options = {}) {
53
56
  let server = {};
54
57
  let schemaIssues = {};
55
58
  let errorsNow = {};
59
+ let shownPaths = new Set();
60
+ let touchedPaths = new Set();
56
61
  const roots = new Map();
57
62
  let checkSeq = 0;
58
63
  let latest = Promise.resolve();
59
64
  let revision = 0;
60
65
  let failed = false;
61
66
  let timer;
67
+ let queued = false;
62
68
  let last = initial;
63
69
  const current = state('');
64
70
  const submitting = state(false);
65
71
  const passed = new Set();
66
72
  const now = () => untrack(() => current.get());
67
- const boxOf = (el, path, root) => {
73
+ const boxOf = (el, path, paths) => {
68
74
  for (let c = el.closest(CONTAINERS); c; c = c.parentElement?.closest(CONTAINERS) ?? null) {
69
75
  const box = c.querySelector('[data-cl-message]');
70
76
  if (!box)
71
77
  continue;
72
- return [...c.querySelectorAll(FIELDS)].every((x) => x === el || pathOf(x, root) === path) ? box : undefined;
78
+ return [...c.querySelectorAll(FIELDS)].every((x) => x === el || paths.get(x) === path) ? box : undefined;
73
79
  }
74
80
  };
75
81
  const eventField = (e) => {
@@ -78,10 +84,11 @@ export function form(values, options = {}) {
78
84
  };
79
85
  const fields = () => [...roots.keys()].flatMap((root) => [...root.querySelectorAll(FIELDS)].map((el) => ({ el: el, path: pathOf(el, root), root })));
80
86
  const shownField = (el, path) => shownAll.on || forced.has(path) || checked.has(el) || (show === 'input' ? touched.has(el) || dirty.has(el) : show === 'blur' && touched.has(el));
81
- const shown = (path) => shownAll.on || forced.has(path) || fields().some((f) => f.path === path && shownField(f.el, path));
87
+ const shown = (path) => shownAll.on || forced.has(path) || shownPaths.has(path);
82
88
  function refresh() {
83
89
  const next = {};
84
- for (const { el, path } of fields()) {
90
+ const list = keepSlots(fields);
91
+ for (const { el, path } of list) {
85
92
  el.setCustomValidity('');
86
93
  let native = '';
87
94
  if (!el.validity.valid) {
@@ -99,8 +106,11 @@ export function form(values, options = {}) {
99
106
  if (failed)
100
107
  next[''] ??= options.messages?.schema ?? "The form couldn't be checked. Try again.";
101
108
  errorsNow = next;
102
- for (const { el, path, root } of fields())
103
- paint(el, boxOf(el, path, root), shown(path) ? errorsNow[path] ?? '' : '');
109
+ shownPaths = new Set(list.filter((f) => shownField(f.el, f.path)).map((f) => f.path));
110
+ touchedPaths = new Set(list.filter((f) => touched.has(f.el)).map((f) => f.path));
111
+ const paths = new Map(list.map((f) => [f.el, f.path]));
112
+ for (const { el, path } of list)
113
+ paint(el, boxOf(el, path, paths), shown(path) ? errorsNow[path] ?? '' : '');
104
114
  version.set(untrack(() => version.get()) + 1);
105
115
  }
106
116
  function paint(el, box, message) {
@@ -191,6 +201,13 @@ export function form(values, options = {}) {
191
201
  step?.querySelector('input, select, textarea, button, [tabindex]')?.focus();
192
202
  };
193
203
  const errorsIn = (step) => new Set(fields().filter((f) => step.contains(f.el) && shown(f.path) && errorsNow[f.path]).map((f) => f.path)).size;
204
+ const refreshSoon = () => {
205
+ if (!queued) {
206
+ queued = true;
207
+ queueMicrotask(() => { queued = false; if (roots.size)
208
+ refresh(); });
209
+ }
210
+ };
194
211
  const checkSoon = () => {
195
212
  clearTimeout(timer);
196
213
  timer = setTimeout(check, 300);
@@ -203,10 +220,10 @@ export function form(values, options = {}) {
203
220
  delete server[path];
204
221
  last = value;
205
222
  revision++;
206
- if (roots.size) {
207
- refresh();
223
+ if (roots.size)
224
+ refreshSoon();
225
+ if (roots.size)
208
226
  checkSoon();
209
- }
210
227
  });
211
228
  });
212
229
  const onInput = (e) => {
@@ -215,7 +232,7 @@ export function form(values, options = {}) {
215
232
  return;
216
233
  dirty.add(field);
217
234
  revision++;
218
- refresh();
235
+ refreshSoon();
219
236
  checkSoon();
220
237
  };
221
238
  const onLeave = (e) => {
@@ -241,10 +258,11 @@ export function form(values, options = {}) {
241
258
  version.get();
242
259
  const out = [];
243
260
  const all = fields();
244
- for (const { el, path, root } of all) {
261
+ const paths = new Map(all.map((f) => [f.el, f.path]));
262
+ for (const { el, path } of all) {
245
263
  if (out.some((e) => e.path === path) || !shown(path) || !errorsNow[path])
246
264
  continue;
247
- out.push({ path, message: errorsNow[path], id: boxOf(el, path, root)?.id || el.id, step: el.closest('[data-cl-step]')?.id ?? null });
265
+ out.push({ path, message: errorsNow[path], id: boxOf(el, path, paths)?.id || el.id, step: el.closest('[data-cl-step]')?.id ?? null });
248
266
  }
249
267
  for (const [path, message] of Object.entries(errorsNow)) {
250
268
  if (!all.some((f) => f.path === path) && (shownAll.on || forced.has(path)))
@@ -252,8 +270,10 @@ export function form(values, options = {}) {
252
270
  }
253
271
  return out;
254
272
  },
255
- touched(path) { version.get(); return fields().some((f) => f.path === path && touched.has(f.el)); },
273
+ touched(path) { version.get(); return touchedPaths.has(path); },
256
274
  changed(path) { return read(signal.get(), path) !== read(initial, path); },
275
+ get dirty() { return !same(signal.get(), initial); },
276
+ shown(path) { version.get(); return shown(path); },
257
277
  get valid() { version.get(); return !Object.keys(errorsNow).length; },
258
278
  get pending() { return pending.get(); },
259
279
  setErrors(errors) { server = { ...errors }; for (const path of Object.keys(errors))
@@ -382,7 +402,7 @@ export function connect(ctx, index, get) {
382
402
  }
383
403
  function inert() {
384
404
  return {
385
- error: () => '', errors: [], touched: () => false, changed: () => false, valid: true, pending: false,
405
+ error: () => '', errors: [], touched: () => false, changed: () => false, dirty: false, shown: () => false, valid: true, pending: false,
386
406
  setErrors() { }, focus() { }, reset() { }, step: '', steps: [], next: async () => false, back() { }, go() { },
387
407
  submitting: false, submit: async () => false,
388
408
  };
@@ -71,6 +71,13 @@ export type Form<T> = {
71
71
  touched(path: Path<T>): boolean;
72
72
  /** Differs from the starting value. */
73
73
  changed(path: Path<T>): boolean;
74
+ /** Any value differs from the start (compared by value: typed into and back is clean). For "unsaved changes". */
75
+ readonly dirty: boolean;
76
+ /**
77
+ * Whether this field's error shows now, by the form's `show` rule (or after a step check or a submit): for a field
78
+ * that shows its own error, such as a component's.
79
+ */
80
+ shown(path: Path<T>): boolean;
74
81
  /** No errors at all (shown or not). */
75
82
  readonly valid: boolean;
76
83
  /** An async schema check is running. */
@@ -0,0 +1,26 @@
1
+ import { type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2
+ /** @see https://clarusjs.com/guide/deploy#node */
3
+ export type ServeOptions = {
4
+ /** The project folder (the one with dist/). Default: the current folder. */
5
+ root?: string;
6
+ /** Default: $PORT, else 3000. 0 picks a free port. */
7
+ port?: number;
8
+ /** Default: $HOST, else 0.0.0.0 (every interface, as a container needs). */
9
+ host?: string;
10
+ };
11
+ /**
12
+ * The request listener for a built site, for your own `http.createServer()` (or a framework that takes one). Each
13
+ * request: a file under dist/client (a page at `<path>/index.html`), else a server route or endpoint, else 404.html.
14
+ * @example
15
+ * const site = await createListener('.')
16
+ * createServer((req, res) => (req.url === '/healthz' ? res.end('ok') : site(req, res))).listen(3000)
17
+ * @see https://clarusjs.com/guide/deploy#node
18
+ */
19
+ export declare function createListener(root?: string): Promise<(req: IncomingMessage, res: ServerResponse) => Promise<void>>;
20
+ /**
21
+ * Serves a built site. Resolves once it listens.
22
+ * @example
23
+ * const server = await serve({ root: '.', port: 8080 })
24
+ * @see https://clarusjs.com/guide/deploy#node
25
+ */
26
+ export declare function serve(options?: ServeOptions): Promise<Server>;