vanjs-jsf 0.3.2 → 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.
package/README.md CHANGED
@@ -10,6 +10,7 @@ This library provides a robust and flexible solution for dynamically generating
10
10
 
11
11
  - [x] **Dynamic Form Generation**: Create forms directly from JSON Schema, reducing repetitive coding tasks.
12
12
  - [x] **Theming API**: Inject CSS classes for every form element via a `theme` object — works with Tailwind, Bootstrap, or any CSS framework.
13
+ - [x] **Layout Map**: Control per-field spatial distribution (e.g. grid column spans) without coupling CSS classes to JSON Schema.
13
14
  - [x] **Customizable**: Tailor form styles, layouts, and behaviours to meet specific UI/UX requirements.
14
15
  - [x] **Headless UI Integration**: Utilize Headless UI's components for accessible and modern interfaces.
15
16
  - [x] **TypeScript-first Approach**: Enjoy strong typing and enhanced developer experience with TypeScript.
@@ -23,12 +24,14 @@ The currently supported form element types are:
23
24
  - text = "text"
24
25
  - number = "number"
25
26
  - textarea = "textarea"
27
+ - password = "password"
26
28
  - select = "select"
27
29
  - radio = "radio"
28
30
  - date = "date" (Pikaday)
29
31
  - code = "code" (CodeMirror with JSON, JavaScript, TypeScript support)
30
32
  - fieldset = "fieldset"
31
33
  - file = "file" (drag & drop, with configurable `readAs` mode and size validation)
34
+ - array (repeatable list of scalar items: number/integer/string/boolean, with add/remove controls)
32
35
 
33
36
  ## Getting Started
34
37
 
@@ -210,6 +213,10 @@ const formEl = jsform({
210
213
  | `radioInput` | `<input type="radio">` elements |
211
214
  | `fieldset` | `<fieldset>` elements |
212
215
  | `legend` | `<legend>` elements (falls back to `label` if not set) |
216
+ | `arrayItems` | Container `<div>` wrapping the list of array items |
217
+ | `arrayRow` | `<div>` wrapping each array item (input + remove) |
218
+ | `arrayAddButton` | "Add" button to append a new array item |
219
+ | `arrayRemoveButton` | "Remove" button next to each array item |
213
220
  | `dropZone` | File drop zone container (normal state) |
214
221
  | `dropZoneActive` | File drop zone during dragover |
215
222
  | `dropZoneText` | Text inside the drop zone |
@@ -219,6 +226,75 @@ const formEl = jsform({
219
226
  | `fileClearButton` | "Clear" button |
220
227
  | `fileReading` | "Reading file..." indicator |
221
228
 
229
+ ## Layout
230
+
231
+ The `layout` attribute lets you assign extra CSS classes to specific field containers by name, without modifying the JSON Schema. This is useful for controlling column spans in CSS grid layouts.
232
+
233
+ ```typescript
234
+ import { jsform, JsfTheme, JsfLayout } from "vanjs-jsf";
235
+
236
+ const theme: JsfTheme = {
237
+ container: "mb-4",
238
+ input: "w-full border rounded px-3 py-2",
239
+ label: "block text-sm font-medium mb-1",
240
+ };
241
+
242
+ const layout: JsfLayout = {
243
+ host: "col-span-2", // full row
244
+ dbname: "col-span-2", // full row
245
+ // port, user, password, schema → no entry → default 1 column
246
+ };
247
+
248
+ const formEl = jsform({
249
+ schema: connectionSchema,
250
+ config: { initialValues: {}, formValues: {} },
251
+ theme,
252
+ layout,
253
+ });
254
+ ```
255
+
256
+ Wrap the form in a grid container to activate the column distribution:
257
+
258
+ ```css
259
+ .jsf-grid > form {
260
+ display: grid;
261
+ grid-template-columns: 1fr 1fr;
262
+ gap: 0 1rem;
263
+ }
264
+ ```
265
+
266
+ ```typescript
267
+ const { div } = van.tags;
268
+ van.add(document.body, div({ class: "jsf-grid" }, formEl));
269
+ ```
270
+
271
+ This produces a layout like:
272
+
273
+ ```text
274
+ ┌─────────────── host ────────────────┐
275
+ │ 192.168.1.176 │
276
+ ├────── port ──────┬──── user ────────┤
277
+ │ 5432 │ wolfops │
278
+ ├──── password ────┬──── schema ──────┤
279
+ │ •••••••• │ public │
280
+ ├─────────────── dbname ──────────────┤
281
+ │ wolfops_dev │
282
+ └─────────────────────────────────────┘
283
+ ```
284
+
285
+ ### Nested fields
286
+
287
+ For fields inside a fieldset, `layout` supports both the full path and the short name:
288
+
289
+ ```typescript
290
+ const layout: JsfLayout = {
291
+ "connection.host": "col-span-2", // by full path
292
+ port: "col-span-1", // by short name (also works for nested)
293
+ };
294
+ ```
295
+
296
+ The full path (`fieldset.fieldName`) is checked first, then the short name.
297
+
222
298
  ### Class resolution order
223
299
 
224
300
  For each element, the resolved class follows this priority:
@@ -227,6 +303,8 @@ For each element, the resolved class follows this priority:
227
303
  2. **Theme class** from the `theme` object
228
304
  3. **Empty string** (no class applied)
229
305
 
306
+ Layout classes are appended *after* the resolved container class, so they combine with both per-field and theme classes.
307
+
230
308
  ### Visibility
231
309
 
232
310
  Hidden fields receive the `jsf-hidden` CSS class instead of inline `display: none`. Make sure your CSS includes:
@@ -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,17 +1,15 @@
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) {
14
11
  FieldType["text"] = "text";
12
+ FieldType["password"] = "password";
15
13
  FieldType["code"] = "code";
16
14
  FieldType["number"] = "number";
17
15
  FieldType["textarea"] = "textarea";
@@ -21,21 +19,6 @@ var FieldType;
21
19
  FieldType["fieldset"] = "fieldset";
22
20
  FieldType["file"] = "file";
23
21
  })(FieldType || (FieldType = {}));
24
- const eslintConfig = {
25
- // eslint configuration
26
- languageOptions: {
27
- globals: {
28
- ...globals.node,
29
- },
30
- parserOptions: {
31
- ecmaVersion: 2022,
32
- sourceType: "module",
33
- },
34
- },
35
- rules: {
36
- semi: ["error", "never"],
37
- },
38
- };
39
22
  export class VanJsfField extends VanJSComponent {
40
23
  name;
41
24
  field;
@@ -75,50 +58,6 @@ export class VanJsfField extends VanJSComponent {
75
58
  get isRequired() {
76
59
  return this.field.required ?? false;
77
60
  }
78
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
79
- get codemirrorExtension() {
80
- const cmTheme = EditorView.theme({
81
- '.cm-content, .cm-gutter': {
82
- "min-height": "150px",
83
- },
84
- '.cm-content': {
85
- "min-height": "150px",
86
- },
87
- '.cm-gutters': {
88
- margin: '1px',
89
- },
90
- '.cm-scroller': {
91
- overflow: 'auto',
92
- },
93
- '.cm-wrap': {
94
- border: '1px solid silver',
95
- },
96
- });
97
- const extensions = [cmTheme, EditorView.updateListener.of((e) => {
98
- this.field.error = null;
99
- forEachDiagnostic(e.state, (diag) => {
100
- if (diag.severity === "error") {
101
- this.field.error = diag.message;
102
- }
103
- });
104
- this.handleChange(this, e.state.doc.toString());
105
- }), basicSetup, lintGutter()];
106
- switch (this.field.codemirrorType) {
107
- case "json":
108
- extensions.push(json(), linter(jsonParseLinter()));
109
- break;
110
- case "javascript":
111
- extensions.push(javascript(), linter(esLint(new eslint.Linter(), eslintConfig)));
112
- break;
113
- case "typescript":
114
- extensions.push(javascript({ typescript: true }), linter(esLint(new eslint.Linter(), eslintConfig)));
115
- break;
116
- default:
117
- extensions.push(javascript(), linter(esLint(new eslint.Linter(), eslintConfig)));
118
- break;
119
- }
120
- return extensions;
121
- }
122
61
  get containerClass() {
123
62
  return this.field.containerClass;
124
63
  }
@@ -166,6 +105,149 @@ export class VanJsfField extends VanJSComponent {
166
105
  renderError() {
167
106
  return p({ class: resolve(this.errorClass, this.theme.error) }, () => this.error);
168
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
+ }
169
251
  render() {
170
252
  let el;
171
253
  const baseContainer = resolve(this.containerClass, this.theme.container);
@@ -174,6 +256,13 @@ export class VanJsfField extends VanJSComponent {
174
256
  const props = {
175
257
  class: () => this.isVisible ? containerCls : `${containerCls} jsf-hidden`.trim(),
176
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
+ }
177
266
  switch (this.inputType) {
178
267
  case FieldType.text:
179
268
  el = div(props, this.renderLabel(), this.renderDescription(), input({
@@ -184,6 +273,21 @@ export class VanJsfField extends VanJSComponent {
184
273
  oninput: (e) => this.handleChange(this, e.target.value),
185
274
  }), this.renderError());
186
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;
187
291
  case FieldType.textarea:
188
292
  el = div(props, this.renderLabel(), this.renderDescription(), textarea({
189
293
  id: this.name,
@@ -196,11 +300,9 @@ export class VanJsfField extends VanJSComponent {
196
300
  break;
197
301
  case FieldType.code:
198
302
  el = div(props, this.renderLabel(), this.renderDescription());
199
- new EditorView({
200
- doc: String(this.iniVal),
201
- parent: el,
202
- extensions: this.codemirrorExtension
203
- });
303
+ // CodeMirror + ESLint are loaded on demand; the editor mounts into `el`
304
+ // once the chunk resolves.
305
+ void this.mountCodeEditor(el);
204
306
  break;
205
307
  case FieldType.select:
206
308
  el = div(props, this.renderLabel(), this.renderDescription(), select({
@@ -222,25 +324,8 @@ export class VanJsfField extends VanJSComponent {
222
324
  div(props, this.renderLabel(), this.renderDescription(), calendarInput, this.renderError(),
223
325
  // External CDN dependency for Pikaday CSS — consider bundling for production
224
326
  link({ rel: "stylesheet", type: "text/css", href: "https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css" }));
225
- new pikaday({
226
- field: calendarInput,
227
- format: 'YYYY-MM-DD',
228
- container: el,
229
- firstDay: 1,
230
- toString(date) {
231
- const day = date.getDate();
232
- const month = date.getMonth() + 1;
233
- const year = date.getFullYear();
234
- return `${year}-${("0" + month).slice(-2)}-${("0" + day).slice(-2)}`;
235
- },
236
- parse(dateString) {
237
- const parts = dateString.split('-');
238
- const year = parseInt(parts[0], 10);
239
- const month = parseInt(parts[1], 10) - 1;
240
- const day = parseInt(parts[2], 10);
241
- return new Date(year, month, day);
242
- }
243
- });
327
+ // Pikaday is loaded on demand and attached to the input once available.
328
+ void this.mountDatePicker(el, calendarInput);
244
329
  break;
245
330
  }
246
331
  case FieldType.number: