@tristan2828/ui-foundation 4.70.0 → 4.72.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.
@@ -0,0 +1,409 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Input } from '../ui/input.js';
3
+ import { InputGroup, InputGroupAddon, InputGroupInput, InputGroupText } from '../ui/input-group.js';
4
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select.js';
5
+ import { linkHost, linkRule } from '../../lib/link-href.js';
6
+ import { formatPlainDate } from '../../lib/plain-date.js';
7
+ import { DateField } from './date-field.js';
8
+ import { NONE, Parts, ReferencePicker } from './edit-in-place-controls.js';
9
+ import { LinkOut } from './row-edit-cells.js';
10
+ const REQUIRED = 'Required';
11
+ // The props every control spreads onto its element.
12
+ function controlAria(props) {
13
+ return {
14
+ 'aria-label': props.label,
15
+ 'aria-describedby': props.describedBy,
16
+ 'aria-invalid': props.invalid || undefined,
17
+ };
18
+ }
19
+ // ─── The kinds ──────────────────────────────────────────────────────────
20
+ const blank = (text) => text.trim() === '';
21
+ function textKind(config) {
22
+ return {
23
+ editKind: 'text',
24
+ toDraft: (value) => value ?? '',
25
+ check: (draft) => {
26
+ const text = draft.trim();
27
+ if (text === '')
28
+ return config.required ? { ok: false, message: REQUIRED } : { ok: true, value: null };
29
+ if (config.maxLength !== undefined && text.length > config.maxLength)
30
+ return { ok: false, message: `At most ${config.maxLength} characters` };
31
+ return { ok: true, value: text };
32
+ },
33
+ show: (value) => (value ? value : null),
34
+ control: (props) => (_jsx(Input, { id: props.id, value: props.value, placeholder: config.placeholder, readOnly: props.disabled, onChange: (event) => props.onChange(event.target.value), ...controlAria(props) })),
35
+ };
36
+ }
37
+ function numberKind(config) {
38
+ const format = new Intl.NumberFormat(config.locale);
39
+ return {
40
+ editKind: 'text',
41
+ toDraft: (value) => (value == null ? '' : String(value)),
42
+ check: (draft) => {
43
+ if (blank(draft))
44
+ return config.required ? { ok: false, message: REQUIRED } : { ok: true, value: null };
45
+ const typed = draft.trim().replace(/,/g, '');
46
+ const number = /^[-+]?(\d+\.?\d*|\.\d+)$/.test(typed) ? Number(typed) : Number.NaN;
47
+ if (!Number.isFinite(number))
48
+ return { ok: false, message: 'Enter a number' };
49
+ if (config.integer && !Number.isInteger(number))
50
+ return { ok: false, message: 'Enter a whole number' };
51
+ if (config.min !== undefined && number < config.min)
52
+ return { ok: false, message: `At least ${format.format(config.min)}` };
53
+ if (config.max !== undefined && number > config.max)
54
+ return { ok: false, message: `At most ${format.format(config.max)}` };
55
+ return { ok: true, value: number };
56
+ },
57
+ show: (value) => (value == null ? null : config.unit ? `${format.format(value)} ${config.unit}` : format.format(value)),
58
+ control: (props) => {
59
+ const input = {
60
+ id: props.id,
61
+ inputMode: config.integer && (config.min ?? 0) >= 0 ? 'numeric' : 'decimal',
62
+ value: props.value,
63
+ placeholder: config.placeholder,
64
+ readOnly: props.disabled,
65
+ onChange: (event) => props.onChange(event.target.value),
66
+ ...controlAria(props),
67
+ };
68
+ if (!config.unit)
69
+ return _jsx(Input, { ...input });
70
+ return (_jsxs(InputGroup, { children: [_jsx(InputGroupInput, { ...input }), _jsx(InputGroupAddon, { align: "inline-end", children: _jsx(InputGroupText, { children: config.unit }) })] }));
71
+ },
72
+ };
73
+ }
74
+ const MONEY = /^(-)?(\d+)(?:\.(\d{0,2}))?$/;
75
+ function moneyKind(config) {
76
+ const locale = config.locale ?? 'en-US';
77
+ const currency = config.currency ?? 'USD';
78
+ const money = new Intl.NumberFormat(locale, { style: 'currency', currency });
79
+ const symbol = money.formatToParts(0).find((part) => part.type === 'currency')?.value ?? currency;
80
+ const min = config.min ?? 0;
81
+ return {
82
+ editKind: 'text',
83
+ toDraft: (value) => {
84
+ if (value == null || value === '')
85
+ return '';
86
+ const number = Number(value);
87
+ return Number.isFinite(number) ? number.toFixed(2) : String(value);
88
+ },
89
+ check: (draft) => {
90
+ if (blank(draft))
91
+ return config.required ? { ok: false, message: REQUIRED } : { ok: true, value: null };
92
+ // `$1,234.5` is 1234.50: the symbol, spaces and separators go.
93
+ const typed = draft.replaceAll(symbol, '').replace(/[\s,]/g, '');
94
+ const match = MONEY.exec(typed);
95
+ if (!match)
96
+ return { ok: false, message: 'Enter an amount, like 12.50' };
97
+ // Built from the digits, never through a float: 0.1 + 0.2 stays 0.30.
98
+ const amount = `${match[1] ?? ''}${String(Number(match[2]))}.${(match[3] ?? '').padEnd(2, '0')}`;
99
+ const number = Number(amount);
100
+ if (number < min)
101
+ return { ok: false, message: `At least ${money.format(min)}` };
102
+ if (config.max !== undefined && number > config.max)
103
+ return { ok: false, message: `At most ${money.format(config.max)}` };
104
+ return { ok: true, value: amount === '-0.00' ? '0.00' : amount };
105
+ },
106
+ show: (value) => {
107
+ if (value == null || value === '')
108
+ return null;
109
+ const number = Number(value);
110
+ return Number.isFinite(number) ? money.format(number) : String(value);
111
+ },
112
+ control: (props) => (_jsxs(InputGroup, { children: [_jsx(InputGroupAddon, { children: _jsx(InputGroupText, { children: symbol }) }), _jsx(InputGroupInput, { id: props.id, inputMode: "decimal", value: props.value, placeholder: config.placeholder ?? '0.00', readOnly: props.disabled, onChange: (event) => props.onChange(event.target.value), ...controlAria(props) })] })),
113
+ };
114
+ }
115
+ function dateKind(config) {
116
+ return {
117
+ editKind: 'choice',
118
+ toDraft: (value) => value ?? '',
119
+ check: (draft) => {
120
+ if (draft === '')
121
+ return config.required ? { ok: false, message: REQUIRED } : { ok: true, value: null };
122
+ return formatPlainDate(draft) === '' ? { ok: false, message: 'Pick a date' } : { ok: true, value: draft };
123
+ },
124
+ show: (value) => (value ? formatPlainDate(value, config.format, config.locale) || value : null),
125
+ control: (props, alone) => (_jsx(DateField, { id: props.id, value: props.value,
126
+ // Alone, a pick saves and the calendar opens with the field; closing
127
+ // it with nothing picked gives up (a pick has already saved by then).
128
+ onChange: alone ? (day) => props.commit(day) : props.onChange, clearable: !config.required, placeholder: config.placeholder, format: config.format, locale: config.locale, invalid: props.invalid, readOnly: props.disabled, defaultOpen: alone, modal: alone ? false : undefined, onOpenChange: alone
129
+ ? (open) => {
130
+ if (!open)
131
+ props.cancel();
132
+ }
133
+ : undefined, "aria-label": props.label, "aria-describedby": props.describedBy })),
134
+ };
135
+ }
136
+ function selectKind(config) {
137
+ const labelOf = (value) => config.options.find((option) => option.value === value)?.label ?? String(value);
138
+ const shownOf = (value) => (config.render ? config.render(value, labelOf(value)) : labelOf(value));
139
+ const keyOf = (value) => {
140
+ const at = value == null ? -1 : config.options.findIndex((option) => option.value === value);
141
+ return at === -1 ? null : String(at);
142
+ };
143
+ const valueOf = (key) => (key === null || key === NONE ? null : (config.options[Number(key)]?.value ?? null));
144
+ const emptyLabel = config.emptyLabel ?? 'Not set';
145
+ return {
146
+ editKind: 'choice',
147
+ toDraft: (value) => value,
148
+ check: (draft) => (draft == null && config.required ? { ok: false, message: REQUIRED } : { ok: true, value: draft }),
149
+ show: (value) => (value == null ? null : shownOf(value)),
150
+ control: (props, alone) => (_jsxs(Select, { value: keyOf(props.value) ?? (config.required ? null : NONE), onValueChange: (key) => {
151
+ if (key === null)
152
+ return;
153
+ const picked = valueOf(key);
154
+ if (alone)
155
+ props.commit(picked);
156
+ else
157
+ props.onChange(picked);
158
+ }, disabled: props.disabled, defaultOpen: alone, modal: false, onOpenChange: alone
159
+ ? (open) => {
160
+ if (!open)
161
+ props.cancel();
162
+ }
163
+ : undefined, children: [_jsx(SelectTrigger, { id: props.id, className: "min-w-40", ...controlAria(props), children: _jsx(SelectValue, { placeholder: config.placeholder ?? 'Pick one', children: (key) => {
164
+ const value = valueOf(key);
165
+ return value == null ? (key === NONE ? emptyLabel : (config.placeholder ?? 'Pick one')) : shownOf(value);
166
+ } }) }), _jsxs(SelectContent, { children: [!config.required && _jsx(SelectItem, { value: NONE, children: emptyLabel }), config.options.map((option, index) => (_jsx(SelectItem, { value: String(index), children: shownOf(option.value) }, String(option.value))))] })] })),
167
+ };
168
+ }
169
+ function referenceKind(config) {
170
+ return {
171
+ editKind: 'choice',
172
+ toDraft: (value) => value,
173
+ check: (draft) => (draft == null && config.required ? { ok: false, message: REQUIRED } : { ok: true, value: draft }),
174
+ show: (value) => (value == null ? null : (config.label ?? String(value))),
175
+ control: (props, alone) => _jsx(ReferencePicker, { props: props, alone: alone, config: config }),
176
+ };
177
+ }
178
+ // A link's address: `linkRule` (LinkCell's), which also says what's refused.
179
+ function urlKind(config) {
180
+ return {
181
+ editKind: 'text',
182
+ toDraft: (value) => value ?? '',
183
+ check: (draft) => {
184
+ const result = linkRule.safeParse(draft);
185
+ return result.success ? { ok: true, value: result.data } : { ok: false, message: result.error.issues[0].message };
186
+ },
187
+ show: (value) => value,
188
+ control: (props) => (_jsx(Input, { id: props.id, type: "url", inputMode: "url", value: props.value, placeholder: config.placeholder ?? 'https://', readOnly: props.disabled, onChange: (event) => props.onChange(event.target.value), ...controlAria(props) })),
189
+ };
190
+ }
191
+ function kindOf(part) {
192
+ switch (part.kind) {
193
+ case 'text':
194
+ return textKind(part);
195
+ case 'number':
196
+ return numberKind(part);
197
+ case 'money':
198
+ return moneyKind(part);
199
+ case 'date':
200
+ return dateKind(part);
201
+ case 'select':
202
+ return selectKind(part);
203
+ case 'reference':
204
+ return referenceKind(part);
205
+ }
206
+ }
207
+ // ─── A field of one kind ────────────────────────────────────────────────
208
+ // Two drafts are the same value when both check to the same thing (`12`
209
+ // and `12.0`, `$5` and `5.00`), else when they're the same text.
210
+ function sameValue(check) {
211
+ return (a, b) => {
212
+ const [left, right] = [check(a), check(b)];
213
+ if (left.ok && right.ok)
214
+ return JSON.stringify(left.value) === JSON.stringify(right.value);
215
+ return JSON.stringify(a) === JSON.stringify(b);
216
+ };
217
+ }
218
+ function single(kind, options) {
219
+ return {
220
+ kind: kind.editKind,
221
+ value: kind.toDraft(options.value),
222
+ control: (props) => kind.control(props, true),
223
+ schema: {
224
+ safeParse: (draft) => {
225
+ const checked = kind.check(draft);
226
+ return checked.ok ? { success: true, data: checked.value } : { success: false, error: { issues: [{ message: checked.message }] } };
227
+ },
228
+ },
229
+ save: options.save,
230
+ isEqual: sameValue(kind.check),
231
+ shown: options.shown !== undefined ? options.shown : kind.show(options.value),
232
+ };
233
+ }
234
+ // Which parts a refusal names: the check's issues (each part's own, by
235
+ // its key), or a 422's field errors (`model`, `effort.level`).
236
+ function partErrors(keys, cause) {
237
+ const errors = {};
238
+ if (cause && typeof cause === 'object' && 'issues' in cause) {
239
+ for (const issue of cause.issues) {
240
+ const key = issue.path?.[0];
241
+ if (typeof key === 'string' && keys.includes(key) && !(key in errors))
242
+ errors[key] = issue.message;
243
+ }
244
+ }
245
+ else if (cause && typeof cause === 'object' && 'kind' in cause) {
246
+ for (const [field, messages] of Object.entries(cause.fieldErrors ?? {})) {
247
+ const key = keys.find((name) => field === name || field.startsWith(`${name}.`));
248
+ if (key && !(key in errors) && messages[0])
249
+ errors[key] = messages[0];
250
+ }
251
+ }
252
+ return Object.keys(errors).length > 0 ? errors : null;
253
+ }
254
+ function fieldsInPlace(options) {
255
+ const keys = Object.keys(options.fields);
256
+ const parts = options.fields;
257
+ const kinds = Object.fromEntries(keys.map((key) => [key, kindOf(parts[key])]));
258
+ const value = options.value;
259
+ const check = (draft) => {
260
+ const issues = [];
261
+ const checked = {};
262
+ for (const key of keys) {
263
+ const result = kinds[key].check(draft[key]);
264
+ if (result.ok)
265
+ checked[key] = result.value;
266
+ else
267
+ issues.push({ message: `${parts[key].label}: ${result.message}`, path: [key] });
268
+ }
269
+ if (issues.length > 0)
270
+ return { ok: false, message: issues[0].message, issues };
271
+ const message = options.rule?.(checked) ?? null;
272
+ return message === null ? { ok: true, value: checked } : { ok: false, message, issues: [{ message }] };
273
+ };
274
+ // Enter saves when every part is typed into; with a list among them,
275
+ // Enter is the list's, and leaving or Ctrl/Cmd+Enter saves.
276
+ const typed = keys.every((key) => kinds[key].editKind === 'text');
277
+ const shownParts = keys.map((key) => kinds[key].show(value[key])).filter((shown) => shown !== null && shown !== '');
278
+ return {
279
+ kind: typed ? 'text' : 'multi',
280
+ value: Object.fromEntries(keys.map((key) => [key, kinds[key].toDraft(value[key])])),
281
+ control: (props) => (_jsx(Parts, { props: props, keys: keys, parts: parts, kinds: kinds })),
282
+ schema: {
283
+ safeParse: (draft) => {
284
+ const result = check(draft);
285
+ return result.ok ? { success: true, data: result.value } : { success: false, error: { issues: result.issues ?? [] } };
286
+ },
287
+ },
288
+ save: options.save,
289
+ isEqual: sameValue((draft) => {
290
+ const checked = {};
291
+ for (const key of keys) {
292
+ const result = kinds[key].check(draft[key]);
293
+ if (!result.ok)
294
+ return result;
295
+ checked[key] = result.value;
296
+ }
297
+ return { ok: true, value: checked };
298
+ }),
299
+ fieldErrors: (cause) => partErrors(keys, cause),
300
+ errorsOnFields: true,
301
+ shown: options.shown !== undefined
302
+ ? options.shown
303
+ : shownParts.length === 0
304
+ ? null
305
+ : shownParts.map((shown, index) => (_jsxs("span", { children: [index > 0 && ' · ', shown] }, index))),
306
+ };
307
+ }
308
+ // ─── A link ─────────────────────────────────────────────────────────────
309
+ function linkInPlace(options) {
310
+ const { url, label } = options.value;
311
+ const href = url ? linkRule.safeParse(url) : null;
312
+ // Only an address the box would have saved is a link: a stored
313
+ // `javascript:` reads as text, never as something to click.
314
+ const shown = options.shown !== undefined
315
+ ? options.shown
316
+ : !url
317
+ ? (options.emptyLabel ? _jsx("span", { className: "text-muted-foreground", children: options.emptyLabel }) : null)
318
+ : href?.success && href.data
319
+ ? _jsx(LinkOut, { href: href.data, children: label || linkHost(href.data) })
320
+ : url;
321
+ const urls = urlKind(options);
322
+ const labels = textKind({ placeholder: 'Label (optional)' });
323
+ const kinds = { url: urls, label: labels };
324
+ const parts = {
325
+ url: { kind: 'text', label: 'URL' },
326
+ label: { kind: 'text', label: 'Label' },
327
+ };
328
+ const check = (draft) => {
329
+ const address = urls.check(draft.url);
330
+ if (!address.ok)
331
+ return { success: false, error: { issues: [{ message: address.message, path: ['url'] }] } };
332
+ const words = labels.check(draft.label);
333
+ if (!words.ok)
334
+ return { success: false, error: { issues: [{ message: words.message, path: ['label'] }] } };
335
+ if (address.value === null && words.value !== null)
336
+ return { success: false, error: { issues: [{ message: 'Add the address, or clear the label', path: ['url'] }] } };
337
+ return { success: true, data: { url: address.value, label: words.value } };
338
+ };
339
+ return {
340
+ // Enter in either box saves, as a one-line field does.
341
+ kind: 'text',
342
+ value: { url: url ?? '', label: label ?? '' },
343
+ control: (props) => (_jsx(Parts, { props: props, keys: ['url', 'label'], parts: parts, kinds: kinds })),
344
+ save: options.save,
345
+ fieldErrors: (cause) => partErrors(['url', 'label'], cause),
346
+ errorsOnFields: true,
347
+ schema: { safeParse: (draft) => check(draft) },
348
+ isEqual: (a, b) => {
349
+ const [left, right] = [check(a), check(b)];
350
+ if (left.success && right.success)
351
+ return JSON.stringify(left.data) === JSON.stringify(right.data);
352
+ return JSON.stringify(a) === JSON.stringify(b);
353
+ },
354
+ shown,
355
+ };
356
+ }
357
+ // ─── The presets ────────────────────────────────────────────────────────
358
+ /**
359
+ * Ready-made fields for editing in place, one per kind of control. Each
360
+ * returns an `EditInPlace` carrying its control, its check and how it
361
+ * reads at rest (`shown`), so a field is one line:
362
+ * `{ label: 'Due', edit: inPlace.date({ value: task.due, save: (due) => save({ due }) }) }`.
363
+ */
364
+ export const inPlace = {
365
+ /** One line of text; Enter saves. Trimmed; blank saves `null` unless `required`. */
366
+ text(options) {
367
+ return single(textKind(options), { ...options, value: options.value ?? null });
368
+ },
369
+ /** A number in one line, checked against `min`, `max` and `integer`; `unit` reads after it. */
370
+ number(options) {
371
+ return single(numberKind(options), { ...options, value: options.value ?? null });
372
+ },
373
+ /** Money, two decimals, saved as the decimal string (`"1234.50"`), shown as "$1,234.50". */
374
+ money(options) {
375
+ return single(moneyKind(options), { ...options, value: options.value ?? null });
376
+ },
377
+ /** A plain day (`'YYYY-MM-DD'`) in DateField's calendar, which opens with the field; a pick saves. */
378
+ date(options) {
379
+ return single(dateKind(options), { ...options, value: options.value || null });
380
+ },
381
+ /** One of a fixed list; its list opens with the field and a pick saves. */
382
+ select(options) {
383
+ return single(selectKind(options), { ...options, value: options.value ?? null });
384
+ },
385
+ /** Another record, searched as you type through the app's `search`; a pick saves its id. */
386
+ reference(options) {
387
+ return single(referenceKind(options), { ...options, value: options.value ?? null });
388
+ },
389
+ /**
390
+ * A link: at rest its label (or the address's host when it has none),
391
+ * opening in a new tab; edited as two boxes, URL and an optional Label,
392
+ * saved together as `{ url, label }`. The address is checked by
393
+ * `linkRule` (LinkCell's): `example.com` gains https://, another scheme
394
+ * is refused. A blank address with no label saves `{ url: null, label: null }`.
395
+ */
396
+ link(options) {
397
+ return linkInPlace(options);
398
+ },
399
+ /**
400
+ * Two or more fields edited as one value and saved together, with a
401
+ * `rule` across them: each part its own control and label, a part's
402
+ * refusal (its own check, or a 422 naming its field) under it, the
403
+ * rule's under them all. Saves on leaving it or Ctrl/Cmd+Enter (and on
404
+ * Enter when every part is typed into).
405
+ */
406
+ fields(options) {
407
+ return fieldsInPlace(options);
408
+ },
409
+ };
@@ -25,6 +25,13 @@ export type EditFieldConfig = {
25
25
  autosave?: boolean;
26
26
  /** Always open: the control is the value, with no click to open. Autosaves. */
27
27
  alwaysEditable?: boolean;
28
+ /**
29
+ * Which of the value's own fields a refusal is about: given the schema's
30
+ * error (`{ issues }`) or the save's rejection (the AppError), the
31
+ * message for each field it names, keyed by the field's path inside the
32
+ * value (`text`, `effort`). `null` or `{}` when it names none.
33
+ */
34
+ fieldErrors?: (cause: unknown) => Record<string, string> | null;
28
35
  };
29
36
  export type EditFieldState = {
30
37
  status: 'closed';
@@ -39,6 +46,8 @@ export type OpenFieldState = {
39
46
  error: string | null;
40
47
  /** A problem the control reports itself (rich text that can't save as it stands). */
41
48
  problem: string | null;
49
+ /** The refusal's messages for the value's own fields (`fieldErrors`), shown on those fields. */
50
+ fieldErrors?: Record<string, string> | null;
42
51
  /**
43
52
  * An autosaving field's save: in flight (the control stays editable),
44
53
  * or done with nothing typed since. Absent otherwise.
@@ -11,6 +11,11 @@ export function messageOf(error) {
11
11
  return error.message;
12
12
  return 'The save failed. Try again.';
13
13
  }
14
+ // The refusal's messages for the value's own fields, or null for none.
15
+ function fieldErrorsOf(config, cause) {
16
+ const found = config?.fieldErrors?.(cause);
17
+ return found && Object.keys(found).length > 0 ? found : undefined;
18
+ }
14
19
  export class EditInPlaceStore {
15
20
  configs = new Map();
16
21
  states = new Map();
@@ -210,17 +215,18 @@ export class EditInPlaceStore {
210
215
  }
211
216
  const parsed = config.schema ? config.schema.safeParse(open.draft) : { success: true, data: open.draft };
212
217
  if (!parsed.success) {
213
- this.set(key, { ...open, error: parsed.error.issues[0]?.message ?? 'Check this value.' });
218
+ const fieldErrors = fieldErrorsOf(config, parsed.error);
219
+ this.set(key, { ...open, error: parsed.error.issues[0]?.message ?? 'Check this value.', fieldErrors });
214
220
  return Promise.resolve(false);
215
221
  }
216
- this.set(key, { ...open, status: 'saving', error: null });
222
+ this.set(key, { ...open, status: 'saving', error: null, fieldErrors: undefined });
217
223
  const save = config
218
224
  .save(parsed.data)
219
225
  .then(() => {
220
226
  this.set(key, CLOSED);
221
227
  return true;
222
228
  }, (error) => {
223
- this.set(key, { ...open, status: 'open', error: messageOf(error) });
229
+ this.set(key, { ...open, status: 'open', error: messageOf(error), fieldErrors: fieldErrorsOf(config, error) });
224
230
  return false;
225
231
  })
226
232
  .finally(() => this.saving.delete(key));
@@ -296,24 +302,25 @@ export class EditInPlaceStore {
296
302
  }
297
303
  const parsed = config.schema ? config.schema.safeParse(state.draft) : { success: true, data: state.draft };
298
304
  if (!parsed.success) {
299
- this.set(key, { ...state, error: parsed.error.issues[0]?.message ?? 'Check this value.' });
305
+ const fieldErrors = fieldErrorsOf(config, parsed.error);
306
+ this.set(key, { ...state, error: parsed.error.issues[0]?.message ?? 'Check this value.', fieldErrors });
300
307
  return Promise.resolve(false);
301
308
  }
302
309
  const sent = state.draft;
303
- this.set(key, { ...state, error: null, autosave: 'saving' });
310
+ this.set(key, { ...state, error: null, fieldErrors: undefined, autosave: 'saving' });
304
311
  const promise = config
305
312
  .save(parsed.data)
306
313
  .then(() => {
307
314
  const now = this.state(key);
308
315
  if (now.status === 'open') {
309
316
  const status = isEqual(now.draft, sent) ? 'saved' : this.queued.has(key) ? 'saving' : undefined;
310
- this.set(key, { ...now, initial: sent, error: null, autosave: status });
317
+ this.set(key, { ...now, initial: sent, error: null, fieldErrors: undefined, autosave: status });
311
318
  }
312
319
  return true;
313
320
  }, (error) => {
314
321
  const now = this.state(key);
315
322
  if (now.status === 'open')
316
- this.set(key, { ...now, error: messageOf(error), autosave: undefined });
323
+ this.set(key, { ...now, error: messageOf(error), fieldErrors: fieldErrorsOf(config, error), autosave: undefined });
317
324
  return false;
318
325
  })
319
326
  .finally(() => this.autosaving.delete(key));
@@ -1,4 +1,5 @@
1
1
  import { type ReactNode } from 'react';
2
+ import type { FieldValues, UseFormReturn } from 'react-hook-form';
2
3
  import type { EditInPlaceStore } from './edit-in-place-store.js';
3
4
  /** What an editable value's control is given. Spread what applies onto the form's own control. */
4
5
  export type EditControlProps<TDraft> = {
@@ -29,6 +30,12 @@ export type EditControlProps<TDraft> = {
29
30
  * Give it to RichTextEditor's `inline` (with `toolbar="floating"`).
30
31
  */
31
32
  inline?: boolean;
33
+ /**
34
+ * A refusal's messages about the value's own fields (`fieldErrors`),
35
+ * keyed by each field's path inside the value (`text`, `effort`). Show
36
+ * each on its field (`aria-invalid`, the message under it).
37
+ */
38
+ errors?: Readonly<Record<string, string>>;
32
39
  };
33
40
  /**
34
41
  * How the value saves, which follows from its control:
@@ -53,7 +60,7 @@ type SafeParseResult<TValue> = {
53
60
  }[];
54
61
  };
55
62
  };
56
- /** A field marked editable. Make one with `editInPlace({...})`. */
63
+ /** A field marked editable. Make one with `editInPlace({...})`, or a ready-made one with `inPlace`. */
57
64
  export type EditInPlace = {
58
65
  kind: EditKind;
59
66
  value: unknown;
@@ -66,6 +73,9 @@ export type EditInPlace = {
66
73
  autosave?: boolean;
67
74
  alwaysEditable?: boolean;
68
75
  inline?: boolean;
76
+ shown?: ReactNode;
77
+ fieldErrors?: (cause: unknown) => Record<string, string> | null;
78
+ errorsOnFields?: boolean;
69
79
  };
70
80
  export type EditInPlaceOptions<TDraft, TValue> = {
71
81
  kind: EditKind;
@@ -115,6 +125,24 @@ export type EditInPlaceOptions<TDraft, TValue> = {
115
125
  * shows the editor's `placeholder`, not the view's "Not set".
116
126
  */
117
127
  inline?: boolean;
128
+ /**
129
+ * How the value reads at rest, for a field that gives no `value` of its
130
+ * own (EntityView's field, EditableValue's children). The `inPlace`
131
+ * presets set it. `null` reads as the field's "Not set".
132
+ */
133
+ shown?: ReactNode;
134
+ /**
135
+ * Which of the value's own fields a refusal is about, for a value made of
136
+ * several (a pair saved as one): given the schema's error (`{ issues }`)
137
+ * or the save's rejection (the AppError), each field's message keyed by
138
+ * its path inside the value. The control gets them as `errors`.
139
+ */
140
+ fieldErrors?: (cause: unknown) => Record<string, string> | null;
141
+ /**
142
+ * The control shows `errors` on its own fields, so a refusal about one
143
+ * of them isn't repeated under the control; one about none still shows there.
144
+ */
145
+ errorsOnFields?: boolean;
118
146
  };
119
147
  /** What a list item's fields are given while it's edited: a control's props, plus where the item is. */
120
148
  export type EditListItemProps<TItem> = EditControlProps<TItem> & {
@@ -122,6 +150,16 @@ export type EditListItemProps<TItem> = EditControlProps<TItem> & {
122
150
  index: number;
123
151
  /** The item being added at the end, not one already in the list. */
124
152
  isNew: boolean;
153
+ /**
154
+ * With the list's `itemForm`: a react-hook-form form holding the list
155
+ * under its `name`, the draft at `index`, so the form's own row works
156
+ * here unchanged (`form.register('checklist.2.text')` for item 2, a
157
+ * `Controller` on `form.control`, its errors in `form.formState.errors`).
158
+ * Every change to it is the item's draft.
159
+ */
160
+ form?: UseFormReturn<FieldValues>;
161
+ /** With `groupBy`: the group the item being added goes in (what its "Add" was under). */
162
+ group?: string;
125
163
  };
126
164
  /** What a list's own `add` is given: how to put new items at the end, saved as the list's other changes are. */
127
165
  export type EditListAddProps<TItem> = {
@@ -162,8 +200,12 @@ export type EditInPlaceListOptions<TItem> = {
162
200
  renderItem: (props: EditListItemProps<TItem>) => ReactNode;
163
201
  /** How the item reads when it isn't being edited. Its own controls (a done box) keep working. */
164
202
  renderShown: (item: TItem, index: number) => ReactNode;
165
- /** A blank item, what "Add" starts from. Not needed with `add`; one or the other is. */
166
- newItem?: () => TItem;
203
+ /**
204
+ * A blank item, what "Add" starts from. Not needed with `add`; one or
205
+ * the other is. With `groupBy`, each group has its own Add, given that
206
+ * group's key (`(room) => ({ text: '', room })`).
207
+ */
208
+ newItem?: (group?: string) => TItem;
167
209
  /**
168
210
  * In place of "Add" and its blank item: what adds items, such as a file
169
211
  * upload or a picker, e.g. a button that uploads, then calls
@@ -191,9 +233,57 @@ export type EditInPlaceListOptions<TItem> = {
191
233
  * Rejects with the AppError; a 422's message shows where the change was made.
192
234
  */
193
235
  save: (change: (current: TItem[]) => TItem[]) => Promise<unknown>;
236
+ /**
237
+ * Shows the items under headings, by one of their fields (a room, a
238
+ * day): each group its own list with its own move buttons (an item moves
239
+ * past the group's next item, never into another group) and its own Add.
240
+ * The list still saves as one, in its own order.
241
+ */
242
+ groupBy?: {
243
+ /** The item's group. */
244
+ key: (item: TItem) => string;
245
+ /** The group's heading. Defaults to its key. */
246
+ label?: (key: string) => string;
247
+ /**
248
+ * The groups in this order, each shown even with no items (so its Add
249
+ * is there). Groups not named follow, in the order their first item comes.
250
+ */
251
+ order?: readonly string[];
252
+ };
253
+ /**
254
+ * Shows only the items this keeps (the view's filter, a pill's value).
255
+ * The others stay in the list as they are: a move passes over them, a
256
+ * save keeps them. A new item that this drops goes out of sight once saved.
257
+ */
258
+ filter?: (item: TItem, index: number) => boolean;
259
+ /**
260
+ * Puts a Duplicate button beside Remove ("Duplicate item 2"), as on the
261
+ * form's ListEditor: the copy this makes of an item goes right after it,
262
+ * saved as a move is. Leave out what a copy mustn't share (a saved id).
263
+ */
264
+ duplicate?: (item: TItem) => TItem;
265
+ /**
266
+ * The list's field name on the record (`checklist`). A refusal from the
267
+ * server about an item's field (a 422 at `checklist.2.text`) is then
268
+ * given to that item's row as `errors.text`. Needed by `itemForm`.
269
+ */
270
+ name?: string;
271
+ /**
272
+ * The row shows `props.errors` on its own fields (the schema's and the
273
+ * server's), so they aren't repeated under the row; a message about no
274
+ * one field still shows there. Implied by `itemForm`.
275
+ */
276
+ errorsOnFields?: boolean;
277
+ /**
278
+ * The row is the form's react-hook-form row: `renderItem` gets `form`, a
279
+ * form of the list under `name`, so the row registers its fields as on
280
+ * the form and shows their errors (the schema's and a 422's, set on it
281
+ * with `setError`) as the form does. No form of the app's own per item.
282
+ */
283
+ itemForm?: boolean;
194
284
  };
195
285
  /** A list marked editable in place. Make one with `editInPlace({ kind: 'list', ... })`. */
196
- export type EditInPlaceList = Omit<EditInPlaceListOptions<unknown>, 'renderItem' | 'renderShown' | 'schema' | 'save' | 'add'> & {
286
+ export type EditInPlaceList = Omit<EditInPlaceListOptions<unknown>, 'renderItem' | 'renderShown' | 'schema' | 'save' | 'add' | 'groupBy' | 'filter' | 'duplicate'> & {
197
287
  add?: (props: EditListAddProps<unknown>) => ReactNode;
198
288
  renderItem: (props: EditListItemProps<unknown>) => ReactNode;
199
289
  renderShown: (item: unknown, index: number) => ReactNode;
@@ -201,6 +291,13 @@ export type EditInPlaceList = Omit<EditInPlaceListOptions<unknown>, 'renderItem'
201
291
  safeParse: (value: unknown) => SafeParseResult<unknown[]>;
202
292
  };
203
293
  save: (change: (current: unknown[]) => unknown[]) => Promise<unknown>;
294
+ groupBy?: {
295
+ key: (item: unknown) => string;
296
+ label?: (key: string) => string;
297
+ order?: readonly string[];
298
+ };
299
+ filter?: (item: unknown, index: number) => boolean;
300
+ duplicate?: (item: unknown) => unknown;
204
301
  };
205
302
  /** Marks a list editable in place: its items added, edited, removed and moved on the view. */
206
303
  export declare function editInPlace<TItem>(options: EditInPlaceListOptions<TItem>): EditInPlaceList;