vanjs-jsf 0.4.0 → 0.5.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.
@@ -27,7 +27,6 @@ export declare class VanJsfField extends VanJSComponent {
27
27
  get class(): string;
28
28
  get errorClass(): string;
29
29
  get isRequired(): boolean;
30
- get codemirrorExtension(): Array<any>;
31
30
  get containerClass(): string;
32
31
  get containerId(): string;
33
32
  get titleClass(): string;
@@ -41,6 +40,22 @@ export declare class VanJsfField extends VanJSComponent {
41
40
  private renderLabel;
42
41
  private renderDescription;
43
42
  private renderError;
43
+ /**
44
+ * Lazily loads CodeMirror + ESLint and mounts a code editor into `parent`.
45
+ * These are the heaviest dependencies in the library; importing them only here
46
+ * keeps them out of the main bundle for forms that don't use a `code` field.
47
+ */
48
+ private mountCodeEditor;
49
+ /** Lazily loads Pikaday and attaches a date picker to `calendarInput`. */
50
+ private mountDatePicker;
51
+ /**
52
+ * Renders an editable list for an array property. json-schema-form reports
53
+ * arrays as an unusable "select", so we read the item schema from the field's
54
+ * scopedJsonSchema and render one input per element with add/remove controls.
55
+ * Supports scalar item types (number/integer/string/boolean). The value is kept
56
+ * in formValues as a real JS array.
57
+ */
58
+ private renderArray;
44
59
  render(): Element;
45
60
  isVanJsfFieldArray(fields: unknown): fields is VanJsfField[];
46
61
  }
@@ -1,13 +1,10 @@
1
1
  import van from "vanjs-core";
2
2
  import { VanJSComponent } from "./VanJSComponent";
3
3
  import { resolve } from "./theme";
4
- import pikaday from "pikaday";
5
- import { basicSetup, EditorView } from "codemirror";
6
- import { javascript, esLint } from "@codemirror/lang-javascript";
7
- import { json, jsonParseLinter } from "@codemirror/lang-json";
8
- import { lintGutter, linter, forEachDiagnostic } from "@codemirror/lint";
9
- import * as eslint from "eslint-linter-browserify";
10
- import globals from "globals";
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.
11
8
  const { div, p, input, label, textarea, legend, link, fieldset, span, select, option, button, strong, small } = van.tags;
12
9
  var FieldType;
13
10
  (function (FieldType) {
@@ -22,21 +19,6 @@ var FieldType;
22
19
  FieldType["fieldset"] = "fieldset";
23
20
  FieldType["file"] = "file";
24
21
  })(FieldType || (FieldType = {}));
25
- const eslintConfig = {
26
- // eslint configuration
27
- languageOptions: {
28
- globals: {
29
- ...globals.node,
30
- },
31
- parserOptions: {
32
- ecmaVersion: 2022,
33
- sourceType: "module",
34
- },
35
- },
36
- rules: {
37
- semi: ["error", "never"],
38
- },
39
- };
40
22
  export class VanJsfField extends VanJSComponent {
41
23
  name;
42
24
  field;
@@ -76,50 +58,6 @@ export class VanJsfField extends VanJSComponent {
76
58
  get isRequired() {
77
59
  return this.field.required ?? false;
78
60
  }
79
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
80
- get codemirrorExtension() {
81
- const cmTheme = EditorView.theme({
82
- '.cm-content, .cm-gutter': {
83
- "min-height": "150px",
84
- },
85
- '.cm-content': {
86
- "min-height": "150px",
87
- },
88
- '.cm-gutters': {
89
- margin: '1px',
90
- },
91
- '.cm-scroller': {
92
- overflow: 'auto',
93
- },
94
- '.cm-wrap': {
95
- border: '1px solid silver',
96
- },
97
- });
98
- const extensions = [cmTheme, EditorView.updateListener.of((e) => {
99
- this.field.error = null;
100
- forEachDiagnostic(e.state, (diag) => {
101
- if (diag.severity === "error") {
102
- this.field.error = diag.message;
103
- }
104
- });
105
- this.handleChange(this, e.state.doc.toString());
106
- }), basicSetup, lintGutter()];
107
- switch (this.field.codemirrorType) {
108
- case "json":
109
- extensions.push(json(), linter(jsonParseLinter()));
110
- break;
111
- case "javascript":
112
- extensions.push(javascript(), linter(esLint(new eslint.Linter(), eslintConfig)));
113
- break;
114
- case "typescript":
115
- extensions.push(javascript({ typescript: true }), linter(esLint(new eslint.Linter(), eslintConfig)));
116
- break;
117
- default:
118
- extensions.push(javascript(), linter(esLint(new eslint.Linter(), eslintConfig)));
119
- break;
120
- }
121
- return extensions;
122
- }
123
61
  get containerClass() {
124
62
  return this.field.containerClass;
125
63
  }
@@ -167,6 +105,149 @@ export class VanJsfField extends VanJSComponent {
167
105
  renderError() {
168
106
  return p({ class: resolve(this.errorClass, this.theme.error) }, () => this.error);
169
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;
162
+ }
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
+ }
186
+ });
187
+ }
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
+ });
232
+ };
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
+ }
170
251
  render() {
171
252
  let el;
172
253
  const baseContainer = resolve(this.containerClass, this.theme.container);
@@ -175,6 +256,13 @@ export class VanJsfField extends VanJSComponent {
175
256
  const props = {
176
257
  class: () => this.isVisible ? containerCls : `${containerCls} jsf-hidden`.trim(),
177
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
+ }
178
266
  switch (this.inputType) {
179
267
  case FieldType.text:
180
268
  el = div(props, this.renderLabel(), this.renderDescription(), input({
@@ -212,11 +300,9 @@ export class VanJsfField extends VanJSComponent {
212
300
  break;
213
301
  case FieldType.code:
214
302
  el = div(props, this.renderLabel(), this.renderDescription());
215
- new EditorView({
216
- doc: String(this.iniVal),
217
- parent: el,
218
- extensions: this.codemirrorExtension
219
- });
303
+ // CodeMirror + ESLint are loaded on demand; the editor mounts into `el`
304
+ // once the chunk resolves.
305
+ void this.mountCodeEditor(el);
220
306
  break;
221
307
  case FieldType.select:
222
308
  el = div(props, this.renderLabel(), this.renderDescription(), select({
@@ -238,25 +324,8 @@ export class VanJsfField extends VanJSComponent {
238
324
  div(props, this.renderLabel(), this.renderDescription(), calendarInput, this.renderError(),
239
325
  // External CDN dependency for Pikaday CSS — consider bundling for production
240
326
  link({ rel: "stylesheet", type: "text/css", href: "https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css" }));
241
- new pikaday({
242
- field: calendarInput,
243
- format: 'YYYY-MM-DD',
244
- container: el,
245
- firstDay: 1,
246
- toString(date) {
247
- const day = date.getDate();
248
- const month = date.getMonth() + 1;
249
- const year = date.getFullYear();
250
- return `${year}-${("0" + month).slice(-2)}-${("0" + day).slice(-2)}`;
251
- },
252
- parse(dateString) {
253
- const parts = dateString.split('-');
254
- const year = parseInt(parts[0], 10);
255
- const month = parseInt(parts[1], 10) - 1;
256
- const day = parseInt(parts[2], 10);
257
- return new Date(year, month, day);
258
- }
259
- });
327
+ // Pikaday is loaded on demand and attached to the input once available.
328
+ void this.mountDatePicker(el, calendarInput);
260
329
  break;
261
330
  }
262
331
  case FieldType.number: