vanjs-jsf 0.5.1 → 0.6.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 (54) hide show
  1. package/README.md +136 -15
  2. package/dist/VanJsfField.d.ts +40 -57
  3. package/dist/VanJsfField.js +124 -566
  4. package/dist/VanJsfField.js.map +1 -1
  5. package/dist/VanJsfForm.d.ts +82 -1
  6. package/dist/VanJsfForm.js +213 -119
  7. package/dist/VanJsfForm.js.map +1 -1
  8. package/dist/index.d.ts +5 -1
  9. package/dist/index.js +2 -0
  10. package/dist/index.js.map +1 -1
  11. package/dist/jsf-defaults.css +80 -0
  12. package/dist/schema.d.ts +13 -0
  13. package/dist/schema.js +29 -0
  14. package/dist/schema.js.map +1 -0
  15. package/dist/theme.d.ts +20 -2
  16. package/dist/theme.js +12 -1
  17. package/dist/theme.js.map +1 -1
  18. package/dist/types.d.ts +83 -0
  19. package/dist/types.js +2 -0
  20. package/dist/types.js.map +1 -0
  21. package/dist/util.d.ts +10 -0
  22. package/dist/util.js +17 -0
  23. package/dist/util.js.map +1 -0
  24. package/dist/values.d.ts +11 -0
  25. package/dist/values.js +51 -0
  26. package/dist/values.js.map +1 -0
  27. package/dist/widgets/array.d.ts +16 -0
  28. package/dist/widgets/array.js +108 -0
  29. package/dist/widgets/array.js.map +1 -0
  30. package/dist/widgets/basic.d.ts +2 -0
  31. package/dist/widgets/basic.js +97 -0
  32. package/dist/widgets/basic.js.map +1 -0
  33. package/dist/widgets/choice.d.ts +2 -0
  34. package/dist/widgets/choice.js +127 -0
  35. package/dist/widgets/choice.js.map +1 -0
  36. package/dist/widgets/code.d.ts +2 -0
  37. package/dist/widgets/code.js +146 -0
  38. package/dist/widgets/code.js.map +1 -0
  39. package/dist/widgets/date.d.ts +3 -0
  40. package/dist/widgets/date.js +43 -0
  41. package/dist/widgets/date.js.map +1 -0
  42. package/dist/widgets/file.d.ts +6 -0
  43. package/dist/widgets/file.js +130 -0
  44. package/dist/widgets/file.js.map +1 -0
  45. package/dist/widgets/index.d.ts +3 -0
  46. package/dist/widgets/index.js +22 -0
  47. package/dist/widgets/index.js.map +1 -0
  48. package/package.json +19 -17
  49. package/dist/JsfUtils.d.ts +0 -4
  50. package/dist/JsfUtils.js +0 -11
  51. package/dist/JsfUtils.js.map +0 -1
  52. package/dist/VanJSComponent.d.ts +0 -3
  53. package/dist/VanJSComponent.js +0 -3
  54. package/dist/VanJSComponent.js.map +0 -1
@@ -1,579 +1,137 @@
1
1
  import van from "vanjs-core";
2
- import { VanJSComponent } from "./VanJSComponent";
3
2
  import { resolve } from "./theme";
4
- // Heavy, field-type-specific dependencies (CodeMirror + ESLint for the `code`
5
- // field, Pikaday for the `date` field) are loaded lazily via dynamic import inside
6
- // the relevant renderers. This keeps them out of the main bundle so a form that
7
- // only uses text/number/select/etc. never pays for them.
8
- const { div, p, input, label, textarea, legend, link, fieldset, span, select, option, button, strong, small } = van.tags;
9
- var FieldType;
10
- (function (FieldType) {
11
- FieldType["text"] = "text";
12
- FieldType["password"] = "password";
13
- FieldType["code"] = "code";
14
- FieldType["number"] = "number";
15
- FieldType["textarea"] = "textarea";
16
- FieldType["select"] = "select";
17
- FieldType["radio"] = "radio";
18
- FieldType["date"] = "date";
19
- FieldType["fieldset"] = "fieldset";
20
- FieldType["file"] = "file";
21
- })(FieldType || (FieldType = {}));
22
- /**
23
- * Rules the `code` field lints with. These are ESLint's own `eslint:recommended` set, spelled
24
- * out because `eslint-linter-browserify` ships no config resolver — a bare `Linter` with no
25
- * `rules` reports parse errors and nothing else, which looks like a working editor while
26
- * catching none of the mistakes people actually make.
27
- *
28
- * Stylistic rules are deliberately absent. A host embedding this editor has no say in the
29
- * code style of whoever types into it, and flagging every semicolon as an error is worse than
30
- * flagging nothing: the real diagnostics drown.
31
- */
32
- const ESLINT_RULES = {
33
- "constructor-super": "error",
34
- "for-direction": "error",
35
- "getter-return": "error",
36
- "no-async-promise-executor": "error",
37
- "no-case-declarations": "error",
38
- "no-class-assign": "error",
39
- "no-compare-neg-zero": "error",
40
- "no-cond-assign": "error",
41
- "no-const-assign": "error",
42
- "no-constant-binary-expression": "error",
43
- "no-constant-condition": "error",
44
- "no-control-regex": "error",
45
- "no-debugger": "error",
46
- "no-delete-var": "error",
47
- "no-dupe-args": "error",
48
- "no-dupe-class-members": "error",
49
- "no-dupe-else-if": "error",
50
- "no-dupe-keys": "error",
51
- "no-duplicate-case": "error",
52
- "no-empty": "error",
53
- "no-empty-character-class": "error",
54
- "no-empty-pattern": "error",
55
- "no-empty-static-block": "error",
56
- "no-ex-assign": "error",
57
- "no-extra-boolean-cast": "error",
58
- "no-fallthrough": "error",
59
- "no-func-assign": "error",
60
- "no-global-assign": "error",
61
- "no-import-assign": "error",
62
- "no-invalid-regexp": "error",
63
- "no-irregular-whitespace": "error",
64
- "no-loss-of-precision": "error",
65
- "no-misleading-character-class": "error",
66
- "no-new-native-nonconstructor": "error",
67
- "no-nonoctal-decimal-escape": "error",
68
- "no-obj-calls": "error",
69
- "no-octal": "error",
70
- "no-prototype-builtins": "error",
71
- "no-redeclare": "error",
72
- "no-regex-spaces": "error",
73
- "no-self-assign": "error",
74
- "no-setter-return": "error",
75
- "no-shadow-restricted-names": "error",
76
- "no-sparse-arrays": "error",
77
- "no-this-before-super": "error",
78
- "no-undef": "error",
79
- "no-unexpected-multiline": "error",
80
- "no-unreachable": "error",
81
- "no-unsafe-finally": "error",
82
- "no-unsafe-negation": "error",
83
- "no-unsafe-optional-chaining": "error",
84
- "no-unused-labels": "error",
85
- "no-unused-private-class-members": "error",
86
- "no-unused-vars": "error",
87
- "no-useless-backreference": "error",
88
- "no-useless-catch": "error",
89
- "no-useless-escape": "error",
90
- "no-with": "error",
91
- "require-yield": "error",
92
- "use-isnan": "error",
93
- "valid-typeof": "error",
94
- };
95
- export class VanJsfField extends VanJSComponent {
96
- name;
97
- field;
98
- iniVal;
99
- handleChange;
100
- isVisibleState;
101
- errorState;
102
- theme;
103
- layoutClass;
104
- /** Used by file fields to pass file metadata to formValues */
105
- fileNameValue = "";
106
- fileSizeValue = "";
107
- fileTypeValue = "";
108
- constructor(field, initVal, handleChange, theme = {}, layoutClass = "") {
109
- super();
110
- this.field = field;
111
- this.name = field.name;
112
- this.iniVal = initVal;
113
- this.handleChange = handleChange;
114
- this.theme = theme;
115
- this.layoutClass = layoutClass;
116
- this.isVisibleState = van.state(this.field.isVisible);
117
- this.errorState = van.state("");
3
+ import { compact } from "./util";
4
+ const { div, label, p, span } = van.tags;
5
+ /** Container types that never hold a value of their own. */
6
+ const NON_ARRAY_TYPES = new Set(["file", "code", "group-array"]);
7
+ export class VanJsfField {
8
+ def;
9
+ path;
10
+ id;
11
+ visible;
12
+ /** Message on screen: the validation or widget error, once touched or submitted. */
13
+ error = van.state("");
14
+ /** Fieldset sub-fields. */
15
+ children = [];
16
+ /** group-array: sub-fields of each item, rebuilt whenever items are added or removed. */
17
+ items = [];
18
+ touched = false;
19
+ validationError = "";
20
+ widgetError = "";
21
+ host;
22
+ constructor(def, path, host) {
23
+ this.def = def;
24
+ this.path = path;
25
+ this.host = host;
26
+ this.id = `${host.idPrefix}-${path.join("-")}`;
27
+ this.visible = van.state(def.isVisible ?? true);
28
+ }
29
+ get name() {
30
+ return this.def.name;
118
31
  }
119
32
  get inputType() {
120
- return this.field.inputType;
121
- }
122
- get label() {
123
- return this.field.label;
124
- }
125
- get class() {
126
- return this.field.class;
127
- }
128
- get errorClass() {
129
- return this.field.errorClass;
130
- }
131
- get isRequired() {
132
- return this.field.required ?? false;
133
- }
134
- get containerClass() {
135
- return this.field.containerClass;
136
- }
137
- get containerId() {
138
- return this.field.containerId;
139
- }
140
- get titleClass() {
141
- return this.field.titleClass;
142
- }
143
- get descriptionClass() {
144
- return this.field.descriptionClass;
145
- }
146
- get description() {
147
- return this.field.description;
148
- }
149
- get options() {
150
- return this.field.options;
151
- }
152
- get isVisible() {
153
- return this.isVisibleState.val;
154
- }
155
- set isVisible(val) {
156
- this.isVisibleState.val = val;
157
- }
158
- get error() {
159
- return this.errorState.val;
160
- }
161
- set error(val) {
162
- this.errorState.val = val;
163
- }
164
- renderLabel() {
165
- const cls = resolve(this.titleClass, this.theme.label);
166
- return label({ for: this.name, class: cls }, this.label, this.isRequired
167
- ? span({ class: this.theme.requiredIndicator || "" }, " *")
168
- : null);
169
- }
170
- renderDescription() {
171
- if (!this.description)
172
- return null;
173
- return div({
174
- id: `${this.name}-description`,
175
- class: resolve(this.descriptionClass, this.theme.description),
176
- }, this.description);
177
- }
178
- renderError() {
179
- return p({ class: resolve(this.errorClass, this.theme.error) }, () => this.error);
180
- }
181
- /**
182
- * Lazily loads CodeMirror + ESLint and mounts a code editor into `parent`.
183
- * These are the heaviest dependencies in the library; importing them only here
184
- * keeps them out of the main bundle for forms that don't use a `code` field.
185
- */
186
- async mountCodeEditor(parent) {
187
- const [{ basicSetup, EditorView }, { javascript, esLint }, { json, jsonParseLinter }, { lintGutter, linter, forEachDiagnostic }, eslint, globalsModule, { dracula },] = await Promise.all([
188
- import("codemirror"),
189
- import("@codemirror/lang-javascript"),
190
- import("@codemirror/lang-json"),
191
- import("@codemirror/lint"),
192
- import("eslint-linter-browserify"),
193
- import("globals"),
194
- import("thememirror"),
195
- ]);
196
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
197
- const globals = globalsModule.default ?? globalsModule;
198
- // A `code` field may declare the globals its host injects at runtime. Those names are in
199
- // no environment preset, so without this every single one of them reads as `no-undef`.
200
- const fieldGlobals = this.field.globals && typeof this.field.globals === "object" ? this.field.globals : {};
201
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
202
- const eslintConfig = {
203
- languageOptions: {
204
- globals: { ...fieldGlobals, ...globals.node },
205
- parserOptions: { ecmaVersion: 2022, sourceType: "module" },
206
- },
207
- rules: ESLINT_RULES,
208
- };
209
- const cmTheme = EditorView.theme({
210
- '.cm-content, .cm-gutter': { "min-height": "150px" },
211
- '.cm-content': { "min-height": "150px" },
212
- '.cm-gutters': { margin: '1px' },
213
- '.cm-scroller': { overflow: 'auto' },
214
- '.cm-wrap': { border: '1px solid silver' },
215
- });
216
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
217
- const extensions = [dracula, cmTheme, EditorView.updateListener.of((e) => {
218
- this.field.error = null;
219
- forEachDiagnostic(e.state, (diag) => {
220
- if (diag.severity === "error") {
221
- this.field.error = diag.message;
222
- }
223
- });
224
- this.handleChange(this, e.state.doc.toString());
225
- }), basicSetup, lintGutter()];
226
- switch (this.field.codemirrorType) {
227
- case "json":
228
- extensions.push(json(), linter(jsonParseLinter()));
229
- break;
230
- case "javascript":
231
- extensions.push(javascript(), linter(esLint(new eslint.Linter(), eslintConfig)));
232
- break;
233
- case "typescript":
234
- extensions.push(javascript({ typescript: true }), linter(esLint(new eslint.Linter(), eslintConfig)));
235
- break;
236
- default:
237
- extensions.push(javascript(), linter(esLint(new eslint.Linter(), eslintConfig)));
238
- break;
33
+ return this.def.inputType;
34
+ }
35
+ /** Key used to pick the widget: `x-jsf-presentation.widget`, else derived from the field. */
36
+ get widgetKey() {
37
+ const d = this.def;
38
+ if (typeof d.widget === "string")
39
+ return d.widget;
40
+ if (d.inputType === "group-array")
41
+ return "group-array";
42
+ // json-schema-form reports arrays as a "select"; with options that is a multi-select,
43
+ // without them a repeatable list of scalars.
44
+ if (d.jsonType === "array" && !NON_ARRAY_TYPES.has(d.inputType)) {
45
+ return d.options?.length ? "multiselect" : "array";
239
46
  }
240
- new EditorView({ doc: String(this.iniVal), parent, extensions });
241
- }
242
- /** Lazily loads Pikaday and attaches a date picker to `calendarInput`. */
243
- async mountDatePicker(parent, calendarInput) {
244
- const Pikaday = (await import("pikaday")).default;
245
- new Pikaday({
246
- field: calendarInput,
247
- format: 'YYYY-MM-DD',
248
- container: parent,
249
- firstDay: 1,
250
- toString(date) {
251
- const day = date.getDate();
252
- const month = date.getMonth() + 1;
253
- const year = date.getFullYear();
254
- return `${year}-${("0" + month).slice(-2)}-${("0" + day).slice(-2)}`;
255
- },
256
- parse(dateString) {
257
- const parts = dateString.split('-');
258
- const year = parseInt(parts[0], 10);
259
- const month = parseInt(parts[1], 10) - 1;
260
- const day = parseInt(parts[2], 10);
261
- return new Date(year, month, day);
262
- }
47
+ return d.inputType;
48
+ }
49
+ /** This field and every field below it, in document order. */
50
+ *walk() {
51
+ yield this;
52
+ for (const c of this.children)
53
+ yield* c.walk();
54
+ for (const item of this.items)
55
+ for (const f of item)
56
+ yield* f.walk();
57
+ }
58
+ showError(showAll) {
59
+ const msg = this.validationError || this.widgetError;
60
+ this.error.val = this.touched || showAll ? msg : "";
61
+ }
62
+ attrs() {
63
+ const d = this.def;
64
+ return compact({
65
+ id: this.id,
66
+ name: this.path.join("."),
67
+ placeholder: d.placeholder,
68
+ readOnly: d.readOnly || undefined,
69
+ disabled: d.disabled || undefined,
70
+ autocomplete: d.autocomplete,
71
+ "aria-required": d.required ? "true" : undefined,
72
+ "aria-describedby": [d.description ? `${this.id}-description` : "", `${this.id}-error`]
73
+ .filter(Boolean).join(" "),
74
+ "aria-invalid": () => (this.error.val ? "true" : "false"),
263
75
  });
264
76
  }
265
- /**
266
- * Renders an editable list for an array property. json-schema-form reports
267
- * arrays as an unusable "select", so we read the item schema from the field's
268
- * scopedJsonSchema and render one input per element with add/remove controls.
269
- * Supports scalar item types (number/integer/string/boolean). The value is kept
270
- * in formValues as a real JS array.
271
- */
272
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
273
- renderArray(props) {
274
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
275
- const scoped = this.field.scopedJsonSchema;
276
- const arraySchema = scoped?.properties?.[this.name] ?? {};
277
- const itemSchema = arraySchema.items ?? { type: "string" };
278
- const itemType = itemSchema.type ?? "string";
279
- const isNumeric = itemType === "number" || itemType === "integer";
280
- const isBoolean = itemType === "boolean";
281
- const minItems = arraySchema.minItems ?? 0;
282
- const maxItems = arraySchema.maxItems ?? Infinity;
283
- const blank = () => (isNumeric ? 0 : isBoolean ? false : "");
284
- const coerce = (raw) => (isNumeric ? (raw === "" ? "" : Number(raw)) : raw);
285
- const values = Array.isArray(this.iniVal) ? [...this.iniVal] : [];
286
- while (values.length < minItems)
287
- values.push(blank());
288
- // Bumped only on add/remove so typing into a row never re-renders it (avoids
289
- // losing input focus on every keystroke).
290
- const version = van.state(0);
291
- const emit = () => this.handleChange(this, values.slice());
292
- emit();
293
- const itemClass = resolve(this.class, this.theme.input);
294
- const rowInput = (i) => {
295
- if (isBoolean) {
296
- return input({
297
- type: "checkbox",
298
- class: itemClass,
299
- checked: Boolean(values[i]),
300
- onchange: (e) => { values[i] = e.target.checked; emit(); },
301
- });
302
- }
303
- return input({
304
- type: isNumeric ? "number" : "text",
305
- class: itemClass,
306
- value: String(values[i] ?? ""),
307
- oninput: (e) => { values[i] = coerce(e.target.value); emit(); },
308
- });
77
+ requiredMark() {
78
+ return this.def.required ? span({ class: this.host.theme.requiredIndicator || "" }, " *") : null;
79
+ }
80
+ context() {
81
+ const { host, def } = this;
82
+ const theme = host.theme;
83
+ return {
84
+ field: def,
85
+ name: this.name,
86
+ path: this.path,
87
+ id: this.id,
88
+ theme,
89
+ texts: host.texts,
90
+ getValue: () => host.getValue(this.path),
91
+ setValue: (value) => {
92
+ this.touched = true;
93
+ host.setValue(this, value);
94
+ },
95
+ setMeta: (key, value) => host.setMeta(this, key, value),
96
+ setWidgetError: (message) => {
97
+ if (message === this.widgetError)
98
+ return;
99
+ this.widgetError = message;
100
+ if (message)
101
+ this.touched = true;
102
+ host.refresh();
103
+ },
104
+ error: this.error,
105
+ visible: this.visible,
106
+ attrs: () => this.attrs(),
107
+ label: () => label({ for: this.id, id: `${this.id}-label`, class: resolve(def.titleClass, theme.label) }, def.label ?? "", this.requiredMark()),
108
+ description: () => def.description
109
+ ? div({ id: `${this.id}-description`, class: resolve(def.descriptionClass, theme.description) }, def.description)
110
+ : null,
111
+ errorMessage: () => p({ id: `${this.id}-error`, class: resolve(def.errorClass, theme.error), "aria-live": "polite" }, () => this.error.val),
112
+ renderChildren: () => this.children.map((c) => c.render()),
113
+ renderItems: () => {
114
+ const value = host.getValue(this.path);
115
+ const count = Array.isArray(value) ? value.length : 0;
116
+ const templates = () => (typeof def.fields === "function" ? def.fields() : def.fields ?? []);
117
+ this.items = Array.from({ length: count }, (_, i) => host.buildFields(templates(), [...this.path, String(i)]));
118
+ host.refresh();
119
+ return this.items.map((fields) => fields.map((f) => f.render()));
120
+ },
309
121
  };
310
- const rows = () => div({ class: this.theme.arrayItems || "jsf-array-items" }, values.map((_, i) => div({ class: this.theme.arrayRow || "jsf-array-row" }, rowInput(i), button({
311
- type: "button",
312
- class: this.theme.arrayRemoveButton || "jsf-array-remove",
313
- disabled: values.length <= minItems,
314
- onclick: () => { values.splice(i, 1); version.val++; emit(); },
315
- }, "✕"))));
316
- return div(props, this.renderLabel(), this.renderDescription(),
317
- // Re-render the row list whenever an item is added or removed.
318
- () => { void version.val; return rows(); }, button({
319
- type: "button",
320
- class: this.theme.arrayAddButton || "jsf-array-add",
321
- onclick: () => { if (values.length < maxItems) {
322
- values.push(blank());
323
- version.val++;
324
- emit();
325
- } },
326
- }, "+ Add"), this.renderError());
327
122
  }
328
123
  render() {
329
- let el;
330
- const baseContainer = resolve(this.containerClass, this.theme.container);
331
- const containerCls = this.layoutClass ? `${baseContainer} ${this.layoutClass}` : baseContainer;
332
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
333
- const props = {
334
- class: () => this.isVisible ? containerCls : `${containerCls} jsf-hidden`.trim(),
335
- };
336
- // json-schema-form reports arrays as inputType "select" with no options, which
337
- // is not usable. Detect the array jsonType and render an editable repeatable
338
- // list of scalar items instead.
339
- if (this.field.jsonType === "array") {
340
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
341
- return this.renderArray(props);
342
- }
343
- switch (this.inputType) {
344
- case FieldType.text:
345
- el = div(props, this.renderLabel(), this.renderDescription(), input({
346
- id: this.name,
347
- type: "text",
348
- class: resolve(this.class, this.theme.input),
349
- value: this.iniVal,
350
- oninput: (e) => this.handleChange(this, e.target.value),
351
- }), this.renderError());
352
- break;
353
- case FieldType.password:
354
- // Password is rendered with type="password" so the user agent
355
- // masks the value as it is typed. Otherwise behaves identically
356
- // to a text input — same theme.input class, same oninput
357
- // wiring. autocomplete="new-password" hints to browsers that
358
- // this is a credential entry form, not a "remember me" field.
359
- el = div(props, this.renderLabel(), this.renderDescription(), input({
360
- id: this.name,
361
- type: "password",
362
- autocomplete: "new-password",
363
- class: resolve(this.class, this.theme.input),
364
- value: this.iniVal,
365
- oninput: (e) => this.handleChange(this, e.target.value),
366
- }), this.renderError());
367
- break;
368
- case FieldType.textarea:
369
- el = div(props, this.renderLabel(), this.renderDescription(), textarea({
370
- id: this.name,
371
- name: this.name,
372
- class: resolve(this.class, this.theme.textarea),
373
- rows: this.field.rows,
374
- cols: this.field.columns,
375
- oninput: (e) => this.handleChange(this, e.target.value),
376
- }), this.renderError());
377
- break;
378
- case FieldType.code:
379
- el = div(props, this.renderLabel(), this.renderDescription());
380
- // CodeMirror + ESLint are loaded on demand; the editor mounts into `el`
381
- // once the chunk resolves.
382
- void this.mountCodeEditor(el);
383
- break;
384
- case FieldType.select:
385
- el = div(props, this.renderLabel(), this.renderDescription(), select({
386
- id: this.name,
387
- name: this.name,
388
- class: resolve(this.class, this.theme.select),
389
- oninput: (e) => this.handleChange(this, e.target.value),
390
- }, this.options?.map((opt) => option({ class: this.theme.option || "", value: opt.value }, opt.label, opt.description))), this.renderError());
391
- break;
392
- case FieldType.date: {
393
- const calendarInput = input({
394
- id: this.name,
395
- type: "text",
396
- class: resolve(this.class, this.theme.input),
397
- value: this.iniVal,
398
- onchange: (e) => this.handleChange(this, e.target.value),
399
- });
400
- el =
401
- div(props, this.renderLabel(), this.renderDescription(), calendarInput, this.renderError(),
402
- // External CDN dependency for Pikaday CSS — consider bundling for production
403
- link({ rel: "stylesheet", type: "text/css", href: "https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css" }));
404
- // Pikaday is loaded on demand and attached to the input once available.
405
- void this.mountDatePicker(el, calendarInput);
406
- break;
407
- }
408
- case FieldType.number:
409
- el = div(props, this.renderLabel(), this.renderDescription(), input({
410
- id: this.name,
411
- type: "number",
412
- class: resolve(this.class, this.theme.input),
413
- value: this.iniVal,
414
- oninput: (e) => {
415
- const val = e.target.value;
416
- this.handleChange(this, val === "" ? "" : Number(val));
417
- },
418
- }), this.renderError());
419
- break;
420
- case FieldType.fieldset:
421
- el = div(props, fieldset({ class: this.theme.fieldset || "" }, legend({ class: resolve(this.titleClass, this.theme.legend || this.theme.label) }, this.label), this.renderDescription(), this.isVanJsfFieldArray(this.field.fields)
422
- ? this.field.fields.map((field) => field.render())
423
- : null));
424
- break;
425
- case FieldType.radio:
426
- el = div(props, legend({ class: resolve(this.titleClass, this.theme.legend || this.theme.label) }, this.label), this.renderDescription(), div({ class: this.theme.radioGroup || "" }, this.options?.map((opt) => label({ class: this.theme.radioLabel || "" }, input({
427
- type: "radio",
428
- name: this.name,
429
- class: resolve(this.class, this.theme.radioInput),
430
- value: opt.value,
431
- checked: this.iniVal === opt.value,
432
- onchange: (e) => this.handleChange(this, e.target.value),
433
- }), opt.label, opt.description))), this.renderError());
434
- break;
435
- case FieldType.file: {
436
- const accept = this.field.accept || "";
437
- const maxSizeMB = this.field.maxSizeMB;
438
- const readAs = this.field.readAs || "auto";
439
- const TEXT_EXTENSIONS = new Set([
440
- "json", "csv", "tsv", "txt", "xml", "yaml", "yml",
441
- "log", "md", "html", "css", "js", "ts", "sql", "env",
442
- ]);
443
- // Reactive states
444
- const fileNameState = van.state("");
445
- const fileSizeState = van.state("");
446
- const dragOverState = van.state(false);
447
- const readingState = van.state(false);
448
- const formatSize = (bytes) => {
449
- if (bytes < 1024)
450
- return `${bytes} B`;
451
- if (bytes < 1024 * 1024)
452
- return `${(bytes / 1024).toFixed(1)} KB`;
453
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
454
- };
455
- const readFile = (file) => {
456
- this.error = "";
457
- // Validate size
458
- if (maxSizeMB && file.size > maxSizeMB * 1024 * 1024) {
459
- this.error = `File exceeds maximum size of ${maxSizeMB} MB`;
460
- return;
461
- }
462
- fileNameState.val = file.name;
463
- fileSizeState.val = formatSize(file.size);
464
- readingState.val = true;
465
- // Store metadata
466
- this.fileNameValue = file.name;
467
- this.fileSizeValue = String(file.size);
468
- this.fileTypeValue = file.type;
469
- const reader = new FileReader();
470
- reader.onload = () => {
471
- readingState.val = false;
472
- let result = reader.result;
473
- if (reader.result instanceof ArrayBuffer) {
474
- // Convert binary to base64 (applies to "arrayBuffer" and "auto" for binary files)
475
- const bytes = new Uint8Array(reader.result);
476
- let binary = "";
477
- for (let i = 0; i < bytes.byteLength; i++) {
478
- binary += String.fromCharCode(bytes[i]);
479
- }
480
- result = btoa(binary);
481
- }
482
- this.handleChange(this, result);
483
- };
484
- reader.onerror = () => {
485
- readingState.val = false;
486
- this.error = "Error reading file";
487
- };
488
- if (readAs === "dataURL") {
489
- reader.readAsDataURL(file);
490
- }
491
- else if (readAs === "arrayBuffer") {
492
- reader.readAsArrayBuffer(file);
493
- }
494
- else if (readAs === "auto") {
495
- const ext = file.name.split(".").pop()?.toLowerCase() ?? "";
496
- if (TEXT_EXTENSIONS.has(ext)) {
497
- reader.readAsText(file);
498
- }
499
- else {
500
- reader.readAsArrayBuffer(file);
501
- }
502
- }
503
- else {
504
- reader.readAsText(file);
505
- }
506
- };
507
- const clearFile = () => {
508
- fileNameState.val = "";
509
- fileSizeState.val = "";
510
- readingState.val = false;
511
- this.fileNameValue = "";
512
- this.fileSizeValue = "";
513
- this.fileTypeValue = "";
514
- this.error = "";
515
- this.handleChange(this, "");
516
- };
517
- const fileInput = input({
518
- type: "file",
519
- accept,
520
- style: "display: none;",
521
- onchange: (e) => {
522
- const files = e.target.files;
523
- if (files && files[0])
524
- readFile(files[0]);
525
- },
526
- });
527
- const dzBase = this.theme.dropZone || "jsf-dropzone";
528
- const dzActive = this.theme.dropZoneActive || "jsf-dropzone-active";
529
- const dropZone = div({
530
- class: () => dragOverState.val ? `${dzBase} ${dzActive}` : dzBase,
531
- ondragover: (e) => { e.preventDefault(); dragOverState.val = true; },
532
- ondragleave: () => { dragOverState.val = false; },
533
- ondrop: (e) => {
534
- e.preventDefault();
535
- dragOverState.val = false;
536
- const files = e.dataTransfer?.files;
537
- if (files && files[0])
538
- readFile(files[0]);
539
- },
540
- onclick: () => fileInput.click(),
541
- }, p({ class: this.theme.dropZoneText || "jsf-dropzone-text" }, accept
542
- ? `Drop a file here or click to browse (${accept})`
543
- : "Drop a file here or click to browse"));
544
- const fileInfoBar = () => {
545
- return div(() => {
546
- const name = fileNameState.val;
547
- if (!name)
548
- return div();
549
- return div({ class: this.theme.fileInfoBar || "jsf-file-info" }, strong({ class: this.theme.fileName || "" }, name), small({ class: this.theme.fileSize || "jsf-file-size" }, `(${fileSizeState.val})`), button({
550
- type: "button",
551
- class: this.theme.fileClearButton || "jsf-file-clear",
552
- onclick: (e) => {
553
- e.stopPropagation();
554
- clearFile();
555
- fileInput.value = "";
556
- },
557
- }, "Clear"));
558
- });
559
- };
560
- const readingIndicator = () => {
561
- return div(() => {
562
- if (!readingState.val)
563
- return div();
564
- return div({ class: this.theme.fileReading || "jsf-file-reading" }, "Reading file...");
565
- });
566
- };
567
- el = div(props, this.renderLabel(), this.renderDescription(), fileInput, dropZone, fileInfoBar(), readingIndicator(), this.renderError());
568
- break;
569
- }
570
- default:
571
- el = div({ style: "border: 1px dashed gray; padding: 8px;" }, `Field "${this.name}" unsupported: The type "${this.inputType}" has no UI component built yet.`);
572
- }
573
- return el;
574
- }
575
- isVanJsfFieldArray(fields) {
576
- return Array.isArray(fields) && fields.every(field => field instanceof VanJsfField);
124
+ const key = this.widgetKey;
125
+ const widget = this.host.widget(key);
126
+ const base = [resolve(this.def.containerClass, this.host.theme.container), this.host.layoutClass(this)]
127
+ .filter(Boolean).join(" ");
128
+ const alwaysHidden = key === "hidden";
129
+ return div(compact({
130
+ id: this.def.containerId,
131
+ class: () => (alwaysHidden || !this.visible.val ? `${base} jsf-hidden`.trim() : base),
132
+ }), widget
133
+ ? widget(this.context())
134
+ : div({ class: "jsf-unsupported" }, `Field "${this.name}" unsupported: the type "${key}" has no UI component built yet.`));
577
135
  }
578
136
  }
579
137
  //# sourceMappingURL=VanJsfField.js.map