@cslug/vue 0.6.1 → 0.7.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/docs/api.md CHANGED
@@ -13,7 +13,8 @@
13
13
  | `useT()` | `t`, `tr`, `locale`, `formatMoney`, `formatDate` in the current locale |
14
14
  | `route(name, params?, options?)` | |
15
15
  | `formatDuration(minutes)`, `formatMoney`, `formatDate` | |
16
- | `useForm(initial)` | `data`, `errors`, `error`, `processing`, `response`, `post/put/patch/delete(url)` → boolean, `reset`, `clearErrors`; JSON with `X-CSRF-Token` |
16
+ | `useForm(initial, options?)` | `data`, `errors`, `hasErrors`, `error`, `processing`, `progress`, `isDirty`, `wasSuccessful`, `recentlySuccessful`, `response`; `submit(event \| method, url?, options?)`, `get/post/put/patch/delete(url, options?)` → boolean, `cancel`, `transform`, `setError`, `clearErrors(...fields)`, `reset(...fields)`, `defaults(field?, value?)`. Callbacks (`FormCallbacks`): `onBefore`, `onStart`, `onProgress`, `onSuccess(response, { redirect })`, `onError(errors, { status, message })`, `onCancel`, `onFinish`; per call also `followRedirects`, `headers` (`SubmitOptions`). Live validation (`FormOptions`): `schema` (a `v` schema: browser checks), `validate` (`'client' \| 'server' \| 'both'`), `action`/`method`, `validationTimeout`; `validate(fields?, event?)`, `touch`, `touched`, `valid`, `invalid`, `validating`; `submit()` with `options.action` |
17
+ | `http` | `get(url, query?, options?)`, `post/put/patch/delete(url, data?, options?)` → `HttpResult` (`{ ok, status, data, errors, error, redirect?, cancelled? }`); JSON or multipart, CSRF, `X-Cslug-Request`; `RequestOptions` `{ headers, onProgress, signal }` |
17
18
  | `csrfHeaders()` | For hand-written `fetch` |
18
19
  | `defineStore(name, init, { persist? })` | State shared by the page's islands (fresh per call on the server) |
19
20
  | `mountIslands({ setup? })` | Browser: hydrate the page's islands (`resources/client.ts`) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cslug/vue",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "Vue views rendered on the server, components hydrated as islands, composables and asset build.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -33,9 +33,9 @@
33
33
  "bun": ">=1.3.14"
34
34
  },
35
35
  "peerDependencies": {
36
- "@cslug/core": "0.6.1",
37
- "@cslug/http": "0.6.1",
38
- "@cslug/validation": "0.6.1",
36
+ "@cslug/core": "0.7.0",
37
+ "@cslug/http": "0.7.0",
38
+ "@cslug/validation": "0.7.0",
39
39
  "vue": "^3.5.0",
40
40
  "sass": "^1.80.0",
41
41
  "tailwindcss": "^4.0.0",
@@ -9,7 +9,15 @@ import { buildUrl } from '../shared/url'
9
9
  import { pageData } from './data'
10
10
 
11
11
  export { type Serialized, serialize } from '../serialize'
12
- export { csrfHeaders, type Form, useForm } from '../shared/form'
12
+ export {
13
+ type ClientSchema,
14
+ type Form,
15
+ type FormCallbacks,
16
+ type FormOptions,
17
+ type SubmitOptions,
18
+ useForm,
19
+ } from '../shared/form'
20
+ export { csrfHeaders, type HttpResult, http, type Progress, type RequestOptions } from '../shared/http'
13
21
  export { defineStore } from '../shared/store'
14
22
  export { type PageData, pageData } from './data'
15
23
 
package/src/index.ts CHANGED
@@ -26,5 +26,13 @@ export {
26
26
  view,
27
27
  } from './render'
28
28
  export { type Serialized, serialize } from './serialize'
29
- export { csrfHeaders, type Form, useForm } from './shared/form'
29
+ export {
30
+ type ClientSchema,
31
+ type Form,
32
+ type FormCallbacks,
33
+ type FormOptions,
34
+ type SubmitOptions,
35
+ useForm,
36
+ } from './shared/form'
37
+ export { csrfHeaders, type HttpResult, http, type Progress, type RequestOptions } from './shared/http'
30
38
  export { defineStore } from './shared/store'
@@ -1,87 +1,376 @@
1
+ import { formatIcu, formatMessage, type Issue } from '@cslug/validation'
1
2
  import { reactive, type UnwrapRef } from 'vue'
3
+ import { pageData } from '../client/data'
4
+ import { type HttpResult, type Progress, send } from './http'
2
5
 
3
- /** `X-CSRF-Token` from the page's `<meta name="csrf-token">` (rendered by `<Assets>`), for hand-written `fetch`. */
4
- export function csrfHeaders(): Record<string, string> {
5
- if (typeof document === 'undefined') return {}
6
- const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content')
7
- return token ? { 'x-csrf-token': token } : {}
6
+ export { csrfHeaders } from './http'
7
+
8
+ /** The callbacks of a submission (Inertia's names), on the form and per call; the form's run first. */
9
+ export type FormCallbacks<R> = {
10
+ /** Before sending; return `false` to cancel. */
11
+ onBefore?: () => boolean | undefined | void
12
+ onStart?: () => void
13
+ /** Upload progress (requests with files). */
14
+ onProgress?: (progress: Progress) => void
15
+ /** A 2xx: the JSON response, and where the server redirects (the page goes there after the callbacks). */
16
+ onSuccess?: (response: unknown, info: { redirect?: string }) => void
17
+ /** A failure: `errors` per field for a 422 (else `{}`), and the status and message. */
18
+ onError?: (errors: Record<string, string>, info: { status: number; message: string | null }) => void
19
+ /** Cancelled by `cancel()` or a newer submission. */
20
+ onCancel?: () => void
21
+ /** After any outcome. */
22
+ onFinish?: () => void
23
+ }
24
+
25
+ export type SubmitOptions<R> = FormCallbacks<R> & {
26
+ /** Follow a server `redirect()` (default true); false leaves the page and gives `redirect` to `onSuccess`. */
27
+ followRedirects?: boolean
28
+ headers?: Record<string, string>
29
+ }
30
+
31
+ type Method = 'get' | 'post' | 'put' | 'patch' | 'delete'
32
+
33
+ /** A schema `form.validate()` can check fields with in the browser (a `v` schema: the server's validator). */
34
+ export type ClientSchema = {
35
+ safeParse(input: unknown): { success: true } | { success: false; error: { issues: Issue[] } }
36
+ }
37
+
38
+ /** `useForm(initial, options)`: the callbacks, and what live validation needs. */
39
+ export type FormOptions<R> = FormCallbacks<R> & {
40
+ /** Where `submit()` (without arguments) and server-side `validate()` send the form. */
41
+ action?: string
42
+ method?: Method
43
+ /** Check fields in the browser with the same `v` schema as the server (no request). */
44
+ schema?: ClientSchema
45
+ /**
46
+ * `client` (the schema, instantly), `server` (a validate-only request to the route, debounced: needs
47
+ * `.validates(schema)` on it), or `both` (the server when the schema passes: unique emails…). Default: `client`
48
+ * with a schema, else `server`.
49
+ */
50
+ validate?: 'client' | 'server' | 'both'
51
+ /** Debounce of server-side validation, in ms (default 300). */
52
+ validationTimeout?: number
8
53
  }
9
54
 
10
55
  export type Form<F extends object, R> = {
11
56
  data: UnwrapRef<F>
12
57
  /** First message per field from a 422 response; cleared on the next submit. */
13
58
  errors: Partial<Record<keyof F & string, string>> & Record<string, string | undefined>
59
+ hasErrors: boolean
14
60
  /** A message for failures that are not field errors (network, 403, 419, 500). */
15
61
  error: string | null
16
62
  processing: boolean
63
+ /** Upload progress of the request in flight (requests with files), else null. */
64
+ progress: Progress | null
65
+ /** The data differs from its defaults (the initial values, or the last `defaults()`). */
66
+ isDirty: boolean
67
+ /** The last submission succeeded. */
68
+ wasSuccessful: boolean
69
+ /** True for 2 seconds after a success (a "Saved" message). */
70
+ recentlySuccessful: boolean
17
71
  /** Parsed JSON of the last successful response. */
18
72
  response: R
19
- post(url: string): Promise<boolean>
20
- put(url: string): Promise<boolean>
21
- patch(url: string): Promise<boolean>
22
- delete(url: string): Promise<boolean>
23
- reset(): void
24
- clearErrors(): void
73
+ /** A server-side validation is in flight. */
74
+ validating: boolean
75
+ /**
76
+ * Check fields now (default: the touched ones), in the browser or on the server (`options.validate`), and set or
77
+ * clear their errors. `event` (an input's blur) gives the `<form>` to validate against. Resolves to true when valid.
78
+ */
79
+ validate(fields?: string | string[], event?: Event): Promise<boolean>
80
+ /** Mark fields as touched (what `validate()` without fields checks). */
81
+ touch(...fields: string[]): void
82
+ /** Was the field (or any field) touched? */
83
+ touched(field?: string): boolean
84
+ /** Touched, validated and without an error. */
85
+ valid(field: string): boolean
86
+ /** Has an error (from validation or a submission). */
87
+ invalid(field: string): boolean
88
+ /**
89
+ * Submit: from a `<form>` event (`@submit.prevent="form.submit"`: its `action`, `method` and `_method`), or with a
90
+ * method and URL. Resolves to true on a 2xx.
91
+ */
92
+ submit(event: Event, options?: SubmitOptions<R>): Promise<boolean>
93
+ /** With `options.action` (and `method`, default post). */
94
+ submit(): Promise<boolean>
95
+ submit(method: Method, url: string, options?: SubmitOptions<R>): Promise<boolean>
96
+ get(url: string, options?: SubmitOptions<R>): Promise<boolean>
97
+ post(url: string, options?: SubmitOptions<R>): Promise<boolean>
98
+ put(url: string, options?: SubmitOptions<R>): Promise<boolean>
99
+ patch(url: string, options?: SubmitOptions<R>): Promise<boolean>
100
+ delete(url: string, options?: SubmitOptions<R>): Promise<boolean>
101
+ /** Abort the submission in flight (`onCancel`). */
102
+ cancel(): void
103
+ /** Change the data just before it is sent: `form.transform((d) => ({ ...d, remember: !!d.remember }))`. */
104
+ transform(fn: (data: UnwrapRef<F>) => Record<string, unknown>): Form<F, R>
105
+ /** Set errors by hand: `setError('email', '…')` or `setError({ email: '…' })`. */
106
+ setError(field: string | Record<string, string>, message?: string): void
107
+ clearErrors(...fields: string[]): void
108
+ /** Back to the defaults: every field, or the ones named. Errors are cleared too. */
109
+ reset(...fields: (keyof F & string)[]): void
110
+ /** The current data (or one field's value) becomes the defaults `reset()` and `isDirty` compare with. */
111
+ defaults(field?: keyof F & string, value?: unknown): void
112
+ }
113
+
114
+ const RECENT_MS = 2000
115
+
116
+ /** A validation message in the page's language: the `validation` namespace if the island loaded it, else English. */
117
+ const message = (issue: Issue) =>
118
+ formatMessage(issue, (key, params) => {
119
+ const data = pageData()
120
+ const text = data.messages[key]
121
+ return text === undefined ? undefined : formatIcu(text, params, data.locale)
122
+ })
123
+ const matches = (path: string, field: string) => path === field || path.startsWith(`${field}.`)
124
+ /** The data without files: validate-only requests never upload. */
125
+ const withoutFiles = (value: unknown): unknown =>
126
+ Array.isArray(value)
127
+ ? value.filter((v) => !(typeof Blob !== 'undefined' && v instanceof Blob)).map(withoutFiles)
128
+ : value && typeof value === 'object' && !(value instanceof Date)
129
+ ? Object.fromEntries(
130
+ Object.entries(value)
131
+ .filter(([, v]) => !(typeof Blob !== 'undefined' && v instanceof Blob))
132
+ .map(([k, v]) => [k, withoutFiles(v)]),
133
+ )
134
+ : value
135
+
136
+ /** A deep copy that also reads Vue's reactive proxies (structuredClone cannot) and keeps files and dates. */
137
+ function clone<T>(value: T): T {
138
+ if (Array.isArray(value)) return value.map(clone) as T
139
+ if (value instanceof Date) return new Date(value.getTime()) as T
140
+ if (typeof Blob !== 'undefined' && value instanceof Blob) return value
141
+ if (value && typeof value === 'object')
142
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, clone(v)])) as T
143
+ return value
25
144
  }
26
145
 
27
146
  /**
28
- * Reactive form state that submits JSON (with the CSRF token) and maps a 422 problem's `errors` to fields:
29
- * `const form = useForm({ title: '' }); if (await form.post(route('todos.store'))) …`.
147
+ * Reactive form state that submits without reloading the page: JSON (or multipart with files) with the CSRF token,
148
+ * 422 errors mapped to fields, callbacks, and a server `redirect()` followed. Works with web routes and API routes.
149
+ *
150
+ * ```ts
151
+ * const form = useForm({ title: '' }, { onSuccess: () => form.reset() })
152
+ * // <form :action="route('todos.store')" method="post" @submit.prevent="form.submit">
153
+ * ```
30
154
  */
31
155
  // biome-ignore lint/suspicious/noExplicitAny: the response type defaults to what the caller reads
32
- export function useForm<F extends object, R = any>(initial: F): Form<F, R> {
33
- const copy = () => structuredClone(initial)
34
- const submit = async (method: string, url: string): Promise<boolean> => {
156
+ export function useForm<F extends object, R = any>(initial: F, callbacks: FormOptions<R> = {}): Form<F, R> {
157
+ let defaults = clone(initial)
158
+ let target: [string, string] | undefined = callbacks.action
159
+ ? [callbacks.method ?? 'post', callbacks.action]
160
+ : undefined
161
+ let timer: ReturnType<typeof setTimeout> | undefined
162
+ let waiting: { fields: Set<string>; resolvers: ((valid: boolean) => void)[] } = { fields: new Set(), resolvers: [] }
163
+ let transform: ((data: UnwrapRef<F>) => Record<string, unknown>) | undefined
164
+ let controller: AbortController | undefined
165
+ let recent: ReturnType<typeof setTimeout> | undefined
166
+
167
+ const run = async (method: string, url: string, options: SubmitOptions<R> = {}): Promise<boolean> => {
168
+ const each = <K extends keyof FormCallbacks<R>>(name: K, ...args: Parameters<NonNullable<FormCallbacks<R>[K]>>) => {
169
+ const results = [callbacks[name], options[name]].map((fn) =>
170
+ (fn as ((...a: unknown[]) => unknown) | undefined)?.(...args),
171
+ )
172
+ return results
173
+ }
174
+ if (each('onBefore').includes(false)) return false
175
+ target = [method, url]
176
+ controller?.abort() // a newer submission replaces the one in flight
177
+ const own = new AbortController()
178
+ controller = own
35
179
  form.processing = true
180
+ form.progress = null
181
+ form.wasSuccessful = false
36
182
  form.clearErrors()
183
+ each('onStart')
184
+ const data = transform ? transform(form.data) : (form.data as Record<string, unknown>)
185
+ let result: HttpResult<R>
37
186
  try {
38
- const hasBody = method !== 'DELETE' || Object.keys(form.data as object).length > 0
39
- const res = await fetch(url, {
40
- method,
41
- credentials: 'same-origin',
42
- headers: {
43
- accept: 'application/json',
44
- ...(hasBody ? { 'content-type': 'application/json' } : {}),
45
- ...csrfHeaders(),
187
+ result = await send<R>(method, url, data, {
188
+ signal: own.signal,
189
+ ...(options.headers ? { headers: options.headers } : {}),
190
+ onProgress: (p) => {
191
+ form.progress = p
192
+ each('onProgress', p)
46
193
  },
47
- body: hasBody ? JSON.stringify(form.data) : undefined,
48
194
  })
49
- const body = (res.headers.get('content-type') ?? '').includes('json') ? await res.json() : undefined
50
- if (res.ok) {
51
- form.response = body as UnwrapRef<R>
52
- return true
53
- }
54
- if (res.status === 422 && body?.errors) {
55
- for (const [field, messages] of Object.entries(body.errors as Record<string, string[]>))
56
- (form.errors as Record<string, string>)[field] = messages[0] ?? ''
57
- } else {
58
- form.error = body?.detail ?? body?.title ?? `${res.status} ${res.statusText}`
195
+ } finally {
196
+ if (controller === own) {
197
+ form.processing = false
198
+ controller = undefined
59
199
  }
200
+ }
201
+ if (result.cancelled) {
202
+ each('onCancel')
203
+ each('onFinish')
60
204
  return false
61
- } catch (e) {
62
- form.error = e instanceof Error ? e.message : String(e)
63
- return false
64
- } finally {
65
- form.processing = false
66
205
  }
206
+ if (result.ok) {
207
+ form.response = result.data as UnwrapRef<R>
208
+ form.wasSuccessful = true
209
+ form.recentlySuccessful = true
210
+ clearTimeout(recent)
211
+ recent = setTimeout(() => {
212
+ form.recentlySuccessful = false
213
+ }, RECENT_MS)
214
+ each('onSuccess', result.data, result.redirect ? { redirect: result.redirect } : {})
215
+ each('onFinish')
216
+ if (result.redirect && options.followRedirects !== false && typeof window !== 'undefined')
217
+ window.location.assign(result.redirect)
218
+ return true
219
+ }
220
+ form.errors = result.errors as never
221
+ form.error = result.error
222
+ each('onError', result.errors, { status: result.status, message: result.error })
223
+ each('onFinish')
224
+ return false
225
+ }
226
+
227
+ const payload = () => (transform ? transform(form.data) : (form.data as Record<string, unknown>))
228
+
229
+ /** Replace the errors of `fields` (and their nested paths) with `errors`. */
230
+ const setFieldErrors = (fields: string[], errors: Record<string, string>) => {
231
+ for (const key of Object.keys(form.errors)) if (fields.some((f) => matches(key, f))) delete form.errors[key]
232
+ for (const [key, text] of Object.entries(errors)) if (fields.some((f) => matches(key, f))) form.errors[key] = text
233
+ for (const f of fields) form.validated[f] = true
234
+ }
235
+
236
+ const inBrowser = (fields: string[]): Record<string, string> => {
237
+ const result = (callbacks.schema as ClientSchema).safeParse(payload())
238
+ if (result.success) return {}
239
+ const errors: Record<string, string> = {}
240
+ for (const issue of result.error.issues) {
241
+ const path = issue.path.join('.')
242
+ if (fields.some((f) => matches(path, f)) && errors[path] === undefined) errors[path] = message(issue)
243
+ }
244
+ return errors
245
+ }
246
+
247
+ /** Debounced validate-only requests: fields asked for within the timeout go in one request. */
248
+ const onServer = (fields: string[]): Promise<boolean> => {
249
+ if (!target)
250
+ throw new Error(
251
+ 'form.validate() needs the route: useForm(data, { action: route(…) }), form.validate(field, $event), or a first submit',
252
+ )
253
+ const [method, url] = target
254
+ for (const f of fields) waiting.fields.add(f)
255
+ clearTimeout(timer)
256
+ return new Promise((resolve) => {
257
+ waiting.resolvers.push(resolve)
258
+ timer = setTimeout(async () => {
259
+ const batch = waiting
260
+ waiting = { fields: new Set(), resolvers: [] }
261
+ const names = [...batch.fields]
262
+ form.validating = true
263
+ const result = await send(method, url, withoutFiles(payload()) as Record<string, unknown>, {
264
+ headers: { 'x-cslug-validate': names.join(',') },
265
+ })
266
+ form.validating = false
267
+ if (result.ok || result.status === 422) setFieldErrors(names, result.errors)
268
+ else if (!result.cancelled) form.error = result.error
269
+ const valid = result.ok
270
+ for (const r of batch.resolvers) r(valid)
271
+ }, callbacks.validationTimeout ?? 300)
272
+ })
273
+ }
274
+
275
+ /** A `<form>`'s method (`_method` first) and action. */
276
+ const fromForm = (el: HTMLFormElement): [string, string] => {
277
+ const override = (el.querySelector?.('input[name="_method"]') as HTMLInputElement | null)?.value
278
+ return [override || el.getAttribute('method') || 'get', el.getAttribute('action') || window.location.href]
279
+ }
280
+
281
+ const fromEvent = (event: Event): [string, string] => {
282
+ const el = (event.currentTarget ?? event.target) as HTMLFormElement | null
283
+ if (!el || typeof el.getAttribute !== 'function')
284
+ throw new Error('form.submit(event) needs the submit event of a <form>: @submit.prevent="form.submit"')
285
+ event.preventDefault?.()
286
+ return fromForm(el)
67
287
  }
288
+
68
289
  const form = reactive({
69
- data: copy(),
70
- errors: {},
290
+ data: clone(initial),
291
+ errors: {} as Record<string, string | undefined>,
71
292
  error: null as string | null,
72
293
  processing: false,
294
+ progress: null as Progress | null,
295
+ wasSuccessful: false,
296
+ recentlySuccessful: false,
73
297
  response: undefined as unknown,
74
- post: (url: string) => submit('POST', url),
75
- put: (url: string) => submit('PUT', url),
76
- patch: (url: string) => submit('PATCH', url),
77
- delete: (url: string) => submit('DELETE', url),
78
- reset() {
79
- form.data = copy() as never
80
- form.clearErrors()
298
+ validating: false,
299
+ touchedFields: {} as Record<string, true>,
300
+ validated: {} as Record<string, true>,
301
+ async validate(fields?: string | string[], event?: Event): Promise<boolean> {
302
+ const element = (event?.target as HTMLInputElement | null)?.form
303
+ if (element) target = fromForm(element)
304
+ const names = fields === undefined ? Object.keys(form.touchedFields) : Array.isArray(fields) ? fields : [fields]
305
+ if (!names.length) return true
306
+ form.touch(...names)
307
+ const mode = callbacks.validate ?? (callbacks.schema ? 'client' : 'server')
308
+ if (mode !== 'server' && callbacks.schema) {
309
+ const errors = inBrowser(names)
310
+ setFieldErrors(names, errors)
311
+ if (mode === 'client' || Object.keys(errors).length) return !Object.keys(errors).length
312
+ }
313
+ return onServer(names)
314
+ },
315
+ touch(...fields: string[]) {
316
+ for (const f of fields) form.touchedFields[f] = true
317
+ },
318
+ touched(field?: string) {
319
+ return field === undefined ? Object.keys(form.touchedFields).length > 0 : !!form.touchedFields[field]
320
+ },
321
+ valid(field: string) {
322
+ return !!form.touchedFields[field] && !!form.validated[field] && !form.invalid(field)
323
+ },
324
+ invalid(field: string) {
325
+ return Object.entries(form.errors).some(([key, text]) => !!text && matches(key, field))
326
+ },
327
+ get hasErrors(): boolean {
328
+ return Object.values(this.errors).some(Boolean)
329
+ },
330
+ get isDirty(): boolean {
331
+ return JSON.stringify(this.data) !== JSON.stringify(defaults)
332
+ },
333
+ submit(how?: Event | Method, url?: string | SubmitOptions<R>, options?: SubmitOptions<R>) {
334
+ if (how === undefined) {
335
+ if (!callbacks.action) throw new Error('form.submit() without arguments needs useForm(data, { action })')
336
+ return run(callbacks.method ?? 'post', callbacks.action)
337
+ }
338
+ if (typeof how === 'string') return run(how, url as string, options)
339
+ const [method, action] = fromEvent(how)
340
+ return run(method, action, url as SubmitOptions<R> | undefined)
341
+ },
342
+ get: (url: string, options?: SubmitOptions<R>) => run('GET', url, options),
343
+ post: (url: string, options?: SubmitOptions<R>) => run('POST', url, options),
344
+ put: (url: string, options?: SubmitOptions<R>) => run('PUT', url, options),
345
+ patch: (url: string, options?: SubmitOptions<R>) => run('PATCH', url, options),
346
+ delete: (url: string, options?: SubmitOptions<R>) => run('DELETE', url, options),
347
+ cancel() {
348
+ controller?.abort()
349
+ },
350
+ transform(fn: (data: UnwrapRef<F>) => Record<string, unknown>) {
351
+ transform = fn
352
+ return form
353
+ },
354
+ setError(field: string | Record<string, string>, message?: string) {
355
+ Object.assign(form.errors, typeof field === 'string' ? { [field]: message ?? '' } : field)
356
+ },
357
+ clearErrors(...fields: string[]) {
358
+ if (!fields.length) {
359
+ form.errors = {}
360
+ form.error = null
361
+ } else for (const f of fields) delete form.errors[f]
362
+ },
363
+ reset(...fields: string[]) {
364
+ const fresh = clone(defaults) as Record<string, unknown>
365
+ if (!fields.length) form.data = fresh as never
366
+ else for (const f of fields) (form.data as Record<string, unknown>)[f] = fresh[f]
367
+ form.clearErrors(...fields)
81
368
  },
82
- clearErrors() {
83
- form.errors = {}
84
- form.error = null
369
+ defaults(field?: string, value?: unknown) {
370
+ if (field === undefined) defaults = clone(form.data) as F
371
+ else
372
+ (defaults as Record<string, unknown>)[field] =
373
+ value === undefined ? clone((form.data as Record<string, unknown>)[field]) : value
85
374
  },
86
375
  })
87
376
  return form as unknown as Form<F, R>
@@ -0,0 +1,177 @@
1
+ /** `X-CSRF-Token` from the page's `<meta name="csrf-token">` (rendered by `<Assets>`), for hand-written `fetch`. */
2
+ export function csrfHeaders(): Record<string, string> {
3
+ if (typeof document === 'undefined') return {}
4
+ const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content')
5
+ return token ? { 'x-csrf-token': token } : {}
6
+ }
7
+
8
+ /** Sent with every request `useForm` and `http` make: `redirect()` then answers with the URL instead of a 3xx. */
9
+ export const REQUEST_HEADER = 'x-cslug-request'
10
+ /** Where `redirect()` sends the page, for a request from `useForm` / `http` (with a 204). */
11
+ export const REDIRECT_HEADER = 'x-cslug-redirect'
12
+
13
+ export type Progress = { loaded: number; total: number; percentage: number }
14
+
15
+ /** What a request returns: never throws for HTTP errors or network failures. */
16
+ export type HttpResult<T = unknown> = {
17
+ ok: boolean
18
+ /** 0 for a network failure or a cancelled request. */
19
+ status: number
20
+ /** The parsed JSON body of a successful response. */
21
+ data: T
22
+ /** First message per field of a 422 response. */
23
+ errors: Record<string, string>
24
+ /** A message for failures that are not field errors (network, 403, 419, 500). */
25
+ error: string | null
26
+ /** Where the server sent the page (`redirect()` on the server). */
27
+ redirect?: string
28
+ cancelled?: boolean
29
+ }
30
+
31
+ export type RequestOptions = {
32
+ headers?: Record<string, string>
33
+ /** Upload progress (requests with files). */
34
+ onProgress?: (progress: Progress) => void
35
+ signal?: AbortSignal
36
+ }
37
+
38
+ const isFile = (v: unknown): v is Blob => typeof Blob !== 'undefined' && v instanceof Blob
39
+ const hasFiles = (v: unknown): boolean =>
40
+ isFile(v) || (Array.isArray(v) ? v.some(hasFiles) : !!v && typeof v === 'object' && Object.values(v).some(hasFiles))
41
+
42
+ /**
43
+ * A multipart body with the server's key syntax (`a[b]`, `list[]`): what `request.body()` nests back. Lists of
44
+ * objects do not round-trip; keep requests with files flat.
45
+ */
46
+ export function toFormData(data: Record<string, unknown>): FormData {
47
+ const form = new FormData()
48
+ const add = (key: string, value: unknown) => {
49
+ if (value === undefined) return
50
+ if (isFile(value)) form.append(key, value)
51
+ else if (Array.isArray(value)) for (const item of value) add(`${key}[]`, item)
52
+ else if (value !== null && typeof value === 'object' && !(value instanceof Date))
53
+ for (const [k, v] of Object.entries(value)) add(`${key}[${k}]`, v)
54
+ else form.append(key, value === null ? '' : value instanceof Date ? value.toISOString() : String(value))
55
+ }
56
+ for (const [k, v] of Object.entries(data)) add(k, v)
57
+ return form
58
+ }
59
+
60
+ const errorsOf = (body: unknown): Record<string, string> => {
61
+ const errors = (body as { errors?: Record<string, string[] | string> } | undefined)?.errors ?? {}
62
+ return Object.fromEntries(Object.entries(errors).map(([k, m]) => [k, (Array.isArray(m) ? m[0] : m) ?? '']))
63
+ }
64
+
65
+ /** Upload with progress events (fetch has none). */
66
+ function xhrSend(
67
+ method: string,
68
+ url: string,
69
+ headers: Record<string, string>,
70
+ body: FormData,
71
+ options: RequestOptions,
72
+ ): Promise<Response> {
73
+ return new Promise((resolve, reject) => {
74
+ const xhr = new XMLHttpRequest()
75
+ xhr.open(method, url)
76
+ xhr.withCredentials = true
77
+ for (const [k, v] of Object.entries(headers)) xhr.setRequestHeader(k, v)
78
+ xhr.upload.onprogress = (e) =>
79
+ e.lengthComputable &&
80
+ options.onProgress?.({ loaded: e.loaded, total: e.total, percentage: Math.round((e.loaded / e.total) * 100) })
81
+ xhr.onload = () => {
82
+ const responseHeaders = new Headers()
83
+ for (const line of xhr
84
+ .getAllResponseHeaders()
85
+ .trim()
86
+ .split(/[\r\n]+/)) {
87
+ const at = line.indexOf(':')
88
+ if (at > 0) responseHeaders.append(line.slice(0, at).trim(), line.slice(at + 1).trim())
89
+ }
90
+ const status = xhr.status === 1223 ? 204 : xhr.status
91
+ resolve(
92
+ new Response([101, 204, 205, 304].includes(status) ? null : xhr.responseText, {
93
+ status,
94
+ headers: responseHeaders,
95
+ }),
96
+ )
97
+ }
98
+ xhr.onerror = () => reject(new TypeError('Network error'))
99
+ xhr.onabort = () => reject(new DOMException('Aborted', 'AbortError'))
100
+ options.signal?.addEventListener('abort', () => xhr.abort())
101
+ xhr.send(body)
102
+ })
103
+ }
104
+
105
+ /**
106
+ * Send a request as cslug's front end does: JSON (or multipart when the data holds a `File`), `Accept: JSON`, the
107
+ * CSRF token, the session cookie. 422 errors are mapped to fields; a server `redirect()` comes back as `redirect`.
108
+ */
109
+ export async function send<T = unknown>(
110
+ method: string,
111
+ url: string,
112
+ data?: Record<string, unknown>,
113
+ options: RequestOptions = {},
114
+ ): Promise<HttpResult<T>> {
115
+ const result = (patch: Partial<HttpResult<T>>): HttpResult<T> => ({
116
+ ok: false,
117
+ status: 0,
118
+ data: undefined as T,
119
+ errors: {},
120
+ error: null,
121
+ ...patch,
122
+ })
123
+ const upper = method.toUpperCase()
124
+ const bodyless = upper === 'GET' || upper === 'HEAD'
125
+ let target = url
126
+ if (bodyless && data && Object.keys(data).length) {
127
+ const query = new URLSearchParams()
128
+ for (const [k, v] of Object.entries(data))
129
+ if (v !== undefined && v !== null) for (const item of Array.isArray(v) ? v : [v]) query.append(k, String(item))
130
+ target += (url.includes('?') ? '&' : '?') + query
131
+ }
132
+ const withBody = !bodyless && !!data && (upper !== 'DELETE' || Object.keys(data).length > 0)
133
+ const files = withBody && hasFiles(data)
134
+ const headers: Record<string, string> = {
135
+ accept: 'application/json',
136
+ [REQUEST_HEADER]: '1',
137
+ ...(withBody && !files ? { 'content-type': 'application/json' } : {}),
138
+ ...csrfHeaders(),
139
+ ...options.headers,
140
+ }
141
+ const body = withBody ? (files ? toFormData(data as Record<string, unknown>) : JSON.stringify(data)) : undefined
142
+ try {
143
+ const res =
144
+ files && typeof XMLHttpRequest !== 'undefined'
145
+ ? await xhrSend(upper, target, headers, body as FormData, options)
146
+ : await fetch(target, { method: upper, credentials: 'same-origin', headers, body, signal: options.signal })
147
+ const redirect = res.headers.get(REDIRECT_HEADER) ?? undefined
148
+ const json = (res.headers.get('content-type') ?? '').includes('json')
149
+ ? await res.json().catch(() => undefined)
150
+ : undefined
151
+ if (res.ok) return result({ ok: true, status: res.status, data: json as T, ...(redirect ? { redirect } : {}) })
152
+ if (res.status === 422 && (json as { errors?: unknown } | undefined)?.errors)
153
+ return result({ status: 422, errors: errorsOf(json), error: null })
154
+ const problem = json as { detail?: string; title?: string } | undefined
155
+ return result({ status: res.status, error: problem?.detail ?? problem?.title ?? `${res.status} ${res.statusText}` })
156
+ } catch (e) {
157
+ if (e instanceof Error && e.name === 'AbortError') return result({ cancelled: true, error: null })
158
+ return result({ error: e instanceof Error ? e.message : String(e) })
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Requests that are not a form (a button, loading a list), with the same CSRF, JSON and error handling as
164
+ * `useForm`: `const { ok, data } = await http.get<Todo[]>(route('api.todos.index'))`. Never throws for HTTP errors.
165
+ */
166
+ export const http = {
167
+ get: <T = unknown>(url: string, query?: Record<string, unknown>, options?: RequestOptions) =>
168
+ send<T>('GET', url, query, options),
169
+ post: <T = unknown>(url: string, data?: Record<string, unknown>, options?: RequestOptions) =>
170
+ send<T>('POST', url, data ?? {}, options),
171
+ put: <T = unknown>(url: string, data?: Record<string, unknown>, options?: RequestOptions) =>
172
+ send<T>('PUT', url, data ?? {}, options),
173
+ patch: <T = unknown>(url: string, data?: Record<string, unknown>, options?: RequestOptions) =>
174
+ send<T>('PATCH', url, data ?? {}, options),
175
+ delete: <T = unknown>(url: string, data?: Record<string, unknown>, options?: RequestOptions) =>
176
+ send<T>('DELETE', url, data, options),
177
+ }