vanjs-jsf 0.5.1 → 0.6.1

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 +137 -15
  2. package/dist/VanJsfField.d.ts +40 -57
  3. package/dist/VanJsfField.js +125 -567
  4. package/dist/VanJsfField.js.map +1 -1
  5. package/dist/VanJsfForm.d.ts +82 -1
  6. package/dist/VanJsfForm.js +219 -120
  7. package/dist/VanJsfForm.js.map +1 -1
  8. package/dist/index.d.ts +6 -2
  9. package/dist/index.js +3 -1
  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 +20 -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
package/README.md CHANGED
@@ -15,23 +15,33 @@ This library provides a robust and flexible solution for dynamically generating
15
15
  - [x] **Headless UI Integration**: Utilize Headless UI's components for accessible and modern interfaces.
16
16
  - [x] **TypeScript-first Approach**: Enjoy strong typing and enhanced developer experience with TypeScript.
17
17
  - [x] **Validation Support**: Easily integrate JSON Schema-based validation for seamless user input handling.
18
- - [ ] **Extensible Architecture**: Add custom widgets, field types, and behaviours as needed.
18
+ - [x] **Extensible Architecture**: Register your own widgets, or replace the built-in ones, with the `widgets` option.
19
19
 
20
20
  ### Available components
21
21
 
22
- The currently supported form element types are:
23
-
24
- - text = "text"
25
- - number = "number"
26
- - textarea = "textarea"
27
- - password = "password"
28
- - select = "select"
29
- - radio = "radio"
30
- - date = "date" (Pikaday)
31
- - code = "code" (CodeMirror with JSON, JavaScript, TypeScript support)
32
- - fieldset = "fieldset"
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)
22
+ The input type comes from `x-jsf-presentation.inputType` or, when absent, is inferred from the schema (`boolean` → checkbox, `format: "email"` → email, `format: "date"` → date, `object` → fieldset, array of objects → group-array…).
23
+
24
+ | Input type | Renders | Value |
25
+ | --- | --- | --- |
26
+ | `text`, `password`, `email`, `url`, `tel`, `search` | `<input>` of that type | string |
27
+ | `time`, `datetime-local`, `month`, `week` | native picker | string |
28
+ | `color` | colour picker (starts at `#000000`) | string |
29
+ | `number` | `<input type="number">` with `min`/`max`/`step` (`step=1` for `integer`) | number |
30
+ | `range` | slider plus its current value (starts at `default` or `minimum`) | number |
31
+ | `textarea` | `<textarea>` (`rows`, `columns`) | string |
32
+ | `select` | `<select>` with an empty first option (`placeholder` is its text) | the option's `const`, numbers kept as numbers |
33
+ | `radio` | radio group | the option's `const` |
34
+ | `checkbox` | checkbox; `variant: "switch"` renders a toggle | `true`/`false` for booleans, the `const` otherwise |
35
+ | `date` | native `<input type="date">`; `picker: "pikaday"` uses Pikaday | `YYYY-MM-DD` |
36
+ | `code` | CodeMirror with JSON/JavaScript/TypeScript linting | string |
37
+ | `file` | drag & drop zone (see below) | file content |
38
+ | `hidden` | `<input type="hidden">` | the value as given |
39
+ | `fieldset` | `<fieldset>` with its sub-fields | nested object |
40
+ | multi-select (array with `items.anyOf`) | one checkbox per option | array of the chosen `const`s |
41
+ | array of scalars | editable list with add/remove, honours `minItems`/`maxItems` | array |
42
+ | `group-array` (array of objects) | one fieldset per item with add/remove | array of objects |
43
+
44
+ Every control also takes from `x-jsf-presentation`: `placeholder`, `autocomplete`, `disabled`, `class`, `titleClass`, `descriptionClass`, `errorClass`, `containerClass`; and from the schema: `readOnly`, `maxLength`, `minimum`, `maximum`.
35
45
 
36
46
  ## Getting Started
37
47
 
@@ -137,6 +147,101 @@ const schema = {
137
147
 
138
148
  The file content is stored in `formValues` under the field name. Additional metadata is stored as `<fieldName>__fileName`, `<fieldName>__fileSize`, and `<fieldName>__fileType`.
139
149
 
150
+ ## Values and validation
151
+
152
+ - **Values are nested as the schema is.** A field `street` inside the object `address` is `formValues.address.street`. `initialValues` may be nested too; the dotted form (`{"address.street": "…"}`) is still accepted.
153
+ - **`config.formValues` is reassigned** (not mutated) when the form is built and after every change, so a `Proxy` on `config` sees each update.
154
+ - **Hidden fields are left out** of `config.formValues`, but what the user typed is kept: if the field is shown again, its value comes back.
155
+ - **An empty input is an absent value**, not `""`: an optional number left blank no longer fails as "must be a number".
156
+ - **Falsy initial values are kept**: `0`, `false` and `""` in `initialValues` or `default` are not replaced.
157
+ - **`isValid`** (a `State<boolean>`) is set when the form is built and after every change.
158
+ - **Errors show once a field is touched**, and on every field after a submit attempt (or `form.jsf.validate()`).
159
+ - **Inferred input types**: `jsform()` passes `strictInputType: false` to json-schema-form unless your config sets it. A schema json-schema-form rejects throws an error instead of rendering an empty form.
160
+
161
+ > A required boolean must be checked only when it declares `"x-jsf-presentation": { "inputType": "checkbox" }`; with an inferred checkbox json-schema-form accepts `false`.
162
+
163
+ vanjs-jsf rewrites two schema shapes json-schema-form 0.12 cannot handle, without changing what they accept: `inputType: "date"` without `format: "date"` (it silently disabled validation of the whole form) gets `format: "date"`, and `type: "integer"` with `oneOf`/`anyOf` options (it broke the form) becomes `number`.
164
+
165
+ ## Form handle
166
+
167
+ `jsform()` returns the `<form>` element with a `jsf` property:
168
+
169
+ ```typescript
170
+ const formEl = jsform({ schema, config });
171
+ formEl.jsf.getValues(); // values of the visible fields
172
+ formEl.jsf.setValues({ a: "x" }); // replace the values and re-render
173
+ formEl.jsf.reset(); // back to initialValues
174
+ formEl.jsf.validate(); // show every error, return validity
175
+ ```
176
+
177
+ The form is rendered with `novalidate`: validation is json-schema-form's, and native constraints such as `max` or `maxLength` only act as input hints.
178
+
179
+ ## Custom widgets
180
+
181
+ A widget renders the content of one field container. Register widgets by input type, or pick one per field with `x-jsf-presentation.widget`:
182
+
183
+ ```typescript
184
+ import { jsform, type Widget } from "vanjs-jsf";
185
+ import van from "vanjs-core";
186
+ const { input } = van.tags;
187
+
188
+ const slug: Widget = (ctx) => [
189
+ ctx.label(),
190
+ ctx.description(),
191
+ input({
192
+ ...ctx.attrs(), // id, name, placeholder, readOnly, aria wiring
193
+ value: String(ctx.getValue() ?? ""),
194
+ oninput: (e: Event) =>
195
+ ctx.setValue((e.target as HTMLInputElement).value.toLowerCase().replace(/\W+/g, "-")),
196
+ }),
197
+ ctx.errorMessage(),
198
+ ];
199
+
200
+ jsform({
201
+ schema: {
202
+ type: "object",
203
+ properties: {
204
+ id: { type: "string", title: "Id", "x-jsf-presentation": { inputType: "slug" } },
205
+ title: { type: "string", title: "Title", "x-jsf-presentation": { widget: "slug" } },
206
+ },
207
+ },
208
+ widgets: { slug },
209
+ });
210
+ ```
211
+
212
+ The context also gives `setWidgetError(msg)` for errors the widget itself detects (they keep the form invalid), `setMeta(key, value)` to store `<name>__<key>` next to the value, `error` and `visible` states, and `theme`/`texts`. `builtinWidgets` is exported, so a custom widget can wrap a built-in one; a `widgets` entry with a built-in key (`text`, `select`…) replaces it.
213
+
214
+ ## Texts
215
+
216
+ The strings the library renders itself can be replaced, e.g. for translation:
217
+
218
+ ```typescript
219
+ jsform({
220
+ schema,
221
+ texts: {
222
+ add: "+ Añadir",
223
+ remove: "Quitar",
224
+ dropFile: "Suelta un fichero o haz clic",
225
+ dropFileAccept: "Suelta un fichero o haz clic ({accept})",
226
+ clearFile: "Quitar",
227
+ readingFile: "Leyendo…",
228
+ fileTooLarge: "El fichero supera {max} MB",
229
+ fileReadError: "No se pudo leer el fichero",
230
+ selectPlaceholder: "Elige…",
231
+ },
232
+ });
233
+ ```
234
+
235
+ A group-array's add button takes `x-jsf-presentation.addFieldText` first.
236
+
237
+ ## Date picker
238
+
239
+ `date` fields render the browser's native date input. For Pikaday instead, set `"x-jsf-presentation": { "inputType": "date", "picker": "pikaday" }` and include its stylesheet, which the library no longer loads from a CDN:
240
+
241
+ ```typescript
242
+ import "pikaday/css/pikaday.css";
243
+ ```
244
+
140
245
  ## Theming
141
246
 
142
247
  By default, vanjs-jsf applies minimal semantic CSS classes (e.g. `jsf-dropzone`, `jsf-file-info`). You can import the default styles:
@@ -204,7 +309,7 @@ const formEl = jsform({
204
309
  | `description` | Description `<div>` below the label |
205
310
  | `error` | Error `<p>` below the input |
206
311
  | `requiredIndicator` | `<span>` with "\*" next to required field labels |
207
- | `input` | `<input>` for text, number, and date fields |
312
+ | `input` | `<input>` for text-like, number, range and date fields |
208
313
  | `textarea` | `<textarea>` elements |
209
314
  | `select` | `<select>` elements |
210
315
  | `option` | `<option>` elements inside selects |
@@ -212,6 +317,11 @@ const formEl = jsform({
212
317
  | `radioLabel` | `<label>` wrapping each radio option |
213
318
  | `radioInput` | `<input type="radio">` elements |
214
319
  | `fieldset` | `<fieldset>` elements |
320
+ | `rangeOutput` | Current value next to a slider |
321
+ | `checkboxLabel` | `<label>` wrapping a checkbox (single or in a group) |
322
+ | `checkboxInput` | `<input type="checkbox">` elements |
323
+ | `checkboxGroup` | Container of a multi-select's checkboxes |
324
+ | `arrayGroupItem` | `<fieldset>` of each group-array item |
215
325
  | `legend` | `<legend>` elements (falls back to `label` if not set) |
216
326
  | `arrayItems` | Container `<div>` wrapping the list of array items |
217
327
  | `arrayRow` | `<div>` wrapping each array item (input + remove) |
@@ -324,9 +434,21 @@ npm install # Install dependencies
324
434
  npm run dev # Start Vite dev server (port 3030)
325
435
  npm run build # Compile lib/ → dist/ (tsc, ESM + .d.ts) + copy CSS
326
436
  npm run lint # Run ESLint
437
+ npm test # Run the tests (vitest + happy-dom)
438
+ npm run test:pack # Pack and import the package with plain Node ESM
327
439
  npm run lint:fix # Run ESLint with auto-fix
328
440
  ```
329
441
 
442
+ ## Upgrading from 0.5
443
+
444
+ - Values of fields inside a fieldset are nested (`{address: {street}}`), not dotted keys (`{"address.street"}`).
445
+ - `config.formValues` leaves out hidden fields, and blank inputs are absent rather than `""`.
446
+ - `config.formValues` is set as soon as the form is built, not only after the first change.
447
+ - `date` is the native date input; Pikaday is opt-in with `picker: "pikaday"` and its CSS is no longer fetched from jsdelivr.
448
+ - Field ids are prefixed per form (`jsf1-name`) so two forms can share a page; pass `idPrefix` to choose it.
449
+ - Fields with types that used to show "unsupported" (`checkbox`, `email`, arrays of objects…) now render.
450
+ - An invalid schema throws.
451
+
330
452
  ## Publishing
331
453
 
332
454
  1. Update the version in `package.json`
@@ -1,61 +1,44 @@
1
- import { State } from "vanjs-core";
2
- import { VanJSComponent } from "./VanJSComponent";
3
- import { JsfTheme } from "./theme";
4
- export interface Option {
5
- label: string;
6
- value: string;
7
- description?: string;
8
- img?: string;
9
- }
10
- export type MultiType = string | number | boolean;
11
- export declare class VanJsfField extends VanJSComponent {
12
- name: string;
13
- field: Record<string, unknown>;
14
- iniVal: MultiType;
15
- handleChange: (field: VanJsfField, value: MultiType) => void;
16
- isVisibleState: State<boolean>;
17
- errorState: State<string>;
1
+ import type { JsfField, Widget } from "./types.js";
2
+ import { JsfTheme, JsfTexts } from "./theme.js";
3
+ /** What a field needs from the form that owns it. */
4
+ export interface FieldHost {
18
5
  theme: JsfTheme;
19
- layoutClass: string;
20
- /** Used by file fields to pass file metadata to formValues */
21
- fileNameValue: string;
22
- fileSizeValue: string;
23
- fileTypeValue: string;
24
- constructor(field: Record<string, unknown>, initVal: MultiType, handleChange: (field: VanJsfField, value: MultiType) => void, theme?: JsfTheme, layoutClass?: string);
6
+ texts: JsfTexts;
7
+ idPrefix: string;
8
+ layoutClass(field: VanJsfField): string;
9
+ widget(key: string): Widget | undefined;
10
+ getValue(path: readonly string[]): unknown;
11
+ setValue(field: VanJsfField, value: unknown): void;
12
+ setMeta(field: VanJsfField, key: string, value: unknown): void;
13
+ buildFields(defs: JsfField[], parentPath: string[]): VanJsfField[];
14
+ /** Re-applies validation to every field without changing values. */
15
+ refresh(): void;
16
+ }
17
+ export declare class VanJsfField {
18
+ readonly def: JsfField;
19
+ readonly path: string[];
20
+ readonly id: string;
21
+ readonly visible: import("vanjs-core").State<boolean>;
22
+ /** Message on screen: the validation or widget error, once touched or submitted. */
23
+ readonly error: import("vanjs-core").State<string>;
24
+ /** Fieldset sub-fields. */
25
+ children: VanJsfField[];
26
+ /** group-array: sub-fields of each item, rebuilt whenever items are added or removed. */
27
+ items: VanJsfField[][];
28
+ touched: boolean;
29
+ validationError: string;
30
+ widgetError: string;
31
+ private readonly host;
32
+ constructor(def: JsfField, path: string[], host: FieldHost);
33
+ get name(): string;
25
34
  get inputType(): string;
26
- get label(): string;
27
- get class(): string;
28
- get errorClass(): string;
29
- get isRequired(): boolean;
30
- get containerClass(): string;
31
- get containerId(): string;
32
- get titleClass(): string;
33
- get descriptionClass(): string;
34
- get description(): string;
35
- get options(): Option[];
36
- get isVisible(): boolean;
37
- set isVisible(val: boolean);
38
- get error(): string;
39
- set error(val: string);
40
- private renderLabel;
41
- private renderDescription;
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;
35
+ /** Key used to pick the widget: `x-jsf-presentation.widget`, else derived from the field. */
36
+ get widgetKey(): string;
37
+ /** This field and every field below it, in document order. */
38
+ walk(): Generator<VanJsfField>;
39
+ showError(showAll: boolean): void;
40
+ attrs(): Record<string, unknown>;
41
+ private requiredMark;
42
+ private context;
59
43
  render(): Element;
60
- isVanJsfFieldArray(fields: unknown): fields is VanJsfField[];
61
44
  }