@punica/form-mcp 0.4.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.
- package/bundled/form/package.json +1 -1
- package/bundled/form-json/package.json +1 -1
- package/bundled/form-kit/decorators.d.ts +1 -1
- package/bundled/form-kit/dom/index.d.ts +63 -0
- package/bundled/form-kit/package.json +1 -1
- package/bundled/form-service/index.d.ts +3 -0
- package/bundled/form-service/package.json +1 -1
- package/bundled/form-service/rows.d.ts +7 -0
- package/bundled/form-service/setErrors/index.d.ts +46 -0
- package/bundled/form-service/validateItem.d.ts +10 -0
- package/package.json +5 -5
- package/src/guide.md +129 -48
- package/src/main.mjs +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":"2.
|
|
1
|
+
{"version":"2.3.0"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":"0.
|
|
1
|
+
{"version":"0.2.0"}
|
|
@@ -9,7 +9,7 @@ export type FormKitOptions = {
|
|
|
9
9
|
columns?: 1 | 2 | 3 | 4;
|
|
10
10
|
/**
|
|
11
11
|
* Services in addition to GetValues, SetValue, Validate, Trigger, Reset,
|
|
12
|
-
* Touch, Submit and
|
|
12
|
+
* Touch, Submit, FieldArray and SetErrors.
|
|
13
13
|
*/
|
|
14
14
|
services?: Array<IService | (new () => IService)>;
|
|
15
15
|
/** Readers in addition to the kit's. */
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { FormController } from '@punica/form';
|
|
2
|
+
import { type JsonFormItem, type JsonFormValues, type RuleDefinition } from '@punica/form-json';
|
|
3
|
+
/**
|
|
4
|
+
* A form you draw yourself (your own markup, @punica/components or native
|
|
5
|
+
* controls) whose values, rules and submit are Punica Form's: the engine
|
|
6
|
+
* holds the value of each named control as the person types or chooses; a
|
|
7
|
+
* submit checks the engine's rules and each control's own constraints (in the
|
|
8
|
+
* words the control already uses), shows what is wrong on the control's
|
|
9
|
+
* `punica-field`, focuses the first wrong control, holds the submit buttons
|
|
10
|
+
* while it works, and hands on the values. A control of the form the engine
|
|
11
|
+
* was not given still holds to its own constraints.
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { bindForm } from '@punica/form-kit/dom';
|
|
15
|
+
*
|
|
16
|
+
* const form = bindForm(element, {
|
|
17
|
+
* fields: { name: nameInput, amount: amountInput },
|
|
18
|
+
* rules: { amount: [{ rule: 'pattern', value: '^[0-9]+$', message: 'A whole number.' }] },
|
|
19
|
+
* onSubmit: (values) => save(values),
|
|
20
|
+
* alert: errorLine
|
|
21
|
+
* });
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
/** A control of a hand-drawn form: a @punica/components field control (or a native one) with a value. */
|
|
25
|
+
export type BoundControl = HTMLElement & {
|
|
26
|
+
value?: unknown;
|
|
27
|
+
checked?: boolean;
|
|
28
|
+
disabled?: boolean;
|
|
29
|
+
validity?: ValidityState;
|
|
30
|
+
validationMessage?: string;
|
|
31
|
+
checkValidity?: () => boolean;
|
|
32
|
+
setCustomValidity?: (message: string) => void;
|
|
33
|
+
updateComplete?: Promise<unknown>;
|
|
34
|
+
};
|
|
35
|
+
export interface BindFormOptions {
|
|
36
|
+
/** The form's controls, by the name each value is handed on under. */
|
|
37
|
+
fields: Record<string, BoundControl>;
|
|
38
|
+
/** Rules of the engine beyond what each control says itself: `{ rule, value?, message? }`. */
|
|
39
|
+
rules?: Record<string, RuleDefinition[]>;
|
|
40
|
+
/** Called with the values when every rule and every control holds. What it throws is said in `alert` (or `failed`). */
|
|
41
|
+
onSubmit: (values: Record<string, unknown>) => unknown;
|
|
42
|
+
/** Called when a submit failed, instead of saying it in `alert`. */
|
|
43
|
+
failed?: (err: unknown) => void;
|
|
44
|
+
/** Where a failure is said. */
|
|
45
|
+
alert?: HTMLElement;
|
|
46
|
+
/** After a submit that went through, put every field back to where the form started. */
|
|
47
|
+
reset?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* `false` for a form whose buttons decide how it goes (several ways through, Ctrl+Enter): the browser's and the
|
|
50
|
+
* controls' implicit submit (Enter in a field) is let go, and only `submit()` sends it. `true` by default.
|
|
51
|
+
*/
|
|
52
|
+
submitOnEnter?: boolean;
|
|
53
|
+
}
|
|
54
|
+
export interface BoundForm {
|
|
55
|
+
ready: Promise<FormController<JsonFormValues, JsonFormItem>>;
|
|
56
|
+
submit: () => Promise<boolean>;
|
|
57
|
+
values: () => Promise<Record<string, unknown>>;
|
|
58
|
+
set: (name: string, value: unknown) => Promise<void>;
|
|
59
|
+
dispose: () => void;
|
|
60
|
+
}
|
|
61
|
+
export declare function bindForm(form: HTMLFormElement, opts: BindFormOptions): BoundForm;
|
|
62
|
+
/** `bindForm`, handing the form back: for a form built inside an expression. */
|
|
63
|
+
export declare function boundForm(form: HTMLFormElement, opts: BindFormOptions): HTMLFormElement;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":"0.
|
|
1
|
+
{"version":"0.5.0"}
|
|
@@ -5,6 +5,7 @@ import type { FieldArray } from './fieldArray';
|
|
|
5
5
|
import type { GetValues } from './getValues';
|
|
6
6
|
import type { Reset } from './reset';
|
|
7
7
|
import type { ResetItem } from './resetItem';
|
|
8
|
+
import type { SetErrors } from './setErrors';
|
|
8
9
|
import type { SetValue } from './setValue';
|
|
9
10
|
import type { Submit } from './submit';
|
|
10
11
|
import type { Touch } from './touch';
|
|
@@ -20,6 +21,7 @@ export type { FormRow } from './rows';
|
|
|
20
21
|
export * from './getValues';
|
|
21
22
|
export * from './reset';
|
|
22
23
|
export * from './resetItem';
|
|
24
|
+
export * from './setErrors';
|
|
23
25
|
export * from './setValue';
|
|
24
26
|
export * from './store';
|
|
25
27
|
export * from './submit';
|
|
@@ -34,6 +36,7 @@ declare module '@punica/form' {
|
|
|
34
36
|
getValues: GetValues<E, F>;
|
|
35
37
|
reset: Reset<E, F>;
|
|
36
38
|
resetItem: ResetItem<E, F>;
|
|
39
|
+
setErrors: SetErrors<E, F>;
|
|
37
40
|
setValue: SetValue<E, F>;
|
|
38
41
|
submit: Submit<E, F>;
|
|
39
42
|
touch: Touch<E, F>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":"2.
|
|
1
|
+
{"version":"2.3.0"}
|
|
@@ -26,6 +26,13 @@ export declare const rowsOf: (command: object, property: PropertyKey) => readonl
|
|
|
26
26
|
export declare const createLists: <E, F extends FormItem<E>>(command: CommandService<E, F>, validate: new () => IService & {
|
|
27
27
|
run: () => Promise<boolean>;
|
|
28
28
|
}) => Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* Shows an error on the item of a list itself, as its own validation would:
|
|
31
|
+
* it stays while the rows change and goes when the list is validated again,
|
|
32
|
+
* cleared or reset.
|
|
33
|
+
* @returns `false` when the item of the property is not a list
|
|
34
|
+
*/
|
|
35
|
+
export declare const setListError: <E, F extends FormItem<E>>(command: CommandService<E, F>, property: keyof E, errorMessages: string[]) => boolean;
|
|
29
36
|
/**
|
|
30
37
|
* Wraps the validations of the items of a form, for a service that adds a
|
|
31
38
|
* validation of its own to them. It works with lists whatever the order of
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { CommandService, FormItem, IServiceControl, IServiceInitialize } from '@punica/form';
|
|
2
|
+
/**
|
|
3
|
+
* Messages by item, as a server sends them for what it refused. A name is a
|
|
4
|
+
* property of the form; `lines.1.price` (or `lines[1].price`) is the item
|
|
5
|
+
* `price` of the second row of the list `lines`. Nested objects and arrays
|
|
6
|
+
* say the same: `{ lines: [{}, { price: ['Too high'] }] }`.
|
|
7
|
+
*/
|
|
8
|
+
export type ItemErrors = {
|
|
9
|
+
readonly [name: string]: string | readonly string[] | ItemErrors | unknown;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Shows errors that were found outside the form, by a server for example,
|
|
13
|
+
* on the items they are about.
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* try {
|
|
17
|
+
* await save(values);
|
|
18
|
+
* } catch (error) {
|
|
19
|
+
* // { email: ['This email is already registered'], capacity: ['Full'] }
|
|
20
|
+
* const rest = await controller.getService(SetErrors).run(error.fields);
|
|
21
|
+
*
|
|
22
|
+
* if (rest.length) throw new Error(rest.join(' ')); // shown by the form
|
|
23
|
+
* }
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* An error set this way replaces the messages its item had. It goes when
|
|
27
|
+
* the item is validated again (`Trigger`, `Validate`, `Submit`), also when
|
|
28
|
+
* the item has no validation of its own, and with `ClearError`,
|
|
29
|
+
* `ClearErrors`, `ResetItem` and `Reset`. A validation that was running
|
|
30
|
+
* when the error was set does not erase it.
|
|
31
|
+
*/
|
|
32
|
+
export declare class SetErrors<E, F extends FormItem<E> = FormItem<E>> implements IServiceInitialize<E, F>, IServiceControl {
|
|
33
|
+
#private;
|
|
34
|
+
get name(): string;
|
|
35
|
+
initialize(command: CommandService<E, F>): void;
|
|
36
|
+
/**
|
|
37
|
+
* Writes the messages onto the items they name. The rows of a list are
|
|
38
|
+
* reached through their index.
|
|
39
|
+
* @param errors - Messages by item: see `ItemErrors`. What is no object
|
|
40
|
+
* of messages (a text, `null`) names no item
|
|
41
|
+
* @returns The messages that are about no item of the form, to be shown
|
|
42
|
+
* for the form as a whole; those of a row stand where the row was first
|
|
43
|
+
* named
|
|
44
|
+
*/
|
|
45
|
+
run(errors: ItemErrors | unknown): Promise<string[]>;
|
|
46
|
+
}
|
|
@@ -5,6 +5,16 @@ import { CommandService, FormItem } from '@punica/form';
|
|
|
5
5
|
* and their results are not written.
|
|
6
6
|
*/
|
|
7
7
|
export declare const dropValidations: <E, F extends FormItem<E>>(command: CommandService<E, F>, property?: keyof E) => void;
|
|
8
|
+
/**
|
|
9
|
+
* Notes that the error of a property was set from outside, by `SetErrors`.
|
|
10
|
+
*
|
|
11
|
+
* A validation of the property that is running, or waiting for its delay,
|
|
12
|
+
* is cancelled: what it finds was asked before the error was known and must
|
|
13
|
+
* not erase it. A validation that starts afterwards replaces the error, and
|
|
14
|
+
* so the error of an item that is not validated at all (no validation,
|
|
15
|
+
* hidden, disabled) goes when the item is asked to be validated.
|
|
16
|
+
*/
|
|
17
|
+
export declare const noteExternalError: <E, F extends FormItem<E>>(command: CommandService<E, F>, property: keyof E) => void;
|
|
8
18
|
/**
|
|
9
19
|
* Waits for the delay of a validation (`validateDebounce` of the item).
|
|
10
20
|
* @returns Whether to validate: `false` when the property was validated,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@punica/form-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "MCP server for Punica Form: look up the exact API of its packages, read the rules and check code that uses them.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"mcp",
|
|
@@ -36,14 +36,14 @@
|
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
39
|
-
"@punica/form-json": "^0.
|
|
39
|
+
"@punica/form-json": "^0.2.0",
|
|
40
40
|
"zod": "^4.6.7"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
|
-
"@punica/form": "^2.
|
|
44
|
-
"@punica/form-service": "^2.
|
|
43
|
+
"@punica/form": "^2.3.0",
|
|
44
|
+
"@punica/form-service": "^2.3.0",
|
|
45
45
|
"@punica/form-react": "^0.2.0",
|
|
46
|
-
"@punica/form-kit": "^0.
|
|
46
|
+
"@punica/form-kit": "^0.5.0",
|
|
47
47
|
"@punica/form-schema": "^0.1.0"
|
|
48
48
|
},
|
|
49
49
|
"scripts": {
|
package/src/guide.md
CHANGED
|
@@ -16,7 +16,7 @@ Punica Form is a headless form engine. `@punica/form` holds the engine,
|
|
|
16
16
|
or Yup; see "Validation with a schema" below.
|
|
17
17
|
- `@punica/form-service`: `Validate`, `GetValues`, `SetValue`, `Reset`,
|
|
18
18
|
`ResetItem`, `Trigger`, `ClearError`, `ClearErrors`, `Touch`, `Submit`,
|
|
19
|
-
`FieldArray`, `Store`.
|
|
19
|
+
`SetErrors`, `FieldArray`, `Store`.
|
|
20
20
|
- NOT provided: `@Title`, `@Description`, `@Layout`, `@FormItemInputText` or
|
|
21
21
|
any other form item decorator, a `Reader` class, a base form item. These
|
|
22
22
|
belong to the application's own form system. Build them with the `define*`
|
|
@@ -33,18 +33,20 @@ Punica Form is a headless form engine. `@punica/form` holds the engine,
|
|
|
33
33
|
call:
|
|
34
34
|
|
|
35
35
|
```ts
|
|
36
|
-
import { defineForm, field, Services } from
|
|
36
|
+
import { defineForm, field, Services } from '@punica/form';
|
|
37
37
|
|
|
38
38
|
const UserForm = defineForm(
|
|
39
39
|
{
|
|
40
|
-
name: field(
|
|
41
|
-
age: field<number | undefined>(undefined, NumberInput({ label:
|
|
40
|
+
name: field('', Text({ label: 'Name' })),
|
|
41
|
+
age: field<number | undefined>(undefined, NumberInput({ label: 'Age' }))
|
|
42
42
|
},
|
|
43
43
|
Services([GetValues, SetValue]) // or FormKit({ title: "User" })
|
|
44
44
|
);
|
|
45
45
|
type User = InstanceType<typeof UserForm>;
|
|
46
46
|
|
|
47
|
-
const controller = await FormController.fromEntity(
|
|
47
|
+
const controller = await FormController.fromEntity(
|
|
48
|
+
new UserForm({ name: 'Jane' })
|
|
49
|
+
);
|
|
48
50
|
```
|
|
49
51
|
|
|
50
52
|
The result is a form class like a decorated one; do not mix both styles in
|
|
@@ -89,6 +91,34 @@ and runs it.
|
|
|
89
91
|
- `fromJsonSchema(schema)` turns a flat JSON Schema (string, number, integer,
|
|
90
92
|
boolean and enum properties) into a definition.
|
|
91
93
|
|
|
94
|
+
## A form drawn by hand, without React
|
|
95
|
+
|
|
96
|
+
When the markup is your own (a page drawn with the DOM, a framework other
|
|
97
|
+
than React, server-rendered HTML), bind the form to the engine with
|
|
98
|
+
`bindForm` from `@punica/form-kit/dom` instead of rewriting it as a class.
|
|
99
|
+
It takes the controls by name (@punica/components elements or native ones);
|
|
100
|
+
the engine holds their values, checks its rules and each control's own
|
|
101
|
+
constraints on submit, shows errors on each control's `punica-field`,
|
|
102
|
+
focuses the first wrong control and holds the submit buttons while it works.
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { bindForm } from '@punica/form-kit/dom';
|
|
106
|
+
|
|
107
|
+
const form = bindForm(document.querySelector('form')!, {
|
|
108
|
+
fields: { email: emailInput, seats: seatsInput },
|
|
109
|
+
rules: { seats: [{ rule: 'min', value: 1, message: 'At least one seat.' }] },
|
|
110
|
+
onSubmit: (values) => api.post('orders', { json: values }),
|
|
111
|
+
alert: document.querySelector<HTMLElement>('.form-error')!
|
|
112
|
+
});
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
- `onSubmit` runs only when everything holds; what it throws is shown in
|
|
116
|
+
`alert` (or given to `failed`).
|
|
117
|
+
- `submitOnEnter: false` for a form whose buttons decide (several actions):
|
|
118
|
+
call `form.submit()` from each button.
|
|
119
|
+
- `form.set(name, value)` writes into the engine and the control;
|
|
120
|
+
`form.dispose()` before the form is drawn again.
|
|
121
|
+
|
|
92
122
|
## Lifecycle
|
|
93
123
|
|
|
94
124
|
```ts
|
|
@@ -110,7 +140,7 @@ The form is immutable. Every change produces a new form object; items that
|
|
|
110
140
|
did not change keep their identity.
|
|
111
141
|
|
|
112
142
|
```ts
|
|
113
|
-
controller.getForm();
|
|
143
|
+
controller.getForm(); // the current form
|
|
114
144
|
const unsubscribe = controller.subscribe(() => {}); // after every change
|
|
115
145
|
```
|
|
116
146
|
|
|
@@ -138,26 +168,27 @@ Never change a form or an item in place; use the services.
|
|
|
138
168
|
Services are read by class and executed with `run`. They are bound to the
|
|
139
169
|
entity of the form, so property names and results are type-checked.
|
|
140
170
|
|
|
141
|
-
| Class
|
|
142
|
-
|
|
143
|
-
| `Validate`
|
|
144
|
-
| `Trigger`
|
|
145
|
-
| `GetValues`
|
|
146
|
-
| `SetValue`
|
|
147
|
-
| `Reset`
|
|
148
|
-
| `ResetItem`
|
|
149
|
-
| `ClearError`
|
|
150
|
-
| `ClearErrors` | `run(): Promise<void>`
|
|
151
|
-
| `Touch`
|
|
152
|
-
| `Submit`
|
|
153
|
-
| `
|
|
154
|
-
| `
|
|
171
|
+
| Class | Call |
|
|
172
|
+
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
173
|
+
| `Validate` | `run(): Promise<boolean>`, validates every item that is not hidden or disabled |
|
|
174
|
+
| `Trigger` | `run(property): Promise<void>`, validates one item |
|
|
175
|
+
| `GetValues` | `run(): Promise<E>`, a copy of the entity filled with the item values |
|
|
176
|
+
| `SetValue` | `run(property, value): Promise<void>`, then runs the `control` function of the item |
|
|
177
|
+
| `Reset` | `run(): Promise<void>` |
|
|
178
|
+
| `ResetItem` | `run(property): Promise<void>` |
|
|
179
|
+
| `ClearError` | `run(property): Promise<void>` |
|
|
180
|
+
| `ClearErrors` | `run(): Promise<void>` |
|
|
181
|
+
| `Touch` | `run(property): Promise<void>`, marks the item as touched; call it when the user leaves the field (since 2.2) |
|
|
182
|
+
| `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) |
|
|
183
|
+
| `SetErrors` | `run(errors): Promise<string[]>`, shows messages found outside the form (by a server) on the items they name; returns those that name no item (since 2.3) |
|
|
184
|
+
| `FieldArray` | no `run`: `rows(property)`, `append`, `insert`, `remove`, `move`, `replace`; see "Lists of rows" (since 2.2) |
|
|
185
|
+
| `Store` | no `run`: it adds `readStoreItem`, `writeStoreItem`, `deleteStoreItem` to the command passed to item functions (`CommandItem<E, F, StoreCommand>`) |
|
|
155
186
|
|
|
156
187
|
```ts
|
|
157
|
-
import { GetValues, SetValue, Trigger, Validate } from
|
|
188
|
+
import { GetValues, SetValue, Trigger, Validate } from '@punica/form-service';
|
|
158
189
|
|
|
159
|
-
await controller.getService(SetValue).run(
|
|
160
|
-
await controller.getService(Trigger).run(
|
|
190
|
+
await controller.getService(SetValue).run('name', 'Jane');
|
|
191
|
+
await controller.getService(Trigger).run('name');
|
|
161
192
|
|
|
162
193
|
if (await controller.getService(Validate).run()) {
|
|
163
194
|
const values = await controller.getService(GetValues).run();
|
|
@@ -178,6 +209,31 @@ if (await controller.getService(Validate).run()) {
|
|
|
178
209
|
- Setting a value does not validate it. Run `Trigger` for that.
|
|
179
210
|
- To submit a form prefer `Submit` (since 2.2) over calling `Validate` and
|
|
180
211
|
`GetValues` by hand. Do not keep your own `submitting` or `dirty` flags.
|
|
212
|
+
- When a server refuses what was submitted with messages by field, show them
|
|
213
|
+
with `SetErrors` (since 2.3) instead of writing items yourself, and throw
|
|
214
|
+
the rest so the form shows it:
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
await controller.getService(Submit).run(async (values) => {
|
|
218
|
+
try {
|
|
219
|
+
await save(values);
|
|
220
|
+
} catch (error) {
|
|
221
|
+
// { email: ["Already registered"], "lines.1.price": ["Too high"], capacity: ["Full"] }
|
|
222
|
+
const rest = await controller
|
|
223
|
+
.getService(SetErrors)
|
|
224
|
+
.run(fieldErrorsOf(error));
|
|
225
|
+
|
|
226
|
+
throw new Error(rest.join(' ') || 'Correct the marked fields.');
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
A name is a property; `lines.1.price` is an item of a row of a list, and
|
|
232
|
+
nested objects (`{ lines: [{}, { price: ["Too high"] }] }`) say the same.
|
|
233
|
+
Such an error goes when its item is validated again (`Trigger`, `Validate`,
|
|
234
|
+
`Submit`), cleared or reset; a validation that was running when it was set
|
|
235
|
+
does not erase it. `@FormKit`, `fromSchema` and `JsonForm` list `SetErrors`
|
|
236
|
+
already; a form with its own `@Services` has to list it.
|
|
181
237
|
|
|
182
238
|
## Lists of rows
|
|
183
239
|
|
|
@@ -273,18 +329,41 @@ class UserForm { … }
|
|
|
273
329
|
`addFormValidation(command, () => messages)` of `@punica/form-service` in
|
|
274
330
|
its `initialize` (since 2.2).
|
|
275
331
|
|
|
332
|
+
## With the other Punica libraries
|
|
333
|
+
|
|
334
|
+
Punica Form is one of three libraries made to be used together: Punica
|
|
335
|
+
Request (`@punica/request`, the HTTP client) and Punica Components
|
|
336
|
+
(`@punica/components`, the elements the kit renders with). Each has an MCP
|
|
337
|
+
server; when the project has them, look their APIs up there instead of
|
|
338
|
+
guessing. Where they meet:
|
|
339
|
+
|
|
340
|
+
- **Choices from a server**: `options: () => listCountries()` of a kit field
|
|
341
|
+
may return a promise; give it a function that asks the client.
|
|
342
|
+
- **A validation that asks a server**: pass `context.signal` on as the
|
|
343
|
+
`signal` of the request, and set `validateDebounce`. A request for a value
|
|
344
|
+
the user typed over is cancelled.
|
|
345
|
+
- **What a server refuses**: a failed request of Punica Request rejects with
|
|
346
|
+
an `HttpError` whose `response.data` is the body the server sent. Give its
|
|
347
|
+
messages by field to `SetErrors` and throw the rest, as shown above.
|
|
348
|
+
- **Submitting**: do the request inside the handler of `Submit` (or
|
|
349
|
+
`onSubmit` of `KitForm`); the form shows that it is submitting and keeps a
|
|
350
|
+
second submit out.
|
|
351
|
+
|
|
352
|
+
A whole application on the three, with its tests:
|
|
353
|
+
https://github.com/punicalab/punica-starter (start with its `AGENTS.md`).
|
|
354
|
+
|
|
276
355
|
## Events
|
|
277
356
|
|
|
278
357
|
`controller.on(event, handler)` returns the function that removes the
|
|
279
358
|
handler. Payloads are typed.
|
|
280
359
|
|
|
281
|
-
| Event
|
|
282
|
-
|
|
283
|
-
| `UPDATE_FORM`
|
|
284
|
-
| `UPDATE_ITEM`
|
|
285
|
-
| `RESET`
|
|
286
|
-
| `SUBMIT`
|
|
287
|
-
| `SUBMIT_ERROR`
|
|
360
|
+
| Event | Payload |
|
|
361
|
+
| ---------------- | ------------------------------------------------------------------------- |
|
|
362
|
+
| `UPDATE_FORM` | the form; fired after every change |
|
|
363
|
+
| `UPDATE_ITEM` | an array: the changed item, then the items its `control` returned |
|
|
364
|
+
| `RESET` | the form; fired by `Reset`, after `UPDATE_FORM` |
|
|
365
|
+
| `SUBMIT` | the values the submit handler received; fired by `Submit` (since 2.2) |
|
|
366
|
+
| `SUBMIT_ERROR` | what a validation or the submit handler threw (since 2.2) |
|
|
288
367
|
| `REGISTER_ITEMS` | `string[]` of registered form item types; fired at the start of `start()` |
|
|
289
368
|
|
|
290
369
|
## A complete example
|
|
@@ -298,44 +377,46 @@ import {
|
|
|
298
377
|
getFormProperty,
|
|
299
378
|
type Form,
|
|
300
379
|
type FormItem,
|
|
301
|
-
type IReader
|
|
302
|
-
} from
|
|
380
|
+
type IReader
|
|
381
|
+
} from '@punica/form';
|
|
303
382
|
|
|
304
|
-
export const Title = defineFormProperty<string>(
|
|
383
|
+
export const Title = defineFormProperty<string>('app:title');
|
|
305
384
|
|
|
306
|
-
export class Reader<E extends object, F extends FormItem<E>> implements IReader<
|
|
385
|
+
export class Reader<E extends object, F extends FormItem<E>> implements IReader<
|
|
386
|
+
E,
|
|
387
|
+
F
|
|
388
|
+
> {
|
|
307
389
|
public read(entity: E, form: Form<E, F>): void {
|
|
308
|
-
form.title = getFormProperty<string>(entity,
|
|
390
|
+
form.title = getFormProperty<string>(entity, 'app:title');
|
|
309
391
|
}
|
|
310
392
|
}
|
|
311
393
|
|
|
312
394
|
// The second argument is the renderer; defaultFormItemRegister.getItem(item.type) returns it
|
|
313
|
-
export const FormItemInputText = defineFormItem<
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
);
|
|
395
|
+
export const FormItemInputText = defineFormItem<
|
|
396
|
+
Omit<FormItem<any>, 'property'>
|
|
397
|
+
>('app:input-text', InputText);
|
|
317
398
|
```
|
|
318
399
|
|
|
319
400
|
A business form:
|
|
320
401
|
|
|
321
402
|
```ts
|
|
322
|
-
import { Readers, Services } from
|
|
323
|
-
import { GetValues, SetValue, Trigger, Validate } from
|
|
324
|
-
import { FormItemInputText, Reader, Title } from
|
|
403
|
+
import { Readers, Services } from '@punica/form';
|
|
404
|
+
import { GetValues, SetValue, Trigger, Validate } from '@punica/form-service';
|
|
405
|
+
import { FormItemInputText, Reader, Title } from './formSystem';
|
|
325
406
|
|
|
326
|
-
@Title(
|
|
407
|
+
@Title('Create User')
|
|
327
408
|
@Readers([new Reader()])
|
|
328
409
|
@Services([GetValues, SetValue, Validate, Trigger])
|
|
329
410
|
export class UserForm {
|
|
330
411
|
@FormItemInputText({
|
|
331
|
-
label:
|
|
412
|
+
label: 'Name',
|
|
332
413
|
required: true,
|
|
333
414
|
validation: async ({ formItem }) => ({
|
|
334
415
|
error: !formItem.value,
|
|
335
|
-
errorMessages: formItem.value ? [] : [
|
|
336
|
-
})
|
|
416
|
+
errorMessages: formItem.value ? [] : ['Name is required']
|
|
417
|
+
})
|
|
337
418
|
})
|
|
338
|
-
name =
|
|
419
|
+
name = '';
|
|
339
420
|
}
|
|
340
421
|
```
|
|
341
422
|
|
|
@@ -347,7 +428,7 @@ const controller = await FormController.fromEntity(new UserForm());
|
|
|
347
428
|
controller.subscribe(() => render(controller.getForm()));
|
|
348
429
|
await controller.start();
|
|
349
430
|
|
|
350
|
-
await controller.getService(SetValue).run(
|
|
431
|
+
await controller.getService(SetValue).run('name', 'Jane');
|
|
351
432
|
|
|
352
433
|
if (await controller.getService(Validate).run()) {
|
|
353
434
|
const values = await controller.getService(GetValues).run(); // UserForm
|
package/src/main.mjs
CHANGED
|
@@ -12,6 +12,7 @@ const packages = [
|
|
|
12
12
|
loadPackage('@punica/form-kit'),
|
|
13
13
|
loadPackage('@punica/form-kit', process.cwd(), 'react'),
|
|
14
14
|
loadPackage('@punica/form-kit', process.cwd(), 'json'),
|
|
15
|
+
loadPackage('@punica/form-kit', process.cwd(), 'dom'),
|
|
15
16
|
loadPackage('@punica/form-json'),
|
|
16
17
|
loadPackage('@punica/form-schema')
|
|
17
18
|
].filter(Boolean);
|