@latticecms/admin 0.0.0 → 0.1.1

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.
Files changed (134) hide show
  1. package/README.md +166 -2
  2. package/dist/admin.css +2 -0
  3. package/dist/admin.d.ts +18 -0
  4. package/dist/admin.d.ts.map +1 -0
  5. package/dist/admin.js +92 -0
  6. package/dist/admin.js.map +1 -0
  7. package/dist/catalog.d.ts +45 -0
  8. package/dist/catalog.d.ts.map +1 -0
  9. package/dist/catalog.js +147 -0
  10. package/dist/catalog.js.map +1 -0
  11. package/dist/collections.d.ts +54 -0
  12. package/dist/collections.d.ts.map +1 -0
  13. package/dist/collections.js +103 -0
  14. package/dist/collections.js.map +1 -0
  15. package/dist/confirm.d.ts +16 -0
  16. package/dist/confirm.d.ts.map +1 -0
  17. package/dist/confirm.js +10 -0
  18. package/dist/confirm.js.map +1 -0
  19. package/dist/data.d.ts +28 -0
  20. package/dist/data.d.ts.map +1 -0
  21. package/dist/data.js +55 -0
  22. package/dist/data.js.map +1 -0
  23. package/dist/delete-action.d.ts +10 -0
  24. package/dist/delete-action.d.ts.map +1 -0
  25. package/dist/delete-action.js +44 -0
  26. package/dist/delete-action.js.map +1 -0
  27. package/dist/detail-page.d.ts +12 -0
  28. package/dist/detail-page.d.ts.map +1 -0
  29. package/dist/detail-page.js +65 -0
  30. package/dist/detail-page.js.map +1 -0
  31. package/dist/document-table.d.ts +17 -0
  32. package/dist/document-table.d.ts.map +1 -0
  33. package/dist/document-table.js +41 -0
  34. package/dist/document-table.js.map +1 -0
  35. package/dist/filters.d.ts +18 -0
  36. package/dist/filters.d.ts.map +1 -0
  37. package/dist/filters.js +149 -0
  38. package/dist/filters.js.map +1 -0
  39. package/dist/form.d.ts +80 -0
  40. package/dist/form.d.ts.map +1 -0
  41. package/dist/form.js +318 -0
  42. package/dist/form.js.map +1 -0
  43. package/dist/index-page.d.ts +3 -0
  44. package/dist/index-page.d.ts.map +1 -0
  45. package/dist/index-page.js +11 -0
  46. package/dist/index-page.js.map +1 -0
  47. package/dist/index.d.ts +2 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +2 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/labels.d.ts +13 -0
  52. package/dist/labels.d.ts.map +1 -0
  53. package/dist/labels.js +33 -0
  54. package/dist/labels.js.map +1 -0
  55. package/dist/list-page.d.ts +25 -0
  56. package/dist/list-page.d.ts.map +1 -0
  57. package/dist/list-page.js +82 -0
  58. package/dist/list-page.js.map +1 -0
  59. package/dist/list-state.d.ts +17 -0
  60. package/dist/list-state.d.ts.map +1 -0
  61. package/dist/list-state.js +39 -0
  62. package/dist/list-state.js.map +1 -0
  63. package/dist/method-action.d.ts +16 -0
  64. package/dist/method-action.d.ts.map +1 -0
  65. package/dist/method-action.js +78 -0
  66. package/dist/method-action.js.map +1 -0
  67. package/dist/model.d.ts +11 -0
  68. package/dist/model.d.ts.map +1 -0
  69. package/dist/model.js +16 -0
  70. package/dist/model.js.map +1 -0
  71. package/dist/ref-picker.d.ts +24 -0
  72. package/dist/ref-picker.d.ts.map +1 -0
  73. package/dist/ref-picker.js +77 -0
  74. package/dist/ref-picker.js.map +1 -0
  75. package/dist/refusal-alert.d.ts +12 -0
  76. package/dist/refusal-alert.d.ts.map +1 -0
  77. package/dist/refusal-alert.js +87 -0
  78. package/dist/refusal-alert.js.map +1 -0
  79. package/dist/refusal.d.ts +20 -0
  80. package/dist/refusal.d.ts.map +1 -0
  81. package/dist/refusal.js +40 -0
  82. package/dist/refusal.js.map +1 -0
  83. package/dist/relation-tab.d.ts +14 -0
  84. package/dist/relation-tab.d.ts.map +1 -0
  85. package/dist/relation-tab.js +205 -0
  86. package/dist/relation-tab.js.map +1 -0
  87. package/dist/router.d.ts +50 -0
  88. package/dist/router.d.ts.map +1 -0
  89. package/dist/router.js +121 -0
  90. package/dist/router.js.map +1 -0
  91. package/dist/schema.d.ts +39 -0
  92. package/dist/schema.d.ts.map +1 -0
  93. package/dist/schema.js +113 -0
  94. package/dist/schema.js.map +1 -0
  95. package/dist/states.d.ts +18 -0
  96. package/dist/states.d.ts.map +1 -0
  97. package/dist/states.js +21 -0
  98. package/dist/states.js.map +1 -0
  99. package/dist/value.d.ts +33 -0
  100. package/dist/value.d.ts.map +1 -0
  101. package/dist/value.js +96 -0
  102. package/dist/value.js.map +1 -0
  103. package/dist/write-pages.d.ts +15 -0
  104. package/dist/write-pages.d.ts.map +1 -0
  105. package/dist/write-pages.js +70 -0
  106. package/dist/write-pages.js.map +1 -0
  107. package/package.json +77 -2
  108. package/src/admin.css +14 -0
  109. package/src/admin.tsx +171 -0
  110. package/src/catalog.ts +192 -0
  111. package/src/collections.ts +147 -0
  112. package/src/confirm.tsx +57 -0
  113. package/src/data.tsx +94 -0
  114. package/src/delete-action.tsx +65 -0
  115. package/src/detail-page.tsx +189 -0
  116. package/src/document-table.tsx +129 -0
  117. package/src/filters.tsx +348 -0
  118. package/src/form.tsx +605 -0
  119. package/src/index-page.tsx +26 -0
  120. package/src/index.ts +1 -0
  121. package/src/labels.ts +41 -0
  122. package/src/list-page.tsx +191 -0
  123. package/src/list-state.ts +53 -0
  124. package/src/method-action.tsx +162 -0
  125. package/src/model.tsx +29 -0
  126. package/src/ref-picker.tsx +227 -0
  127. package/src/refusal-alert.tsx +146 -0
  128. package/src/refusal.ts +67 -0
  129. package/src/relation-tab.tsx +440 -0
  130. package/src/router.tsx +186 -0
  131. package/src/schema.ts +151 -0
  132. package/src/states.tsx +67 -0
  133. package/src/value.tsx +171 -0
  134. package/src/write-pages.tsx +146 -0
package/src/form.tsx ADDED
@@ -0,0 +1,605 @@
1
+ import { Button } from '@shadalaya/react/button';
2
+ import {
3
+ Field,
4
+ FieldError,
5
+ FieldLabel,
6
+ FieldLegend,
7
+ FieldSet,
8
+ } from '@shadalaya/react/field';
9
+ import { Input } from '@shadalaya/react/input';
10
+ import {
11
+ NativeSelect,
12
+ NativeSelectOption,
13
+ } from '@shadalaya/react/native-select';
14
+ import { Textarea } from '@shadalaya/react/textarea';
15
+ import type { JsonSchema } from '@ts-pf/docs';
16
+ import { useId, useState } from 'react';
17
+ import { isRecord } from './catalog.js';
18
+ import { type Confirmation, ConfirmDialog } from './confirm.js';
19
+ import { fieldLabel } from './labels.js';
20
+ import { RefPicker, RefsPicker } from './ref-picker.js';
21
+ import { type Issue, issuesUnder, type Refusal, refusalOf } from './refusal.js';
22
+ import { RefusalAlert } from './refusal-alert.js';
23
+ import { plainOf, propertiesOf, typesOf } from './schema.js';
24
+ import { refIdOf } from './value.js';
25
+
26
+ /** How a field is edited, from the subset of JSON Schema Lattice emits. */
27
+ type InputKind =
28
+ | 'text'
29
+ | 'datetime'
30
+ | 'enum'
31
+ | 'number'
32
+ | 'boolean'
33
+ | 'ref'
34
+ | 'texts'
35
+ | 'enums'
36
+ | 'refs'
37
+ | 'json';
38
+
39
+ /** An input field: one property of a procedure's input schema. */
40
+ export type InputField = {
41
+ readonly name: string;
42
+ readonly title: string | undefined;
43
+ readonly kind: InputKind;
44
+ /** Null is a value: clearing the field sends null. */
45
+ readonly nullable: boolean;
46
+ /** An enum's values, or a list of enums' values. */
47
+ readonly values: readonly string[];
48
+ /** The collection a ref, or a list of refs, points to. */
49
+ readonly ref: string | undefined;
50
+ readonly min: number | undefined;
51
+ readonly max: number | undefined;
52
+ readonly integer: boolean;
53
+ readonly defaultValue: unknown;
54
+ };
55
+
56
+ /** What an input holds while it is edited. */
57
+ export type Draft = string | boolean | readonly string[];
58
+
59
+ export type Drafts = Readonly<Record<string, Draft>>;
60
+
61
+ function enumOf(schema: JsonSchema): string[] {
62
+ return Array.isArray(schema.enum)
63
+ ? schema.enum.filter((value): value is string => typeof value === 'string')
64
+ : [];
65
+ }
66
+
67
+ function numberOf(value: unknown): number | undefined {
68
+ return typeof value === 'number' ? value : undefined;
69
+ }
70
+
71
+ function isNullable(schema: JsonSchema): boolean {
72
+ const { anyOf, type } = schema;
73
+ return (
74
+ (Array.isArray(type) && type.includes('null')) ||
75
+ (Array.isArray(anyOf) &&
76
+ anyOf.some((branch) => isRecord(branch) && branch.type === 'null'))
77
+ );
78
+ }
79
+
80
+ /** A list's kind, from its items: strings, enums or refs. Else JSON. */
81
+ function listKindOf(items: JsonSchema): InputKind {
82
+ if (typeof items['x-lattice-ref'] === 'string') return 'refs';
83
+ if (enumOf(items).length > 0) return 'enums';
84
+ const [type] = typesOf(items);
85
+ return type === 'string' && items.format === undefined ? 'texts' : 'json';
86
+ }
87
+
88
+ function kindOf(schema: JsonSchema): InputKind {
89
+ if (typeof schema['x-lattice-ref'] === 'string') return 'ref';
90
+ if (enumOf(schema).length > 0) return 'enum';
91
+ const [type, ...others] = typesOf(schema);
92
+ // A union of types has no one input: JSON says it exactly.
93
+ if (others.length > 0) return 'json';
94
+ if (type === 'string') {
95
+ return schema.format === 'date-time' ? 'datetime' : 'text';
96
+ }
97
+ if (type === 'number' || type === 'integer') return 'number';
98
+ if (type === 'boolean') return 'boolean';
99
+ if (type === 'array' && isRecord(schema.items)) {
100
+ return listKindOf(plainOf(schema.items));
101
+ }
102
+ return 'json';
103
+ }
104
+
105
+ /**
106
+ * The fields of an input schema, in schema order, but `omit`: such as
107
+ * update's `id`, which the page supplies. The schema says which kind of
108
+ * input each one gets; anything outside Lattice's subset is JSON text.
109
+ */
110
+ export function inputFieldsOf(
111
+ schema: JsonSchema | undefined,
112
+ omit: readonly string[],
113
+ ): InputField[] {
114
+ if (schema === undefined) return [];
115
+ return propertiesOf(schema)
116
+ .filter(([name]) => !omit.includes(name))
117
+ .map(([name, property]) => {
118
+ const plain = plainOf(property);
119
+ const kind = kindOf(plain);
120
+ const items = isRecord(plain.items) ? plainOf(plain.items) : {};
121
+ const element = kind === 'enums' || kind === 'refs' ? items : plain;
122
+ const ref = element['x-lattice-ref'];
123
+ const title = property.title ?? plain.title;
124
+ return {
125
+ name,
126
+ title: typeof title === 'string' ? title : undefined,
127
+ kind,
128
+ nullable: isNullable(property),
129
+ values: enumOf(element),
130
+ ref: typeof ref === 'string' ? ref : undefined,
131
+ min: numberOf(plain.minimum),
132
+ max: numberOf(plain.maximum),
133
+ integer: typesOf(plain).includes('integer'),
134
+ defaultValue: property.default,
135
+ };
136
+ });
137
+ }
138
+
139
+ /** `2026-11-23T09:30` in local time, as a datetime-local input takes it. */
140
+ function localDateTime(iso: string): string {
141
+ const date = new Date(iso);
142
+ if (Number.isNaN(date.getTime())) return '';
143
+ const pad = (part: number) => String(part).padStart(2, '0');
144
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
145
+ }
146
+
147
+ /** What a field's input starts with: `value`, else its default. */
148
+ export function draftOf(field: InputField, value: unknown): Draft {
149
+ const start = value === undefined ? field.defaultValue : value;
150
+ switch (field.kind) {
151
+ case 'boolean':
152
+ // A nullable boolean has three answers, so it is a select.
153
+ if (field.nullable) {
154
+ return start === true ? 'true' : start === false ? 'false' : '';
155
+ }
156
+ return start === true;
157
+ case 'texts':
158
+ case 'enums':
159
+ case 'refs':
160
+ return Array.isArray(start)
161
+ ? start.flatMap((item) => {
162
+ const id = refIdOf(item);
163
+ return id === undefined ? [] : [id];
164
+ })
165
+ : [];
166
+ case 'ref':
167
+ return refIdOf(start) ?? '';
168
+ case 'datetime':
169
+ return typeof start === 'string' ? localDateTime(start) : '';
170
+ case 'number':
171
+ return typeof start === 'number' ? String(start) : '';
172
+ case 'json':
173
+ return start === undefined ? '' : JSON.stringify(start, null, 2);
174
+ default:
175
+ return typeof start === 'string' ? start : '';
176
+ }
177
+ }
178
+
179
+ /** The drafts of `fields`, from a document or input, else defaults. */
180
+ export function draftsOf(
181
+ fields: readonly InputField[],
182
+ values: Readonly<Record<string, unknown>>,
183
+ ): Drafts {
184
+ return Object.fromEntries(
185
+ fields.map((field) => [field.name, draftOf(field, values[field.name])]),
186
+ );
187
+ }
188
+
189
+ /** A draft as JSON: a value to send, nothing to send, or why it is not one. */
190
+ type Converted =
191
+ | { readonly value: unknown }
192
+ | { readonly omit: true }
193
+ | { readonly problem: string };
194
+
195
+ function converted(field: InputField, draft: Draft | undefined): Converted {
196
+ if (typeof draft === 'boolean') return { value: draft };
197
+ // A list of refs with no title field to search is typed as ids.
198
+ const list = Array.isArray(draft)
199
+ ? draft
200
+ : field.kind === 'refs' && typeof draft === 'string'
201
+ ? draft.split(',')
202
+ : undefined;
203
+ if (list !== undefined) {
204
+ const items = list.map((item) => item.trim()).filter((item) => item !== '');
205
+ return items.length === 0 && field.nullable
206
+ ? { value: null }
207
+ : { value: items };
208
+ }
209
+ const text = typeof draft === 'string' ? draft : '';
210
+ // An empty input sends nothing, or null where null is a value. The server
211
+ // says when a required field is missing.
212
+ if (text.trim() === '')
213
+ return field.nullable ? { value: null } : { omit: true };
214
+ switch (field.kind) {
215
+ case 'boolean':
216
+ return { value: text === 'true' };
217
+ case 'number': {
218
+ const number = Number(text);
219
+ return Number.isNaN(number)
220
+ ? { problem: 'Enter a number.' }
221
+ : { value: number };
222
+ }
223
+ case 'datetime': {
224
+ const date = new Date(text);
225
+ return Number.isNaN(date.getTime())
226
+ ? { problem: 'Enter a date and time.' }
227
+ : { value: date.toISOString() };
228
+ }
229
+ case 'json':
230
+ try {
231
+ return { value: JSON.parse(text) };
232
+ } catch {
233
+ return { problem: 'Enter valid JSON.' };
234
+ }
235
+ default:
236
+ return { value: text };
237
+ }
238
+ }
239
+
240
+ /** An input body, and any field whose draft is not a value. */
241
+ export type Body = {
242
+ readonly body: Record<string, unknown>;
243
+ readonly problems: readonly Issue[];
244
+ };
245
+
246
+ /**
247
+ * Why a cleared field is not sent: only update's optional fields take null,
248
+ * which clears them, so a field that does not is required or defaulted.
249
+ */
250
+ const cannotClear = 'This field is required.';
251
+
252
+ /**
253
+ * The input `drafts` make: only the fields that differ from `baseline`.
254
+ * An untouched field is not sent, so update leaves it as it is and create
255
+ * applies its default. A field cleared to nothing sends null where the
256
+ * schema takes it, which clears it on update, and cannot be sent otherwise.
257
+ */
258
+ export function bodyOf(
259
+ fields: readonly InputField[],
260
+ drafts: Drafts,
261
+ baseline: Drafts,
262
+ ): Body {
263
+ const body: Record<string, unknown> = {};
264
+ const problems: Issue[] = [];
265
+ for (const field of fields) {
266
+ const now = converted(field, drafts[field.name]);
267
+ if ('problem' in now) {
268
+ problems.push({ path: [field.name], message: now.problem });
269
+ continue;
270
+ }
271
+ const before = converted(field, baseline[field.name]);
272
+ if (JSON.stringify(now) === JSON.stringify(before)) continue;
273
+ if ('value' in now) {
274
+ body[field.name] = now.value;
275
+ } else {
276
+ problems.push({ path: [field.name], message: cannotClear });
277
+ }
278
+ }
279
+ return { body, problems };
280
+ }
281
+
282
+ function textOf(draft: Draft): string {
283
+ return typeof draft === 'string' ? draft : '';
284
+ }
285
+
286
+ function listOf(draft: Draft): readonly string[] {
287
+ return Array.isArray(draft) ? draft : [];
288
+ }
289
+
290
+ /** A native checkbox, styled: Base UI's would add about 5 KB gzip. */
291
+ const checkbox = 'size-4 accent-primary';
292
+
293
+ /**
294
+ * What a number input reports for text that is not a number, such as `1e`:
295
+ * it reports '', so the draft keeps NaN, and the form says why.
296
+ */
297
+ const notANumber = 'NaN';
298
+
299
+ /** The input for one field, by its kind. Not a list of enums. */
300
+ function FieldControl({
301
+ id,
302
+ field,
303
+ draft,
304
+ onChange,
305
+ }: {
306
+ readonly id: string;
307
+ readonly field: InputField;
308
+ readonly draft: Draft;
309
+ readonly onChange: (draft: Draft) => void;
310
+ }) {
311
+ const text = textOf(draft);
312
+ switch (field.kind) {
313
+ case 'boolean':
314
+ return typeof draft === 'boolean' ? (
315
+ <input
316
+ id={id}
317
+ type="checkbox"
318
+ className={checkbox}
319
+ checked={draft}
320
+ onChange={(event) => onChange(event.target.checked)}
321
+ />
322
+ ) : (
323
+ <NativeSelect
324
+ id={id}
325
+ value={text}
326
+ onChange={(event) => onChange(event.target.value)}
327
+ >
328
+ <NativeSelectOption value="">—</NativeSelectOption>
329
+ <NativeSelectOption value="true">Yes</NativeSelectOption>
330
+ <NativeSelectOption value="false">No</NativeSelectOption>
331
+ </NativeSelect>
332
+ );
333
+ case 'enum':
334
+ return (
335
+ <NativeSelect
336
+ id={id}
337
+ value={text}
338
+ onChange={(event) => onChange(event.target.value)}
339
+ >
340
+ <NativeSelectOption value="">—</NativeSelectOption>
341
+ {field.values.map((value) => (
342
+ <NativeSelectOption key={value} value={value}>
343
+ {value}
344
+ </NativeSelectOption>
345
+ ))}
346
+ </NativeSelect>
347
+ );
348
+ case 'ref':
349
+ return (
350
+ <RefPicker
351
+ id={id}
352
+ target={field.ref}
353
+ value={text}
354
+ onChange={onChange}
355
+ />
356
+ );
357
+ case 'refs':
358
+ return (
359
+ <RefsPicker
360
+ id={id}
361
+ target={field.ref}
362
+ value={typeof draft === 'boolean' ? [] : draft}
363
+ onChange={onChange}
364
+ />
365
+ );
366
+ case 'texts':
367
+ return (
368
+ <Textarea
369
+ id={id}
370
+ placeholder="One per line"
371
+ value={listOf(draft).join('\n')}
372
+ onChange={(event) => onChange(event.target.value.split('\n'))}
373
+ />
374
+ );
375
+ case 'json':
376
+ return (
377
+ <Textarea
378
+ id={id}
379
+ className="font-mono"
380
+ placeholder="JSON"
381
+ value={text}
382
+ onChange={(event) => onChange(event.target.value)}
383
+ />
384
+ );
385
+ case 'number':
386
+ return (
387
+ <Input
388
+ id={id}
389
+ type="number"
390
+ min={field.min}
391
+ max={field.max}
392
+ step={field.integer ? 1 : 'any'}
393
+ value={text}
394
+ onChange={(event) =>
395
+ onChange(
396
+ event.target.validity.badInput ? notANumber : event.target.value,
397
+ )
398
+ }
399
+ />
400
+ );
401
+ default:
402
+ return (
403
+ <Input
404
+ id={id}
405
+ type={field.kind === 'datetime' ? 'datetime-local' : 'text'}
406
+ value={text}
407
+ onChange={(event) => onChange(event.target.value)}
408
+ />
409
+ );
410
+ }
411
+ }
412
+
413
+ /** A list of enums: a checkbox per value, in a fieldset named by the field. */
414
+ function EnumsInput({
415
+ field,
416
+ draft,
417
+ issues,
418
+ onChange,
419
+ }: {
420
+ readonly field: InputField;
421
+ readonly draft: Draft;
422
+ readonly issues: readonly Issue[];
423
+ readonly onChange: (draft: Draft) => void;
424
+ }) {
425
+ const picked = listOf(draft);
426
+ return (
427
+ <FieldSet data-invalid={issues.length > 0 || undefined}>
428
+ <FieldLegend variant="label">{fieldLabel(field)}</FieldLegend>
429
+ <div className="flex flex-wrap gap-3">
430
+ {field.values.map((value) => (
431
+ <label key={value} className="inline-flex items-center gap-2">
432
+ <input
433
+ type="checkbox"
434
+ className={checkbox}
435
+ checked={picked.includes(value)}
436
+ onChange={(event) =>
437
+ onChange(
438
+ event.target.checked
439
+ ? [...picked, value]
440
+ : picked.filter((item) => item !== value),
441
+ )
442
+ }
443
+ />
444
+ {value}
445
+ </label>
446
+ ))}
447
+ </div>
448
+ <FieldError errors={[...issues]} />
449
+ </FieldSet>
450
+ );
451
+ }
452
+
453
+ /** One field: its label, its input, and any issue at it. */
454
+ export function FieldInput({
455
+ field,
456
+ draft,
457
+ issues,
458
+ onChange,
459
+ }: {
460
+ readonly field: InputField;
461
+ readonly draft: Draft;
462
+ readonly issues: readonly Issue[];
463
+ readonly onChange: (draft: Draft) => void;
464
+ }) {
465
+ const id = useId();
466
+ if (field.kind === 'enums') {
467
+ return (
468
+ <EnumsInput
469
+ field={field}
470
+ draft={draft}
471
+ issues={issues}
472
+ onChange={onChange}
473
+ />
474
+ );
475
+ }
476
+ return (
477
+ <Field data-invalid={issues.length > 0 || undefined}>
478
+ <FieldLabel htmlFor={id}>{fieldLabel(field)}</FieldLabel>
479
+ <FieldControl id={id} field={field} draft={draft} onChange={onChange} />
480
+ <FieldError errors={[...issues]} />
481
+ </Field>
482
+ );
483
+ }
484
+
485
+ /**
486
+ * The fields of an input, each with the issues whose path starts with its
487
+ * name below `at`, such as `['links', 0]` for a link of a relation's set.
488
+ */
489
+ export function FormFields({
490
+ fields,
491
+ drafts,
492
+ issues,
493
+ at = [],
494
+ onChange,
495
+ }: {
496
+ readonly fields: readonly InputField[];
497
+ readonly drafts: Drafts;
498
+ readonly issues: readonly Issue[];
499
+ readonly at?: readonly (string | number)[];
500
+ readonly onChange: (drafts: Drafts) => void;
501
+ }) {
502
+ return (
503
+ <div className="flex flex-col gap-4">
504
+ {fields.map((field) => (
505
+ <FieldInput
506
+ key={field.name}
507
+ field={field}
508
+ draft={drafts[field.name] ?? draftOf(field, undefined)}
509
+ issues={issuesUnder(issues, [...at, field.name])}
510
+ onChange={(draft) => onChange({ ...drafts, [field.name]: draft })}
511
+ />
512
+ ))}
513
+ </div>
514
+ );
515
+ }
516
+
517
+ /**
518
+ * A form for one procedure's input: its fields, its submit, and what the
519
+ * server refused. It sends only what differs from `initial`. Each issue
520
+ * shows at the field its path names; the rest, and any other refusal, show
521
+ * in the form's alert. With `confirmation`, a submit asks first.
522
+ */
523
+ export function InputForm({
524
+ label,
525
+ fields,
526
+ initial,
527
+ submitLabel,
528
+ confirmation,
529
+ onSubmit,
530
+ }: {
531
+ readonly label: string;
532
+ readonly fields: readonly InputField[];
533
+ readonly initial: Drafts;
534
+ readonly submitLabel: string;
535
+ readonly confirmation?: Confirmation;
536
+ readonly onSubmit: (body: Record<string, unknown>) => Promise<void>;
537
+ }) {
538
+ // Frozen with the drafts: a refetch of the document must not change what
539
+ // counts as changed, or a stale value would be sent over another's edit.
540
+ const [baseline] = useState(initial);
541
+ const [drafts, setDrafts] = useState(initial);
542
+ const [problems, setProblems] = useState<readonly Issue[]>([]);
543
+ const [refusal, setRefusal] = useState<Refusal | undefined>();
544
+ const [pending, setPending] = useState<Record<string, unknown> | undefined>();
545
+ const [busy, setBusy] = useState(false);
546
+ const submit = async (body: Record<string, unknown>) => {
547
+ setBusy(true);
548
+ setRefusal(undefined);
549
+ try {
550
+ await onSubmit(body);
551
+ } catch (error) {
552
+ setRefusal(refusalOf(error));
553
+ } finally {
554
+ setBusy(false);
555
+ }
556
+ };
557
+ const issues = [...problems, ...(refusal?.issues ?? [])];
558
+ return (
559
+ <form
560
+ aria-label={label}
561
+ className="flex flex-col gap-4"
562
+ onSubmit={(event) => {
563
+ event.preventDefault();
564
+ const made = bodyOf(fields, drafts, baseline);
565
+ setProblems(made.problems);
566
+ if (made.problems.length > 0) return;
567
+ if (confirmation === undefined) {
568
+ void submit(made.body);
569
+ } else {
570
+ setPending(made.body);
571
+ }
572
+ }}
573
+ >
574
+ <FormFields
575
+ fields={fields}
576
+ drafts={drafts}
577
+ issues={issues}
578
+ onChange={setDrafts}
579
+ />
580
+ {refusal === undefined ? null : (
581
+ <RefusalAlert
582
+ refusal={refusal}
583
+ placed={(issue) => fields.some(({ name }) => issue.path[0] === name)}
584
+ />
585
+ )}
586
+ <div>
587
+ <Button type="submit" disabled={busy}>
588
+ {submitLabel}
589
+ </Button>
590
+ </div>
591
+ {confirmation === undefined ? null : (
592
+ <ConfirmDialog
593
+ confirmation={confirmation}
594
+ open={pending !== undefined}
595
+ onOpenChange={(open) => {
596
+ if (!open) setPending(undefined);
597
+ }}
598
+ onConfirm={() => {
599
+ if (pending !== undefined) void submit(pending);
600
+ }}
601
+ />
602
+ )}
603
+ </form>
604
+ );
605
+ }
@@ -0,0 +1,26 @@
1
+ import { pluralHeading } from './labels.js';
2
+ import { useCollections } from './model.js';
3
+ import { Link, useRouter } from './router.js';
4
+
5
+ /** Every collection in the catalog, by its label. */
6
+ export function IndexPage() {
7
+ const collections = useCollections();
8
+ const { href } = useRouter();
9
+ return (
10
+ <section className="flex flex-col gap-4">
11
+ <h1 className="text-2xl font-semibold">Collections</h1>
12
+ <ul className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
13
+ {collections.map((collection) => (
14
+ <li key={collection.slug}>
15
+ <Link
16
+ className="block rounded-lg border p-4 font-medium hover:bg-muted"
17
+ href={href(collection.slug)}
18
+ >
19
+ {pluralHeading(collection.label)}
20
+ </Link>
21
+ </li>
22
+ ))}
23
+ </ul>
24
+ </section>
25
+ );
26
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { Admin } from './admin.js';
package/src/labels.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { LatticeMeta } from '@latticecms/core';
2
+ import type { Field } from './schema.js';
3
+
4
+ /** `companyId` as "Company id", and `deal_contacts` as "Deal contacts". */
5
+ function inWords(name: string): string {
6
+ const words = name
7
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
8
+ .split(/[\s_-]+/)
9
+ .filter((word) => word !== '')
10
+ .map((word) => word.toLowerCase());
11
+ return capitalize(words.join(' '));
12
+ }
13
+
14
+ function capitalize(text: string): string {
15
+ return text.charAt(0).toUpperCase() + text.slice(1);
16
+ }
17
+
18
+ /** A field's label: its schema `title`, or its name in words. */
19
+ export function fieldLabel(field: Pick<Field, 'name' | 'title'>): string {
20
+ return field.title ?? inWords(field.name);
21
+ }
22
+
23
+ /** A relation's label: its name in words. */
24
+ export function relationLabel(name: string): string {
25
+ return inWords(name);
26
+ }
27
+
28
+ /** A method's label: its name in words, such as "Close" for `close`. */
29
+ export function methodLabel(name: string): string {
30
+ return inWords(name);
31
+ }
32
+
33
+ /** A collection's heading, such as "Deals". */
34
+ export function pluralHeading(label: LatticeMeta['label']): string {
35
+ return capitalize(label.plural);
36
+ }
37
+
38
+ /** One document's heading, such as "Deal". */
39
+ export function singularHeading(label: LatticeMeta['label']): string {
40
+ return capitalize(label.singular);
41
+ }