@punica/form-mcp 0.3.1 → 0.4.0-next.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.
- package/README.md +8 -6
- package/bundled/form/controller/index.d.ts +6 -0
- package/bundled/form/define/Form.d.ts +41 -0
- package/bundled/form/define/index.d.ts +2 -0
- package/bundled/form/model/command/service.d.ts +7 -1
- package/bundled/form/model/constants/index.d.ts +4 -0
- package/bundled/form/model/form/index.d.ts +32 -0
- package/bundled/form/model/item/index.d.ts +35 -2
- package/bundled/form/package.json +1 -1
- package/bundled/form/utils/deepCopy.d.ts +2 -1
- package/bundled/form/utils/index.d.ts +1 -0
- package/bundled/form/utils/isEqual.d.ts +7 -0
- package/bundled/form-json/conditions.d.ts +8 -0
- package/bundled/form-json/definition/fromJsonSchema.d.ts +22 -0
- package/bundled/form-json/definition/index.d.ts +6 -0
- package/bundled/form-json/definition/limits.d.ts +31 -0
- package/bundled/form-json/definition/schema.d.ts +202 -0
- package/bundled/form-json/definition/types.d.ts +87 -0
- package/bundled/form-json/definition/validate.d.ts +15 -0
- package/bundled/form-json/fromSchema.d.ts +50 -0
- package/bundled/form-json/index.d.ts +4 -0
- package/bundled/form-json/package.json +1 -0
- package/bundled/form-json/rules.d.ts +19 -0
- package/bundled/form-kit/decorators.d.ts +39 -1
- package/bundled/form-kit/json/index.d.ts +33 -0
- package/bundled/form-kit/package.json +1 -1
- package/bundled/form-kit/react/FieldList.d.ts +33 -0
- package/bundled/form-kit/react/Rows.d.ts +9 -0
- package/bundled/form-kit/react/fields.d.ts +5 -11
- package/bundled/form-kit/react/index.d.ts +5 -4
- package/bundled/form-kit/types.d.ts +45 -3
- package/bundled/form-kit/validation.d.ts +4 -0
- package/bundled/form-react/index.d.ts +3 -0
- package/bundled/form-react/package.json +1 -1
- package/bundled/form-react/useController.d.ts +15 -0
- package/bundled/form-react/useFieldArray.d.ts +34 -0
- package/bundled/form-react/useFormController.d.ts +2 -7
- package/bundled/form-react/useFormState.d.ts +7 -0
- package/bundled/form-schema/decorator.d.ts +26 -0
- package/bundled/form-schema/index.d.ts +11 -0
- package/bundled/form-schema/issues.d.ts +22 -0
- package/bundled/form-schema/package.json +1 -0
- package/bundled/form-schema/schema.d.ts +17 -0
- package/bundled/form-schema/service.d.ts +27 -0
- package/bundled/form-schema/standard.d.ts +30 -0
- package/bundled/form-service/fieldArray/index.d.ts +47 -0
- package/bundled/form-service/formValidation.d.ts +36 -0
- package/bundled/form-service/index.d.ts +13 -0
- package/bundled/form-service/message.d.ts +2 -0
- package/bundled/form-service/package.json +1 -1
- package/bundled/form-service/readValues.d.ts +6 -0
- package/bundled/form-service/rows.d.ts +67 -0
- package/bundled/form-service/setValue/index.d.ts +1 -0
- package/bundled/form-service/submit/index.d.ts +20 -0
- package/bundled/form-service/touch/index.d.ts +13 -0
- package/bundled/form-service/trigger/index.d.ts +3 -0
- package/bundled/form-service/validate/index.d.ts +2 -1
- package/bundled/form-service/validateItem.d.ts +25 -9
- package/bundled/form-service/valuesOf.d.ts +3 -0
- package/package.json +7 -5
- package/src/create.mjs +78 -3
- package/src/guide.md +156 -8
- package/src/load.mjs +7 -2
- package/src/main.mjs +5 -2
package/src/guide.md
CHANGED
|
@@ -11,8 +11,12 @@ Punica Form is a headless form engine. `@punica/form` holds the engine,
|
|
|
11
11
|
`getFormProperty` and `getFormItemProperties`, the form item register,
|
|
12
12
|
`deepCopy`, the DevTools switches and the types. Use `search_api` for the
|
|
13
13
|
exact list.
|
|
14
|
+
- `@punica/form-json`: forms as data; see "Forms as data" below.
|
|
15
|
+
- `@punica/form-schema`: validation with a schema of Zod, Valibot, ArkType
|
|
16
|
+
or Yup; see "Validation with a schema" below.
|
|
14
17
|
- `@punica/form-service`: `Validate`, `GetValues`, `SetValue`, `Reset`,
|
|
15
|
-
`ResetItem`, `Trigger`, `ClearError`, `ClearErrors`, `
|
|
18
|
+
`ResetItem`, `Trigger`, `ClearError`, `ClearErrors`, `Touch`, `Submit`,
|
|
19
|
+
`FieldArray`, `Store`.
|
|
16
20
|
- NOT provided: `@Title`, `@Description`, `@Layout`, `@FormItemInputText` or
|
|
17
21
|
any other form item decorator, a `Reader` class, a base form item. These
|
|
18
22
|
belong to the application's own form system. Build them with the `define*`
|
|
@@ -21,18 +25,70 @@ Punica Form is a headless form engine. `@punica/form` holds the engine,
|
|
|
21
25
|
- Decorators work with both the legacy implementation of TypeScript
|
|
22
26
|
(`"experimentalDecorators": true`) and the standard one. There is no
|
|
23
27
|
`reflect-metadata`: never call `Reflect.getMetadata`.
|
|
28
|
+
- Before writing a decorated class, check that the build compiles decorator
|
|
29
|
+
syntax: `"experimentalDecorators": true` in `tsconfig.json` is enough for
|
|
30
|
+
Vite and esbuild. When it does not and you should not change it, define the
|
|
31
|
+
form with `defineForm` (since 2.2), which needs no decorator syntax. Every
|
|
32
|
+
decorator (`Services`, the kit's `TextField`, your own) is then a function
|
|
33
|
+
call:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { defineForm, field, Services } from "@punica/form";
|
|
37
|
+
|
|
38
|
+
const UserForm = defineForm(
|
|
39
|
+
{
|
|
40
|
+
name: field("", Text({ label: "Name" })),
|
|
41
|
+
age: field<number | undefined>(undefined, NumberInput({ label: "Age" })),
|
|
42
|
+
},
|
|
43
|
+
Services([GetValues, SetValue]) // or FormKit({ title: "User" })
|
|
44
|
+
);
|
|
45
|
+
type User = InstanceType<typeof UserForm>;
|
|
46
|
+
|
|
47
|
+
const controller = await FormController.fromEntity(new UserForm({ name: "Jane" }));
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The result is a form class like a decorated one; do not mix both styles in
|
|
51
|
+
one class. `fromEntity` warns when a class ends up without form items.
|
|
24
52
|
|
|
25
53
|
## The ready-made form system
|
|
26
54
|
|
|
27
55
|
`@punica/form-kit` provides what the application would otherwise build:
|
|
28
56
|
`@FormKit({ title, columns })` on the class, the field decorators `TextField`,
|
|
29
|
-
`NumberField`, `TextAreaField`, `SelectField`, `CheckboxField
|
|
30
|
-
`SwitchField
|
|
31
|
-
`
|
|
57
|
+
`NumberField`, `TextAreaField`, `SelectField`, `CheckboxField`,
|
|
58
|
+
`SwitchField`, `RadioGroupField`, `MultiSelectField`, `DateField` (its value
|
|
59
|
+
is `yyyy-mm-dd`), `PasswordField`, `FileField` and `ArrayField` (a list of
|
|
60
|
+
rows: `@ArrayField({ label, row: () => new LineForm() })`, the kit renders a
|
|
61
|
+
form for every row) with the rules `required`, `minLength`, `maxLength`,
|
|
62
|
+
`pattern`, `min`, `max`, `minDate`, `maxDate`, `minItems`, `maxItems` and
|
|
63
|
+
`maxFileSize`; `options` may be a function that loads the choices. And from `@punica/form-kit/react` the component
|
|
32
64
|
`<KitForm entity={() => new UserForm()} onSubmit={…} />`, which renders the
|
|
33
|
-
form with `@punica/components
|
|
65
|
+
form with `@punica/components`, shows what `onSubmit` throws above the
|
|
66
|
+
fields and reports it to `onError`. Use it when the project has it installed;
|
|
34
67
|
otherwise build the form system as described below.
|
|
35
68
|
|
|
69
|
+
## Forms as data, written at run time
|
|
70
|
+
|
|
71
|
+
Everything above is for code. When the form itself has to be produced at run
|
|
72
|
+
time (an agent asking the user for information, a form sent by a server),
|
|
73
|
+
write a form definition instead: JSON, no code. `@punica/form-json` checks
|
|
74
|
+
and runs it.
|
|
75
|
+
|
|
76
|
+
- Read `get_form_schema` for the format and check every definition with
|
|
77
|
+
`validate_form` before handing it over.
|
|
78
|
+
- Render it with `<JsonForm definition={definition} onSubmit={…} />` from
|
|
79
|
+
`@punica/form-kit/json`, or create the controller with
|
|
80
|
+
`fromSchema(definition, { types, rules })` from `@punica/form-json`. Both
|
|
81
|
+
refuse a definition that is not valid with a `FormDefinitionError` whose
|
|
82
|
+
`problems` have a `path` and a `message`.
|
|
83
|
+
- Types with the kit: `text`, `textarea`, `number`, `select`, `checkbox`,
|
|
84
|
+
`switch`, `radio`, `date`, `multiselect`, `password`, `file`. Kit options such as `inputType`, `rows` and `span` go into `props`.
|
|
85
|
+
- Never put functions, expressions or HTML into a definition, and never
|
|
86
|
+
build one by string concatenation: produce the object and validate it.
|
|
87
|
+
- In React a definition is read when the component mounts; give `JsonForm` a
|
|
88
|
+
`key` to show another one.
|
|
89
|
+
- `fromJsonSchema(schema)` turns a flat JSON Schema (string, number, integer,
|
|
90
|
+
boolean and enum properties) into a definition.
|
|
91
|
+
|
|
36
92
|
## Lifecycle
|
|
37
93
|
|
|
38
94
|
```ts
|
|
@@ -68,6 +124,13 @@ const form = useForm(controller); // in a component that has the controller
|
|
|
68
124
|
|
|
69
125
|
Without that package: `useSyncExternalStore(controller.subscribe, controller.getForm)`.
|
|
70
126
|
`start()` publishes the started form the same way (since 2.1).
|
|
127
|
+
|
|
128
|
+
Since 2.2 every item has `dirty` (its value differs from the initial one) and
|
|
129
|
+
`touched` (set by the `Touch` service), and a started form has
|
|
130
|
+
`form.state`: `{ dirty, touched, valid, validating, submitting, submitCount, errors }`.
|
|
131
|
+
`dirty`, `touched` and `valid` follow from the items; `errors` are the errors
|
|
132
|
+
of the form as a whole, such as a rejected submit. In React
|
|
133
|
+
`useFormState(controller)` returns it and only renders again when it changes.
|
|
71
134
|
Never change a form or an item in place; use the services.
|
|
72
135
|
|
|
73
136
|
## Services
|
|
@@ -77,7 +140,7 @@ entity of the form, so property names and results are type-checked.
|
|
|
77
140
|
|
|
78
141
|
| Class | Call |
|
|
79
142
|
|---|---|
|
|
80
|
-
| `Validate` | `run(): Promise<boolean>`, validates every
|
|
143
|
+
| `Validate` | `run(): Promise<boolean>`, validates every item that is not hidden or disabled |
|
|
81
144
|
| `Trigger` | `run(property): Promise<void>`, validates one item |
|
|
82
145
|
| `GetValues` | `run(): Promise<E>`, a copy of the entity filled with the item values |
|
|
83
146
|
| `SetValue` | `run(property, value): Promise<void>`, then runs the `control` function of the item |
|
|
@@ -85,6 +148,9 @@ entity of the form, so property names and results are type-checked.
|
|
|
85
148
|
| `ResetItem` | `run(property): Promise<void>` |
|
|
86
149
|
| `ClearError` | `run(property): Promise<void>` |
|
|
87
150
|
| `ClearErrors` | `run(): Promise<void>` |
|
|
151
|
+
| `Touch` | `run(property): Promise<void>`, marks the item as touched; call it when the user leaves the field (since 2.2) |
|
|
152
|
+
| `Submit` | `run(handler?): Promise<boolean>`, validates, then calls `handler(values)`; sets `state.submitting`, ignores a second submit meanwhile, and turns what the handler throws into `state.errors` instead of rejecting (since 2.2) |
|
|
153
|
+
| `FieldArray` | no `run`: `rows(property)`, `append`, `insert`, `remove`, `move`, `replace`; see "Lists of rows" (since 2.2) |
|
|
88
154
|
| `Store` | no `run`: it adds `readStoreItem`, `writeStoreItem`, `deleteStoreItem` to the command passed to item functions (`CommandItem<E, F, StoreCommand>`) |
|
|
89
155
|
|
|
90
156
|
```ts
|
|
@@ -110,11 +176,56 @@ if (await controller.getService(Validate).run()) {
|
|
|
110
176
|
- `Validate.run()` returns `false` when the form is invalid. Other failures
|
|
111
177
|
(an unknown property, an error thrown by a validation function) reject.
|
|
112
178
|
- Setting a value does not validate it. Run `Trigger` for that.
|
|
179
|
+
- To submit a form prefer `Submit` (since 2.2) over calling `Validate` and
|
|
180
|
+
`GetValues` by hand. Do not keep your own `submitting` or `dirty` flags.
|
|
181
|
+
|
|
182
|
+
## Lists of rows
|
|
183
|
+
|
|
184
|
+
For repeated rows (the lines of an invoice, a list of phone numbers) do not
|
|
185
|
+
keep an array in a single item and do not build property names such as
|
|
186
|
+
`lines.0.price`. Since 2.2 a form item with a `row` function is a list: every
|
|
187
|
+
row is a form of its own, created from the entity `row` returns.
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
class LineForm {
|
|
191
|
+
@FormItemInputText({ label: 'Product' })
|
|
192
|
+
product = '';
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
@Services([FieldArray, GetValues, SetValue, Validate, Trigger, Submit])
|
|
196
|
+
class InvoiceForm {
|
|
197
|
+
// Any form item decorator of the application; `row` makes it a list
|
|
198
|
+
@FormItemList({ label: 'Lines', row: () => new LineForm() })
|
|
199
|
+
lines: LineForm[] = [];
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const list = controller.getService(FieldArray);
|
|
203
|
+
|
|
204
|
+
const row = await list.append('lines', { product: 'Paper' });
|
|
205
|
+
await row.controller.getService(SetValue).run('product', 'Ink');
|
|
206
|
+
await list.remove('lines', row); // or an index
|
|
207
|
+
list.rows('lines'); // [{ key, controller }], a new array only when rows change
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
- The form has to list `FieldArray`. A row class without `@Services` gets the
|
|
211
|
+
services of the form around it; one with `@Services` keeps its own.
|
|
212
|
+
- The value of the list item is the array of the values of its rows.
|
|
213
|
+
`GetValues` and `Submit` return it; never collect the rows by hand.
|
|
214
|
+
- `Validate` and `Submit` validate the rows. The list item is `dirty`,
|
|
215
|
+
`touched` and in `error` when a row is, and `Reset` brings back the rows the
|
|
216
|
+
form was started with. `SetValue` on the list replaces its rows.
|
|
217
|
+
- A `validation` of the list item itself counts besides the rows, for
|
|
218
|
+
example "add at least one line".
|
|
219
|
+
- In React: `const { rows, append, remove, move } = useFieldArray(controller, "lines")`
|
|
220
|
+
from `@punica/form-react`. Render `rows.map((row) => <Line key={row.key} controller={row.controller} />)`
|
|
221
|
+
and call `useForm(row.controller)` inside `Line`, so typing into a row
|
|
222
|
+
renders that row only.
|
|
113
223
|
|
|
114
224
|
## Form items
|
|
115
225
|
|
|
116
226
|
A form item is a plain object: `property`, `label`, `type`, `value`,
|
|
117
|
-
`required`, `disabled`, `hidden`, `error`, `errorMessages
|
|
227
|
+
`required`, `disabled`, `hidden`, `error`, `errorMessages`, `dirty`,
|
|
228
|
+
`touched`, `validating`, and `row` for a list of rows. Add the
|
|
118
229
|
properties of your form system with a type of your own:
|
|
119
230
|
`type AppItem<E> = FormItem<E> & { layout?: Layout }`, then use
|
|
120
231
|
`FormController<UserForm, AppItem<UserForm>>`.
|
|
@@ -122,11 +233,46 @@ properties of your form system with a type of your own:
|
|
|
122
233
|
The functions of an item receive a command `{ formItem, initialEntity,
|
|
123
234
|
getItem }` holding copies, and return items instead of changing them:
|
|
124
235
|
|
|
125
|
-
- `validation(command): Promise<{ error: boolean, errorMessages?: string[] }
|
|
236
|
+
- `validation(command, context?): Promise<{ error: boolean, errorMessages?: string[] }>`.
|
|
237
|
+
Since 2.2 the services pass `context.signal`, an `AbortSignal` that is
|
|
238
|
+
aborted when the item is validated again, changed or reset: give it to
|
|
239
|
+
`fetch(url, { signal: context?.signal })`. A validation that rejects after
|
|
240
|
+
it was aborted is ignored. The item is `validating` meanwhile.
|
|
241
|
+
- `validateDebounce: 300` on an item makes `Trigger` wait that many
|
|
242
|
+
milliseconds and validate once after the last trigger (since 2.2). Use it
|
|
243
|
+
for validations that ask a server while the user types; do not write your
|
|
244
|
+
own debounce around `Trigger`. `Validate` and `Submit` do not wait.
|
|
126
245
|
- `control(command): Promise<FormItem[]>`, run after its value is set; the
|
|
127
246
|
returned items are written to the form
|
|
128
247
|
- `initialize(command): Promise<FormItem[]>`, run once while the form is created
|
|
129
248
|
|
|
249
|
+
## Validation with a schema
|
|
250
|
+
|
|
251
|
+
When the project has a schema library (Zod, Valibot, ArkType, Yup: anything
|
|
252
|
+
that implements Standard Schema) and `@punica/form-schema`, do not write the
|
|
253
|
+
same rules again as validation functions.
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
import { Schema, SchemaValidation, schema } from "@punica/form-schema";
|
|
257
|
+
|
|
258
|
+
const User = z.object({ email: z.email(), age: z.number().min(18) });
|
|
259
|
+
|
|
260
|
+
@Schema(User) // the class does not compile when its properties do not fit
|
|
261
|
+
@Services([SchemaValidation, GetValues, SetValue, Validate, Trigger, Submit])
|
|
262
|
+
class UserForm { … }
|
|
263
|
+
|
|
264
|
+
// Or one item only, without the service:
|
|
265
|
+
// validation: schema(z.email("Enter an email"))
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
- `SchemaValidation` has to be listed. It shows every issue on the item its
|
|
269
|
+
path is about; issues that belong to no item become `state.errors`, make
|
|
270
|
+
`state.valid` false and keep the form from being submitted.
|
|
271
|
+
- For a form without a class: `services: [SchemaValidation.of(User), …]`.
|
|
272
|
+
- A rule about the form as a whole without a schema: a service that calls
|
|
273
|
+
`addFormValidation(command, () => messages)` of `@punica/form-service` in
|
|
274
|
+
its `initialize` (since 2.2).
|
|
275
|
+
|
|
130
276
|
## Events
|
|
131
277
|
|
|
132
278
|
`controller.on(event, handler)` returns the function that removes the
|
|
@@ -137,6 +283,8 @@ handler. Payloads are typed.
|
|
|
137
283
|
| `UPDATE_FORM` | the form; fired after every change |
|
|
138
284
|
| `UPDATE_ITEM` | an array: the changed item, then the items its `control` returned |
|
|
139
285
|
| `RESET` | the form; fired by `Reset`, after `UPDATE_FORM` |
|
|
286
|
+
| `SUBMIT` | the values the submit handler received; fired by `Submit` (since 2.2) |
|
|
287
|
+
| `SUBMIT_ERROR` | what a validation or the submit handler threw (since 2.2) |
|
|
140
288
|
| `REGISTER_ITEMS` | `string[]` of registered form item types; fired at the start of `start()` |
|
|
141
289
|
|
|
142
290
|
## A complete example
|
package/src/load.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Reads the type declarations of a Punica Form package from disk: the copy
|
|
2
2
|
// installed in the project the server is started in, so the answers match
|
|
3
3
|
// that version; without one, the copy bundled with this server.
|
|
4
|
-
import { readdirSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
5
5
|
import { createRequire } from 'node:module';
|
|
6
6
|
import { dirname, join, relative, sep } from 'node:path';
|
|
7
7
|
import { fileURLToPath } from 'node:url';
|
|
@@ -28,7 +28,8 @@ export function readTypes(root) {
|
|
|
28
28
|
* @param {string} [cwd] - The project to look for the package in
|
|
29
29
|
* @param {string} [entry] - A second entry point of the package, such as
|
|
30
30
|
* `react` for `@punica/form-kit/react`
|
|
31
|
-
* @returns {{ name: string, version: string, files: Map<string, string>, installed: boolean }}
|
|
31
|
+
* @returns {{ name: string, version: string, files: Map<string, string>, installed: boolean } | undefined}
|
|
32
|
+
* `undefined` for an entry point the installed version does not have
|
|
32
33
|
*/
|
|
33
34
|
export function loadPackage(name, cwd = process.cwd(), entry = '') {
|
|
34
35
|
const entryName = entry ? `${name}/${entry}` : name;
|
|
@@ -39,6 +40,10 @@ export function loadPackage(name, cwd = process.cwd(), entry = '') {
|
|
|
39
40
|
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
40
41
|
const root = join(dirname(join(dirname(manifestPath), manifest.types)), entry);
|
|
41
42
|
|
|
43
|
+
// An installed version from before the entry point existed: the project
|
|
44
|
+
// cannot import it, so it is not part of what the server knows
|
|
45
|
+
if (entry && !existsSync(root)) return undefined;
|
|
46
|
+
|
|
42
47
|
return { name: entryName, version: manifest.version, files: readTypes(root), installed: true };
|
|
43
48
|
} catch {
|
|
44
49
|
const root = join(BUNDLED, name.split('/')[1]);
|
package/src/main.mjs
CHANGED
|
@@ -10,8 +10,11 @@ const packages = [
|
|
|
10
10
|
loadPackage('@punica/form-service'),
|
|
11
11
|
loadPackage('@punica/form-react'),
|
|
12
12
|
loadPackage('@punica/form-kit'),
|
|
13
|
-
loadPackage('@punica/form-kit', process.cwd(), 'react')
|
|
14
|
-
|
|
13
|
+
loadPackage('@punica/form-kit', process.cwd(), 'react'),
|
|
14
|
+
loadPackage('@punica/form-kit', process.cwd(), 'json'),
|
|
15
|
+
loadPackage('@punica/form-json'),
|
|
16
|
+
loadPackage('@punica/form-schema')
|
|
17
|
+
].filter(Boolean);
|
|
15
18
|
const guide = readFileSync(new URL('./guide.md', import.meta.url), 'utf8');
|
|
16
19
|
|
|
17
20
|
const server = createPunicaFormServer({ packages, guide });
|