clarusjs 0.8.0 → 0.9.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.
- package/dist/check/generate.d.ts +26 -4
- package/dist/check/generate.js +160 -21
- package/dist/cli/check.d.ts +13 -0
- package/dist/cli/check.js +76 -19
- package/dist/cli/index.js +9 -3
- package/dist/cli/mapper.d.ts +25 -0
- package/dist/cli/mapper.js +65 -0
- package/dist/cli/project.d.ts +5 -0
- package/dist/cli/project.js +21 -0
- package/dist/compiler/emit-client.js +23 -4
- package/dist/compiler/emit-server.js +3 -2
- package/dist/compiler/html-expr.js +5 -2
- package/dist/compiler/index.d.ts +8 -1
- package/dist/compiler/index.js +34 -23
- package/dist/compiler/ir.d.ts +13 -0
- package/dist/compiler/ir.js +157 -7
- package/dist/compiler/parse.d.ts +18 -1
- package/dist/compiler/parse.js +134 -6
- package/dist/compiler/script.d.ts +22 -1
- package/dist/compiler/script.js +81 -5
- package/dist/forms/index.d.ts +7 -0
- package/dist/forms/index.js +374 -0
- package/dist/forms/types.d.ts +94 -0
- package/dist/forms/types.js +1 -0
- package/dist/runtime/dom.d.ts +12 -5
- package/dist/runtime/dom.js +76 -5
- package/dist/runtime/env.d.ts +7 -0
- package/dist/runtime/env.js +7 -0
- package/dist/runtime/fragments.d.ts +1 -1
- package/dist/runtime/fragments.js +10 -35
- package/dist/runtime/index.d.ts +3 -2
- package/dist/runtime/index.js +3 -2
- package/dist/runtime/loader.d.ts +1 -1
- package/dist/runtime/loader.js +38 -5
- package/dist/runtime/navigate.d.ts +38 -0
- package/dist/runtime/navigate.js +88 -0
- package/dist/runtime/navigation.d.ts +88 -0
- package/dist/runtime/navigation.js +165 -0
- package/dist/runtime/router.d.ts +8 -1
- package/dist/runtime/router.js +38 -40
- package/dist/runtime/server.d.ts +1 -1
- package/dist/runtime/server.js +4 -2
- package/dist/runtime/signals.d.ts +2 -0
- package/dist/runtime/signals.js +25 -3
- package/dist/server/handler.d.ts +8 -0
- package/dist/server/handler.js +36 -9
- package/dist/vite/aliases.d.ts +10 -0
- package/dist/vite/aliases.js +42 -0
- package/dist/vite/build.d.ts +2 -1
- package/dist/vite/build.js +3 -2
- package/dist/vite/plugin.d.ts +6 -0
- package/dist/vite/plugin.js +82 -20
- package/dist/vite/redirects.d.ts +10 -0
- package/dist/vite/redirects.js +41 -0
- package/package.json +29 -1
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import { effect, onDispose, state, untrack } from '../runtime/index.js';
|
|
2
|
+
import { marked } from '../runtime/dom.js';
|
|
3
|
+
import { browser } from '../runtime/env.js';
|
|
4
|
+
const CONTAINERS = 'label, [data-cl-field], fieldset, cl-island';
|
|
5
|
+
const FIELDS = 'input[data-cl-path],select[data-cl-path],textarea[data-cl-path]';
|
|
6
|
+
const FLAGS = ['valueMissing', 'typeMismatch', 'patternMismatch', 'tooLong', 'tooShort', 'rangeUnderflow', 'rangeOverflow', 'stepMismatch', 'badInput'];
|
|
7
|
+
let ids = 0;
|
|
8
|
+
const read = (value, path) => path.split('.').reduce((v, k) => (v == null ? v : v[k]), value);
|
|
9
|
+
const dotted = (path = []) => path.map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
|
|
10
|
+
function pathOf(field, root) {
|
|
11
|
+
const parts = [];
|
|
12
|
+
for (let el = field; el && el !== root.parentElement; el = el.parentElement) {
|
|
13
|
+
const here = el;
|
|
14
|
+
let part = here.getAttribute('data-cl-path');
|
|
15
|
+
if (part?.startsWith('@')) {
|
|
16
|
+
const [model, ...rest] = part.slice(1).split('.');
|
|
17
|
+
const island = here.parentElement?.closest(`[data-cl-path-${model}]`);
|
|
18
|
+
if (!island)
|
|
19
|
+
return '';
|
|
20
|
+
part = [island.getAttribute(`data-cl-path-${model}`), ...rest].filter(Boolean).join('.');
|
|
21
|
+
el = island;
|
|
22
|
+
}
|
|
23
|
+
if (part)
|
|
24
|
+
parts.unshift(part);
|
|
25
|
+
}
|
|
26
|
+
return parts.join('.');
|
|
27
|
+
}
|
|
28
|
+
export function form(values, options = {}) {
|
|
29
|
+
if (!browser || !values || typeof values.get !== 'function')
|
|
30
|
+
return inert();
|
|
31
|
+
const signal = values;
|
|
32
|
+
let initial = untrack(() => signal.get());
|
|
33
|
+
const show = options.show ?? 'blur';
|
|
34
|
+
const version = state(0);
|
|
35
|
+
const pending = state(false);
|
|
36
|
+
let touched = new WeakSet();
|
|
37
|
+
let dirty = new WeakSet();
|
|
38
|
+
let checked = new WeakSet();
|
|
39
|
+
const shownAll = { on: false };
|
|
40
|
+
const forced = new Set();
|
|
41
|
+
let server = {};
|
|
42
|
+
let schemaIssues = {};
|
|
43
|
+
let errorsNow = {};
|
|
44
|
+
const roots = new Map();
|
|
45
|
+
let checkSeq = 0;
|
|
46
|
+
let latest = Promise.resolve();
|
|
47
|
+
let revision = 0;
|
|
48
|
+
let failed = false;
|
|
49
|
+
let timer;
|
|
50
|
+
let last = initial;
|
|
51
|
+
const current = state('');
|
|
52
|
+
const submitting = state(false);
|
|
53
|
+
const passed = new Set();
|
|
54
|
+
const now = () => untrack(() => current.get());
|
|
55
|
+
const boxOf = (el, path, root) => {
|
|
56
|
+
for (let c = el.closest(CONTAINERS); c; c = c.parentElement?.closest(CONTAINERS) ?? null) {
|
|
57
|
+
const box = c.querySelector('[data-cl-message]');
|
|
58
|
+
if (!box)
|
|
59
|
+
continue;
|
|
60
|
+
return [...c.querySelectorAll(FIELDS)].every((x) => x === el || pathOf(x, root) === path) ? box : undefined;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const eventField = (e) => {
|
|
64
|
+
const field = e.target.closest?.(FIELDS);
|
|
65
|
+
return field && [...roots.keys()].some((r) => r.contains(field)) ? field : undefined;
|
|
66
|
+
};
|
|
67
|
+
const fields = () => [...roots.keys()].flatMap((root) => [...root.querySelectorAll(FIELDS)].map((el) => ({ el: el, path: pathOf(el, root), root })));
|
|
68
|
+
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));
|
|
69
|
+
const shown = (path) => shownAll.on || forced.has(path) || fields().some((f) => f.path === path && shownField(f.el, path));
|
|
70
|
+
function refresh() {
|
|
71
|
+
const next = {};
|
|
72
|
+
for (const { el, path } of fields()) {
|
|
73
|
+
el.setCustomValidity('');
|
|
74
|
+
let native = '';
|
|
75
|
+
if (!el.validity.valid) {
|
|
76
|
+
const flag = FLAGS.find((f) => el.validity[f]);
|
|
77
|
+
native = options.messages?.[path] ?? (flag && options.messages?.[flag]) ?? el.validationMessage;
|
|
78
|
+
}
|
|
79
|
+
const message = server[path] || schemaIssues[path] || native || next[path] || '';
|
|
80
|
+
if (message)
|
|
81
|
+
next[path] = message;
|
|
82
|
+
if (server[path] || schemaIssues[path])
|
|
83
|
+
el.setCustomValidity(message);
|
|
84
|
+
}
|
|
85
|
+
for (const path of new Set([...Object.keys(schemaIssues), ...Object.keys(server)]))
|
|
86
|
+
next[path] ??= server[path] || schemaIssues[path];
|
|
87
|
+
if (failed)
|
|
88
|
+
next[''] ??= options.messages?.schema ?? "The form couldn't be checked. Try again.";
|
|
89
|
+
errorsNow = next;
|
|
90
|
+
for (const { el, path, root } of fields())
|
|
91
|
+
paint(el, boxOf(el, path, root), shown(path) ? errorsNow[path] ?? '' : '');
|
|
92
|
+
version.set(untrack(() => version.get()) + 1);
|
|
93
|
+
}
|
|
94
|
+
function paint(el, box, message) {
|
|
95
|
+
if (box) {
|
|
96
|
+
if (!box.id)
|
|
97
|
+
box.id = `cl-msg-${++ids}`;
|
|
98
|
+
const described = (el.getAttribute('aria-describedby') ?? '').split(/\s+/).filter(Boolean);
|
|
99
|
+
if (!described.includes(box.id))
|
|
100
|
+
el.setAttribute('aria-describedby', [...described, box.id].join(' '));
|
|
101
|
+
box.textContent = message;
|
|
102
|
+
box.hidden = !message;
|
|
103
|
+
}
|
|
104
|
+
if (message)
|
|
105
|
+
el.setAttribute('aria-invalid', 'true');
|
|
106
|
+
else
|
|
107
|
+
el.removeAttribute('aria-invalid');
|
|
108
|
+
}
|
|
109
|
+
function check() {
|
|
110
|
+
const schema = options.schema;
|
|
111
|
+
if (!schema)
|
|
112
|
+
return (latest = Promise.resolve());
|
|
113
|
+
const seq = ++checkSeq;
|
|
114
|
+
const apply = (result) => {
|
|
115
|
+
if (seq !== checkSeq)
|
|
116
|
+
return;
|
|
117
|
+
schemaIssues = {};
|
|
118
|
+
failed = false;
|
|
119
|
+
for (const issue of result.issues ?? []) {
|
|
120
|
+
const path = dotted(issue.path);
|
|
121
|
+
schemaIssues[path] ??= issue.message;
|
|
122
|
+
}
|
|
123
|
+
pending.set(false);
|
|
124
|
+
refresh();
|
|
125
|
+
};
|
|
126
|
+
const result = schema['~standard'].validate(untrack(() => signal.get()));
|
|
127
|
+
if (!(result instanceof Promise))
|
|
128
|
+
return (latest = Promise.resolve(apply(result)));
|
|
129
|
+
pending.set(true);
|
|
130
|
+
return (latest = result.then(apply, (err) => {
|
|
131
|
+
if (seq === checkSeq) {
|
|
132
|
+
pending.set(false);
|
|
133
|
+
failed = true;
|
|
134
|
+
refresh();
|
|
135
|
+
}
|
|
136
|
+
console.error('[clarusjs] the form schema failed', err);
|
|
137
|
+
}));
|
|
138
|
+
}
|
|
139
|
+
async function settle() {
|
|
140
|
+
for (;;) {
|
|
141
|
+
clearTimeout(timer);
|
|
142
|
+
const start = revision;
|
|
143
|
+
const p = check();
|
|
144
|
+
await p;
|
|
145
|
+
if (p === latest && revision === start)
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const steps = () => [...roots.keys()].flatMap((root) => [...root.querySelectorAll('[data-cl-step][id]')]);
|
|
150
|
+
function showStep(id, push) {
|
|
151
|
+
current.set(id);
|
|
152
|
+
for (const step of steps()) {
|
|
153
|
+
step.hidden = step.id !== id;
|
|
154
|
+
step.toggleAttribute('data-cl-current', step.id === id);
|
|
155
|
+
}
|
|
156
|
+
if (push && location.hash !== `#${id}`)
|
|
157
|
+
history.pushState(null, '', `#${id}`);
|
|
158
|
+
refresh();
|
|
159
|
+
}
|
|
160
|
+
const hashStep = () => {
|
|
161
|
+
let id = '';
|
|
162
|
+
try {
|
|
163
|
+
id = decodeURIComponent(location.hash.slice(1));
|
|
164
|
+
}
|
|
165
|
+
catch { }
|
|
166
|
+
return steps().find((s) => s.id === id)?.id;
|
|
167
|
+
};
|
|
168
|
+
const onHash = () => {
|
|
169
|
+
const id = hashStep() ?? (location.hash.length > 1 ? undefined : steps()[0]?.id);
|
|
170
|
+
if (id && id !== now())
|
|
171
|
+
showStep(id, false);
|
|
172
|
+
};
|
|
173
|
+
const go = (id) => {
|
|
174
|
+
showStep(id, true);
|
|
175
|
+
const step = steps().find((s) => s.id === id);
|
|
176
|
+
step?.querySelector('input, select, textarea, button, [tabindex]')?.focus();
|
|
177
|
+
};
|
|
178
|
+
const errorsIn = (step) => new Set(fields().filter((f) => step.contains(f.el) && shown(f.path) && errorsNow[f.path]).map((f) => f.path)).size;
|
|
179
|
+
const checkSoon = () => {
|
|
180
|
+
clearTimeout(timer);
|
|
181
|
+
timer = setTimeout(check, 300);
|
|
182
|
+
};
|
|
183
|
+
effect(() => {
|
|
184
|
+
const value = signal.get();
|
|
185
|
+
untrack(() => {
|
|
186
|
+
for (const path of Object.keys(server))
|
|
187
|
+
if (read(value, path) !== read(last, path))
|
|
188
|
+
delete server[path];
|
|
189
|
+
last = value;
|
|
190
|
+
revision++;
|
|
191
|
+
if (roots.size) {
|
|
192
|
+
refresh();
|
|
193
|
+
checkSoon();
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
});
|
|
197
|
+
const onInput = (e) => {
|
|
198
|
+
const field = eventField(e);
|
|
199
|
+
if (!field)
|
|
200
|
+
return;
|
|
201
|
+
dirty.add(field);
|
|
202
|
+
revision++;
|
|
203
|
+
refresh();
|
|
204
|
+
checkSoon();
|
|
205
|
+
};
|
|
206
|
+
const onLeave = (e) => {
|
|
207
|
+
const field = eventField(e);
|
|
208
|
+
if (!field)
|
|
209
|
+
return;
|
|
210
|
+
touched.add(field);
|
|
211
|
+
refresh();
|
|
212
|
+
check();
|
|
213
|
+
};
|
|
214
|
+
const onSubmit = (e) => { e.preventDefault(); void engine.submit(); };
|
|
215
|
+
const listeners = [['input', onInput], ['change', onInput], ['focusout', onLeave], ['submit', onSubmit]];
|
|
216
|
+
const toFirstError = () => {
|
|
217
|
+
const first = fields().find((f) => errorsNow[f.path]);
|
|
218
|
+
if (first)
|
|
219
|
+
engine.focus(first.path);
|
|
220
|
+
return !Object.keys(errorsNow).length;
|
|
221
|
+
};
|
|
222
|
+
const urlEvents = ['popstate', 'hashchange'];
|
|
223
|
+
const engine = {
|
|
224
|
+
error(path) { version.get(); return shown(path) ? errorsNow[path] ?? '' : ''; },
|
|
225
|
+
get errors() {
|
|
226
|
+
version.get();
|
|
227
|
+
const out = [];
|
|
228
|
+
const all = fields();
|
|
229
|
+
for (const { el, path, root } of all) {
|
|
230
|
+
if (out.some((e) => e.path === path) || !shown(path) || !errorsNow[path])
|
|
231
|
+
continue;
|
|
232
|
+
out.push({ path, message: errorsNow[path], id: boxOf(el, path, root)?.id || el.id, step: el.closest('[data-cl-step]')?.id ?? null });
|
|
233
|
+
}
|
|
234
|
+
for (const [path, message] of Object.entries(errorsNow)) {
|
|
235
|
+
if (!all.some((f) => f.path === path) && (shownAll.on || forced.has(path)))
|
|
236
|
+
out.push({ path, message, id: '', step: null });
|
|
237
|
+
}
|
|
238
|
+
return out;
|
|
239
|
+
},
|
|
240
|
+
touched(path) { version.get(); return fields().some((f) => f.path === path && touched.has(f.el)); },
|
|
241
|
+
changed(path) { return read(signal.get(), path) !== read(initial, path); },
|
|
242
|
+
get valid() { version.get(); return !Object.keys(errorsNow).length; },
|
|
243
|
+
get pending() { return pending.get(); },
|
|
244
|
+
setErrors(errors) { server = { ...errors }; for (const path of Object.keys(errors))
|
|
245
|
+
forced.add(path); refresh(); },
|
|
246
|
+
focus(path) {
|
|
247
|
+
const group = fields().filter((f) => f.path === path).map((f) => f.el);
|
|
248
|
+
const el = group.find((x) => x.checked) ?? group[0];
|
|
249
|
+
const step = el?.closest('[data-cl-step][id]');
|
|
250
|
+
if (step?.hidden)
|
|
251
|
+
showStep(step.id, true);
|
|
252
|
+
el?.focus();
|
|
253
|
+
},
|
|
254
|
+
get step() { return current.get(); },
|
|
255
|
+
get steps() {
|
|
256
|
+
version.get();
|
|
257
|
+
const shownStep = current.get();
|
|
258
|
+
return steps().map((s) => { const errors = errorsIn(s); return { id: s.id, current: s.id === shownStep, done: passed.has(s.id) && !errors, errors }; });
|
|
259
|
+
},
|
|
260
|
+
async next() {
|
|
261
|
+
const list = steps();
|
|
262
|
+
const at = list.findIndex((s) => s.id === now());
|
|
263
|
+
const step = list[at];
|
|
264
|
+
if (!step)
|
|
265
|
+
return false;
|
|
266
|
+
for (const f of fields())
|
|
267
|
+
if (step.contains(f.el))
|
|
268
|
+
checked.add(f.el);
|
|
269
|
+
await settle();
|
|
270
|
+
refresh();
|
|
271
|
+
const bad = fields().find((f) => step.contains(f.el) && errorsNow[f.path]);
|
|
272
|
+
if (bad) {
|
|
273
|
+
bad.el.focus();
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
passed.add(step.id);
|
|
277
|
+
if (list[at + 1])
|
|
278
|
+
go(list[at + 1].id);
|
|
279
|
+
return true;
|
|
280
|
+
},
|
|
281
|
+
back() {
|
|
282
|
+
const list = steps();
|
|
283
|
+
const prev = list[list.findIndex((s) => s.id === now()) - 1];
|
|
284
|
+
if (prev)
|
|
285
|
+
go(prev.id);
|
|
286
|
+
},
|
|
287
|
+
go,
|
|
288
|
+
get submitting() { return submitting.get(); },
|
|
289
|
+
async submit() {
|
|
290
|
+
if (untrack(() => submitting.get()))
|
|
291
|
+
return false;
|
|
292
|
+
submitting.set(true);
|
|
293
|
+
try {
|
|
294
|
+
shownAll.on = true;
|
|
295
|
+
await settle();
|
|
296
|
+
refresh();
|
|
297
|
+
if (!toFirstError())
|
|
298
|
+
return false;
|
|
299
|
+
const sent = untrack(() => signal.get());
|
|
300
|
+
const answer = await options.submit?.(sent);
|
|
301
|
+
const now = untrack(() => signal.get());
|
|
302
|
+
const errors = Object.entries(answer?.errors ?? {}).filter(([path]) => !path || read(now, path) === read(sent, path));
|
|
303
|
+
if (errors.length) {
|
|
304
|
+
engine.setErrors(Object.fromEntries(errors));
|
|
305
|
+
return toFirstError();
|
|
306
|
+
}
|
|
307
|
+
return true;
|
|
308
|
+
}
|
|
309
|
+
finally {
|
|
310
|
+
submitting.set(false);
|
|
311
|
+
}
|
|
312
|
+
},
|
|
313
|
+
reset(next) {
|
|
314
|
+
if (next !== undefined)
|
|
315
|
+
initial = next;
|
|
316
|
+
touched = new WeakSet();
|
|
317
|
+
dirty = new WeakSet();
|
|
318
|
+
checked = new WeakSet();
|
|
319
|
+
forced.clear();
|
|
320
|
+
server = {};
|
|
321
|
+
shownAll.on = false;
|
|
322
|
+
signal.set(initial);
|
|
323
|
+
refresh();
|
|
324
|
+
},
|
|
325
|
+
connect(el) {
|
|
326
|
+
const root = el.closest('form') ?? el;
|
|
327
|
+
const count = roots.get(root) ?? 0;
|
|
328
|
+
roots.set(root, count + 1);
|
|
329
|
+
if (!count) {
|
|
330
|
+
if (root instanceof HTMLFormElement)
|
|
331
|
+
root.noValidate = true;
|
|
332
|
+
for (const [type, fn] of listeners)
|
|
333
|
+
root.addEventListener(type, fn);
|
|
334
|
+
if (roots.size === 1)
|
|
335
|
+
for (const type of urlEvents)
|
|
336
|
+
addEventListener(type, onHash);
|
|
337
|
+
const list = steps();
|
|
338
|
+
if (list.length) {
|
|
339
|
+
root.setAttribute('data-cl-steps', '');
|
|
340
|
+
showStep(hashStep() || now() || list[0].id, false);
|
|
341
|
+
}
|
|
342
|
+
refresh();
|
|
343
|
+
check();
|
|
344
|
+
}
|
|
345
|
+
return () => {
|
|
346
|
+
const left = (roots.get(root) ?? 1) - 1;
|
|
347
|
+
if (left)
|
|
348
|
+
return void roots.set(root, left);
|
|
349
|
+
roots.delete(root);
|
|
350
|
+
for (const [type, fn] of listeners)
|
|
351
|
+
root.removeEventListener(type, fn);
|
|
352
|
+
if (!roots.size) {
|
|
353
|
+
for (const type of urlEvents)
|
|
354
|
+
removeEventListener(type, onHash);
|
|
355
|
+
clearTimeout(timer);
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
},
|
|
359
|
+
};
|
|
360
|
+
return engine;
|
|
361
|
+
}
|
|
362
|
+
export function connect(ctx, index, get) {
|
|
363
|
+
const el = marked(ctx, `[data-cl-form="${index}"]`);
|
|
364
|
+
const engine = get();
|
|
365
|
+
if (el && typeof engine.connect === 'function')
|
|
366
|
+
onDispose(engine.connect(el));
|
|
367
|
+
}
|
|
368
|
+
function inert() {
|
|
369
|
+
return {
|
|
370
|
+
error: () => '', errors: [], touched: () => false, changed: () => false, valid: true, pending: false,
|
|
371
|
+
setErrors() { }, focus() { }, reset() { }, step: '', steps: [], next: async () => false, back() { }, go() { },
|
|
372
|
+
submitting: false, submit: async () => false,
|
|
373
|
+
};
|
|
374
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/** A Standard Schema (https://standardschema.dev): Zod, Valibot, ArkType… Declared here, so there's no dependency. */
|
|
2
|
+
export type StandardSchema<T = unknown> = {
|
|
3
|
+
readonly '~standard': {
|
|
4
|
+
readonly version: 1;
|
|
5
|
+
readonly vendor: string;
|
|
6
|
+
validate(value: unknown): StandardResult<T> | Promise<StandardResult<T>>;
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
export type StandardIssue = {
|
|
10
|
+
readonly message: string;
|
|
11
|
+
readonly path?: ReadonlyArray<PropertyKey | {
|
|
12
|
+
readonly key: PropertyKey;
|
|
13
|
+
}>;
|
|
14
|
+
};
|
|
15
|
+
export type StandardResult<T> = {
|
|
16
|
+
readonly value: T;
|
|
17
|
+
readonly issues?: undefined;
|
|
18
|
+
} | {
|
|
19
|
+
readonly issues: ReadonlyArray<StandardIssue>;
|
|
20
|
+
};
|
|
21
|
+
/** The dotted paths of a form's values: `customer.email`, `lines.0.item` (any string for values typed `any`). */
|
|
22
|
+
export type Path<T> = 0 extends 1 & T ? string : PathOf<T, 6>;
|
|
23
|
+
type Prev = [never, 0, 1, 2, 3, 4, 5];
|
|
24
|
+
type PathOf<T, D extends number> = [D] extends [never] ? never : T extends readonly (infer U)[] ? `${number}` | `${number}.${PathOf<U, Prev[D]>}` : T extends object ? {
|
|
25
|
+
[K in keyof T & string]: K | `${K}.${PathOf<T[K], Prev[D]>}`;
|
|
26
|
+
}[keyof T & string] : never;
|
|
27
|
+
export type FormOptions<T> = {
|
|
28
|
+
/** Validates the whole object; its issues land on their fields by path. Sync or async. */
|
|
29
|
+
schema?: StandardSchema<T>;
|
|
30
|
+
/** When a field's error appears: after it's been left once ('blur', the default), on input, or on submit. */
|
|
31
|
+
show?: 'blur' | 'input' | 'submit';
|
|
32
|
+
/** Messages for native constraints, by path (`'customer.email'`) or by constraint (`valueMissing`, `typeMismatch`…). */
|
|
33
|
+
messages?: Record<string, string>;
|
|
34
|
+
/** Called with the values once everything is valid; may return server errors by path. */
|
|
35
|
+
submit?(values: T): void | {
|
|
36
|
+
errors?: Record<string, string>;
|
|
37
|
+
} | Promise<void | {
|
|
38
|
+
errors?: Record<string, string>;
|
|
39
|
+
}>;
|
|
40
|
+
};
|
|
41
|
+
/** An error being shown, for a summary: its path, message, its message element's id, and its step. */
|
|
42
|
+
export type FormError<T = any> = {
|
|
43
|
+
path: Path<T>;
|
|
44
|
+
message: string;
|
|
45
|
+
id: string;
|
|
46
|
+
step: string | null;
|
|
47
|
+
};
|
|
48
|
+
export type Form<T> = {
|
|
49
|
+
/** The message shown for a field now: '' when there is none, or it isn't shown yet. */
|
|
50
|
+
error(path: Path<T>): string;
|
|
51
|
+
/** Every error being shown, in document order. */
|
|
52
|
+
readonly errors: FormError<T>[];
|
|
53
|
+
/** Left at least once. */
|
|
54
|
+
touched(path: Path<T>): boolean;
|
|
55
|
+
/** Differs from the starting value. */
|
|
56
|
+
changed(path: Path<T>): boolean;
|
|
57
|
+
/** No errors at all (shown or not). */
|
|
58
|
+
readonly valid: boolean;
|
|
59
|
+
/** An async schema check is running. */
|
|
60
|
+
readonly pending: boolean;
|
|
61
|
+
/** Server errors by path (they show until that field's value changes). */
|
|
62
|
+
setErrors(errors: Record<string, string>): void;
|
|
63
|
+
/** Focus a field (the checked radio of a group, else the first). */
|
|
64
|
+
focus(path: Path<T>): void;
|
|
65
|
+
/**
|
|
66
|
+
* Back to the starting values, with touched and errors cleared. With `values` (a record loaded after the form was
|
|
67
|
+
* made, or saved), those become the values and the new starting point.
|
|
68
|
+
*/
|
|
69
|
+
reset(values?: T): void;
|
|
70
|
+
/** Multi-step forms: the current step's id. */
|
|
71
|
+
readonly step: string;
|
|
72
|
+
/** Every step, in document order: current, done (left with next() and now without errors), errors shown in it. */
|
|
73
|
+
readonly steps: {
|
|
74
|
+
id: string;
|
|
75
|
+
current: boolean;
|
|
76
|
+
done: boolean;
|
|
77
|
+
errors: number;
|
|
78
|
+
}[];
|
|
79
|
+
/** Check the current step; with errors, stay and focus the first (false); else go to the next step (true). */
|
|
80
|
+
next(): Promise<boolean>;
|
|
81
|
+
/** The previous step, without checks. */
|
|
82
|
+
back(): void;
|
|
83
|
+
/** Go to a step by id. */
|
|
84
|
+
go(id: string): void;
|
|
85
|
+
/** The submit callback is running. */
|
|
86
|
+
readonly submitting: boolean;
|
|
87
|
+
/**
|
|
88
|
+
* Check everything; with errors, go to the first (its step, its field) and resolve false. Else call `submit` with
|
|
89
|
+
* the values: server errors it returns land the same way (false); otherwise true. A connected <form> runs this on
|
|
90
|
+
* submit. One at a time.
|
|
91
|
+
*/
|
|
92
|
+
submit(): Promise<boolean>;
|
|
93
|
+
};
|
|
94
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/runtime/dom.d.ts
CHANGED
|
@@ -37,11 +37,6 @@ export declare function block(ctx: Ctx, index: number, which: () => number, bran
|
|
|
37
37
|
html: () => string;
|
|
38
38
|
wire: () => void;
|
|
39
39
|
}[]): void;
|
|
40
|
-
/**
|
|
41
|
-
* A child component inside an island whose props or content read state. `html()` renders it with the current
|
|
42
|
-
* values; when anything it read changes, the old HTML is disposed and replaced, and `wire()` wires the island's own
|
|
43
|
-
* holes and events in the child's slot content again. A stateful child is remounted with its new props.
|
|
44
|
-
*/
|
|
45
40
|
export declare function region(ctx: Ctx, index: number, html: () => string, wire: () => void): void;
|
|
46
41
|
/**
|
|
47
42
|
* A @for list. Rows the server rendered are adopted in place. When the list changes, rows are matched by key:
|
|
@@ -65,6 +60,18 @@ export declare function text(hole: Hole, fn: () => unknown): void;
|
|
|
65
60
|
* for elements in that row.
|
|
66
61
|
*/
|
|
67
62
|
export declare function on(ctx: Ctx, index: number, type: string, fn: (e: Event) => void): void;
|
|
63
|
+
/** The element matching `selector` in `ctx`: this island's (not a nested island's), and in a row, that row's. */
|
|
64
|
+
export declare function marked(ctx: Ctx, selector: string): Element | undefined;
|
|
68
65
|
/** Keep attribute `name` of the element marked `data-cl-a="index"` in `ctx` in sync with `fn()`. */
|
|
69
66
|
export declare function attr(ctx: Ctx, index: number, name: string, fn: () => unknown, tag?: string): void;
|
|
67
|
+
/**
|
|
68
|
+
* A @model input: writing it asks the parent island to update its state (a bubbling, cancelable cl:model event from
|
|
69
|
+
* the island); when no parent takes it (a top-level island), the input keeps the value itself. New props from the
|
|
70
|
+
* parent set it with own().
|
|
71
|
+
*/
|
|
72
|
+
export declare function modelInput<T>(root: Element, name: string, initial: T): Signal<T> & {
|
|
73
|
+
own(value: T): void;
|
|
74
|
+
};
|
|
75
|
+
/** [(name)]="…" on a child island in region `index`: the child's writes to its @model name arrive here. */
|
|
76
|
+
export declare function model(ctx: Ctx, index: number, name: string, set: (value: unknown) => void): void;
|
|
70
77
|
export {};
|
package/dist/runtime/dom.js
CHANGED
|
@@ -133,6 +133,11 @@ export function block(ctx, index, which, branches) {
|
|
|
133
133
|
* values; when anything it read changes, the old HTML is disposed and replaced, and `wire()` wires the island's own
|
|
134
134
|
* holes and events in the child's slot content again. A stateful child is remounted with its new props.
|
|
135
135
|
*/
|
|
136
|
+
/** The one <cl-island> among `nodes` (blank text aside), or null. */
|
|
137
|
+
const onlyIsland = (nodes) => {
|
|
138
|
+
const kept = nodes.filter((n) => n.nodeType !== 3 || n.textContent.trim());
|
|
139
|
+
return kept.length === 1 && kept[0].localName === 'cl-island' ? kept[0] : null;
|
|
140
|
+
};
|
|
136
141
|
export function region(ctx, index, html, wire) {
|
|
137
142
|
const r = scan(ctx).regions[index];
|
|
138
143
|
if (!r)
|
|
@@ -144,6 +149,16 @@ export function region(ctx, index, html, wire) {
|
|
|
144
149
|
const next = html();
|
|
145
150
|
untrack(() => {
|
|
146
151
|
if (!first) {
|
|
152
|
+
// A nested island with new props is updated in place (DOM and state kept), not replaced.
|
|
153
|
+
const t = document.createElement('template');
|
|
154
|
+
t.innerHTML = next;
|
|
155
|
+
const between = [];
|
|
156
|
+
for (let n = r.start.nextSibling; n && n !== r.end; n = n.nextSibling)
|
|
157
|
+
between.push(n);
|
|
158
|
+
const old = onlyIsland(between);
|
|
159
|
+
const fresh = onlyIsland([...t.content.childNodes]);
|
|
160
|
+
if (old && fresh && globalThis.__clUpdate?.(old, fresh))
|
|
161
|
+
return;
|
|
147
162
|
dispose?.();
|
|
148
163
|
while (r.start.nextSibling && r.start.nextSibling !== r.end)
|
|
149
164
|
r.start.nextSibling.remove();
|
|
@@ -188,7 +203,10 @@ export function forBlock(ctx, index, list, keyOf, row, empty) {
|
|
|
188
203
|
const keys = items.map((item, i) => {
|
|
189
204
|
let key = keyOf(item, i);
|
|
190
205
|
if (seen.has(key)) {
|
|
191
|
-
|
|
206
|
+
// Development only: Vite replaces import.meta.env.DEV, so a production build drops it (no ImportMeta
|
|
207
|
+
// declaration needed: consumers of this source typecheck without one).
|
|
208
|
+
if (import.meta.env?.DEV)
|
|
209
|
+
console.warn(`[clarusjs] @for: duplicate key ${String(key)}; rows with repeated keys are matched by position`);
|
|
192
210
|
key = `${String(key)}\u0000${i}`;
|
|
193
211
|
}
|
|
194
212
|
seen.add(key);
|
|
@@ -257,7 +275,10 @@ export function text(hole, fn) {
|
|
|
257
275
|
}
|
|
258
276
|
const registry = new WeakMap();
|
|
259
277
|
// These don't bubble, so they are caught on the way down instead.
|
|
260
|
-
const CAPTURE = new Set([
|
|
278
|
+
const CAPTURE = new Set([
|
|
279
|
+
'focus', 'blur', 'mouseenter', 'mouseleave', 'pointerenter', 'pointerleave', 'load', 'error', 'scroll', 'toggle',
|
|
280
|
+
'invalid', 'close', 'cancel', 'play', 'pause', 'ended', 'timeupdate', 'volumechange', 'loadedmetadata', 'canplay',
|
|
281
|
+
]);
|
|
261
282
|
/**
|
|
262
283
|
* Register a handler for elements marked `data-cl-e="index"` inside `ctx`.
|
|
263
284
|
* One listener per island per event type; it walks from the target up to the island root, running handlers
|
|
@@ -274,7 +295,8 @@ export function on(ctx, index, type, fn) {
|
|
|
274
295
|
const own = (handlers = new Map());
|
|
275
296
|
types.set(type, own);
|
|
276
297
|
root.addEventListener(type, (e) => {
|
|
277
|
-
|
|
298
|
+
// An event that doesn't bubble (mouseenter, focus) is its target's alone, not its ancestors'.
|
|
299
|
+
for (let el = e.target; el && el !== root.parentElement; el = e.bubbles ? el.parentElement : null) {
|
|
278
300
|
const i = el.getAttribute?.('data-cl-e');
|
|
279
301
|
if (i === null || i === undefined || el.closest('cl-island') !== root)
|
|
280
302
|
continue;
|
|
@@ -294,10 +316,15 @@ export function on(ctx, index, type, fn) {
|
|
|
294
316
|
onDispose(() => { const at = list.indexOf(handler); if (at !== -1)
|
|
295
317
|
list.splice(at, 1); }); // a removed branch or row stops listening
|
|
296
318
|
}
|
|
319
|
+
/** The element matching `selector` in `ctx`: this island's (not a nested island's), and in a row, that row's. */
|
|
320
|
+
export function marked(ctx, selector) {
|
|
321
|
+
const root = rootOf(ctx);
|
|
322
|
+
const island = root.closest('cl-island');
|
|
323
|
+
return [...root.querySelectorAll(selector)].find((e) => e.closest('cl-island') === island && inside(ctx, e));
|
|
324
|
+
}
|
|
297
325
|
/** Keep attribute `name` of the element marked `data-cl-a="index"` in `ctx` in sync with `fn()`. */
|
|
298
326
|
export function attr(ctx, index, name, fn, tag) {
|
|
299
|
-
const
|
|
300
|
-
const el = [...root.querySelectorAll(`[data-cl-a="${index}"]`)].find((e) => e.closest('cl-island') === root && inside(ctx, e));
|
|
327
|
+
const el = marked(ctx, `[data-cl-a="${index}"]`);
|
|
301
328
|
if (!el)
|
|
302
329
|
return;
|
|
303
330
|
effect(() => {
|
|
@@ -306,5 +333,49 @@ export function attr(ctx, index, name, fn, tag) {
|
|
|
306
333
|
el.removeAttribute(name);
|
|
307
334
|
else
|
|
308
335
|
el.setAttribute(name, v === true ? '' : v);
|
|
336
|
+
// A form field shows its property once someone has typed or clicked in it, not the attribute: set both.
|
|
337
|
+
if (name === 'value' && 'value' in el)
|
|
338
|
+
el.value = v === null || v === true ? '' : v;
|
|
339
|
+
if (name === 'checked' && 'checked' in el)
|
|
340
|
+
el.checked = v !== null;
|
|
309
341
|
});
|
|
310
342
|
}
|
|
343
|
+
/**
|
|
344
|
+
* A @model input: writing it asks the parent island to update its state (a bubbling, cancelable cl:model event from
|
|
345
|
+
* the island); when no parent takes it (a top-level island), the input keeps the value itself. New props from the
|
|
346
|
+
* parent set it with own().
|
|
347
|
+
*/
|
|
348
|
+
export function modelInput(root, name, initial) {
|
|
349
|
+
const value = state(initial);
|
|
350
|
+
return {
|
|
351
|
+
initial,
|
|
352
|
+
get: value.get,
|
|
353
|
+
own: value.set,
|
|
354
|
+
set(next) {
|
|
355
|
+
if (root.dispatchEvent(new CustomEvent('cl:model', { detail: { name, value: next }, bubbles: true, cancelable: true })))
|
|
356
|
+
value.set(next);
|
|
357
|
+
},
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
/** [(name)]="…" on a child island in region `index`: the child's writes to its @model name arrive here. */
|
|
361
|
+
export function model(ctx, index, name, set) {
|
|
362
|
+
const r = scan(ctx).regions[index];
|
|
363
|
+
if (!r)
|
|
364
|
+
return;
|
|
365
|
+
const host = r.start.parentNode;
|
|
366
|
+
const listen = (event) => {
|
|
367
|
+
const detail = event.detail;
|
|
368
|
+
const from = event.target;
|
|
369
|
+
// Only from inside this region: 4 = the target follows the start marker, 2 = it precedes the end marker.
|
|
370
|
+
if (detail.name !== name || !(r.start.compareDocumentPosition(from) & 4) || !(r.end.compareDocumentPosition(from) & 2))
|
|
371
|
+
return;
|
|
372
|
+
// Only the child island this region binds: an island nested in it, which nobody bound, keeps its own value.
|
|
373
|
+
if (from.parentElement?.closest('cl-island') !== rootOf(ctx))
|
|
374
|
+
return;
|
|
375
|
+
event.preventDefault();
|
|
376
|
+
event.stopPropagation();
|
|
377
|
+
set(detail.value);
|
|
378
|
+
};
|
|
379
|
+
host.addEventListener('cl:model', listen);
|
|
380
|
+
onDispose(() => host.removeEventListener('cl:model', listen));
|
|
381
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* True in the browser, false on the server. A component's script runs in both (the server renders it, the browser
|
|
3
|
+
* attaches it), so code that needs the DOM, timers that keep running or listeners on `window` goes under
|
|
4
|
+
* `if (browser) { … }`. A window without a document (some server runtimes define one) is the server.
|
|
5
|
+
* @see https://clarusjs.com/guide/events
|
|
6
|
+
*/
|
|
7
|
+
export declare const browser: boolean;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* True in the browser, false on the server. A component's script runs in both (the server renders it, the browser
|
|
3
|
+
* attaches it), so code that needs the DOM, timers that keep running or listeners on `window` goes under
|
|
4
|
+
* `if (browser) { … }`. A window without a document (some server runtimes define one) is the server.
|
|
5
|
+
* @see https://clarusjs.com/guide/events
|
|
6
|
+
*/
|
|
7
|
+
export const browser = typeof window !== 'undefined' && typeof document !== 'undefined';
|
|
@@ -2,4 +2,4 @@ import './loader.ts';
|
|
|
2
2
|
/** '/guide/lists/' → '/guide/lists/index.frag.html', keeping the query. */
|
|
3
3
|
export declare function fragmentUrl(url: URL): string;
|
|
4
4
|
/** Fetch the page's fragment and swap it in. Throws when there is none (the caller then loads the page normally). */
|
|
5
|
-
export declare function swap(url: URL, get?: (url: string) => Promise<Response>, isCurrent?: () => boolean): Promise<void>;
|
|
5
|
+
export declare function swap(url: URL, get?: (url: string) => Promise<Response>, isCurrent?: () => Promise<boolean> | boolean): Promise<void>;
|