@timber-js/app 0.2.0-alpha.218 → 0.2.0-alpha.219
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/agent-skill.md +5 -5
- package/dist/_chunks/{actions-CUh3cClk.js → actions-BwkmAYXq.js} +8 -1
- package/dist/_chunks/{actions-CUh3cClk.js.map → actions-BwkmAYXq.js.map} +1 -1
- package/dist/client/form.d.ts +34 -37
- package/dist/client/form.d.ts.map +1 -1
- package/dist/client/index.d.ts +3 -3
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +40 -75
- package/dist/client/index.js.map +1 -1
- package/dist/client/{use-form-field.d.ts → use-field-state.d.ts} +10 -7
- package/dist/client/use-field-state.d.ts.map +1 -0
- package/dist/config-types.d.ts +15 -18
- package/dist/config-types.d.ts.map +1 -1
- package/dist/index.js +0 -1
- package/dist/index.js.map +1 -1
- package/dist/plugins/shims.d.ts.map +1 -1
- package/dist/server/action-client.d.ts +11 -172
- package/dist/server/action-client.d.ts.map +1 -1
- package/dist/server/action-handler.d.ts +0 -7
- package/dist/server/action-handler.d.ts.map +1 -1
- package/dist/server/action-schema.d.ts +126 -0
- package/dist/server/action-schema.d.ts.map +1 -0
- package/dist/server/action-types.d.ts +108 -0
- package/dist/server/action-types.d.ts.map +1 -0
- package/dist/server/form-data.d.ts +7 -0
- package/dist/server/form-data.d.ts.map +1 -1
- package/dist/server/index.d.ts +3 -2
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +511 -148
- package/dist/server/index.js.map +1 -1
- package/dist/server/internal.js +1 -1
- package/dist/server/rsc-entry/action-dispatcher.d.ts +0 -3
- package/dist/server/rsc-entry/action-dispatcher.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/schema-introspection.d.ts +68 -0
- package/dist/server/schema-introspection.d.ts.map +1 -0
- package/dist/server/sensitive-fields.d.ts +40 -26
- package/dist/server/sensitive-fields.d.ts.map +1 -1
- package/docs/api/31-api-client.mdx +19 -18
- package/docs/api/34-api-config.mdx +1 -1
- package/docs/learn/08-forms-and-actions.mdx +57 -23
- package/package.json +1 -1
- package/src/client/form.tsx +57 -108
- package/src/client/index.ts +3 -3
- package/src/client/{use-form-field.ts → use-field-state.ts} +20 -8
- package/src/config-types.ts +15 -18
- package/src/plugins/shims.ts +0 -1
- package/src/server/action-client.ts +82 -307
- package/src/server/action-handler.ts +1 -42
- package/src/server/action-schema.ts +203 -0
- package/src/server/action-types.ts +145 -0
- package/src/server/form-data.ts +7 -0
- package/src/server/index.ts +5 -3
- package/src/server/rsc-entry/action-dispatcher.ts +0 -4
- package/src/server/rsc-entry/index.ts +1 -2
- package/src/server/schema-introspection.ts +393 -0
- package/src/server/sensitive-fields.ts +115 -58
- package/dist/client/use-form-field.d.ts.map +0 -1
|
@@ -52,22 +52,22 @@ The `.schema()` method accepts any Standard Schema-compatible validator — Zod,
|
|
|
52
52
|
'use client';
|
|
53
53
|
|
|
54
54
|
import { useActionState } from 'react';
|
|
55
|
-
import {
|
|
55
|
+
import { readFormErrors } from '@timber-js/app/client';
|
|
56
56
|
import { createTodo } from './actions';
|
|
57
57
|
|
|
58
58
|
export default function TodoForm() {
|
|
59
59
|
const [state, action, pending] = useActionState(createTodo, null);
|
|
60
|
-
const errors =
|
|
60
|
+
const errors = readFormErrors(state);
|
|
61
61
|
|
|
62
62
|
return (
|
|
63
63
|
<form action={action}>
|
|
64
64
|
<div>
|
|
65
65
|
<input name="title" required />
|
|
66
|
-
{errors.
|
|
67
|
-
<p className="text-red-600">{errors.
|
|
66
|
+
{errors.field('title') && (
|
|
67
|
+
<p className="text-red-600">{errors.field('title')}</p>
|
|
68
68
|
)}
|
|
69
69
|
</div>
|
|
70
|
-
{errors.
|
|
70
|
+
{errors.server && (
|
|
71
71
|
<p className="text-red-600">Something went wrong. Please try again.</p>
|
|
72
72
|
)}
|
|
73
73
|
<button type="submit" disabled={pending}>
|
|
@@ -82,19 +82,22 @@ export default function TodoForm() {
|
|
|
82
82
|
|
|
83
83
|
### Form Errors
|
|
84
84
|
|
|
85
|
-
`
|
|
85
|
+
`readFormErrors` from `@timber-js/app/client` reads the errors out of the result:
|
|
86
86
|
|
|
87
87
|
```tsx
|
|
88
88
|
const [state, action, pending] = useActionState(myAction, null);
|
|
89
|
-
const errors =
|
|
89
|
+
const errors = readFormErrors(state);
|
|
90
90
|
|
|
91
|
-
errors.
|
|
92
|
-
errors.
|
|
93
|
-
errors.
|
|
94
|
-
errors.hasErrors;
|
|
95
|
-
errors.getFieldError('title'); // string | null (first error for field)
|
|
91
|
+
errors.field('title'); // string | null (first error for the field)
|
|
92
|
+
errors.form; // string[] (form-level errors)
|
|
93
|
+
errors.server; // { code: string; data?: Record<string, unknown> } | null
|
|
94
|
+
errors.hasErrors; // boolean
|
|
96
95
|
```
|
|
97
96
|
|
|
97
|
+
`errors.field()` takes the field names of the action's schema, including paths into lists like `'sets.0.name'`, so a typo is a type error.
|
|
98
|
+
|
|
99
|
+
An action can also run outside a form, from a delete button for example. Dispatch it inside a transition: `startTransition(() => dispatch({ id }))`. A direct call takes the schema's input types, before coercion, so `deleteTodo({ id: 5 })` works with `id: z.coerce.number()`.
|
|
100
|
+
|
|
98
101
|
## Keeping What the User Typed
|
|
99
102
|
|
|
100
103
|
React resets a form after every action: each field goes back to its `defaultValue`. Build forms on that reset, and they keep the user's input after a failure and show the saved values after a save, with or without JavaScript:
|
|
@@ -120,7 +123,8 @@ export const saveEvent = action
|
|
|
120
123
|
category: z.string(),
|
|
121
124
|
ticketed: z.preprocess(coerce.checkbox, z.boolean()),
|
|
122
125
|
// sets.0.name, sets.1.name… arrive as an array
|
|
123
|
-
|
|
126
|
+
// no rows at all arrive as []
|
|
127
|
+
sets: z.array(z.object({ name: z.string().min(1) })),
|
|
124
128
|
})
|
|
125
129
|
)
|
|
126
130
|
.action(async ({ input }) => {
|
|
@@ -129,7 +133,7 @@ export const saveEvent = action
|
|
|
129
133
|
});
|
|
130
134
|
```
|
|
131
135
|
|
|
132
|
-
`submittedValues` is the raw form: strings,
|
|
136
|
+
`submittedValues` is the raw form: strings, an unchecked box absent, and every field the schema declares as a list as an array, whether it was submitted zero, one or many times. Page data is typed. One small, lenient function reads either into what the fields render:
|
|
133
137
|
|
|
134
138
|
```ts title="app/events/[id]/draft.ts"
|
|
135
139
|
export function toDraft(values: Record<string, unknown>) {
|
|
@@ -148,7 +152,7 @@ export function toDraft(values: Record<string, unknown>) {
|
|
|
148
152
|
'use client';
|
|
149
153
|
|
|
150
154
|
import { useActionState } from 'react';
|
|
151
|
-
import {
|
|
155
|
+
import { readFormErrors } from '@timber-js/app/client';
|
|
152
156
|
import { saveEvent } from './actions';
|
|
153
157
|
import { toDraft } from './draft';
|
|
154
158
|
|
|
@@ -156,7 +160,7 @@ type Event = { id: string; title: string; category: string; ticketed: boolean; s
|
|
|
156
160
|
|
|
157
161
|
export function EventForm({ event }: { event: Event }) {
|
|
158
162
|
const [result, action, pending] = useActionState(saveEvent, null);
|
|
159
|
-
const errors =
|
|
163
|
+
const errors = readFormErrors(result);
|
|
160
164
|
// After a failure: what the user submitted. Otherwise: the saved event.
|
|
161
165
|
const d = toDraft(result?.submittedValues ?? event);
|
|
162
166
|
|
|
@@ -164,7 +168,7 @@ export function EventForm({ event }: { event: Event }) {
|
|
|
164
168
|
<form action={action}>
|
|
165
169
|
<input type="hidden" name="id" value={event.id} />
|
|
166
170
|
<input name="title" defaultValue={d.title} />
|
|
167
|
-
{errors.
|
|
171
|
+
{errors.field('title')}
|
|
168
172
|
|
|
169
173
|
{/* React applies a select's defaultValue only on mount: key it on the default */}
|
|
170
174
|
<select key={d.category} name="category" defaultValue={d.category}>
|
|
@@ -178,7 +182,7 @@ export function EventForm({ event }: { event: Event }) {
|
|
|
178
182
|
<input key={i} name={`sets.${i}.name`} defaultValue={set.name} />
|
|
179
183
|
))}
|
|
180
184
|
|
|
181
|
-
{errors.
|
|
185
|
+
{errors.server && <p>Could not save. Please try again.</p>}
|
|
182
186
|
<button disabled={pending}>Save</button>
|
|
183
187
|
</form>
|
|
184
188
|
);
|
|
@@ -191,22 +195,52 @@ Three things break the model:
|
|
|
191
195
|
|
|
192
196
|
- **Controlled fields.** A field whose value lives in state keeps showing that state after the reset has put the DOM back to its default, and the next submit sends what the DOM holds, not what the user sees. If a form must be controlled, cancel the reset: `<form action={action} onReset={(e) => e.preventDefault()}>`.
|
|
193
197
|
- **An unkeyed `<select>`.** React ignores a changed `defaultValue` on a mounted `<select>`. Key it on its default, as above. Inputs, checkboxes and textareas don't need this.
|
|
194
|
-
- **`useState` for a field that needs JavaScript.** A combobox or a chip list can't be a native input. Hold its state in `
|
|
198
|
+
- **`useState` for a field that needs JavaScript.** A combobox or a chip list can't be a native input. Hold its state in `useFieldState` instead, which follows the reset like a native input:
|
|
195
199
|
|
|
196
200
|
```tsx
|
|
197
|
-
import {
|
|
201
|
+
import { useFieldState } from '@timber-js/app/client';
|
|
198
202
|
|
|
199
203
|
function TagsField({ defaultValue }: { defaultValue: string[] }) {
|
|
200
|
-
const [tags, setTags, ref] =
|
|
204
|
+
const [tags, setTags, ref] = useFieldState(defaultValue);
|
|
201
205
|
return (
|
|
202
206
|
<div ref={ref}>
|
|
203
|
-
|
|
207
|
+
{tags.map((tag) => (
|
|
208
|
+
<input key={tag} type="hidden" name="tags" value={tag} />
|
|
209
|
+
))}
|
|
204
210
|
<TagPicker value={tags} onChange={setTags} />
|
|
205
211
|
</div>
|
|
206
212
|
);
|
|
207
213
|
}
|
|
208
214
|
```
|
|
209
215
|
|
|
216
|
+
## Where Form State Lives
|
|
217
|
+
|
|
218
|
+
Pick where a form's state lives by what needs to read it.
|
|
219
|
+
|
|
220
|
+
**In the form (the default).** Everything above: uncontrolled fields with defaults from `result?.submittedValues ?? pageData`, and `useFieldState` for fields that need JavaScript. It works without JavaScript. Start here.
|
|
221
|
+
|
|
222
|
+
**Above the form, still resetting.** When something outside the form needs the draft, such as a live preview, call `useFieldState` above the form with the whole draft and put its `ref` on the `<form>` itself. The draft follows the reset like a native field, so it lands on the user's input after a failure and on the saved values after a save, and the form still works without JavaScript:
|
|
223
|
+
|
|
224
|
+
```tsx
|
|
225
|
+
const defaults = toDraft(result?.submittedValues ?? note);
|
|
226
|
+
const [draft, setDraft, ref] = useFieldState(defaults);
|
|
227
|
+
|
|
228
|
+
return (
|
|
229
|
+
<>
|
|
230
|
+
<Preview title={draft.title} />
|
|
231
|
+
<form ref={ref} action={action}>
|
|
232
|
+
<input
|
|
233
|
+
name="title"
|
|
234
|
+
value={draft.title}
|
|
235
|
+
onChange={(e) => setDraft({ ...draft, title: e.target.value })}
|
|
236
|
+
/>
|
|
237
|
+
</form>
|
|
238
|
+
</>
|
|
239
|
+
);
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
**In your app.** A multi-step wizard, fields that appear depending on other answers, or a draft shared across pages can't be one mounted set of fields: an earlier step's inputs are gone by the time the form submits, so `submittedValues` only has the current step. Keep the values in app state, render the other steps as hidden inputs, and cancel React's reset with `onReset={(e) => e.preventDefault()}`. This needs JavaScript, so use it only when the form can't be one set of fields.
|
|
243
|
+
|
|
210
244
|
## After Mutation
|
|
211
245
|
|
|
212
246
|
| Pattern | When to use |
|
|
@@ -219,7 +253,7 @@ function TagsField({ defaultValue }: { defaultValue: string[] }) {
|
|
|
219
253
|
|
|
220
254
|
The same form works with JavaScript disabled, with no extra code. When a no-JS submission's action returns instead of redirecting, timber renders the page again and React hands the result to the `useActionState` hook that submitted it. `result` holds the result on both paths, so errors and the fields' defaults render the same way, and the server writes the user's input back into the HTML.
|
|
221
255
|
|
|
222
|
-
The result goes only to the hook that submitted, so two forms on one page never see each other's results. It has the same types on both paths: a `Date` your action returns is a `Date` in `state` whether or not JavaScript ran. Sensitive fields (password, apiKey, cvv, etc.) are
|
|
256
|
+
The result goes only to the hook that submitted, so two forms on one page never see each other's results. It has the same types on both paths: a `Date` your action returns is a `Date` in `state` whether or not JavaScript ran. Sensitive fields (password, apiKey, cvv, etc.) are left out of the `submittedValues` a `createActionClient` action returns, and so are fields the schema marks with `.meta({ sensitive: true })`, so a password field comes back empty after a failed submit.
|
|
223
257
|
|
|
224
258
|
A form that doesn't use `useActionState` gets no result back, just as with JavaScript, where React discards a plain `<form action>`'s return value. Such an action should `redirect()` to a page that shows the new state (post-redirect-get). An action that throws renders the nearest `error.tsx`: with JavaScript the action rejects to the nearest error boundary, and without it the page answers from the same `error.tsx` with a 500; return errors from `createActionClient` actions instead.
|
|
225
259
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@timber-js/app",
|
|
3
|
-
"version": "0.2.0-alpha.
|
|
3
|
+
"version": "0.2.0-alpha.219",
|
|
4
4
|
"description": "Vite-native React framework built for Servers and Serverless Platforms — correct HTTP semantics, real status codes, pages that work without JavaScript",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare-workers",
|
package/src/client/form.tsx
CHANGED
|
@@ -3,137 +3,86 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Forms use React's own `useActionState`: an action built with
|
|
5
5
|
* `createActionClient` already has the `(prevState, payload)` signature it
|
|
6
|
-
* calls, and the result is typed from it.
|
|
7
|
-
*
|
|
6
|
+
* calls, and the result is typed from it. An imperative call (a delete
|
|
7
|
+
* button) uses the same hook: `startTransition(() => dispatch(input))`.
|
|
8
|
+
* `readFormErrors` reads the errors out of that result.
|
|
8
9
|
*
|
|
9
|
-
* See design/08-forms-and-actions.md §"
|
|
10
|
+
* See design/08-forms-and-actions.md §"Form Errors via readFormErrors"
|
|
10
11
|
*/
|
|
11
12
|
|
|
12
|
-
import {
|
|
13
|
-
import type {
|
|
14
|
-
ActionFn,
|
|
15
|
-
ActionResult,
|
|
16
|
-
InputHint,
|
|
17
|
-
ValidationErrors,
|
|
18
|
-
} from '../server/action-client.ts';
|
|
19
|
-
|
|
20
|
-
// ─── useFormAction ───────────────────────────────────────────────────────
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Hook for calling a server action imperatively (not via a form).
|
|
24
|
-
* Returns [execute, isPending] where execute accepts the input directly.
|
|
25
|
-
*
|
|
26
|
-
* @example
|
|
27
|
-
* ```tsx
|
|
28
|
-
* const [deleteTodo, isPending] = useFormAction(deleteTodoAction)
|
|
29
|
-
* <button onClick={() => deleteTodo({ id: todo.id })} disabled={isPending}>
|
|
30
|
-
* Delete
|
|
31
|
-
* </button>
|
|
32
|
-
* ```
|
|
33
|
-
*/
|
|
34
|
-
export function useFormAction<TData = unknown, TInput = unknown>(
|
|
35
|
-
action: ActionFn<TData, TInput> | ((input: TInput) => Promise<ActionResult<TData>>)
|
|
36
|
-
): [
|
|
37
|
-
(
|
|
38
|
-
...args: undefined extends TInput ? [input?: InputHint<TInput>] : [input: InputHint<TInput>]
|
|
39
|
-
) => Promise<ActionResult<TData>>,
|
|
40
|
-
boolean,
|
|
41
|
-
] {
|
|
42
|
-
const [isPending, startTransition] = useTransition();
|
|
43
|
-
|
|
44
|
-
const execute = (input?: InputHint<TInput>): Promise<ActionResult<TData>> => {
|
|
45
|
-
return new Promise((resolve, reject) => {
|
|
46
|
-
startTransition(async () => {
|
|
47
|
-
// A raw server function that throws rejects (TIM-1570). The caller
|
|
48
|
-
// awaiting `execute` gets that rejection; without the catch the
|
|
49
|
-
// promise would never settle.
|
|
50
|
-
try {
|
|
51
|
-
resolve(
|
|
52
|
-
await (action as (input: InputHint<TInput>) => Promise<ActionResult<TData>>)(
|
|
53
|
-
input as InputHint<TInput>
|
|
54
|
-
)
|
|
55
|
-
);
|
|
56
|
-
} catch (error) {
|
|
57
|
-
reject(error);
|
|
58
|
-
}
|
|
59
|
-
});
|
|
60
|
-
});
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
return [execute, isPending];
|
|
64
|
-
}
|
|
13
|
+
import type { ActionServerError } from '../server/action-types.ts';
|
|
65
14
|
|
|
66
15
|
// ─── Form error extraction ────────────────────────────────────────────────
|
|
67
16
|
|
|
68
|
-
/** What `
|
|
69
|
-
export interface
|
|
70
|
-
/**
|
|
71
|
-
|
|
72
|
-
/** Form-level errors (
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
|
|
17
|
+
/** What `readFormErrors` reads out of an action result. */
|
|
18
|
+
export interface FormErrors<TPath extends string = string> {
|
|
19
|
+
/** The first validation error for a field, or null. Paths are dot paths: `sets.0.name`. */
|
|
20
|
+
field(name: TPath): string | null;
|
|
21
|
+
/** Form-level validation errors (the `_root` key). */
|
|
22
|
+
form: readonly string[];
|
|
23
|
+
/** The server error, if the action threw (an `ActionError`, or `INTERNAL_ERROR`). */
|
|
24
|
+
server: ActionServerError | null;
|
|
76
25
|
/** Whether any errors are present. */
|
|
77
26
|
hasErrors: boolean;
|
|
78
|
-
|
|
79
|
-
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The shape `readFormErrors` reads: any `ActionResult`. */
|
|
30
|
+
interface ResultWithErrors {
|
|
31
|
+
validationErrors?: { [path: string]: string[] | undefined };
|
|
32
|
+
serverError?: ActionServerError;
|
|
80
33
|
}
|
|
81
34
|
|
|
35
|
+
/**
|
|
36
|
+
* The field paths of a result's validation errors, from its schema's input.
|
|
37
|
+
* Distributes over the result union: only the validation-failure member has
|
|
38
|
+
* a non-`never` `validationErrors`.
|
|
39
|
+
*/
|
|
40
|
+
type ErrorPaths<R> = R extends { validationErrors?: infer V }
|
|
41
|
+
? [NonNullable<V>] extends [never]
|
|
42
|
+
? never
|
|
43
|
+
: Exclude<keyof NonNullable<V>, '_root'> & string
|
|
44
|
+
: never;
|
|
45
|
+
|
|
46
|
+
// Shared by every result without errors, so frozen: a caller cannot mutate
|
|
47
|
+
// it into a value later empty results would report.
|
|
48
|
+
const EMPTY: FormErrors<never> = Object.freeze({
|
|
49
|
+
field: () => null,
|
|
50
|
+
form: Object.freeze([]),
|
|
51
|
+
server: null,
|
|
52
|
+
hasErrors: false,
|
|
53
|
+
});
|
|
54
|
+
|
|
82
55
|
/**
|
|
83
56
|
* Read the errors out of an action result — the state `useActionState`
|
|
84
57
|
* returns. `_root` validation errors are form-level; every other key is a
|
|
85
|
-
* field.
|
|
58
|
+
* field. Field names are typed from the action's schema input, so a
|
|
59
|
+
* misspelled path is a type error.
|
|
86
60
|
*
|
|
87
61
|
* @example
|
|
88
62
|
* ```tsx
|
|
89
63
|
* const [result, action, isPending] = useActionState(createTodo, null)
|
|
90
|
-
* const errors =
|
|
91
|
-
* errors.
|
|
64
|
+
* const errors = readFormErrors(result)
|
|
65
|
+
* errors.field('title') // first message for the field, or null
|
|
92
66
|
* ```
|
|
93
67
|
*/
|
|
94
|
-
export function
|
|
95
|
-
result:
|
|
96
|
-
):
|
|
97
|
-
|
|
98
|
-
fieldErrors: {},
|
|
99
|
-
formErrors: [],
|
|
100
|
-
serverError: null,
|
|
101
|
-
hasErrors: false,
|
|
102
|
-
getFieldError: () => null,
|
|
103
|
-
};
|
|
104
|
-
|
|
105
|
-
if (!result) return empty;
|
|
106
|
-
|
|
107
|
-
const validationErrors: ValidationErrors | undefined = result.validationErrors;
|
|
108
|
-
const serverError = result.serverError;
|
|
109
|
-
|
|
110
|
-
if (!validationErrors && !serverError) return empty;
|
|
111
|
-
|
|
112
|
-
// Separate _root (form-level) errors from field errors
|
|
113
|
-
const fieldErrors: Record<string, string[]> = {};
|
|
114
|
-
const formErrors: string[] = [];
|
|
115
|
-
|
|
116
|
-
if (validationErrors) {
|
|
117
|
-
for (const [key, messages] of Object.entries(validationErrors)) {
|
|
118
|
-
if (key === '_root') {
|
|
119
|
-
formErrors.push(...messages);
|
|
120
|
-
} else {
|
|
121
|
-
fieldErrors[key] = messages;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
}
|
|
68
|
+
export function readFormErrors<R extends ResultWithErrors>(
|
|
69
|
+
result: R | null | undefined
|
|
70
|
+
): FormErrors<ErrorPaths<R>> {
|
|
71
|
+
if (!result) return EMPTY;
|
|
125
72
|
|
|
73
|
+
const validationErrors = result.validationErrors ?? {};
|
|
74
|
+
const server = result.serverError ?? null;
|
|
75
|
+
const form = validationErrors._root ?? [];
|
|
126
76
|
const hasErrors =
|
|
127
|
-
Object.
|
|
77
|
+
server !== null || Object.values(validationErrors).some((messages) => messages?.length);
|
|
128
78
|
|
|
79
|
+
if (!hasErrors) return EMPTY;
|
|
129
80
|
return {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
serverError: serverError ?? null,
|
|
133
|
-
hasErrors,
|
|
134
|
-
getFieldError(field: string): string | null {
|
|
135
|
-
const errs = fieldErrors[field];
|
|
136
|
-
return errs && errs.length > 0 ? errs[0] : null;
|
|
81
|
+
field(name) {
|
|
82
|
+
return validationErrors[name]?.[0] ?? null;
|
|
137
83
|
},
|
|
84
|
+
form,
|
|
85
|
+
server,
|
|
86
|
+
hasErrors,
|
|
138
87
|
};
|
|
139
88
|
}
|
package/src/client/index.ts
CHANGED
|
@@ -75,9 +75,9 @@ export {
|
|
|
75
75
|
} from './use-selected-layout-segment.ts';
|
|
76
76
|
|
|
77
77
|
// Forms
|
|
78
|
-
export {
|
|
79
|
-
export {
|
|
80
|
-
export type {
|
|
78
|
+
export { readFormErrors } from './form.tsx';
|
|
79
|
+
export { useFieldState } from './use-field-state.ts';
|
|
80
|
+
export type { FormErrors } from './form.tsx';
|
|
81
81
|
|
|
82
82
|
// Params. Called with no argument this returns the untyped accumulated params;
|
|
83
83
|
// pass the route's SEGMENT_PATH (from its generated `./$segment` module) to get
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* useFieldState — state for a form field that needs JavaScript (a combobox, a
|
|
3
3
|
* chip list, a row list), made to behave like a native uncontrolled input.
|
|
4
4
|
*
|
|
5
5
|
* React resets a form after its action settles, so a native field with a
|
|
@@ -27,8 +27,11 @@ import {
|
|
|
27
27
|
* State for a field that follows its form's reset.
|
|
28
28
|
*
|
|
29
29
|
* Returns `[value, setValue, ref]`. Attach `ref` to any element inside the
|
|
30
|
-
* `<form>`,
|
|
31
|
-
*
|
|
30
|
+
* `<form>`, or to the `<form>` itself (the hook subscribes to
|
|
31
|
+
* `closest('form')`, which includes the element), and render the value into
|
|
32
|
+
* the form data yourself (usually hidden inputs). With the ref on the form,
|
|
33
|
+
* the hook can live above it and hold the whole draft as one object, for a
|
|
34
|
+
* live preview beside the form. `value` is `defaultValue` until `setValue` is called, and is
|
|
32
35
|
* `defaultValue` again after the form resets, unless the form cancels its
|
|
33
36
|
* `reset` event. An edit dispatches a bubbling `change` event from the `ref`
|
|
34
37
|
* element after it commits, so a native `change` listener on the form sees it
|
|
@@ -39,14 +42,14 @@ import {
|
|
|
39
42
|
* @example
|
|
40
43
|
* ```tsx
|
|
41
44
|
* // draft: the form's defaults, read from result?.submittedValues ?? pageData
|
|
42
|
-
* const [tags, setTags, ref] =
|
|
45
|
+
* const [tags, setTags, ref] = useFieldState(draft.tags);
|
|
43
46
|
* <div ref={ref}>
|
|
44
|
-
* <input type="hidden" name="tags" value={
|
|
47
|
+
* {tags.map((tag) => <input key={tag} type="hidden" name="tags" value={tag} />)}
|
|
45
48
|
* <TagPicker value={tags} onChange={setTags} />
|
|
46
49
|
* </div>
|
|
47
50
|
* ```
|
|
48
51
|
*/
|
|
49
|
-
export function
|
|
52
|
+
export function useFieldState<T>(
|
|
50
53
|
defaultValue: T
|
|
51
54
|
): [value: T, setValue: Dispatch<SetStateAction<T>>, ref: RefCallback<HTMLElement>] {
|
|
52
55
|
// `null` means "not edited": the field shows its default. A box, so an edit
|
|
@@ -107,9 +110,18 @@ export function useFormField<T>(
|
|
|
107
110
|
if (!form) return;
|
|
108
111
|
const onReset = (event: Event) => {
|
|
109
112
|
pendingResets.current.push(event);
|
|
110
|
-
|
|
111
|
-
queueMicrotask(() => {
|
|
113
|
+
const apply = () => {
|
|
112
114
|
if (takeResets()) setEdit(null);
|
|
115
|
+
};
|
|
116
|
+
// A reset dispatched from script (`form.reset()`, React's post-action
|
|
117
|
+
// reset) is over by the time a microtask runs. A native one (a
|
|
118
|
+
// `type="reset"` button) is not: the browser drains microtasks
|
|
119
|
+
// between listeners, before React's delegated `onReset` has run. Then
|
|
120
|
+
// apply it in the next task, once dispatch has certainly ended. One
|
|
121
|
+
// task, not a loop: dispatch is synchronous within this one.
|
|
122
|
+
queueMicrotask(() => {
|
|
123
|
+
if (event.eventPhase === Event.NONE) apply();
|
|
124
|
+
else setTimeout(apply, 0);
|
|
113
125
|
});
|
|
114
126
|
};
|
|
115
127
|
form.addEventListener('reset', onReset);
|
package/src/config-types.ts
CHANGED
|
@@ -56,34 +56,31 @@ export interface TimberUserConfig {
|
|
|
56
56
|
forms?: {
|
|
57
57
|
/**
|
|
58
58
|
* Strip sensitive fields (passwords, tokens, CVV, SSN, etc.) from the
|
|
59
|
-
* `submittedValues`
|
|
60
|
-
* failure, or a `serverError` from a form submission).
|
|
59
|
+
* `submittedValues` a `createActionClient` action echoes back when it
|
|
60
|
+
* fails (a validation failure, or a `serverError` from a form submission).
|
|
61
|
+
* A raw `'use server'` action's return value is never changed.
|
|
61
62
|
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
63
|
+
* Hygiene, not a security boundary: the echo only returns to the user who
|
|
64
|
+
* typed it. Stripping keeps credentials out of the re-rendered form (and,
|
|
65
|
+
* without JS, out of the page's HTML), so they come back empty.
|
|
65
66
|
*
|
|
66
67
|
* - `true` / omitted — use the built-in deny-list (default, recommended).
|
|
67
|
-
* - `false` —
|
|
68
|
-
*
|
|
69
|
-
* browser history, proxy logs, and the back-forward cache.
|
|
68
|
+
* - `false` — strip no field by name. Fields the action's schema marks
|
|
69
|
+
* `.meta({ sensitive: true })` are still stripped.
|
|
70
70
|
* - `string[]` — additional field names to strip, merged with the built-in list.
|
|
71
71
|
*
|
|
72
|
-
* The built-in list
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
* cardCvc, ssn, socialSecurityNumber, otp, totp, mfaCode, twoFactorCode,
|
|
76
|
-
* privateKey — plus exact match on `token` (exact-only to avoid
|
|
77
|
-
* false positives on `csrfToken`).
|
|
72
|
+
* The built-in list (passwords, tokens, card numbers, SSNs, one-time
|
|
73
|
+
* codes, keys) is in `server/sensitive-fields.ts` and documented in
|
|
74
|
+
* design/08-forms-and-actions.md §"Sensitive field stripping".
|
|
78
75
|
*
|
|
79
76
|
* **Function predicates are not supported at the global level** because
|
|
80
77
|
* `timber.config.ts` is JSON-serialized into the runtime config and
|
|
81
78
|
* functions cannot cross that boundary. For custom predicates, use
|
|
82
|
-
* the per-
|
|
83
|
-
* (name) => ... })` (functions are supported
|
|
84
|
-
*
|
|
79
|
+
* the per-client override: `createActionClient({ stripSensitiveFields:
|
|
80
|
+
* (name) => ... })` (functions are supported there since
|
|
81
|
+
* `createActionClient` runs in the same module graph as user code).
|
|
85
82
|
*
|
|
86
|
-
* See TIM-816.
|
|
83
|
+
* See TIM-816, TIM-1584.
|
|
87
84
|
*/
|
|
88
85
|
stripSensitiveFields?: boolean | readonly string[];
|
|
89
86
|
};
|