@thomasfosterau/effect-forms-svelte 0.2.0 → 0.3.2
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 +19 -19
- package/dist/ClientValidate.d.ts +1 -2
- package/dist/ClientValidate.js +1 -2
- package/dist/EnhanceCore.d.ts +34 -4
- package/dist/EnhanceCore.js +106 -39
- package/dist/EnhanceCore.js.map +1 -1
- package/dist/EntityForm.d.ts +0 -2
- package/dist/EntityForm.js +29 -30
- package/dist/EntityForm.js.map +1 -1
- package/dist/FormStore.svelte.d.ts +11 -5
- package/dist/FormStore.svelte.js +94 -61
- package/dist/FormStore.svelte.js.map +1 -1
- package/dist/Listeners.d.ts +1 -2
- package/dist/Listeners.js +4 -4
- package/dist/Listeners.js.map +1 -1
- package/dist/SvelteKit.d.ts +1 -2
- package/dist/SvelteKit.js +3 -3
- package/dist/SvelteKit.js.map +1 -1
- package/dist/Tainted.d.ts +1 -2
- package/dist/Tainted.js +28 -41
- package/dist/Tainted.js.map +1 -1
- package/dist/_virtual/_rolldown/runtime.js +1 -2
- package/dist/kit/ActionRedirect.d.ts +0 -2
- package/dist/kit/ActionRedirect.js +12 -15
- package/dist/kit/ActionRedirect.js.map +1 -1
- package/dist/kit/CommandFailure.d.ts +1 -2
- package/dist/kit/CommandFailure.js +18 -20
- package/dist/kit/CommandFailure.js.map +1 -1
- package/dist/kit/Enhance.d.ts +0 -2
- package/dist/kit/Enhance.js +1 -2
- package/dist/kit/FormAction.d.ts +0 -2
- package/dist/kit/FormAction.js +39 -33
- package/dist/kit/FormAction.js.map +1 -1
- package/dist/kit/FormStateReaders.d.ts +0 -2
- package/dist/kit/FormStateReaders.js +4 -4
- package/dist/kit/FormStateReaders.js.map +1 -1
- package/dist/kit/Pointer.d.ts +0 -2
- package/dist/kit/Pointer.js +1 -2
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @thomasfosterau/effect-forms-svelte
|
|
2
2
|
|
|
3
|
-
Svelte 5 (runes) bindings for [`@thomasfosterau/effect-forms`](
|
|
3
|
+
Svelte 5 (runes) bindings for [`@thomasfosterau/effect-forms`](https://www.npmjs.com/package/@thomasfosterau/effect-forms): a reactive form store with progressive-enhancement submission, tainted tracking, lifecycle events, and optional client-side validation against the **same Effect Schema the server uses**.
|
|
4
4
|
|
|
5
5
|
The root entry depends only on `svelte` and the framework-neutral core, not SvelteKit, so it works in any Svelte 5 app. The [`/kit` entry](#kit) (`@thomasfosterau/effect-forms-svelte/kit`) is the SvelteKit-only half: derived form actions, JSON:API error routing and `$app/forms` glue.
|
|
6
6
|
|
|
@@ -45,7 +45,7 @@ Server (`+page.server.ts` or any action) produces a `FormState` with the core's
|
|
|
45
45
|
|
|
46
46
|
## The store
|
|
47
47
|
|
|
48
|
-
`createForm(source, options)` returns a [`FormStore`](src/FormStore.svelte.ts). `source` is a server-produced `FormState`, a `{ schema, defaults }` seed, or a [`FormBuilder`](
|
|
48
|
+
`createForm(source, options)` returns a [`FormStore`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/svelte/src/FormStore.svelte.ts). `source` is a server-produced `FormState`, a `{ schema, defaults }` seed, or a [`FormBuilder`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/forms/src/FormBuilder.ts) — the builder derives its schema, blank defaults, and array-item defaults for you:
|
|
49
49
|
|
|
50
50
|
```ts
|
|
51
51
|
import { createForm } from "@thomasfosterau/effect-forms-svelte";
|
|
@@ -56,13 +56,13 @@ const form = createForm(signup, { mode: { validation: "onChange", debounce: 300
|
|
|
56
56
|
|
|
57
57
|
**Reactive state** — `data` (mutable, bind inputs to it), `errors` (merged client + server), `clientErrors` / `serverErrors` (per-source views), `message`, `constraints`, `submitting`, `delayed`, `posted`, `valid`, `canSubmit`, `isValidating`, `isSubmitted`, `isSubmitSuccessful`, `submissionAttempts`, `tainted`, `isTainted`, and (against the last submission) `changedSinceSubmit` / `hasChangedSinceSubmit`.
|
|
58
58
|
|
|
59
|
-
**Methods** — `enhance(node)` (the form action), `validate()` / `validateField(path)` (client-side, needs `schema`; also runs a builder's `refineEffect` refinements), `errorsAt(path)` / `taintedAt(path)` / `isValidatingAt(path)`, `setValue(path, v)` / `valueAt(path)`, `handleBlur(path)` / `setTouched(path)` / `isTouchedAt(path)`, `isDirtyAt(path)` / `isDefaultValueAt(path)` (persistent per-field dirty tracking — see [Field handles](#field-handles)), `setFieldValidators(path, validators)` (register a field's validators dynamically), `shouldShowError(path)` / `visibleErrorsAt(path)` (mode-aware display gating), `constraintAt(path)`, `revertToLastSubmit()`, `reset()`, `capture()` / `restore()` (SvelteKit snapshots), `setServerState(data, errors)` (apply a result received some other way), `toFormData()`.
|
|
59
|
+
**Methods** — `enhance(node)` (the form action), `validate()` / `validateField(path)` (client-side, needs `schema`; also runs a builder's `refineEffect` refinements, on the decoded values as the server does, once they decode), `errorsAt(path)` / `taintedAt(path)` / `isValidatingAt(path)`, `setValue(path, v)` / `valueAt(path)`, `handleBlur(path)` / `setTouched(path)` / `isTouchedAt(path)`, `isDirtyAt(path)` / `isDefaultValueAt(path)` (persistent per-field dirty tracking — see [Field handles](#field-handles)), `setFieldValidators(path, validators)` (register a field's validators dynamically), `shouldShowError(path)` / `visibleErrorsAt(path)` (mode-aware display gating), `constraintAt(path)`, `revertToLastSubmit()`, `reset()`, `capture()` / `restore()` (SvelteKit snapshots), `setServerState(data, errors)` (apply a result received some other way), `toFormData()`.
|
|
60
60
|
|
|
61
61
|
**Field arrays** — `append(path, value?)`, `insertItem(path, i, value?)`, `replaceItem(path, i, value)`, `removeItem(path, i)`, `clearItems(path)`, `swap(path, a, b)`, `move(path, from, to)` mutate the array at `path` immutably. `append` / `insertItem` derive a blank item by walking the bound schema's AST at `path` (any nesting depth, e.g. `authors[0].emails`), falling back to the top-level `FormBuilder` field when no schema is bound. Every index-shifting mutation (`insertItem` / `removeItem` / `swap` / `move` / `clearItems`) remaps per-index touched flags and errors so they keep following their row — `replaceItem` drops only the replaced index's own touched flag / errors.
|
|
62
62
|
|
|
63
63
|
## Field handles
|
|
64
64
|
|
|
65
|
-
`form.field(path)` (modelled on TanStack Form's `FieldApi`) returns a typed, reactive [`FieldHandle`](src/FormStore.svelte.ts) bundling everything one input needs, instead of wiring `bind:value` / `name` / `handleBlur` / `visibleErrorsAt` / `constraints` against the store separately:
|
|
65
|
+
`form.field(path)` (modelled on TanStack Form's `FieldApi`) returns a typed, reactive [`FieldHandle`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/svelte/src/FormStore.svelte.ts) bundling everything one input needs, instead of wiring `bind:value` / `name` / `handleBlur` / `visibleErrorsAt` / `constraints` against the store separately:
|
|
66
66
|
|
|
67
67
|
```svelte
|
|
68
68
|
<script lang="ts">
|
|
@@ -82,7 +82,7 @@ const form = createForm(signup, { mode: { validation: "onChange", debounce: 300
|
|
|
82
82
|
|
|
83
83
|
`field.meta` exposes TanStack-style field state: `isBlurred` (lost focus at least once), `isTouched` (`isBlurred || isDirty`), `isDirty` (changed away from the default at some point — **persistent**, unlike `taintedAt` it does not clear on reverting to the default; only `reset()` clears it), and `isDefaultValue` (current value equals the default — flips back on revert). `isDirty` only tracks writes made through `field.value = …` / `setValue` / the array mutators (`append` / `removeItem` / `swap` / `move`) — a form that still binds `bind:value={form.data.x}` directly, bypassing `field()`, never marks that field dirty.
|
|
84
84
|
|
|
85
|
-
**Validation modes** — the `mode` option (see [`Mode`](
|
|
85
|
+
**Validation modes** — the `mode` option (see [`Mode`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/forms/src/Mode.ts)) drives when the form validates: `onSubmit` (default), `onBlur` (call `handleBlur` from an input's blur), or `onChange` (debounced). `onBlur` / `onChange` may `autoSubmit`, turning the form into a live-saving surface. `revalidate` (`"onChange"` default / `"onBlur"` / `"never"`) governs what happens _after_ a failed post in `onSubmit` mode: fixing a field re-validates just that field, clearing its error without a resubmit. Errors are computed for the whole form; gate their display per field with `visibleErrorsAt(path)` (shown only once the field is tainted / touched, or after a submit).
|
|
86
86
|
|
|
87
87
|
**Per-field validators** — the `validators` option (or `setFieldValidators`) attaches TanStack-Form-style `{ onChange?, onBlur?, onChangeAsync?, onBlurAsync?, asyncDebounceMs? }` per field, keyed by `Path.toString` (e.g. `"author.name"`, `"tags[0]"`). Sync validators return a `Schema.FilterOutput`; async ones are `Effect`s, run as a fiber per field — a new value interrupts the field's in-flight fiber before forking the next run, which is what gives the debounce + "latest wins" cancellation (no timer bookkeeping needed). Pass `layer` when a validator (or a builder's `refineEffect` refinement) needs services on its `R` channel:
|
|
88
88
|
|
|
@@ -103,23 +103,23 @@ const form = createForm(
|
|
|
103
103
|
|
|
104
104
|
**Error sources** — a field's server-reported error (from the last submission) survives a client-side revalidation of some _other_ field; it clears once _that_ field's own value changes (or the server clears it on the next submit). `errors` is the merged view; `clientErrors` / `serverErrors` expose the two trees separately for a UI that wants to style them differently.
|
|
105
105
|
|
|
106
|
-
**Lifecycle options** — `onSubmit` (with `cancel()`), `onResult`, `onUpdate`, `onUpdated`, `onError`, `onRedirect`, plus `resetForm`, `taintedMessage`, `delayMs`, and a `submit` transport override (defaults to `fetch` to the form's action, parsing a JSON [`FormActionResult`](
|
|
106
|
+
**Lifecycle options** — `onSubmit` (with `cancel()`), `onResult`, `onUpdate`, `onUpdated`, `onError`, `onRedirect`, plus `resetForm`, `taintedMessage`, `delayMs`, and a `submit` transport override (defaults to `fetch` to the form's action, parsing a JSON [`FormActionResult`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/forms/src/Result.ts) or a bare `FormState`).
|
|
107
107
|
|
|
108
108
|
## API
|
|
109
109
|
|
|
110
110
|
Everything below is exported flat from the root entry (`@thomasfosterau/effect-forms-svelte`).
|
|
111
111
|
|
|
112
|
-
| Module
|
|
113
|
-
|
|
|
114
|
-
| [`FormStore`](src/FormStore.svelte.ts) | `createForm`, `FormStore`, `FieldHandle`, `FieldMeta`, `FormOptions`, `FormSeed` — the reactive store above. |
|
|
115
|
-
| [`EntityForm`](src/EntityForm.ts) | `defineEntityForm` — an ordered, key-checked field list over a core `Command.plan`, walked by one generic renderer component; its entry types (`ScalarEntry`, `SelectEntry`, `WidgetEntry`, …). |
|
|
116
|
-
| [`SvelteKit`](src/SvelteKit.ts) | `applyActionResult` — apply a SvelteKit `ActionResult` (`ServerActionResult`) to a store; returns whether it consumed a validation failure. |
|
|
117
|
-
| [`Listeners`](src/Listeners.ts) | `changeEvents` / `dispatchChange` and the `FormListeners` / `FieldListener` types — per-field and form-wide change listeners (linked fields). |
|
|
118
|
-
| [`Tainted`](src/Tainted.ts) | Deep-diff the data to compute the tainted tree. |
|
|
119
|
-
| [`ClientValidate`](src/ClientValidate.ts) | `validateData` / `validateField` — validate the form, or one field, against the schema. |
|
|
120
|
-
| [`EnhanceCore`](src/EnhanceCore.ts) | Serialise data → form body, parse the response, compute the store update. |
|
|
112
|
+
| Module | Exports |
|
|
113
|
+
| ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
114
|
+
| [`FormStore`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/svelte/src/FormStore.svelte.ts) | `createForm`, `FormStore`, `FieldHandle`, `FieldMeta`, `FormOptions`, `FormSeed` — the reactive store above. |
|
|
115
|
+
| [`EntityForm`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/svelte/src/EntityForm.ts) | `defineEntityForm` — an ordered, key-checked field list over a core `Command.plan`, walked by one generic renderer component; its entry types (`ScalarEntry`, `SelectEntry`, `WidgetEntry`, …). |
|
|
116
|
+
| [`SvelteKit`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/svelte/src/SvelteKit.ts) | `applyActionResult` — apply a SvelteKit `ActionResult` (`ServerActionResult`) to a store; returns whether it consumed a validation failure. |
|
|
117
|
+
| [`Listeners`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/svelte/src/Listeners.ts) | `changeEvents` / `dispatchChange` and the `FormListeners` / `FieldListener` types — per-field and form-wide change listeners (linked fields). |
|
|
118
|
+
| [`Tainted`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/svelte/src/Tainted.ts) | Deep-diff the data to compute the tainted tree. |
|
|
119
|
+
| [`ClientValidate`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/svelte/src/ClientValidate.ts) | `validateData` / `validateField` — validate the form, or one field, against the schema. |
|
|
120
|
+
| [`EnhanceCore`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/svelte/src/EnhanceCore.ts) | Serialise data → form body, parse the response, compute the store update. |
|
|
121
121
|
|
|
122
|
-
The reactive store (`FormStore.svelte.ts`, rune-compiled) delegates its logic to the pure, unit-tested modules. The store itself is type-checked
|
|
122
|
+
The reactive store (`FormStore.svelte.ts`, rune-compiled) delegates its logic to the pure, unit-tested modules. The store itself is type-checked (by `vp check` and by `svelte-check`); its submitter-aware submit path (`enhance` → the posted `FormData`) is unit-tested in [`FormStore.svelte.test.ts`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/svelte/tests/FormStore.svelte.test.ts).
|
|
123
123
|
|
|
124
124
|
## /kit
|
|
125
125
|
|
|
@@ -138,7 +138,7 @@ The reactive store (`FormStore.svelte.ts`, rune-compiled) delegates its logic to
|
|
|
138
138
|
|
|
139
139
|
### Peers
|
|
140
140
|
|
|
141
|
-
- `@sveltejs/kit` (`^3.0.0`) is an **optional** peer of the package and **required** by `/kit`. SvelteKit 2 is not supported. The repository's tests run against SvelteKit
|
|
141
|
+
- `@sveltejs/kit` (`^3.0.0`) is an **optional** peer of the package and **required** by `/kit`. SvelteKit 2 is not supported. The repository's tests run against the SvelteKit version pinned in its `pnpm-workspace.yaml`.
|
|
142
142
|
- `$app/forms` is a SvelteKit virtual module, not a dependency. It resolves because SvelteKit compiles this package (its `exports` carry the `svelte` condition), so `/kit` only works inside a SvelteKit build.
|
|
143
143
|
- `@thomasfosterau/effect-jsonapi` (`>=0.16.0`) is an **optional** peer used **for its types only**. `CommandFailure.ErrorObject` is `Document.ErrorObject.Type`. At runtime a failure is recognised by its `_tag`, so an application's own `JsonapiError` with the same shape is recognised too.
|
|
144
144
|
|
|
@@ -203,7 +203,7 @@ export const actions = {
|
|
|
203
203
|
};
|
|
204
204
|
```
|
|
205
205
|
|
|
206
|
-
The runnable copy is [`packages/svelte/tests/kit/examples/login.page.server.ts`](tests/kit/examples/login.page.server.ts). [`login.example.test.ts`](tests/kit/login.example.test.ts) runs it against the real `@sveltejs/kit`, covering the success redirect, the off-site `redirectTo` guard, the 401 with a blanked password, and the rethrow.
|
|
206
|
+
The runnable copy is [`packages/svelte/tests/kit/examples/login.page.server.ts`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/svelte/tests/kit/examples/login.page.server.ts). [`login.example.test.ts`](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/svelte/tests/kit/login.example.test.ts) runs it against the real `@sveltejs/kit`, covering the success redirect, the off-site `redirectTo` guard, the 401 with a blanked password, and the rethrow.
|
|
207
207
|
|
|
208
208
|
The page renders server state without a client store:
|
|
209
209
|
|
|
@@ -226,4 +226,4 @@ With a client store, spread `enhanceForm(form)` onto the `<form>` instead.
|
|
|
226
226
|
|
|
227
227
|
## License
|
|
228
228
|
|
|
229
|
-
[MIT](LICENSE)
|
|
229
|
+
[MIT](https://github.com/thomasfosterau/effect-forms/blob/trunk/packages/svelte/LICENSE)
|
package/dist/ClientValidate.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { Errors, Issues } from "@thomasfosterau/effect-forms";
|
|
2
2
|
import * as Schema from "effect/Schema";
|
|
3
|
-
//#region src/ClientValidate.d.ts
|
|
4
3
|
type FormErrors = Errors.FormErrors;
|
|
5
4
|
type FormPath = Issues.FormPath;
|
|
6
5
|
type LeafFormatter = Issues.LeafFormatter;
|
|
@@ -13,5 +12,5 @@ export declare function validateData<S extends Schema.Top>(schema: S, data: unkn
|
|
|
13
12
|
* field only.
|
|
14
13
|
*/
|
|
15
14
|
export declare function validateField<S extends Schema.Top>(schema: S, data: unknown, path: FormPath, format?: LeafFormatter): readonly string[];
|
|
16
|
-
|
|
15
|
+
export {};
|
|
17
16
|
//# sourceMappingURL=ClientValidate.d.ts.map
|
package/dist/ClientValidate.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Errors, Validate } from "@thomasfosterau/effect-forms";
|
|
2
|
-
|
|
2
|
+
// src/ClientValidate.ts
|
|
3
3
|
/**
|
|
4
4
|
* Client-side validation helpers — validate the whole form or a single field
|
|
5
5
|
* against the same Effect Schema the server uses, returning the nested
|
|
@@ -30,7 +30,6 @@ function validateField(schema, data, path, format) {
|
|
|
30
30
|
const errors = validateData(schema, data, format);
|
|
31
31
|
return getError(errors, path) ?? [];
|
|
32
32
|
}
|
|
33
|
-
//#endregion
|
|
34
33
|
export { validateData, validateField };
|
|
35
34
|
|
|
36
35
|
//# sourceMappingURL=ClientValidate.js.map
|
package/dist/EnhanceCore.d.ts
CHANGED
|
@@ -1,10 +1,40 @@
|
|
|
1
1
|
import { Errors, Result } from "@thomasfosterau/effect-forms";
|
|
2
|
-
//#region src/EnhanceCore.d.ts
|
|
3
2
|
type FormActionResult<A, Message = unknown> = Result.FormActionResult<A, Message>;
|
|
4
3
|
type FormErrors = Errors.FormErrors;
|
|
5
|
-
/**
|
|
4
|
+
/**
|
|
5
|
+
* Flatten a nested data object into `[name, value]` string entries using path
|
|
6
|
+
* notation.
|
|
7
|
+
*
|
|
8
|
+
* Nested objects become dotted names (`author.name`) and array items indexed
|
|
9
|
+
* names (`tags[0]`). Each leaf kind is handled as follows:
|
|
10
|
+
*
|
|
11
|
+
* - A `string`, `number`, `boolean` or `bigint` is stringified.
|
|
12
|
+
* - `null` becomes `""`.
|
|
13
|
+
* - A `Date` becomes the `YYYY-MM-DD` of its **UTC** calendar day (what
|
|
14
|
+
* `<input type="date">` submits, and what `Schema.DateFromString` decodes
|
|
15
|
+
* back to UTC midnight); the time of day is dropped, so a datetime needs its
|
|
16
|
+
* own string field. An invalid `Date` is omitted.
|
|
17
|
+
* - A `Blob` or `File` is omitted here, since a string entry can't carry it;
|
|
18
|
+
* {@link objectToFormData} keeps it.
|
|
19
|
+
* - An `undefined`, `function` or `symbol` is omitted, as `JSON.stringify`
|
|
20
|
+
* omits such object properties, so a callback or symbol left in form data
|
|
21
|
+
* never reaches the form body as `"Symbol(…)"` or function source.
|
|
22
|
+
* - Any other object contributes its own enumerable fields, so one with none
|
|
23
|
+
* (a `Map`, a `Set`, an empty object) contributes no entries.
|
|
24
|
+
*
|
|
25
|
+
* An omitted array item leaves a gap (where `JSON.stringify` would write
|
|
26
|
+
* `null`), so the remaining items keep their indices (`tags[0]`, `tags[2]`).
|
|
27
|
+
*/
|
|
6
28
|
export declare function objectToEntries(data: unknown, prefix?: string): Array<[string, string]>;
|
|
7
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* Serialise the store's data into a {@link FormData} body for submission.
|
|
31
|
+
*
|
|
32
|
+
* Names and leaves follow {@link objectToEntries}, except that a `Blob` or
|
|
33
|
+
* `File` leaf is appended as a file (a `File` keeps its name; a bare `Blob`
|
|
34
|
+
* arrives as a `File` named `"blob"`, the `FormData` default), as an
|
|
35
|
+
* `<input type="file">` would submit it, so it reaches the core's
|
|
36
|
+
* `FormData.formDataToObject` (`@thomasfosterau/effect-forms`) unchanged.
|
|
37
|
+
*/
|
|
8
38
|
export declare function objectToFormData(data: unknown): FormData;
|
|
9
39
|
/**
|
|
10
40
|
* Normalise a parsed JSON response body into a {@link FormActionResult}. The
|
|
@@ -56,5 +86,5 @@ export declare function computeDataApplication<A>(params: {
|
|
|
56
86
|
readonly resetForm: boolean;
|
|
57
87
|
readonly autoSubmit: boolean;
|
|
58
88
|
}): DataApplication<A>;
|
|
59
|
-
|
|
89
|
+
export {};
|
|
60
90
|
//# sourceMappingURL=EnhanceCore.d.ts.map
|
package/dist/EnhanceCore.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { Result } from "@thomasfosterau/effect-forms";
|
|
2
|
-
|
|
2
|
+
import * as Arr from "effect/Array";
|
|
3
|
+
import * as Match from "effect/Match";
|
|
4
|
+
import * as Predicate from "effect/Predicate";
|
|
5
|
+
import * as Record from "effect/Record";
|
|
6
|
+
// src/EnhanceCore.ts
|
|
3
7
|
/**
|
|
4
8
|
* Pure plumbing for the `enhance` action: serialise the store's data back into
|
|
5
9
|
* a form body, interpret a server response into a {@link FormActionResult}, and
|
|
@@ -11,38 +15,105 @@ import { Result } from "@thomasfosterau/effect-forms";
|
|
|
11
15
|
* @module effect-forms-svelte/EnhanceCore
|
|
12
16
|
*/
|
|
13
17
|
const { failure, success } = Result;
|
|
14
|
-
/**
|
|
15
|
-
|
|
18
|
+
/**
|
|
19
|
+
* Whether a value is a `Blob` (a `File` is one). Guards on `globalThis.Blob`
|
|
20
|
+
* so it holds in any runtime, including one without a global `Blob`.
|
|
21
|
+
*/
|
|
22
|
+
const isBlob = (value) => !Predicate.isUndefined(globalThis.Blob) && value instanceof Blob;
|
|
23
|
+
/**
|
|
24
|
+
* Encode a `Date` as the `YYYY-MM-DD` of its UTC calendar day, or `undefined`
|
|
25
|
+
* for an invalid `Date`. The UTC day round-trips: a `YYYY-MM-DD` string
|
|
26
|
+
* decodes to UTC midnight. Taking everything before the `T` keeps
|
|
27
|
+
* `toISOString`'s expanded form for a year outside 0000–9999
|
|
28
|
+
* (`+010000-01-01`), where a fixed 10-character slice would cut it off.
|
|
29
|
+
*/
|
|
30
|
+
const encodeDate = (value) => {
|
|
31
|
+
if (Number.isNaN(value.getTime())) return void 0;
|
|
32
|
+
const iso = value.toISOString();
|
|
33
|
+
return iso.slice(0, iso.indexOf("T"));
|
|
34
|
+
};
|
|
35
|
+
/** Append the entries for one named value to `out`, recursing into containers. */
|
|
36
|
+
function appendEntries(out, key, value) {
|
|
37
|
+
if (value === null) out.push([key, ""]);
|
|
38
|
+
else if (isBlob(value)) out.push([key, value]);
|
|
39
|
+
else if (value instanceof Date) {
|
|
40
|
+
const encoded = encodeDate(value);
|
|
41
|
+
if (encoded !== void 0) out.push([key, encoded]);
|
|
42
|
+
} else if (Array.isArray(value)) value.forEach((item, i) => appendEntries(out, `${key}[${i}]`, item));
|
|
43
|
+
else if (Predicate.isObject(value)) appendFields(out, value, key);
|
|
44
|
+
else if (Predicate.isString(value) || Predicate.isNumber(value) || Predicate.isBoolean(value) || Predicate.isBigInt(value)) out.push([key, String(value)]);
|
|
45
|
+
}
|
|
46
|
+
/** Append an object's own enumerable fields to `out`, as `prefix.key` names. */
|
|
47
|
+
function appendFields(out, data, prefix) {
|
|
48
|
+
Arr.forEach(Record.toEntries(data), ([key, value]) => appendEntries(out, prefix ? `${prefix}.${key}` : key, value));
|
|
49
|
+
}
|
|
50
|
+
/** Flatten `data` into form-body entries, `Blob` / `File` leaves included. */
|
|
51
|
+
function toBodyEntries(data, prefix) {
|
|
16
52
|
const out = [];
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
if (value === null) out.push([key, ""]);
|
|
20
|
-
else if (Array.isArray(value)) value.forEach((item, i) => out.push(...objectToEntries(item, `${key}[${i}]`)));
|
|
21
|
-
else if (typeof value === "object") out.push(...objectToEntries(value, key));
|
|
22
|
-
else out.push([key, String(value)]);
|
|
23
|
-
};
|
|
24
|
-
if (data !== null && typeof data === "object" && !Array.isArray(data)) for (const [key, value] of Object.entries(data)) push(prefix ? `${prefix}.${key}` : key, value);
|
|
25
|
-
else if (prefix) push(prefix, data);
|
|
53
|
+
if (prefix) appendEntries(out, prefix, data);
|
|
54
|
+
else if (Predicate.isObject(data)) appendFields(out, data, "");
|
|
26
55
|
return out;
|
|
27
56
|
}
|
|
28
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* Flatten a nested data object into `[name, value]` string entries using path
|
|
59
|
+
* notation.
|
|
60
|
+
*
|
|
61
|
+
* Nested objects become dotted names (`author.name`) and array items indexed
|
|
62
|
+
* names (`tags[0]`). Each leaf kind is handled as follows:
|
|
63
|
+
*
|
|
64
|
+
* - A `string`, `number`, `boolean` or `bigint` is stringified.
|
|
65
|
+
* - `null` becomes `""`.
|
|
66
|
+
* - A `Date` becomes the `YYYY-MM-DD` of its **UTC** calendar day (what
|
|
67
|
+
* `<input type="date">` submits, and what `Schema.DateFromString` decodes
|
|
68
|
+
* back to UTC midnight); the time of day is dropped, so a datetime needs its
|
|
69
|
+
* own string field. An invalid `Date` is omitted.
|
|
70
|
+
* - A `Blob` or `File` is omitted here, since a string entry can't carry it;
|
|
71
|
+
* {@link objectToFormData} keeps it.
|
|
72
|
+
* - An `undefined`, `function` or `symbol` is omitted, as `JSON.stringify`
|
|
73
|
+
* omits such object properties, so a callback or symbol left in form data
|
|
74
|
+
* never reaches the form body as `"Symbol(…)"` or function source.
|
|
75
|
+
* - Any other object contributes its own enumerable fields, so one with none
|
|
76
|
+
* (a `Map`, a `Set`, an empty object) contributes no entries.
|
|
77
|
+
*
|
|
78
|
+
* An omitted array item leaves a gap (where `JSON.stringify` would write
|
|
79
|
+
* `null`), so the remaining items keep their indices (`tags[0]`, `tags[2]`).
|
|
80
|
+
*/
|
|
81
|
+
function objectToEntries(data, prefix = "") {
|
|
82
|
+
return toBodyEntries(data, prefix).filter((entry) => Predicate.isString(entry[1]));
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Serialise the store's data into a {@link FormData} body for submission.
|
|
86
|
+
*
|
|
87
|
+
* Names and leaves follow {@link objectToEntries}, except that a `Blob` or
|
|
88
|
+
* `File` leaf is appended as a file (a `File` keeps its name; a bare `Blob`
|
|
89
|
+
* arrives as a `File` named `"blob"`, the `FormData` default), as an
|
|
90
|
+
* `<input type="file">` would submit it, so it reaches the core's
|
|
91
|
+
* `FormData.formDataToObject` (`@thomasfosterau/effect-forms`) unchanged.
|
|
92
|
+
*/
|
|
29
93
|
function objectToFormData(data) {
|
|
30
94
|
const formData = new FormData();
|
|
31
|
-
|
|
95
|
+
Arr.forEach(toBodyEntries(data, ""), ([key, value]) => formData.append(key, value));
|
|
32
96
|
return formData;
|
|
33
97
|
}
|
|
34
|
-
/**
|
|
98
|
+
/**
|
|
99
|
+
* Whether a value looks like a {@link FormActionResult} (carries a known
|
|
100
|
+
* `_tag`). Only the tag is checked: `A` / `Message` are the caller's declared
|
|
101
|
+
* expectation of the server's response, not verified here.
|
|
102
|
+
*/
|
|
35
103
|
function isActionResult(value) {
|
|
36
|
-
return
|
|
104
|
+
return Predicate.isObjectOrArray(value) && Predicate.hasProperty(value, "_tag") && Predicate.isString(value._tag) && [
|
|
37
105
|
"Success",
|
|
38
106
|
"Failure",
|
|
39
107
|
"Redirect",
|
|
40
108
|
"Error"
|
|
41
109
|
].includes(value._tag);
|
|
42
110
|
}
|
|
43
|
-
/**
|
|
111
|
+
/**
|
|
112
|
+
* Whether a value looks like a bare {@link FormState}. Only the keys are
|
|
113
|
+
* checked: `A` / `Message` are the caller's declared expectation, not verified.
|
|
114
|
+
*/
|
|
44
115
|
function isFormState(value) {
|
|
45
|
-
return
|
|
116
|
+
return Predicate.isObjectOrArray(value) && "valid" in value && "data" in value && "errors" in value;
|
|
46
117
|
}
|
|
47
118
|
/**
|
|
48
119
|
* Normalise a parsed JSON response body into a {@link FormActionResult}. The
|
|
@@ -52,10 +123,7 @@ function isFormState(value) {
|
|
|
52
123
|
*/
|
|
53
124
|
function parseActionResult(body, status = 200) {
|
|
54
125
|
if (isActionResult(body)) return body;
|
|
55
|
-
if (isFormState(body))
|
|
56
|
-
const state = body;
|
|
57
|
-
return state.valid ? success(state, status) : failure(state, status);
|
|
58
|
-
}
|
|
126
|
+
if (isFormState(body)) return body.valid ? success(body, status) : failure(body, status);
|
|
59
127
|
return {
|
|
60
128
|
_tag: "Error",
|
|
61
129
|
status,
|
|
@@ -68,25 +136,25 @@ function parseActionResult(body, status = 200) {
|
|
|
68
136
|
* `redirect` / `error`.
|
|
69
137
|
*/
|
|
70
138
|
function resultToUpdate(result) {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
data:
|
|
74
|
-
errors:
|
|
75
|
-
message:
|
|
139
|
+
return Match.valueTags(result, {
|
|
140
|
+
Success: ({ state }) => ({
|
|
141
|
+
data: state.data,
|
|
142
|
+
errors: state.errors,
|
|
143
|
+
message: state.message,
|
|
76
144
|
valid: true
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
data:
|
|
80
|
-
errors:
|
|
81
|
-
message:
|
|
145
|
+
}),
|
|
146
|
+
Failure: ({ state }) => ({
|
|
147
|
+
data: state.data,
|
|
148
|
+
errors: state.errors,
|
|
149
|
+
message: state.message,
|
|
82
150
|
valid: false
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
error:
|
|
151
|
+
}),
|
|
152
|
+
Redirect: ({ location }) => ({ redirect: location }),
|
|
153
|
+
Error: ({ message }) => ({
|
|
154
|
+
error: message,
|
|
87
155
|
valid: false
|
|
88
|
-
}
|
|
89
|
-
}
|
|
156
|
+
})
|
|
157
|
+
});
|
|
90
158
|
}
|
|
91
159
|
/**
|
|
92
160
|
* Decide how a submit result's data applies to the store, given a defined
|
|
@@ -116,7 +184,6 @@ function computeDataApplication(params) {
|
|
|
116
184
|
rebaseTo: isSuccess ? appliedData : void 0
|
|
117
185
|
};
|
|
118
186
|
}
|
|
119
|
-
//#endregion
|
|
120
187
|
export { computeDataApplication, objectToEntries, objectToFormData, parseActionResult, resultToUpdate };
|
|
121
188
|
|
|
122
189
|
//# sourceMappingURL=EnhanceCore.js.map
|
package/dist/EnhanceCore.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EnhanceCore.js","names":[],"sources":["../src/EnhanceCore.ts"],"sourcesContent":["/**\n * Pure plumbing for the `enhance` action: serialise the store's data back into\n * a form body, interpret a server response into a {@link FormActionResult}, and\n * compute the store update a result implies. Kept framework-free and side-\n * effect-free so it is unit-testable in isolation; the rune store\n * (`FormStore.svelte.ts`) wires these to the DOM.\n *\n * @copyright Thomas Foster\n * @module effect-forms-svelte/EnhanceCore\n */\n\nimport { Errors, Result, State } from \"@thomasfosterau/effect-forms\";\n\n// Terse local aliases onto the namespaced core exports.\ntype FormActionResult<A, Message = unknown> = Result.FormActionResult<A, Message>;\ntype FormErrors = Errors.FormErrors;\ntype FormState<A, Message = unknown> = State.FormState<A, Message>;\nconst { failure, success } = Result;\n\n/** Flatten a nested data object into `[name, value]` entries using path notation. */\nexport function objectToEntries(data: unknown, prefix = \"\"): Array<[string, string]> {\n const out: Array<[string, string]> = [];\n const push = (key: string, value: unknown): void => {\n if (value === undefined) return;\n if (value === null) {\n out.push([key, \"\"]);\n } else if (Array.isArray(value)) {\n value.forEach((item, i) => out.push(...objectToEntries(item, `${key}[${i}]`)));\n } else if (typeof value === \"object\") {\n out.push(...objectToEntries(value, key));\n } else {\n out.push([key, String(value)]);\n }\n };\n\n if (data !== null && typeof data === \"object\" && !Array.isArray(data)) {\n for (const [key, value] of Object.entries(data as Record<string, unknown>)) {\n push(prefix ? `${prefix}.${key}` : key, value);\n }\n } else if (prefix) {\n push(prefix, data);\n }\n return out;\n}\n\n/** Serialise the store's data into a {@link FormData} body for submission. */\nexport function objectToFormData(data: unknown): FormData {\n const formData = new FormData();\n for (const [key, value] of objectToEntries(data)) formData.append(key, value);\n return formData;\n}\n\n/** Whether a value looks like a {@link FormActionResult} (carries a known `_tag`). */\nfunction isActionResult(value: unknown): value is FormActionResult<unknown, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { _tag?: unknown })._tag === \"string\" &&\n [\"Success\", \"Failure\", \"Redirect\", \"Error\"].includes((value as { _tag: string })._tag)\n );\n}\n\n/** Whether a value looks like a bare {@link FormState}. */\nfunction isFormState(value: unknown): value is FormState<unknown, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"valid\" in value &&\n \"data\" in value &&\n \"errors\" in value\n );\n}\n\n/**\n * Normalise a parsed JSON response body into a {@link FormActionResult}. The\n * server may return a full action result (`{ _tag, … }`) or a bare\n * {@link FormState} — a bare state maps to `Success` / `Failure` by its `valid`\n * flag, using `status` for the failure code.\n */\nexport function parseActionResult<A, Message>(\n body: unknown,\n status = 200,\n): FormActionResult<A, Message> {\n if (isActionResult(body)) return body as FormActionResult<A, Message>;\n if (isFormState(body)) {\n const state = body as FormState<A, Message>;\n return state.valid ? success(state, status) : failure(state, status);\n }\n return { _tag: \"Error\", status, message: \"Unrecognised form response\" };\n}\n\n/** The mutation a {@link FormActionResult} implies for the store. */\nexport interface FormUpdate<A, Message> {\n readonly data?: A | undefined;\n readonly errors?: FormErrors | undefined;\n readonly message?: Message | undefined;\n readonly redirect?: string | undefined;\n readonly error?: string | undefined;\n readonly valid?: boolean | undefined;\n}\n\n/**\n * Compute the store update implied by a {@link FormActionResult}. Pure: the\n * caller applies the returned fields to its reactive state and acts on\n * `redirect` / `error`.\n */\nexport function resultToUpdate<A, Message>(\n result: FormActionResult<A, Message>,\n): FormUpdate<A, Message> {\n switch (result._tag) {\n case \"Success\":\n return {\n data: result.state.data,\n errors: result.state.errors,\n message: result.state.message,\n valid: true,\n };\n case \"Failure\":\n return {\n data: result.state.data,\n errors: result.state.errors,\n message: result.state.message,\n valid: false,\n };\n case \"Redirect\":\n return { redirect: result.location };\n case \"Error\":\n return { error: result.message, valid: false };\n }\n}\n\n/** How a successful/failed submit's data should land on `data` and the tainted baseline. */\nexport interface DataApplication<A> {\n /** The next value for `data`, or `undefined` to leave it untouched (an auto-submit keeps local edits). */\n readonly data: A | undefined;\n /** The next tainted baseline (`#initial`), or `undefined` when this isn't a successful submit. */\n readonly rebaseTo: A | undefined;\n}\n\n/**\n * Decide how a submit result's data applies to the store, given a defined\n * `update.data` (redirects/errors never reach this — see {@link resultToUpdate}).\n * Pure so the save-then-navigate baseline rebase is unit-testable without\n * compiling the rune store: on a successful submit the tainted baseline\n * rebases to whatever was actually persisted, so `isTainted` goes back to\n * `false` for values that were just saved, not just the original seed. An\n * auto-submitting (live-save) form keeps its local `data` as the source of\n * truth while a request is in flight — adopting the server's echo would\n * discard keystrokes made during the round-trip — but on success rebases to\n * `submittedData` (the snapshot actually sent), not the live value, since the\n * user may have typed further edits that haven't been submitted yet.\n */\nexport function computeDataApplication<A>(params: {\n readonly isSuccess: boolean;\n readonly appliedData: A;\n readonly initial: A;\n readonly submittedData: A;\n readonly resetForm: boolean;\n readonly autoSubmit: boolean;\n}): DataApplication<A> {\n const { isSuccess, appliedData, initial, submittedData, resetForm, autoSubmit } = params;\n if (resetForm && isSuccess) return { data: initial, rebaseTo: initial };\n if (autoSubmit) return { data: undefined, rebaseTo: isSuccess ? submittedData : undefined };\n return { data: appliedData, rebaseTo: isSuccess ? appliedData : undefined };\n}\n"],"mappings":";;;;;;;;;;;;AAiBA,MAAM,EAAE,SAAS,YAAY;;AAG7B,SAAgB,gBAAgB,MAAe,SAAS,IAA6B;CACnF,MAAM,MAA+B,CAAC;CACtC,MAAM,QAAQ,KAAa,UAAyB;EAClD,IAAI,UAAU,KAAA,GAAW;EACzB,IAAI,UAAU,MACZ,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;OACb,IAAI,MAAM,QAAQ,KAAK,GAC5B,MAAM,SAAS,MAAM,MAAM,IAAI,KAAK,GAAG,gBAAgB,MAAM,GAAG,IAAI,GAAG,EAAE,EAAE,CAAC,CAAC;OACxE,IAAI,OAAO,UAAU,UAC1B,IAAI,KAAK,GAAG,gBAAgB,OAAO,GAAG,CAAC;OAEvC,IAAI,KAAK,CAAC,KAAK,OAAO,KAAK,CAAC,CAAC;CAEjC;CAEA,IAAI,SAAS,QAAQ,OAAO,SAAS,YAAY,CAAC,MAAM,QAAQ,IAAI,GAClE,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAA+B,GACvE,KAAK,SAAS,GAAG,OAAO,GAAG,QAAQ,KAAK,KAAK;MAE1C,IAAI,QACT,KAAK,QAAQ,IAAI;CAEnB,OAAO;AACT;;AAGA,SAAgB,iBAAiB,MAAyB;CACxD,MAAM,WAAW,IAAI,SAAS;CAC9B,KAAK,MAAM,CAAC,KAAK,UAAU,gBAAgB,IAAI,GAAG,SAAS,OAAO,KAAK,KAAK;CAC5E,OAAO;AACT;;AAGA,SAAS,eAAe,OAA6D;CACnF,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA6B,SAAS,YAC9C;EAAC;EAAW;EAAW;EAAY;CAAO,CAAC,CAAC,SAAU,MAA2B,IAAI;AAEzF;;AAGA,SAAS,YAAY,OAAsD;CACzE,OACE,OAAO,UAAU,YACjB,UAAU,QACV,WAAW,SACX,UAAU,SACV,YAAY;AAEhB;;;;;;;AAQA,SAAgB,kBACd,MACA,SAAS,KACqB;CAC9B,IAAI,eAAe,IAAI,GAAG,OAAO;CACjC,IAAI,YAAY,IAAI,GAAG;EACrB,MAAM,QAAQ;EACd,OAAO,MAAM,QAAQ,QAAQ,OAAO,MAAM,IAAI,QAAQ,OAAO,MAAM;CACrE;CACA,OAAO;EAAE,MAAM;EAAS;EAAQ,SAAS;CAA6B;AACxE;;;;;;AAiBA,SAAgB,eACd,QACwB;CACxB,QAAQ,OAAO,MAAf;EACE,KAAK,WACH,OAAO;GACL,MAAM,OAAO,MAAM;GACnB,QAAQ,OAAO,MAAM;GACrB,SAAS,OAAO,MAAM;GACtB,OAAO;EACT;EACF,KAAK,WACH,OAAO;GACL,MAAM,OAAO,MAAM;GACnB,QAAQ,OAAO,MAAM;GACrB,SAAS,OAAO,MAAM;GACtB,OAAO;EACT;EACF,KAAK,YACH,OAAO,EAAE,UAAU,OAAO,SAAS;EACrC,KAAK,SACH,OAAO;GAAE,OAAO,OAAO;GAAS,OAAO;EAAM;CACjD;AACF;;;;;;;;;;;;;;AAuBA,SAAgB,uBAA0B,QAOnB;CACrB,MAAM,EAAE,WAAW,aAAa,SAAS,eAAe,WAAW,eAAe;CAClF,IAAI,aAAa,WAAW,OAAO;EAAE,MAAM;EAAS,UAAU;CAAQ;CACtE,IAAI,YAAY,OAAO;EAAE,MAAM,KAAA;EAAW,UAAU,YAAY,gBAAgB,KAAA;CAAU;CAC1F,OAAO;EAAE,MAAM;EAAa,UAAU,YAAY,cAAc,KAAA;CAAU;AAC5E"}
|
|
1
|
+
{"version":3,"file":"EnhanceCore.js","names":[],"sources":["../src/EnhanceCore.ts"],"sourcesContent":["/**\n * Pure plumbing for the `enhance` action: serialise the store's data back into\n * a form body, interpret a server response into a {@link FormActionResult}, and\n * compute the store update a result implies. Kept framework-free and side-\n * effect-free so it is unit-testable in isolation; the rune store\n * (`FormStore.svelte.ts`) wires these to the DOM.\n *\n * @copyright Thomas Foster\n * @module effect-forms-svelte/EnhanceCore\n */\n\nimport { Errors, Result, State } from \"@thomasfosterau/effect-forms\";\nimport * as Arr from \"effect/Array\";\nimport * as Match from \"effect/Match\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\n\n// Terse local aliases onto the namespaced core exports.\ntype FormActionResult<A, Message = unknown> = Result.FormActionResult<A, Message>;\ntype FormErrors = Errors.FormErrors;\ntype FormState<A, Message = unknown> = State.FormState<A, Message>;\nconst { failure, success } = Result;\n\n/** A form-body entry: a stringified leaf, or a `Blob` / `File` passed through. */\ntype BodyEntry = [string, string | Blob];\n\n/**\n * Whether a value is a `Blob` (a `File` is one). Guards on `globalThis.Blob`\n * so it holds in any runtime, including one without a global `Blob`.\n */\nconst isBlob = (value: unknown): value is Blob =>\n !Predicate.isUndefined(globalThis.Blob) && value instanceof Blob;\n\n/**\n * Encode a `Date` as the `YYYY-MM-DD` of its UTC calendar day, or `undefined`\n * for an invalid `Date`. The UTC day round-trips: a `YYYY-MM-DD` string\n * decodes to UTC midnight. Taking everything before the `T` keeps\n * `toISOString`'s expanded form for a year outside 0000–9999\n * (`+010000-01-01`), where a fixed 10-character slice would cut it off.\n */\nconst encodeDate = (value: Date): string | undefined => {\n if (Number.isNaN(value.getTime())) return undefined;\n const iso = value.toISOString();\n return iso.slice(0, iso.indexOf(\"T\"));\n};\n\n/** Append the entries for one named value to `out`, recursing into containers. */\nfunction appendEntries(out: Array<BodyEntry>, key: string, value: unknown): void {\n if (value === null) {\n out.push([key, \"\"]);\n } else if (isBlob(value)) {\n out.push([key, value]);\n } else if (value instanceof Date) {\n const encoded = encodeDate(value);\n if (encoded !== undefined) out.push([key, encoded]);\n } else if (Array.isArray(value)) {\n value.forEach((item, i) => appendEntries(out, `${key}[${i}]`, item));\n } else if (Predicate.isObject(value)) {\n appendFields(out, value, key);\n } else if (\n Predicate.isString(value) ||\n Predicate.isNumber(value) ||\n Predicate.isBoolean(value) ||\n Predicate.isBigInt(value)\n ) {\n out.push([key, String(value)]);\n }\n // `undefined`, `function` and `symbol` leaves are omitted.\n}\n\n/** Append an object's own enumerable fields to `out`, as `prefix.key` names. */\nfunction appendFields<V>(\n out: Array<BodyEntry>,\n data: Record.ReadonlyRecord<string, V>,\n prefix: string,\n): void {\n Arr.forEach(Record.toEntries(data), ([key, value]) =>\n appendEntries(out, prefix ? `${prefix}.${key}` : key, value),\n );\n}\n\n/** Flatten `data` into form-body entries, `Blob` / `File` leaves included. */\nfunction toBodyEntries(data: unknown, prefix: string): Array<BodyEntry> {\n const out: Array<BodyEntry> = [];\n if (prefix) appendEntries(out, prefix, data);\n else if (Predicate.isObject(data)) {\n appendFields(out, data, \"\");\n }\n return out;\n}\n\n/**\n * Flatten a nested data object into `[name, value]` string entries using path\n * notation.\n *\n * Nested objects become dotted names (`author.name`) and array items indexed\n * names (`tags[0]`). Each leaf kind is handled as follows:\n *\n * - A `string`, `number`, `boolean` or `bigint` is stringified.\n * - `null` becomes `\"\"`.\n * - A `Date` becomes the `YYYY-MM-DD` of its **UTC** calendar day (what\n * `<input type=\"date\">` submits, and what `Schema.DateFromString` decodes\n * back to UTC midnight); the time of day is dropped, so a datetime needs its\n * own string field. An invalid `Date` is omitted.\n * - A `Blob` or `File` is omitted here, since a string entry can't carry it;\n * {@link objectToFormData} keeps it.\n * - An `undefined`, `function` or `symbol` is omitted, as `JSON.stringify`\n * omits such object properties, so a callback or symbol left in form data\n * never reaches the form body as `\"Symbol(…)\"` or function source.\n * - Any other object contributes its own enumerable fields, so one with none\n * (a `Map`, a `Set`, an empty object) contributes no entries.\n *\n * An omitted array item leaves a gap (where `JSON.stringify` would write\n * `null`), so the remaining items keep their indices (`tags[0]`, `tags[2]`).\n */\nexport function objectToEntries(data: unknown, prefix = \"\"): Array<[string, string]> {\n return toBodyEntries(data, prefix).filter((entry): entry is [string, string] =>\n Predicate.isString(entry[1]),\n );\n}\n\n/**\n * Serialise the store's data into a {@link FormData} body for submission.\n *\n * Names and leaves follow {@link objectToEntries}, except that a `Blob` or\n * `File` leaf is appended as a file (a `File` keeps its name; a bare `Blob`\n * arrives as a `File` named `\"blob\"`, the `FormData` default), as an\n * `<input type=\"file\">` would submit it, so it reaches the core's\n * `FormData.formDataToObject` (`@thomasfosterau/effect-forms`) unchanged.\n */\nexport function objectToFormData(data: unknown): FormData {\n const formData = new FormData();\n Arr.forEach(toBodyEntries(data, \"\"), ([key, value]) => formData.append(key, value));\n return formData;\n}\n\n/**\n * Whether a value looks like a {@link FormActionResult} (carries a known\n * `_tag`). Only the tag is checked: `A` / `Message` are the caller's declared\n * expectation of the server's response, not verified here.\n */\nfunction isActionResult<A, Message>(value: unknown): value is FormActionResult<A, Message> {\n return (\n Predicate.isObjectOrArray(value) &&\n Predicate.hasProperty(value, \"_tag\") &&\n Predicate.isString(value._tag) &&\n [\"Success\", \"Failure\", \"Redirect\", \"Error\"].includes(value._tag)\n );\n}\n\n/**\n * Whether a value looks like a bare {@link FormState}. Only the keys are\n * checked: `A` / `Message` are the caller's declared expectation, not verified.\n */\nfunction isFormState<A, Message>(value: unknown): value is FormState<A, Message> {\n return (\n Predicate.isObjectOrArray(value) && \"valid\" in value && \"data\" in value && \"errors\" in value\n );\n}\n\n/**\n * Normalise a parsed JSON response body into a {@link FormActionResult}. The\n * server may return a full action result (`{ _tag, … }`) or a bare\n * {@link FormState} — a bare state maps to `Success` / `Failure` by its `valid`\n * flag, using `status` for the failure code.\n */\nexport function parseActionResult<A, Message>(\n body: unknown,\n status = 200,\n): FormActionResult<A, Message> {\n if (isActionResult<A, Message>(body)) return body;\n if (isFormState<A, Message>(body)) {\n return body.valid ? success(body, status) : failure(body, status);\n }\n return { _tag: \"Error\", status, message: \"Unrecognised form response\" };\n}\n\n/** The mutation a {@link FormActionResult} implies for the store. */\nexport interface FormUpdate<A, Message> {\n readonly data?: A | undefined;\n readonly errors?: FormErrors | undefined;\n readonly message?: Message | undefined;\n readonly redirect?: string | undefined;\n readonly error?: string | undefined;\n readonly valid?: boolean | undefined;\n}\n\n/**\n * Compute the store update implied by a {@link FormActionResult}. Pure: the\n * caller applies the returned fields to its reactive state and acts on\n * `redirect` / `error`.\n */\nexport function resultToUpdate<A, Message>(\n result: FormActionResult<A, Message>,\n): FormUpdate<A, Message> {\n return Match.valueTags(result, {\n Success: ({ state }): FormUpdate<A, Message> => ({\n data: state.data,\n errors: state.errors,\n message: state.message,\n valid: true,\n }),\n Failure: ({ state }): FormUpdate<A, Message> => ({\n data: state.data,\n errors: state.errors,\n message: state.message,\n valid: false,\n }),\n Redirect: ({ location }): FormUpdate<A, Message> => ({ redirect: location }),\n Error: ({ message }): FormUpdate<A, Message> => ({ error: message, valid: false }),\n });\n}\n\n/** How a successful/failed submit's data should land on `data` and the tainted baseline. */\nexport interface DataApplication<A> {\n /** The next value for `data`, or `undefined` to leave it untouched (an auto-submit keeps local edits). */\n readonly data: A | undefined;\n /** The next tainted baseline (`#initial`), or `undefined` when this isn't a successful submit. */\n readonly rebaseTo: A | undefined;\n}\n\n/**\n * Decide how a submit result's data applies to the store, given a defined\n * `update.data` (redirects/errors never reach this — see {@link resultToUpdate}).\n * Pure so the save-then-navigate baseline rebase is unit-testable without\n * compiling the rune store: on a successful submit the tainted baseline\n * rebases to whatever was actually persisted, so `isTainted` goes back to\n * `false` for values that were just saved, not just the original seed. An\n * auto-submitting (live-save) form keeps its local `data` as the source of\n * truth while a request is in flight — adopting the server's echo would\n * discard keystrokes made during the round-trip — but on success rebases to\n * `submittedData` (the snapshot actually sent), not the live value, since the\n * user may have typed further edits that haven't been submitted yet.\n */\nexport function computeDataApplication<A>(params: {\n readonly isSuccess: boolean;\n readonly appliedData: A;\n readonly initial: A;\n readonly submittedData: A;\n readonly resetForm: boolean;\n readonly autoSubmit: boolean;\n}): DataApplication<A> {\n const { isSuccess, appliedData, initial, submittedData, resetForm, autoSubmit } = params;\n if (resetForm && isSuccess) return { data: initial, rebaseTo: initial };\n if (autoSubmit) return { data: undefined, rebaseTo: isSuccess ? submittedData : undefined };\n return { data: appliedData, rebaseTo: isSuccess ? appliedData : undefined };\n}\n"],"mappings":"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"}
|
package/dist/EntityForm.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { Command } from "@thomasfosterau/effect-forms";
|
|
2
2
|
import * as Schema from "effect/Schema";
|
|
3
3
|
import { Component } from "svelte";
|
|
4
|
-
//#region src/EntityForm.d.ts
|
|
5
4
|
/** A render-time message thunk — pass the message function itself, uncalled. */
|
|
6
5
|
export type MessageThunk = () => string;
|
|
7
6
|
/** Presentation options for a scalar text entry. */
|
|
@@ -153,5 +152,4 @@ export interface DefineEntityFormOptions<C extends CommandStructLike, U extends
|
|
|
153
152
|
* key — a command-struct change must surface here, at definition time.
|
|
154
153
|
*/
|
|
155
154
|
export declare const defineEntityForm: <C extends CommandStructLike, U extends CommandStructLike>(options: DefineEntityFormOptions<C, U>, build: (f: EntryBuilders<CommandKeys<C, U>>) => readonly EntityFormEntry[]) => EntityFormDefinition;
|
|
156
|
-
//#endregion
|
|
157
155
|
//# sourceMappingURL=EntityForm.d.ts.map
|
package/dist/EntityForm.js
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { Command } from "@thomasfosterau/effect-forms";
|
|
2
|
+
import * as Arr from "effect/Array";
|
|
3
|
+
import * as Predicate from "effect/Predicate";
|
|
4
|
+
import * as Record from "effect/Record";
|
|
5
|
+
import * as HashMap from "effect/HashMap";
|
|
6
|
+
import * as HashSet from "effect/HashSet";
|
|
7
|
+
import * as Option from "effect/Option";
|
|
2
8
|
import * as Schema from "effect/Schema";
|
|
3
|
-
|
|
9
|
+
// src/EntityForm.ts
|
|
4
10
|
const builders = {
|
|
5
11
|
text: (key, options) => ({
|
|
6
12
|
_tag: "scalar",
|
|
@@ -37,15 +43,22 @@ const builders = {
|
|
|
37
43
|
})
|
|
38
44
|
};
|
|
39
45
|
/**
|
|
46
|
+
* A definition-time error: the entries don't match the command structs. Thrown
|
|
47
|
+
* synchronously from `defineEntityForm` (and `fieldFor`), never as an Effect
|
|
48
|
+
* failure — a definition module that doesn't match its commands must fail at
|
|
49
|
+
* import.
|
|
50
|
+
*/
|
|
51
|
+
var EntityFormDefinitionError = class extends Schema.TaggedError()("EntityFormDefinitionError", { message: Schema.String }) {};
|
|
52
|
+
/**
|
|
40
53
|
* Validate an `f.select` entry against its plan field at definition time: the
|
|
41
54
|
* field must be `enum`-kind (the only kind `Command.plan` derives option
|
|
42
55
|
* values for), and every derived value must have a matching `optionLabels`
|
|
43
56
|
* thunk.
|
|
44
57
|
*/
|
|
45
58
|
const validateSelectEntry = (entry, field) => {
|
|
46
|
-
if (field.kind !== "enum") throw new
|
|
59
|
+
if (field.kind !== "enum") throw new EntityFormDefinitionError({ message: `defineEntityForm: entry "${entry.key}" is f.select but its command field is "${field.kind}"-kind, not enum` });
|
|
47
60
|
const missingLabels = (field.options ?? []).filter((value) => !Object.prototype.hasOwnProperty.call(entry.options.optionLabels, value));
|
|
48
|
-
if (missingLabels
|
|
61
|
+
if (Arr.isReadonlyArrayNonEmpty(missingLabels)) throw new EntityFormDefinitionError({ message: `defineEntityForm: entry "${entry.key}" is missing optionLabels for: ${missingLabels.join(", ")}` });
|
|
49
62
|
};
|
|
50
63
|
/**
|
|
51
64
|
* Build an entity-form definition from a command-struct pair and an ordered
|
|
@@ -54,30 +67,21 @@ const validateSelectEntry = (entry, field) => {
|
|
|
54
67
|
* key — a command-struct change must surface here, at definition time.
|
|
55
68
|
*/
|
|
56
69
|
const defineEntityForm = (options, build) => {
|
|
57
|
-
const omitted =
|
|
58
|
-
const withoutOmitted = (struct) => {
|
|
59
|
-
if (omitted.size === 0) return struct;
|
|
60
|
-
const fields = {};
|
|
61
|
-
for (const key in struct.fields) if (!omitted.has(key)) fields[key] = struct.fields[key];
|
|
62
|
-
return { fields };
|
|
63
|
-
};
|
|
70
|
+
const omitted = HashSet.fromIterable(options.omit ?? []);
|
|
71
|
+
const withoutOmitted = (struct) => HashSet.size(omitted) === 0 ? struct : { fields: Record.filter(struct.fields, (_, key) => !HashSet.has(omitted, key)) };
|
|
64
72
|
const plan = Command.plan(withoutOmitted(options.create), withoutOmitted(options.update));
|
|
65
73
|
const entries = build(builders);
|
|
66
|
-
const byKey =
|
|
67
|
-
const declared =
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if (
|
|
71
|
-
if (
|
|
72
|
-
|
|
73
|
-
if (entry._tag === "select") validateSelectEntry(entry, field);
|
|
74
|
-
}
|
|
75
|
-
const missing = plan.fields.filter((field) => !declared.has(field.key)).map((field) => field.key);
|
|
76
|
-
if (missing.length > 0) throw new Error(`defineEntityForm: command fields not declared by any entry: ${missing.join(", ")} — declare or explicitly widget them`);
|
|
77
|
-
const entriesFor = (mode) => entries.filter((entry) => {
|
|
78
|
-
const field = byKey.get(entry.key);
|
|
79
|
-
return field !== void 0 && (mode === "create" ? field.inCreate : field.inUpdate);
|
|
74
|
+
const byKey = HashMap.fromIterable(Arr.map(plan.fields, (field) => [field.key, field]));
|
|
75
|
+
const declared = Arr.reduce(entries, HashSet.empty(), (seen, entry) => {
|
|
76
|
+
const field = HashMap.get(byKey, entry.key);
|
|
77
|
+
if (Option.isNone(field)) throw new EntityFormDefinitionError({ message: `defineEntityForm: entry "${entry.key}" is not a field of either command struct` });
|
|
78
|
+
if (HashSet.has(seen, entry.key)) throw new EntityFormDefinitionError({ message: `defineEntityForm: entry "${entry.key}" is declared twice` });
|
|
79
|
+
if (Predicate.isTagged(entry, "select")) validateSelectEntry(entry, field.value);
|
|
80
|
+
return HashSet.add(seen, entry.key);
|
|
80
81
|
});
|
|
82
|
+
const missing = Arr.map(Arr.filter(plan.fields, (field) => !HashSet.has(declared, field.key)), (field) => field.key);
|
|
83
|
+
if (Arr.isReadonlyArrayNonEmpty(missing)) throw new EntityFormDefinitionError({ message: `defineEntityForm: command fields not declared by any entry: ${missing.join(", ")} — declare or explicitly widget them` });
|
|
84
|
+
const entriesFor = (mode) => Arr.filter(entries, (entry) => Option.exists(HashMap.get(byKey, entry.key), (field) => mode === "create" ? field.inCreate : field.inUpdate));
|
|
81
85
|
return {
|
|
82
86
|
plan,
|
|
83
87
|
entries,
|
|
@@ -90,14 +94,9 @@ const defineEntityForm = (options, build) => {
|
|
|
90
94
|
submit: options.submit,
|
|
91
95
|
clientId: plan.clientId,
|
|
92
96
|
entriesFor,
|
|
93
|
-
fieldFor: (key) => {
|
|
94
|
-
const field = byKey.get(key);
|
|
95
|
-
if (field === void 0) throw new Error(`EntityFormDefinition: unknown field "${key}"`);
|
|
96
|
-
return field;
|
|
97
|
-
}
|
|
97
|
+
fieldFor: (key) => Option.getOrThrowWith(HashMap.get(byKey, key), () => new EntityFormDefinitionError({ message: `EntityFormDefinition: unknown field "${key}"` }))
|
|
98
98
|
};
|
|
99
99
|
};
|
|
100
|
-
//#endregion
|
|
101
100
|
export { defineEntityForm };
|
|
102
101
|
|
|
103
102
|
//# sourceMappingURL=EntityForm.js.map
|