vanjs-jsf 0.5.0 → 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 +138 -18
  2. package/dist/VanJsfField.d.ts +40 -57
  3. package/dist/VanJsfField.js +125 -489
  4. package/dist/VanJsfField.js.map +1 -0
  5. package/dist/VanJsfForm.d.ts +82 -1
  6. package/dist/VanJsfForm.js +214 -119
  7. package/dist/VanJsfForm.js.map +1 -0
  8. package/dist/index.d.ts +5 -1
  9. package/dist/index.js +3 -0
  10. package/dist/index.js.map +1 -7
  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 +13 -1
  17. package/dist/theme.js.map +1 -0
  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 +22 -26
  49. package/dist/JsfUtils.d.ts +0 -4
  50. package/dist/JsfUtils.js +0 -10
  51. package/dist/VanJSComponent.d.ts +0 -3
  52. package/dist/VanJSComponent.js +0 -2
  53. package/dist/main.d.ts +0 -1
  54. package/dist/main.js +0 -78
@@ -1,501 +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
- export class VanJsfField extends VanJSComponent {
23
- name;
24
- field;
25
- iniVal;
26
- handleChange;
27
- isVisibleState;
28
- errorState;
29
- theme;
30
- layoutClass;
31
- /** Used by file fields to pass file metadata to formValues */
32
- fileNameValue = "";
33
- fileSizeValue = "";
34
- fileTypeValue = "";
35
- constructor(field, initVal, handleChange, theme = {}, layoutClass = "") {
36
- super();
37
- this.field = field;
38
- this.name = field.name;
39
- this.iniVal = initVal;
40
- this.handleChange = handleChange;
41
- this.theme = theme;
42
- this.layoutClass = layoutClass;
43
- this.isVisibleState = van.state(this.field.isVisible);
44
- 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;
45
31
  }
46
32
  get inputType() {
47
- return this.field.inputType;
48
- }
49
- get label() {
50
- return this.field.label;
51
- }
52
- get class() {
53
- return this.field.class;
54
- }
55
- get errorClass() {
56
- return this.field.errorClass;
57
- }
58
- get isRequired() {
59
- return this.field.required ?? false;
60
- }
61
- get containerClass() {
62
- return this.field.containerClass;
63
- }
64
- get containerId() {
65
- return this.field.containerId;
66
- }
67
- get titleClass() {
68
- return this.field.titleClass;
69
- }
70
- get descriptionClass() {
71
- return this.field.descriptionClass;
72
- }
73
- get description() {
74
- return this.field.description;
75
- }
76
- get options() {
77
- return this.field.options;
78
- }
79
- get isVisible() {
80
- return this.isVisibleState.val;
81
- }
82
- set isVisible(val) {
83
- this.isVisibleState.val = val;
84
- }
85
- get error() {
86
- return this.errorState.val;
87
- }
88
- set error(val) {
89
- this.errorState.val = val;
90
- }
91
- renderLabel() {
92
- const cls = resolve(this.titleClass, this.theme.label);
93
- return label({ for: this.name, class: cls }, this.label, this.isRequired
94
- ? span({ class: this.theme.requiredIndicator || "" }, " *")
95
- : null);
96
- }
97
- renderDescription() {
98
- if (!this.description)
99
- return null;
100
- return div({
101
- id: `${this.name}-description`,
102
- class: resolve(this.descriptionClass, this.theme.description),
103
- }, this.description);
104
- }
105
- renderError() {
106
- return p({ class: resolve(this.errorClass, this.theme.error) }, () => this.error);
107
- }
108
- /**
109
- * Lazily loads CodeMirror + ESLint and mounts a code editor into `parent`.
110
- * These are the heaviest dependencies in the library; importing them only here
111
- * keeps them out of the main bundle for forms that don't use a `code` field.
112
- */
113
- async mountCodeEditor(parent) {
114
- const [{ basicSetup, EditorView }, { javascript, esLint }, { json, jsonParseLinter }, { lintGutter, linter, forEachDiagnostic }, eslint, globalsModule,] = await Promise.all([
115
- import("codemirror"),
116
- import("@codemirror/lang-javascript"),
117
- import("@codemirror/lang-json"),
118
- import("@codemirror/lint"),
119
- import("eslint-linter-browserify"),
120
- import("globals"),
121
- ]);
122
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
123
- const globals = globalsModule.default ?? globalsModule;
124
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
125
- const eslintConfig = {
126
- languageOptions: {
127
- globals: { ...globals.node },
128
- parserOptions: { ecmaVersion: 2022, sourceType: "module" },
129
- },
130
- rules: { semi: ["error", "never"] },
131
- };
132
- const cmTheme = EditorView.theme({
133
- '.cm-content, .cm-gutter': { "min-height": "150px" },
134
- '.cm-content': { "min-height": "150px" },
135
- '.cm-gutters': { margin: '1px' },
136
- '.cm-scroller': { overflow: 'auto' },
137
- '.cm-wrap': { border: '1px solid silver' },
138
- });
139
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
140
- const extensions = [cmTheme, EditorView.updateListener.of((e) => {
141
- this.field.error = null;
142
- forEachDiagnostic(e.state, (diag) => {
143
- if (diag.severity === "error") {
144
- this.field.error = diag.message;
145
- }
146
- });
147
- this.handleChange(this, e.state.doc.toString());
148
- }), basicSetup, lintGutter()];
149
- switch (this.field.codemirrorType) {
150
- case "json":
151
- extensions.push(json(), linter(jsonParseLinter()));
152
- break;
153
- case "javascript":
154
- extensions.push(javascript(), linter(esLint(new eslint.Linter(), eslintConfig)));
155
- break;
156
- case "typescript":
157
- extensions.push(javascript({ typescript: true }), linter(esLint(new eslint.Linter(), eslintConfig)));
158
- break;
159
- default:
160
- extensions.push(javascript(), linter(esLint(new eslint.Linter(), eslintConfig)));
161
- 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";
162
46
  }
163
- new EditorView({ doc: String(this.iniVal), parent, extensions });
164
- }
165
- /** Lazily loads Pikaday and attaches a date picker to `calendarInput`. */
166
- async mountDatePicker(parent, calendarInput) {
167
- const Pikaday = (await import("pikaday")).default;
168
- new Pikaday({
169
- field: calendarInput,
170
- format: 'YYYY-MM-DD',
171
- container: parent,
172
- firstDay: 1,
173
- toString(date) {
174
- const day = date.getDate();
175
- const month = date.getMonth() + 1;
176
- const year = date.getFullYear();
177
- return `${year}-${("0" + month).slice(-2)}-${("0" + day).slice(-2)}`;
178
- },
179
- parse(dateString) {
180
- const parts = dateString.split('-');
181
- const year = parseInt(parts[0], 10);
182
- const month = parseInt(parts[1], 10) - 1;
183
- const day = parseInt(parts[2], 10);
184
- return new Date(year, month, day);
185
- }
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"),
186
75
  });
187
76
  }
188
- /**
189
- * Renders an editable list for an array property. json-schema-form reports
190
- * arrays as an unusable "select", so we read the item schema from the field's
191
- * scopedJsonSchema and render one input per element with add/remove controls.
192
- * Supports scalar item types (number/integer/string/boolean). The value is kept
193
- * in formValues as a real JS array.
194
- */
195
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
196
- renderArray(props) {
197
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
198
- const scoped = this.field.scopedJsonSchema;
199
- const arraySchema = scoped?.properties?.[this.name] ?? {};
200
- const itemSchema = arraySchema.items ?? { type: "string" };
201
- const itemType = itemSchema.type ?? "string";
202
- const isNumeric = itemType === "number" || itemType === "integer";
203
- const isBoolean = itemType === "boolean";
204
- const minItems = arraySchema.minItems ?? 0;
205
- const maxItems = arraySchema.maxItems ?? Infinity;
206
- const blank = () => (isNumeric ? 0 : isBoolean ? false : "");
207
- const coerce = (raw) => (isNumeric ? (raw === "" ? "" : Number(raw)) : raw);
208
- const values = Array.isArray(this.iniVal) ? [...this.iniVal] : [];
209
- while (values.length < minItems)
210
- values.push(blank());
211
- // Bumped only on add/remove so typing into a row never re-renders it (avoids
212
- // losing input focus on every keystroke).
213
- const version = van.state(0);
214
- const emit = () => this.handleChange(this, values.slice());
215
- emit();
216
- const itemClass = resolve(this.class, this.theme.input);
217
- const rowInput = (i) => {
218
- if (isBoolean) {
219
- return input({
220
- type: "checkbox",
221
- class: itemClass,
222
- checked: Boolean(values[i]),
223
- onchange: (e) => { values[i] = e.target.checked; emit(); },
224
- });
225
- }
226
- return input({
227
- type: isNumeric ? "number" : "text",
228
- class: itemClass,
229
- value: String(values[i] ?? ""),
230
- oninput: (e) => { values[i] = coerce(e.target.value); emit(); },
231
- });
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
+ },
232
121
  };
233
- const rows = () => div({ class: this.theme.arrayItems || "jsf-array-items" }, values.map((_, i) => div({ class: this.theme.arrayRow || "jsf-array-row" }, rowInput(i), button({
234
- type: "button",
235
- class: this.theme.arrayRemoveButton || "jsf-array-remove",
236
- disabled: values.length <= minItems,
237
- onclick: () => { values.splice(i, 1); version.val++; emit(); },
238
- }, "✕"))));
239
- return div(props, this.renderLabel(), this.renderDescription(),
240
- // Re-render the row list whenever an item is added or removed.
241
- () => { void version.val; return rows(); }, button({
242
- type: "button",
243
- class: this.theme.arrayAddButton || "jsf-array-add",
244
- onclick: () => { if (values.length < maxItems) {
245
- values.push(blank());
246
- version.val++;
247
- emit();
248
- } },
249
- }, "+ Add"), this.renderError());
250
122
  }
251
123
  render() {
252
- let el;
253
- const baseContainer = resolve(this.containerClass, this.theme.container);
254
- const containerCls = this.layoutClass ? `${baseContainer} ${this.layoutClass}` : baseContainer;
255
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
256
- const props = {
257
- class: () => this.isVisible ? containerCls : `${containerCls} jsf-hidden`.trim(),
258
- };
259
- // json-schema-form reports arrays as inputType "select" with no options, which
260
- // is not usable. Detect the array jsonType and render an editable repeatable
261
- // list of scalar items instead.
262
- if (this.field.jsonType === "array") {
263
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
264
- return this.renderArray(props);
265
- }
266
- switch (this.inputType) {
267
- case FieldType.text:
268
- el = div(props, this.renderLabel(), this.renderDescription(), input({
269
- id: this.name,
270
- type: "text",
271
- class: resolve(this.class, this.theme.input),
272
- value: this.iniVal,
273
- oninput: (e) => this.handleChange(this, e.target.value),
274
- }), this.renderError());
275
- break;
276
- case FieldType.password:
277
- // Password is rendered with type="password" so the user agent
278
- // masks the value as it is typed. Otherwise behaves identically
279
- // to a text input — same theme.input class, same oninput
280
- // wiring. autocomplete="new-password" hints to browsers that
281
- // this is a credential entry form, not a "remember me" field.
282
- el = div(props, this.renderLabel(), this.renderDescription(), input({
283
- id: this.name,
284
- type: "password",
285
- autocomplete: "new-password",
286
- class: resolve(this.class, this.theme.input),
287
- value: this.iniVal,
288
- oninput: (e) => this.handleChange(this, e.target.value),
289
- }), this.renderError());
290
- break;
291
- case FieldType.textarea:
292
- el = div(props, this.renderLabel(), this.renderDescription(), textarea({
293
- id: this.name,
294
- name: this.name,
295
- class: resolve(this.class, this.theme.textarea),
296
- rows: this.field.rows,
297
- cols: this.field.columns,
298
- oninput: (e) => this.handleChange(this, e.target.value),
299
- }), this.renderError());
300
- break;
301
- case FieldType.code:
302
- el = div(props, this.renderLabel(), this.renderDescription());
303
- // CodeMirror + ESLint are loaded on demand; the editor mounts into `el`
304
- // once the chunk resolves.
305
- void this.mountCodeEditor(el);
306
- break;
307
- case FieldType.select:
308
- el = div(props, this.renderLabel(), this.renderDescription(), select({
309
- id: this.name,
310
- name: this.name,
311
- class: resolve(this.class, this.theme.select),
312
- oninput: (e) => this.handleChange(this, e.target.value),
313
- }, this.options?.map((opt) => option({ class: this.theme.option || "", value: opt.value }, opt.label, opt.description))), this.renderError());
314
- break;
315
- case FieldType.date: {
316
- const calendarInput = input({
317
- id: this.name,
318
- type: "text",
319
- class: resolve(this.class, this.theme.input),
320
- value: this.iniVal,
321
- onchange: (e) => this.handleChange(this, e.target.value),
322
- });
323
- el =
324
- div(props, this.renderLabel(), this.renderDescription(), calendarInput, this.renderError(),
325
- // External CDN dependency for Pikaday CSS — consider bundling for production
326
- link({ rel: "stylesheet", type: "text/css", href: "https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css" }));
327
- // Pikaday is loaded on demand and attached to the input once available.
328
- void this.mountDatePicker(el, calendarInput);
329
- break;
330
- }
331
- case FieldType.number:
332
- el = div(props, this.renderLabel(), this.renderDescription(), input({
333
- id: this.name,
334
- type: "number",
335
- class: resolve(this.class, this.theme.input),
336
- value: this.iniVal,
337
- oninput: (e) => {
338
- const val = e.target.value;
339
- this.handleChange(this, val === "" ? "" : Number(val));
340
- },
341
- }), this.renderError());
342
- break;
343
- case FieldType.fieldset:
344
- 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)
345
- ? this.field.fields.map((field) => field.render())
346
- : null));
347
- break;
348
- case FieldType.radio:
349
- 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({
350
- type: "radio",
351
- name: this.name,
352
- class: resolve(this.class, this.theme.radioInput),
353
- value: opt.value,
354
- checked: this.iniVal === opt.value,
355
- onchange: (e) => this.handleChange(this, e.target.value),
356
- }), opt.label, opt.description))), this.renderError());
357
- break;
358
- case FieldType.file: {
359
- const accept = this.field.accept || "";
360
- const maxSizeMB = this.field.maxSizeMB;
361
- const readAs = this.field.readAs || "auto";
362
- const TEXT_EXTENSIONS = new Set([
363
- "json", "csv", "tsv", "txt", "xml", "yaml", "yml",
364
- "log", "md", "html", "css", "js", "ts", "sql", "env",
365
- ]);
366
- // Reactive states
367
- const fileNameState = van.state("");
368
- const fileSizeState = van.state("");
369
- const dragOverState = van.state(false);
370
- const readingState = van.state(false);
371
- const formatSize = (bytes) => {
372
- if (bytes < 1024)
373
- return `${bytes} B`;
374
- if (bytes < 1024 * 1024)
375
- return `${(bytes / 1024).toFixed(1)} KB`;
376
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
377
- };
378
- const readFile = (file) => {
379
- this.error = "";
380
- // Validate size
381
- if (maxSizeMB && file.size > maxSizeMB * 1024 * 1024) {
382
- this.error = `File exceeds maximum size of ${maxSizeMB} MB`;
383
- return;
384
- }
385
- fileNameState.val = file.name;
386
- fileSizeState.val = formatSize(file.size);
387
- readingState.val = true;
388
- // Store metadata
389
- this.fileNameValue = file.name;
390
- this.fileSizeValue = String(file.size);
391
- this.fileTypeValue = file.type;
392
- const reader = new FileReader();
393
- reader.onload = () => {
394
- readingState.val = false;
395
- let result = reader.result;
396
- if (reader.result instanceof ArrayBuffer) {
397
- // Convert binary to base64 (applies to "arrayBuffer" and "auto" for binary files)
398
- const bytes = new Uint8Array(reader.result);
399
- let binary = "";
400
- for (let i = 0; i < bytes.byteLength; i++) {
401
- binary += String.fromCharCode(bytes[i]);
402
- }
403
- result = btoa(binary);
404
- }
405
- this.handleChange(this, result);
406
- };
407
- reader.onerror = () => {
408
- readingState.val = false;
409
- this.error = "Error reading file";
410
- };
411
- if (readAs === "dataURL") {
412
- reader.readAsDataURL(file);
413
- }
414
- else if (readAs === "arrayBuffer") {
415
- reader.readAsArrayBuffer(file);
416
- }
417
- else if (readAs === "auto") {
418
- const ext = file.name.split(".").pop()?.toLowerCase() ?? "";
419
- if (TEXT_EXTENSIONS.has(ext)) {
420
- reader.readAsText(file);
421
- }
422
- else {
423
- reader.readAsArrayBuffer(file);
424
- }
425
- }
426
- else {
427
- reader.readAsText(file);
428
- }
429
- };
430
- const clearFile = () => {
431
- fileNameState.val = "";
432
- fileSizeState.val = "";
433
- readingState.val = false;
434
- this.fileNameValue = "";
435
- this.fileSizeValue = "";
436
- this.fileTypeValue = "";
437
- this.error = "";
438
- this.handleChange(this, "");
439
- };
440
- const fileInput = input({
441
- type: "file",
442
- accept,
443
- style: "display: none;",
444
- onchange: (e) => {
445
- const files = e.target.files;
446
- if (files && files[0])
447
- readFile(files[0]);
448
- },
449
- });
450
- const dzBase = this.theme.dropZone || "jsf-dropzone";
451
- const dzActive = this.theme.dropZoneActive || "jsf-dropzone-active";
452
- const dropZone = div({
453
- class: () => dragOverState.val ? `${dzBase} ${dzActive}` : dzBase,
454
- ondragover: (e) => { e.preventDefault(); dragOverState.val = true; },
455
- ondragleave: () => { dragOverState.val = false; },
456
- ondrop: (e) => {
457
- e.preventDefault();
458
- dragOverState.val = false;
459
- const files = e.dataTransfer?.files;
460
- if (files && files[0])
461
- readFile(files[0]);
462
- },
463
- onclick: () => fileInput.click(),
464
- }, p({ class: this.theme.dropZoneText || "jsf-dropzone-text" }, accept
465
- ? `Drop a file here or click to browse (${accept})`
466
- : "Drop a file here or click to browse"));
467
- const fileInfoBar = () => {
468
- return div(() => {
469
- const name = fileNameState.val;
470
- if (!name)
471
- return div();
472
- 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({
473
- type: "button",
474
- class: this.theme.fileClearButton || "jsf-file-clear",
475
- onclick: (e) => {
476
- e.stopPropagation();
477
- clearFile();
478
- fileInput.value = "";
479
- },
480
- }, "Clear"));
481
- });
482
- };
483
- const readingIndicator = () => {
484
- return div(() => {
485
- if (!readingState.val)
486
- return div();
487
- return div({ class: this.theme.fileReading || "jsf-file-reading" }, "Reading file...");
488
- });
489
- };
490
- el = div(props, this.renderLabel(), this.renderDescription(), fileInput, dropZone, fileInfoBar(), readingIndicator(), this.renderError());
491
- break;
492
- }
493
- default:
494
- el = div({ style: "border: 1px dashed gray; padding: 8px;" }, `Field "${this.name}" unsupported: The type "${this.inputType}" has no UI component built yet.`);
495
- }
496
- return el;
497
- }
498
- isVanJsfFieldArray(fields) {
499
- 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.`));
500
135
  }
501
136
  }
137
+ //# sourceMappingURL=VanJsfField.js.map