@panneau/core 5.0.0-alpha.4 → 5.0.0-alpha.41

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 (78) hide show
  1. package/README.md +5 -3
  2. package/dist/commands.d.ts +38 -0
  3. package/dist/commands.d.ts.map +1 -0
  4. package/dist/commands.js +22 -0
  5. package/dist/commands.js.map +1 -0
  6. package/dist/definition/abilities.d.ts +33 -5
  7. package/dist/definition/abilities.d.ts.map +1 -1
  8. package/dist/definition/abilities.js +44 -6
  9. package/dist/definition/abilities.js.map +1 -1
  10. package/dist/definition/form.d.ts +16 -7
  11. package/dist/definition/form.d.ts.map +1 -1
  12. package/dist/definition/form.js +39 -6
  13. package/dist/definition/form.js.map +1 -1
  14. package/dist/definition/itemActions.d.ts +53 -0
  15. package/dist/definition/itemActions.d.ts.map +1 -0
  16. package/dist/definition/itemActions.js +64 -0
  17. package/dist/definition/itemActions.js.map +1 -0
  18. package/dist/definition/list.d.ts +43 -1
  19. package/dist/definition/list.d.ts.map +1 -1
  20. package/dist/definition/list.js +104 -16
  21. package/dist/definition/list.js.map +1 -1
  22. package/dist/definition/resource.d.ts +3 -2
  23. package/dist/definition/resource.d.ts.map +1 -1
  24. package/dist/definition/resource.js +3 -2
  25. package/dist/definition/resource.js.map +1 -1
  26. package/dist/form/form.d.ts +8 -3
  27. package/dist/form/form.d.ts.map +1 -1
  28. package/dist/form/form.js +1 -0
  29. package/dist/form/form.js.map +1 -1
  30. package/dist/form/messages.d.ts.map +1 -1
  31. package/dist/form/messages.js +11 -1
  32. package/dist/form/messages.js.map +1 -1
  33. package/dist/form/problem.d.ts +1 -1
  34. package/dist/form/problem.js.map +1 -1
  35. package/dist/form/selectors.d.ts +1 -1
  36. package/dist/form/selectors.js.map +1 -1
  37. package/dist/form/store.d.ts +1 -1
  38. package/dist/form/store.js.map +1 -1
  39. package/dist/index.d.ts +23 -16
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +8 -3
  42. package/dist/list/calendar.d.ts +15 -0
  43. package/dist/list/calendar.d.ts.map +1 -0
  44. package/dist/list/calendar.js +42 -0
  45. package/dist/list/calendar.js.map +1 -0
  46. package/dist/list/list.d.ts +40 -3
  47. package/dist/list/list.d.ts.map +1 -1
  48. package/dist/list/list.js +152 -16
  49. package/dist/list/list.js.map +1 -1
  50. package/dist/list/router.js.map +1 -1
  51. package/dist/list/viewStore.d.ts +36 -0
  52. package/dist/list/viewStore.d.ts.map +1 -0
  53. package/dist/list/viewStore.js +54 -0
  54. package/dist/list/viewStore.js.map +1 -0
  55. package/dist/plugins.d.ts +22 -2
  56. package/dist/plugins.d.ts.map +1 -1
  57. package/dist/plugins.js +5 -2
  58. package/dist/plugins.js.map +1 -1
  59. package/dist/preview.d.ts +14 -0
  60. package/dist/preview.d.ts.map +1 -0
  61. package/dist/react/leaveGuards.d.ts +34 -0
  62. package/dist/react/leaveGuards.d.ts.map +1 -0
  63. package/dist/react/leaveGuards.js +84 -0
  64. package/dist/react/leaveGuards.js.map +1 -0
  65. package/dist/react/provider.d.ts +4 -4
  66. package/dist/react/provider.js +3 -1
  67. package/dist/react/provider.js.map +1 -1
  68. package/dist/react/useForm.d.ts +1 -1
  69. package/dist/react/useForm.js.map +1 -1
  70. package/dist/react/useList.d.ts +1 -1
  71. package/dist/react/useList.js.map +1 -1
  72. package/dist/values.d.ts +1 -1
  73. package/dist/values.d.ts.map +1 -1
  74. package/dist/values.js +5 -1
  75. package/dist/values.js.map +1 -1
  76. package/dist/widget.d.ts +15 -0
  77. package/dist/widget.d.ts.map +1 -0
  78. package/package.json +4 -4
@@ -11,6 +11,19 @@ export interface ResolvedColumn {
11
11
  sortable: boolean;
12
12
  width?: number | string;
13
13
  align?: 'start' | 'center' | 'end';
14
+ /** Not shown until the user shows it (decision 0042). */
15
+ hidden: boolean;
16
+ /** Whether the user can hide it. */
17
+ hideable: boolean;
18
+ }
19
+ /** The calendar of a list (decision 0044). */
20
+ export interface ResolvedCalendar {
21
+ /** The `date` or `datetime` field each item is shown on the day of. */
22
+ field: string;
23
+ /** The id of the `date-range` filter the calendar asks for a month through. */
24
+ filter: string;
25
+ /** How many items the calendar asks for a month. */
26
+ perPage: number;
14
27
  }
15
28
  /** A list ready to render. */
16
29
  export interface ResolvedList {
@@ -26,19 +39,48 @@ export interface ResolvedList {
26
39
  layouts: string[];
27
40
  perPage: number;
28
41
  perPageOptions: number[];
42
+ /** `pages` (numbered, with a total), or `cursor`: the list follows the cursors of its pages. */
43
+ pagination: 'pages' | 'cursor';
29
44
  /** Fields editable in the list. */
30
45
  inlineEdit: string[];
31
46
  /** Whether items can be selected: the list allows it and a selection action exists. */
32
47
  selectable: boolean;
33
48
  /** Actions the user can run, by placement. */
34
49
  actions: Record<ActionPlacement, Action[]>;
50
+ /** The calendar of the list, for its `calendar` layout, or `null`. */
51
+ calendar: ResolvedCalendar | null;
35
52
  }
36
53
  export declare const DEFAULT_PER_PAGE = 20;
54
+ /** How many items a calendar asks for a month, without its own `perPage`. */
55
+ export declare const DEFAULT_CALENDAR_PER_PAGE = 100;
56
+ /**
57
+ * Whether running an action asks first (decisions 0017 and 0063): its `confirm`, when it sets one;
58
+ * otherwise, for an `undoable` action, only above `UNDO_LIMIT` items or for a queued one, which
59
+ * can't be undone. `count` is the number of items, from the selection or a dry run.
60
+ */
61
+ export declare function asksConfirmation(action: Action, count?: number): boolean;
37
62
  /** Groups the actions the user can run by placement. */
38
63
  export declare function groupActions(actions: readonly Action[]): Record<ActionPlacement, Action[]>;
64
+ /**
65
+ * The actions of a resource (decision 0040): its built-in item actions (`show`, `edit`,
66
+ * `duplicate`, `delete`, or those of its `itemActions`, in their order), then the actions it
67
+ * declares. A declared action with the id of a built-in one replaces it, at its place, with the
68
+ * built-in one's placement, confirmation, `destructive` and `dryRun` when it doesn't set them, and
69
+ * is left out with it when `itemActions` doesn't list it. Unless items open in the panel
70
+ * (`"open": "panel"`), `show` is left out: it would go to the edit form too. Abilities of the items then hide what they don't allow.
71
+ */
72
+ export declare function getResourceActions(resource: Resource): Action[];
73
+ /**
74
+ * Where the title of an item goes (`open` of the resource, decision 0082): `edit`, its form, the
75
+ * default, or `panel`, the show route with the item's details next to the list. A value it doesn't
76
+ * know is `edit`.
77
+ */
78
+ export declare function getOpenMode(resource: Resource): 'panel' | 'edit';
39
79
  /**
40
80
  * Resolves the list of a resource. Without columns, it shows the item title and the next fields
41
- * (up to four, skipping groups, repeaters and rich text).
81
+ * (up to four, skipping groups, repeaters and rich text). Fields the current user can't see
82
+ * (`abilities.view: false`) have no column, sort or inline editing, and those they can't edit
83
+ * aren't edited inline (decision 0046).
42
84
  */
43
85
  export declare function resolveList(resource: Resource): ResolvedList;
44
86
  //# sourceMappingURL=list.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"list.d.ts","sourceRoot":"","sources":["../../src/definition/list.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,eAAe,EAAU,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAIlG,gCAAgC;AAChC,MAAM,WAAW,cAAc;IAC3B,yDAAyD;IACzD,EAAE,EAAE,MAAM,CAAC;IACX,kDAAkD;IAClD,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,wFAAwF;IACxF,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,QAAQ,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACxB,KAAK,CAAC,EAAE,OAAO,GAAG,QAAQ,GAAG,KAAK,CAAC;CACtC;AAED,8BAA8B;AAC9B,MAAM,WAAW,YAAY;IACzB,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,wCAAwC;IACxC,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,+EAA+E;IAC/E,WAAW,EAAE,MAAM,EA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CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,EAAE,CAwB/D;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,GAAG,MAAM,CAEhE;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,GAAG,YAAY,CA4D5D"}
@@ -1,18 +1,26 @@
1
- import { canRunAction, getActionPlacements } from "./abilities.js";
1
+ import { canRunAction, canUpdateField, canViewField, getActionPlacements } from "./abilities.js";
2
+ import { BUILT_IN_ITEM_ACTIONS, UNDO_LIMIT, getNestedShape, isBuiltInItemAction } from "@panneau/protocol/runtime";
2
3
  //#region src/definition/list.ts
3
4
  /** Fields shown when the list declares no columns. */
4
5
  var DEFAULT_COLUMN_COUNT = 4;
5
- var NON_COLUMN_TYPES = /* @__PURE__ */ new Set([
6
- "group",
7
- "repeater",
8
- "richtext"
9
- ]);
6
+ var NON_COLUMN_TYPES = /* @__PURE__ */ new Set(["richtext"]);
10
7
  var DEFAULT_PER_PAGE = 20;
8
+ /** How many items a calendar asks for a month, without its own `perPage`. */
9
+ var DEFAULT_CALENDAR_PER_PAGE = 100;
11
10
  function columnsFromFields(resource) {
12
11
  const title = resource.itemTitle;
13
- const fields = resource.fields.filter((field) => !NON_COLUMN_TYPES.has(field.type));
12
+ const fields = resource.fields.filter((field) => !NON_COLUMN_TYPES.has(field.type) && getNestedShape(field) === null && canViewField(field));
14
13
  return (title !== void 0 ? [...fields.filter((field) => field.name === title), ...fields.filter((field) => field.name !== title)] : fields).slice(0, DEFAULT_COLUMN_COUNT).map((field) => ({ field: field.name }));
15
14
  }
15
+ /**
16
+ * Whether running an action asks first (decisions 0017 and 0063): its `confirm`, when it sets one;
17
+ * otherwise, for an `undoable` action, only above `UNDO_LIMIT` items or for a queued one, which
18
+ * can't be undone. `count` is the number of items, from the selection or a dry run.
19
+ */
20
+ function asksConfirmation(action, count = 1) {
21
+ if (action.confirm !== void 0) return action.confirm !== false;
22
+ return action.undoable === true && (count > UNDO_LIMIT || action.queued === true);
23
+ }
16
24
  /** Groups the actions the user can run by placement. */
17
25
  function groupActions(actions) {
18
26
  const groups = {
@@ -26,15 +34,84 @@ function groupActions(actions) {
26
34
  });
27
35
  return groups;
28
36
  }
37
+ /** The built-in item actions, as the client shows them when a resource doesn't replace them. */
38
+ var BUILT_IN_ITEM_ACTION_DEFINITIONS = {
39
+ show: {
40
+ id: "show",
41
+ kind: "link",
42
+ scope: ["item"],
43
+ placement: ["row", "form"]
44
+ },
45
+ edit: {
46
+ id: "edit",
47
+ kind: "link",
48
+ scope: ["item"],
49
+ placement: ["row", "form"]
50
+ },
51
+ duplicate: {
52
+ id: "duplicate",
53
+ kind: "server",
54
+ scope: ["item"],
55
+ placement: ["menu", "form"]
56
+ },
57
+ delete: {
58
+ id: "delete",
59
+ kind: "server",
60
+ scope: ["item", "selection"],
61
+ placement: [
62
+ "menu",
63
+ "toolbar",
64
+ "form"
65
+ ],
66
+ destructive: true,
67
+ confirm: true,
68
+ dryRun: true
69
+ }
70
+ };
71
+ /**
72
+ * The actions of a resource (decision 0040): its built-in item actions (`show`, `edit`,
73
+ * `duplicate`, `delete`, or those of its `itemActions`, in their order), then the actions it
74
+ * declares. A declared action with the id of a built-in one replaces it, at its place, with the
75
+ * built-in one's placement, confirmation, `destructive` and `dryRun` when it doesn't set them, and
76
+ * is left out with it when `itemActions` doesn't list it. Unless items open in the panel
77
+ * (`"open": "panel"`), `show` is left out: it would go to the edit form too. Abilities of the items then hide what they don't allow.
78
+ */
79
+ function getResourceActions(resource) {
80
+ const declared = resource.actions ?? [];
81
+ return [...(resource.itemActions ?? BUILT_IN_ITEM_ACTIONS).filter((id, index, all) => isBuiltInItemAction(id) && all.indexOf(id) === index && !(id === "show" && getOpenMode(resource) === "edit")).map((id) => {
82
+ const replacement = declared.find((action) => action.id === id);
83
+ if (replacement === void 0) return BUILT_IN_ITEM_ACTION_DEFINITIONS[id];
84
+ const { confirm, ...builtIn } = BUILT_IN_ITEM_ACTION_DEFINITIONS[id];
85
+ return replacement.undoable === true ? {
86
+ ...builtIn,
87
+ ...replacement
88
+ } : {
89
+ ...builtIn,
90
+ ...confirm !== void 0 ? { confirm } : {},
91
+ ...replacement
92
+ };
93
+ }), ...declared.filter((action) => !isBuiltInItemAction(action.id))];
94
+ }
95
+ /**
96
+ * Where the title of an item goes (`open` of the resource, decision 0082): `edit`, its form, the
97
+ * default, or `panel`, the show route with the item's details next to the list. A value it doesn't
98
+ * know is `edit`.
99
+ */
100
+ function getOpenMode(resource) {
101
+ return resource.open === "panel" ? "panel" : "edit";
102
+ }
29
103
  /**
30
104
  * Resolves the list of a resource. Without columns, it shows the item title and the next fields
31
- * (up to four, skipping groups, repeaters and rich text).
105
+ * (up to four, skipping groups, repeaters and rich text). Fields the current user can't see
106
+ * (`abilities.view: false`) have no column, sort or inline editing, and those they can't edit
107
+ * aren't edited inline (decision 0046).
32
108
  */
33
109
  function resolveList(resource) {
34
110
  const list = resource.list ?? {};
35
111
  const fields = new Map(resource.fields.map((field) => [field.name, field]));
36
- const sorts = list.sorts ?? [];
37
- const columns = (list.columns ?? columnsFromFields(resource)).map((column) => {
112
+ const hidden = new Set(resource.fields.filter((field) => !canViewField(field)).map((field) => field.name));
113
+ const sorts = (list.sorts ?? []).filter((sort) => !hidden.has(sort));
114
+ const columns = (list.columns ?? columnsFromFields(resource)).filter((column) => column.field === void 0 || !hidden.has(column.field)).map((column) => {
38
115
  const field = column.field !== void 0 ? fields.get(column.field) ?? null : null;
39
116
  const id = column.id ?? column.field ?? "";
40
117
  const resolved = {
@@ -42,14 +119,16 @@ function resolveList(resource) {
42
119
  field,
43
120
  label: column.label ?? field?.label ?? id,
44
121
  display: column.display ?? field?.display ?? field?.type ?? null,
45
- sortable: column.sortable ?? (column.field !== void 0 && sorts.includes(column.field))
122
+ sortable: column.sortable ?? (column.field !== void 0 && sorts.includes(column.field)),
123
+ hidden: column.hidden === true && column.hideable !== false,
124
+ hideable: column.hideable !== false
46
125
  };
47
126
  if (column.width !== void 0) resolved.width = column.width;
48
127
  if (column.align !== void 0) resolved.align = column.align;
49
128
  return resolved;
50
129
  });
51
- const actions = groupActions(resource.actions ?? []);
52
- const hasSelectionAction = (resource.actions ?? []).some((action) => action.scope.includes("selection") && canRunAction(action));
130
+ const actions = groupActions(getResourceActions(resource));
131
+ const hasSelectionAction = getResourceActions(resource).some((action) => action.scope.includes("selection") && canRunAction(action));
53
132
  return {
54
133
  columns,
55
134
  filters: list.filters ?? [],
@@ -59,12 +138,21 @@ function resolveList(resource) {
59
138
  layouts: list.layouts ?? ["table"],
60
139
  perPage: list.perPage ?? 20,
61
140
  perPageOptions: list.perPageOptions ?? [],
62
- inlineEdit: list.inlineEdit ?? [],
141
+ pagination: list.pagination ?? "pages",
142
+ inlineEdit: (list.inlineEdit ?? []).filter((name) => {
143
+ const field = fields.get(name);
144
+ return field === void 0 || canUpdateField(field);
145
+ }),
63
146
  selectable: (list.selectable ?? true) && hasSelectionAction,
64
- actions
147
+ actions,
148
+ calendar: list.calendar !== void 0 ? {
149
+ field: list.calendar.field,
150
+ filter: list.calendar.filter ?? list.calendar.field,
151
+ perPage: list.calendar.perPage ?? 100
152
+ } : null
65
153
  };
66
154
  }
67
155
  //#endregion
68
- export { DEFAULT_PER_PAGE, groupActions, resolveList };
156
+ export { DEFAULT_CALENDAR_PER_PAGE, DEFAULT_PER_PAGE, asksConfirmation, getOpenMode, getResourceActions, groupActions, resolveList };
69
157
 
70
158
  //# sourceMappingURL=list.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"list.js","names":[],"sources":["../../src/definition/list.ts"],"sourcesContent":["import type { Action, ActionPlacement, Column, Field, Filter, Resource } from '@panneau/protocol';\n\nimport { canRunAction, getActionPlacements } from './abilities';\n\n/** A column ready to render. */\nexport interface ResolvedColumn {\n /** The column id: its `id`, or the name of its field. */\n id: string;\n /** The field shown, when the column shows one. */\n field: Field | null;\n label: string;\n /** How the value is displayed: the column's display, the field's, or the field type. */\n display: string | null;\n sortable: boolean;\n width?: number | string;\n align?: 'start' | 'center' | 'end';\n}\n\n/** A list ready to render. */\nexport interface ResolvedList {\n columns: ResolvedColumn[];\n filters: Filter[];\n /** Fields the list can be sorted by. */\n sorts: string[];\n /** The default sort, as `sort` query values (`['-published_at', 'title']`). */\n defaultSort: string[];\n /** Whether the list can be searched (`q`). */\n search: boolean;\n /** List layouts, the first one being the default. */\n layouts: string[];\n perPage: number;\n perPageOptions: number[];\n /** Fields editable in the list. */\n inlineEdit: string[];\n /** Whether items can be selected: the list allows it and a selection action exists. */\n selectable: boolean;\n /** Actions the user can run, by placement. */\n actions: Record<ActionPlacement, Action[]>;\n}\n\n/** Fields shown when the list declares no columns. */\nconst DEFAULT_COLUMN_COUNT = 4;\nconst NON_COLUMN_TYPES = new Set(['group', 'repeater', 'richtext']);\n\nexport const DEFAULT_PER_PAGE = 20;\n\nfunction columnsFromFields(resource: Resource): Column[] {\n const title = resource.itemTitle;\n const fields = resource.fields.filter((field) => !NON_COLUMN_TYPES.has(field.type));\n const ordered =\n title !== undefined\n ? [\n ...fields.filter((field) => field.name === title),\n ...fields.filter((field) => field.name !== title),\n ]\n : fields;\n return ordered.slice(0, DEFAULT_COLUMN_COUNT).map((field) => ({ field: field.name }));\n}\n\n/** Groups the actions the user can run by placement. */\nexport function groupActions(actions: readonly Action[]): Record<ActionPlacement, Action[]> {\n const groups: Record<ActionPlacement, Action[]> = { row: [], toolbar: [], form: [], menu: [] };\n actions.filter(canRunAction).forEach((action) => {\n getActionPlacements(action).forEach((placement) => groups[placement].push(action));\n });\n return groups;\n}\n\n/**\n * Resolves the list of a resource. Without columns, it shows the item title and the next fields\n * (up to four, skipping groups, repeaters and rich text).\n */\nexport function resolveList(resource: Resource): ResolvedList {\n const list = resource.list ?? {};\n const fields = new Map(resource.fields.map((field) => [field.name, field]));\n const sorts = list.sorts ?? [];\n const columns = (list.columns ?? columnsFromFields(resource)).map((column): ResolvedColumn => {\n const field = column.field !== undefined ? (fields.get(column.field) ?? null) : null;\n const id = column.id ?? column.field ?? '';\n const resolved: ResolvedColumn = {\n id,\n field,\n label: column.label ?? field?.label ?? id,\n display: column.display ?? field?.display ?? field?.type ?? null,\n sortable:\n column.sortable ?? (column.field !== undefined && sorts.includes(column.field)),\n };\n if (column.width !== undefined) {\n resolved.width = column.width;\n }\n if (column.align !== undefined) {\n resolved.align = column.align;\n }\n return resolved;\n });\n const actions = groupActions(resource.actions ?? []);\n const hasSelectionAction = (resource.actions ?? []).some(\n (action) => action.scope.includes('selection') && canRunAction(action),\n );\n return {\n columns,\n filters: list.filters ?? [],\n sorts,\n defaultSort: (list.defaultSort ?? '').split(',').filter((part) => part !== ''),\n search: list.search ?? false,\n layouts: list.layouts ?? ['table'],\n perPage: list.perPage ?? DEFAULT_PER_PAGE,\n perPageOptions: list.perPageOptions ?? [],\n inlineEdit: list.inlineEdit ?? [],\n selectable: (list.selectable ?? true) && hasSelectionAction,\n actions,\n };\n}\n"],"mappings":";;;AAyCA,IAAM,uBAAuB;AAC7B,IAAM,mCAAmB,IAAI,IAAI;CAAC;CAAS;CAAY;AAAU,CAAC;AAElE,IAAa,mBAAmB;AAEhC,SAAS,kBAAkB,UAA8B;CACrD,MAAM,QAAQ,SAAS;CACvB,MAAM,SAAS,SAAS,OAAO,QAAQ,UAAU,CAAC,iBAAiB,IAAI,MAAM,IAAI,CAAC;CAQlF,QANI,UAAU,KAAA,IACJ,CACI,GAAG,OAAO,QAAQ,UAAU,MAAM,SAAS,KAAK,GAChD,GAAG,OAAO,QAAQ,UAAU,MAAM,SAAS,KAAK,CAAC,IAErD,OAAA,CACK,MAAM,GAAG,oBAAoB,CAAC,CAAC,KAAK,WAAW,EAAE,OAAO,MAAM,KAAK,EAAE;AACxF;;AAGA,SAAgB,aAAa,SAA+D;CACxF,MAAM,SAA4C;EAAE,KAAK,CAAA;EAAI,SAAS,CAAA;EAAI,MAAM,CAAA;EAAI,MAAM,CAAA;CAAG;CAC7F,QA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ACjC,SAAS,KAAK,WAAA;EACd,gBAAgB,KAAK,kBAAkB,CAAA;EACvC,YAAY,KAAK,cAAc,CAAA;EAC/B,aAAa,KAAK,cAAc,SAAS;EACzC;CACJ;AACJ"}
1
+ {"version":3,"file":"list.js","names":["Action","ActionPlacement","Column","Field","Filter","Resource","BUILT_IN_ITEM_ACTIONS","BuiltInItemAction","UNDO_LIMIT","getNestedShape","isBuiltInItemAction","canRunAction","canUpdateField","canViewField","getActionPlacements","ResolvedColumn","id","field","label","display","sortable","width","align","hidden","hideable","ResolvedCalendar","filter","perPage","ResolvedList","columns","filters","sorts","defaultSort","search","layouts","perPageOptions","pagination","inlineEdit","selectable","actions","Record","calendar","DEFAULT_COLUMN_COUNT","NON_COLUMN_TYPES","Set","DEFAULT_PER_PAGE","DEFAULT_CALENDAR_PER_PAGE","columnsFromFields","resource","title","itemTitle","fields","has","type","ordered","undefined","name","slice","map","asksConfirmation","action","count","confirm","undoable","queued","groupActions","groups","row","toolbar","form","menu","forEach","placement","push","BUILT_IN_ITEM_ACTION_DEFINITIONS","Readonly","show","kind","scope","edit","duplicate","delete","destructive","dryRun","getResourceActions","declared","ids","itemActions","index","all","indexOf","getOpenMode","replacement","find","builtIn","open","resolveList","list","Map","sort","declaredColumns","column","get","resolved","includes","hasSelectionAction","some","split","part"],"sources":["../../src/definition/list.ts"],"sourcesContent":["import type { Action, ActionPlacement, Column, Field, Filter, Resource } from '@panneau/protocol';\nimport {\n BUILT_IN_ITEM_ACTIONS,\n type BuiltInItemAction,\n UNDO_LIMIT,\n getNestedShape,\n isBuiltInItemAction,\n} from '@panneau/protocol/runtime';\n\nimport { canRunAction, canUpdateField, canViewField, getActionPlacements } from './abilities';\n\n/** A column ready to render. */\nexport interface ResolvedColumn {\n /** The column id: its `id`, or the name of its field. */\n id: string;\n /** The field shown, when the column shows one. */\n field: Field | null;\n label: string;\n /** How the value is displayed: the column's display, the field's, or the field type. */\n display: string | null;\n sortable: boolean;\n width?: number | string;\n align?: 'start' | 'center' | 'end';\n /** Not shown until the user shows it (decision 0042). */\n hidden: boolean;\n /** Whether the user can hide it. */\n hideable: boolean;\n}\n\n/** The calendar of a list (decision 0044). */\nexport interface ResolvedCalendar {\n /** The `date` or `datetime` field each item is shown on the day of. */\n field: string;\n /** The id of the `date-range` filter the calendar asks for a month through. */\n filter: string;\n /** How many items the calendar asks for a month. */\n perPage: number;\n}\n\n/** A list ready to render. */\nexport interface ResolvedList {\n columns: ResolvedColumn[];\n filters: Filter[];\n /** Fields the list can be sorted by. */\n sorts: string[];\n /** The default sort, as `sort` query values (`['-published_at', 'title']`). */\n defaultSort: string[];\n /** Whether the list can be searched (`q`). */\n search: boolean;\n /** List layouts, the first one being the default. */\n layouts: string[];\n perPage: number;\n perPageOptions: number[];\n /** `pages` (numbered, with a total), or `cursor`: the list follows the cursors of its pages. */\n pagination: 'pages' | 'cursor';\n /** Fields editable in the list. */\n inlineEdit: string[];\n /** Whether items can be selected: the list allows it and a selection action exists. */\n selectable: boolean;\n /** Actions the user can run, by placement. */\n actions: Record<ActionPlacement, Action[]>;\n /** The calendar of the list, for its `calendar` layout, or `null`. */\n calendar: ResolvedCalendar | null;\n}\n\n/** Fields shown when the list declares no columns. */\nconst DEFAULT_COLUMN_COUNT = 4;\nconst NON_COLUMN_TYPES = new Set(['richtext']);\n\nexport const DEFAULT_PER_PAGE = 20;\n\n/** How many items a calendar asks for a month, without its own `perPage`. */\nexport const DEFAULT_CALENDAR_PER_PAGE = 100;\n\nfunction columnsFromFields(resource: Resource): Column[] {\n const title = resource.itemTitle;\n const fields = resource.fields.filter(\n (field) =>\n !NON_COLUMN_TYPES.has(field.type) &&\n getNestedShape(field) === null &&\n canViewField(field),\n );\n const ordered =\n title !== undefined\n ? [\n ...fields.filter((field) => field.name === title),\n ...fields.filter((field) => field.name !== title),\n ]\n : fields;\n return ordered.slice(0, DEFAULT_COLUMN_COUNT).map((field) => ({ field: field.name }));\n}\n\n/**\n * Whether running an action asks first (decisions 0017 and 0063): its `confirm`, when it sets one;\n * otherwise, for an `undoable` action, only above `UNDO_LIMIT` items or for a queued one, which\n * can't be undone. `count` is the number of items, from the selection or a dry run.\n */\nexport function asksConfirmation(action: Action, count = 1): boolean {\n if (action.confirm !== undefined) {\n return action.confirm !== false;\n }\n return action.undoable === true && (count > UNDO_LIMIT || action.queued === true);\n}\n\n/** Groups the actions the user can run by placement. */\nexport function groupActions(actions: readonly Action[]): Record<ActionPlacement, Action[]> {\n const groups: Record<ActionPlacement, Action[]> = { row: [], toolbar: [], form: [], menu: [] };\n actions.filter(canRunAction).forEach((action) => {\n getActionPlacements(action).forEach((placement) => groups[placement].push(action));\n });\n return groups;\n}\n\n/** The built-in item actions, as the client shows them when a resource doesn't replace them. */\nconst BUILT_IN_ITEM_ACTION_DEFINITIONS: Readonly<Record<BuiltInItemAction, Action>> = {\n show: { id: 'show', kind: 'link', scope: ['item'], placement: ['row', 'form'] },\n edit: { id: 'edit', kind: 'link', scope: ['item'], placement: ['row', 'form'] },\n duplicate: { id: 'duplicate', kind: 'server', scope: ['item'], placement: ['menu', 'form'] },\n delete: {\n id: 'delete',\n kind: 'server',\n scope: ['item', 'selection'],\n placement: ['menu', 'toolbar', 'form'],\n destructive: true,\n confirm: true,\n dryRun: true,\n },\n};\n\n/**\n * The actions of a resource (decision 0040): its built-in item actions (`show`, `edit`,\n * `duplicate`, `delete`, or those of its `itemActions`, in their order), then the actions it\n * declares. A declared action with the id of a built-in one replaces it, at its place, with the\n * built-in one's placement, confirmation, `destructive` and `dryRun` when it doesn't set them, and\n * is left out with it when `itemActions` doesn't list it. Unless items open in the panel\n * (`\"open\": \"panel\"`), `show` is left out: it would go to the edit form too. Abilities of the items then hide what they don't allow.\n */\nexport function getResourceActions(resource: Resource): Action[] {\n const declared = resource.actions ?? [];\n const ids = (resource.itemActions ?? BUILT_IN_ITEM_ACTIONS).filter(\n (id, index, all): id is BuiltInItemAction =>\n isBuiltInItemAction(id) &&\n all.indexOf(id) === index &&\n !(id === 'show' && getOpenMode(resource) === 'edit'),\n );\n return [\n ...ids.map((id): Action => {\n const replacement = declared.find((action) => action.id === id);\n // What the declared action doesn't set (placement, confirmation, dry runs) is the\n // built-in one's. An undoable one doesn't take the built-in confirmation (decision\n // 0063): \"Undo\" replaces it.\n if (replacement === undefined) {\n return BUILT_IN_ITEM_ACTION_DEFINITIONS[id];\n }\n const { confirm, ...builtIn } = BUILT_IN_ITEM_ACTION_DEFINITIONS[id];\n return replacement.undoable === true\n ? { ...builtIn, ...replacement }\n : { ...builtIn, ...(confirm !== undefined ? { confirm } : {}), ...replacement };\n }),\n ...declared.filter((action) => !isBuiltInItemAction(action.id)),\n ];\n}\n\n/**\n * Where the title of an item goes (`open` of the resource, decision 0082): `edit`, its form, the\n * default, or `panel`, the show route with the item's details next to the list. A value it doesn't\n * know is `edit`.\n */\nexport function getOpenMode(resource: Resource): 'panel' | 'edit' {\n return resource.open === 'panel' ? 'panel' : 'edit';\n}\n\n/**\n * Resolves the list of a resource. Without columns, it shows the item title and the next fields\n * (up to four, skipping groups, repeaters and rich text). Fields the current user can't see\n * (`abilities.view: false`) have no column, sort or inline editing, and those they can't edit\n * aren't edited inline (decision 0046).\n */\nexport function resolveList(resource: Resource): ResolvedList {\n const list = resource.list ?? {};\n const fields = new Map(resource.fields.map((field) => [field.name, field]));\n const hidden = new Set(\n resource.fields.filter((field) => !canViewField(field)).map((field) => field.name),\n );\n const sorts = (list.sorts ?? []).filter((sort) => !hidden.has(sort));\n const declaredColumns = (list.columns ?? columnsFromFields(resource)).filter(\n (column) => column.field === undefined || !hidden.has(column.field),\n );\n const columns = declaredColumns.map((column): ResolvedColumn => {\n const field = column.field !== undefined ? (fields.get(column.field) ?? null) : null;\n const id = column.id ?? column.field ?? '';\n const resolved: ResolvedColumn = {\n id,\n field,\n label: column.label ?? field?.label ?? id,\n display: column.display ?? field?.display ?? field?.type ?? null,\n sortable:\n column.sortable ?? (column.field !== undefined && sorts.includes(column.field)),\n hidden: column.hidden === true && column.hideable !== false,\n hideable: column.hideable !== false,\n };\n if (column.width !== undefined) {\n resolved.width = column.width;\n }\n if (column.align !== undefined) {\n resolved.align = column.align;\n }\n return resolved;\n });\n const actions = groupActions(getResourceActions(resource));\n const hasSelectionAction = getResourceActions(resource).some(\n (action) => action.scope.includes('selection') && canRunAction(action),\n );\n return {\n columns,\n filters: list.filters ?? [],\n sorts,\n defaultSort: (list.defaultSort ?? '').split(',').filter((part) => part !== ''),\n search: list.search ?? false,\n layouts: list.layouts ?? ['table'],\n perPage: list.perPage ?? DEFAULT_PER_PAGE,\n perPageOptions: list.perPageOptions ?? [],\n pagination: list.pagination ?? 'pages',\n inlineEdit: (list.inlineEdit ?? []).filter((name) => {\n const field = fields.get(name);\n return field === undefined || canUpdateField(field);\n }),\n selectable: (list.selectable ?? true) && hasSelectionAction,\n actions,\n calendar:\n list.calendar !== undefined\n ? {\n field: list.calendar.field,\n filter: list.calendar.filter ?? list.calendar.field,\n perPage: list.calendar.perPage ?? DEFAULT_CALENDAR_PER_PAGE,\n }\n : null,\n };\n}\n"],"mappings":";;;;AAkEA,IAAM0C,uBAAuB;AAC7B,IAAMC,mCAAmB,IAAIC,IAAI,CAAC,UAAU,CAAC;AAE7C,IAAaC,mBAAmB;;AAGhC,IAAaC,4BAA4B;AAEzC,SAASC,kBAAkBC,UAA8B;CACrD,MAAMC,QAAQD,SAASE;CACvB,MAAMC,SAASH,SAASG,OAAOzB,QAC1BT,UACG,CAAC0B,iBAAiBS,IAAInC,MAAMoC,IAAI,KAChC5C,eAAeQ,KAAK,MAAM,QAC1BJ,aAAaI,KAAK,CAC1B;CAQA,QANIgC,UAAUM,KAAAA,IACJ,CACI,GAAGJ,OAAOzB,QAAQT,UAAUA,MAAMuC,SAASP,KAAK,GAChD,GAAGE,OAAOzB,QAAQT,UAAUA,MAAMuC,SAASP,KAAK,CAAC,IAErDE,OAAAA,CACKM,MAAM,GAAGf,oBAAoB,CAAC,CAACgB,KAAKzC,WAAW,EAAEA,OAAOA,MA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,cAAc,CAAA,EAAA,CAAIX,QAAQ8B,SAAS;GACjD,MAAMvC,QAAQkC,OAAOmD,IAAI9C,IAAI;GAC7B,OAAOvC,UAAUsC,KAAAA,KAAa3C,eAAeK,KAAK;EACtD,CAAC;EACDqB,aAAa2D,KAAK3D,cAAc,SAASmE;EACzClE;EACAE,UACIwD,KAAKxD,aAAac,KAAAA,IACZ;GACItC,OAAOgF,KAAKxD,SAASxB;GACrBS,QAAQuE,KAAKxD,SAASf,UAAUuE,KAAKxD,SAASxB;GAC9CU,SAASsE,KAAKxD,SAASd,WAAAA;EAC3B,IACA;CACd;AACJ"}
@@ -1,9 +1,10 @@
1
1
  import type { Definition, Resource } from '@panneau/protocol';
2
- import { type ResolveFormOptions, type ResolvedForm } from './form';
3
- import { type ResolvedList } from './list';
2
+ import { type ResolveFormOptions, type ResolvedForm } from './form.js';
3
+ import { type ResolvedList } from './list.js';
4
4
  /** What the current user can do with a resource as a whole. */
5
5
  export interface ResourceAbilities {
6
6
  viewAny: boolean;
7
+ /** With `types`, only when one of them can be created too (decision 0077). */
7
8
  create: boolean;
8
9
  }
9
10
  /** A resource with its form, its list and its abilities resolved. */
@@ -1 +1 @@
1
- {"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../../src/definition/resource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAG9D,OAAO,EAAE,KAAK,kBAAkB,EAAE,KAAK,YAAY,EAAe,MAAM,QAAQ,CAAC;AACjF,OAAO,EAAE,KAAK,YAAY,EAAe,MAAM,QAAQ,CAAC;AAExD,+DAA+D;AAC/D,MAAM,WAAW,iBAAiB;IAC9B,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,OAAO,CAAC;CACnB;AAED,qEAAqE;AACrE,MAAM,WAAW,gBAAgB;IAC7B,QAAQ,EAAE,QAAQ,CAAC;IACnB,sFAAsF;IACtF,IAAI,EAAE,YAAY,CAAC;IACnB,IAAI,EAAE,YAAY,CAAC;IACnB,SAAS,EAAE,iBAAiB,CAAC;CAChC;AAED,qEAAqE;AACrE,wBAAgB,eAAe,CAC3B,QAAQ,EAAE,QAAQ,EAClB,WAAW,GAAE,kBAAuC,GACrD,gBAAgB,CAUlB;AAED,8CAA8C;AAC9C,wBAAgB,YAAY,CAAC,UAAU,EAAE,UAAU,EAAE,EAAE,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,CAErF"}
1
+ {"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../../src/definition/resource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAI9D,OAAO,EAAE,KAAK,kBAAkB,EAAE,KAAK,YAAY,EAAe,MAAM,QAAQ,CAAC;AACjF,OAAO,EAAE,KAAK,YAAY,EAAe,MAAM,QAAQ,CAAC;AAExD,+DAA+D;AAC/D,MAAM,WAAW,iBAAiB;IAC9B,OAAO,EAAE,OAAO,CAAC;IACjB,8EAA8E;IAC9E,MAAM,EAAE,OAAO,CAAC;CACnB;AAED,qEAAqE;AACrE,MAAM,WAAW,gBAAgB;IAC7B,QAAQ,EAAE,QAAQ,CAAC;IACnB,sFAAsF;IACtF,IAAI,EAAE,YAAY,CAAC;IACnB,IAAI,EAAE,YAAY,CAAC;IACnB,SAAS,EAAE,iBAAiB,CAAC;CAChC;AAED,qEAAqE;AACrE,wBAAgB,eAAe,CAC3B,QAAQ,EAAE,QAAQ,EAClB,WAAW,GAAE,kBAAuC,GACrD,gBAAgB,CAYlB;AAED,8CAA8C;AAC9C,wBAAgB,YAAY,CAAC,UAAU,EAAE,UAAU,EAAE,EAAE,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,CAErF"}
@@ -1,6 +1,7 @@
1
1
  import { can } from "./abilities.js";
2
- import { resolveForm } from "./form.js";
3
2
  import { resolveList } from "./list.js";
3
+ import { resolveForm } from "./form.js";
4
+ import { getCreatableTypes, hasResourceTypes } from "@panneau/protocol/runtime";
4
5
  //#region src/definition/resource.ts
5
6
  /** Resolves a resource into its form, its list and its abilities. */
6
7
  function resolveResource(resource, formOptions = { mode: "create" }) {
@@ -10,7 +11,7 @@ function resolveResource(resource, formOptions = { mode: "create" }) {
10
11
  list: resolveList(resource),
11
12
  abilities: {
12
13
  viewAny: can(resource.abilities, "viewAny"),
13
- create: can(resource.abilities, "create")
14
+ create: can(resource.abilities, "create") && (!hasResourceTypes(resource) || getCreatableTypes(resource).length > 0)
14
15
  }
15
16
  };
16
17
  }
@@ -1 +1 @@
1
- {"version":3,"file":"resource.js","names":[],"sources":["../../src/definition/resource.ts"],"sourcesContent":["import type { Definition, Resource } from '@panneau/protocol';\n\nimport { can } from './abilities';\nimport { type ResolveFormOptions, type ResolvedForm, resolveForm } from './form';\nimport { type ResolvedList, resolveList } from './list';\n\n/** What the current user can do with a resource as a whole. */\nexport interface ResourceAbilities {\n viewAny: boolean;\n create: boolean;\n}\n\n/** A resource with its form, its list and its abilities resolved. */\nexport interface ResolvedResource {\n resource: Resource;\n /** The form to create an item. Use `resolveForm()` for an update, or an item type. */\n form: ResolvedForm;\n list: ResolvedList;\n abilities: ResourceAbilities;\n}\n\n/** Resolves a resource into its form, its list and its abilities. */\nexport function resolveResource(\n resource: Resource,\n formOptions: ResolveFormOptions = { mode: 'create' },\n): ResolvedResource {\n return {\n resource,\n form: resolveForm(resource, formOptions),\n list: resolveList(resource),\n abilities: {\n viewAny: can(resource.abilities, 'viewAny'),\n create: can(resource.abilities, 'create'),\n },\n };\n}\n\n/** Finds a resource of a definition by id. */\nexport function findResource(definition: Definition, id: string): Resource | undefined {\n return definition.resources.find((resource) => resource.id === id);\n}\n"],"mappings":";;;;;AAsBA,SAAgB,gBACZ,UACA,cAAkC,EAAE,MAAM,SAAS,GACnC;CAChB,OAAO;EACH;EACA,MAAM,YAAY,UAAU,WAAW;EACvC,MAAM,YAAY,QAAQ;EAC1B,WAAW;GACP,SAAS,IAAI,SAAS,WAAW,SAAS;GAC1C,QAAQ,IAAI,SAAS,WAAW,QAAQ;EAC5C;CACJ;AACJ;;AAGA,SAAgB,aAAa,YAAwB,IAAkC;CACnF,OAAO,WAAW,UAAU,MAAM,aAAa,SAAS,OAAO,EAAE;AACrE"}
1
+ {"version":3,"file":"resource.js","names":["Definition","Resource","getCreatableTypes","hasResourceTypes","can","ResolveFormOptions","ResolvedForm","resolveForm","ResolvedList","resolveList","ResourceAbilities","viewAny","create","ResolvedResource","resource","form","list","abilities","resolveResource","formOptions","mode","length","findResource","definition","id","resources","find"],"sources":["../../src/definition/resource.ts"],"sourcesContent":["import type { Definition, Resource } from '@panneau/protocol';\nimport { getCreatableTypes, hasResourceTypes } from '@panneau/protocol/runtime';\n\nimport { can } from './abilities';\nimport { type ResolveFormOptions, type ResolvedForm, resolveForm } from './form';\nimport { type ResolvedList, resolveList } from './list';\n\n/** What the current user can do with a resource as a whole. */\nexport interface ResourceAbilities {\n viewAny: boolean;\n /** With `types`, only when one of them can be created too (decision 0077). */\n create: boolean;\n}\n\n/** A resource with its form, its list and its abilities resolved. */\nexport interface ResolvedResource {\n resource: Resource;\n /** The form to create an item. Use `resolveForm()` for an update, or an item type. */\n form: ResolvedForm;\n list: ResolvedList;\n abilities: ResourceAbilities;\n}\n\n/** Resolves a resource into its form, its list and its abilities. */\nexport function resolveResource(\n resource: Resource,\n formOptions: ResolveFormOptions = { mode: 'create' },\n): ResolvedResource {\n return {\n resource,\n form: resolveForm(resource, formOptions),\n list: resolveList(resource),\n abilities: {\n viewAny: can(resource.abilities, 'viewAny'),\n create:\n can(resource.abilities, 'create') &&\n (!hasResourceTypes(resource) || getCreatableTypes(resource).length > 0),\n },\n };\n}\n\n/** Finds a resource of a definition by id. */\nexport function findResource(definition: Definition, id: string): Resource | undefined {\n return definition.resources.find((resource) => resource.id === id);\n}\n"],"mappings":";;;;;;AAwBA,SAAgBkB,gBACZJ,UACAK,cAAkC,EAAEC,MAAM,SAAS,GACnC;CAChB,OAAO;EACHN;EACAC,MAAMR,YAAYO,UAAUK,WAAW;EACvCH,MAAMP,YAAYK,QAAQ;EAC1BG,WAAW;GACPN,SAASP,IAAIU,SAASG,WAAW,SAAS;GAC1CL,QACIR,IAAIU,SAASG,WAAW,QAAQ,MAC/B,CAACd,iBAAiBW,QAAQ,KAAKZ,kBAAkBY,QAAQ,CAAC,CAACO,SAAS;EAC7E;CACJ;AACJ;;AAGA,SAAgBC,aAAaC,YAAwBC,IAAkC;CACnF,OAAOD,WAAWE,UAAUC,MAAMZ,aAAaA,SAASU,OAAOA,EAAE;AACrE"}
@@ -1,7 +1,7 @@
1
1
  import type { Condition, Field, Item, RuleFailure } from '@panneau/protocol';
2
- import type { FormMode } from '../definition/form';
3
- import { type Values } from '../values';
4
- import { type FormStore } from './store';
2
+ import type { FormMode } from '../definition/form.js';
3
+ import { type Values } from '../values.js';
4
+ import { type FormStore } from './store.js';
5
5
  /**
6
6
  * - `idle`: nothing submitted yet, or after a reset;
7
7
  * - `submitting`: waiting for `onSubmit`;
@@ -95,6 +95,11 @@ export interface GetErrorsOptions {
95
95
  * (`selectValue()`, `selectErrors()`, `selectErrorCount()`, `selectVisible()`).
96
96
  */
97
97
  export interface Form {
98
+ /**
99
+ * Whether the form creates or updates an item: its `mode` option, or `update` with a version
100
+ * and `create` without. Rules limited to a mode apply in this one.
101
+ */
102
+ readonly mode: FormMode;
98
103
  getState(): FormState;
99
104
  subscribe(listener: () => void): () => void;
100
105
  /** Updates the options that can change between renders. */
@@ -1 +1 @@
1
- {"version":3,"file":"form.d.ts","sourceRoot":"","sources":["../../src/form/form.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAG7E,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,KAAK,MAAM,EAAyB,MAAM,WAAW,CAAC;AAI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/form.js CHANGED
@@ -160,6 +160,7 @@ function createForm(options) {
160
160
  }
161
161
  };
162
162
  const form = {
163
+ mode,
163
164
  getState() {
164
165
  if (unsubscribeStore === null) onStoreChange();
165
166
  return state;
@@ -1 +1 @@
1
- {"version":3,"file":"form.js","names":[],"sources":["../../src/form/form.ts"],"sourcesContent":["import type { Condition, Field, Item, RuleFailure } from '@panneau/protocol';\nimport { checkValues, getValue } from '@panneau/protocol/runtime';\n\nimport type { FormMode } from '../definition/form';\nimport { type Values, isEqual, isPathWithin } from '../values';\nimport { formatRuleFailure } from './messages';\nimport { getItemValues, getProblem, isItem } from './problem';\nimport { selectErrorCount, selectErrors, selectValue, selectVisible } from './selectors';\nimport { type FormStore, createLocalStore } from './store';\n\n/**\n * - `idle`: nothing submitted yet, or after a reset;\n * - `submitting`: waiting for `onSubmit`;\n * - `submitted`: the last submit succeeded;\n * - `invalid`: client validation or the server (`422`) found errors;\n * - `conflict`: the item changed since the form's version (`412`), see `resolveConflict()`;\n * - `error`: the last submit failed for another reason (network, `403`, `500`…), see `error`.\n */\nexport type FormStatus = 'idle' | 'submitting' | 'submitted' | 'invalid' | 'conflict' | 'error';\n\nexport interface FormConflict {\n /** The current version of the item, when the backend sent it. */\n current: Item | null;\n}\n\n/** A snapshot of a form. A new object is created on every change. */\nexport interface FormState {\n values: Values;\n /** The values the form started from, or was last saved with. `dirty` compares to them. */\n initialValues: Values;\n /** The version of the item the values were edited from, sent with the submit. */\n version: string | null;\n /** Whether the values differ from the initial values. */\n dirty: boolean;\n /**\n * Errors shown, by dot path (`title.fr`): client errors of touched fields (all of them after a\n * submit), then server errors. A server error goes away when its value changes.\n */\n errors: Record<string, string[]>;\n /** Paths of the fields that lost focus at least once. */\n touched: ReadonlySet<string>;\n status: FormStatus;\n /** With the `conflict` status: what the backend says is current. */\n conflict: FormConflict | null;\n /** With the `error` status: what `onSubmit` threw. */\n error: unknown;\n submitCount: number;\n}\n\nexport interface SubmitContext {\n mode: FormMode;\n /** The version to send as `If-Match`. */\n version: string | null;\n /** The top-level values that differ from the initial values, for partial updates. */\n changes: Values;\n}\n\nexport type SubmitResult =\n | { status: 'submitted'; result: unknown }\n | { status: 'invalid'; errors: Record<string, string[]> }\n | { status: 'conflict'; current: Item | null }\n | { status: 'error'; error: unknown };\n\nexport interface FormOptions {\n /** The fields of the form, as resolved by `resolveForm()`. */\n fields: Field[];\n /** Initial values. In `create` mode, fields without a value get their `default`. */\n values?: Values;\n /** The version of the item the values come from. */\n version?: string | null;\n /** Defaults to `update` when a version is given, `create` otherwise. */\n mode?: FormMode;\n /** Locales a `required` localized field must be filled in (all of them, usually). */\n locales?: string[];\n /** Where the values live. Defaults to a local store. */\n store?: FormStore;\n /** Message of a failed rule. Defaults to `formatRuleFailure()`. */\n formatError?: (failure: RuleFailure, path: string) => string;\n /**\n * Saves the values. When it returns an item, the form continues from that item. When it\n * throws an error that carries problem details (`getProblem()`), `422` errors are shown by\n * path and `412` puts the form in the `conflict` status.\n */\n onSubmit?: (values: Values, context: SubmitContext) => unknown;\n}\n\n/** Form options that can change after the form is created. */\nexport type UpdatableFormOptions = Pick<\n FormOptions,\n 'fields' | 'locales' | 'formatError' | 'onSubmit'\n>;\n\nexport interface GetErrorsOptions {\n /** Also return the errors of nested paths (`title.fr` for `title`). */\n nested?: boolean;\n}\n\n/**\n * A headless form: values, errors, visibility and submit. React components use `useForm()`.\n *\n * The methods that read the state (`getValue()`, `getErrors()`, `countErrors()`, `isVisible()`)\n * are not React APIs: the React Compiler memoizes their calls by their arguments, so they return\n * stale results in components. Components read the state they subscribed to with the selectors\n * (`selectValue()`, `selectErrors()`, `selectErrorCount()`, `selectVisible()`).\n */\nexport interface Form {\n getState(): FormState;\n subscribe(listener: () => void): () => void;\n /** Updates the options that can change between renders. */\n setOptions(options: Partial<UpdatableFormOptions>): void;\n /**\n * The value at a dot path. Not a React API: components use `selectValue(state, path)` (see\n * {@link Form}).\n */\n getValue(path: string): unknown;\n setValue(path: string, value: unknown): void;\n /** Marks a field as touched, which shows its client errors. */\n blur(path: string): void;\n /**\n * Errors at a path. Not a React API: components use `selectErrors(state, path, options)` (see\n * {@link Form}).\n */\n getErrors(path: string, options?: GetErrorsOptions): string[];\n /**\n * The number of paths with errors within the given paths, for counts on tabs and sections. Not\n * a React API: components use `selectErrorCount(state, paths)` (see {@link Form}).\n */\n countErrors(paths: readonly string[]): number;\n /**\n * Whether a field or a layout node is visible, from its `visibleWhen`. For nested fields, pass\n * the path of the object they belong to (`blocks.2`): conditions are relative to it. Not a\n * React API: components use `selectVisible(state, target, parentPath)` (see {@link Form}).\n */\n isVisible(target: { visibleWhen?: Condition | undefined }, parentPath?: string): boolean;\n /** Checks every value with the portable rules and shows every error. Returns whether valid. */\n validate(): boolean;\n /** Shows server errors, by dot path. */\n setServerErrors(errors: Record<string, string[]>): void;\n /** Validates, then calls `onSubmit`. */\n submit(): Promise<SubmitResult>;\n /** Starts over from new values (or the initial ones), and a new version. */\n reset(values?: Values, version?: string | null): void;\n /**\n * Leaves the `conflict` status:\n *\n * - `reload` drops the local changes and continues from the current item;\n * - `overwrite` keeps the local changes and submits them again over the current version.\n */\n resolveConflict(choice: 'reload' | 'overwrite'): Promise<SubmitResult | null>;\n}\n\n/** Initial values of fields that have a `default` and no value. */\nexport function getDefaultValues(fields: readonly Field[], values: Values = {}): Values {\n return fields.reduce<Values>(\n (result, field) =>\n field.default !== undefined && result[field.name] === undefined\n ? { ...result, [field.name]: field.default }\n : result,\n values,\n );\n}\n\nfunction mergeErrors(...sources: Record<string, string[]>[]): Record<string, string[]> {\n const merged: Record<string, string[]> = {};\n sources.forEach((source) =>\n Object.entries(source).forEach(([path, messages]) => {\n merged[path] = [...(merged[path] ?? []), ...messages];\n }),\n );\n return merged;\n}\n\n/** Creates a headless form. */\nexport function createForm(options: FormOptions): Form {\n const current: Required<UpdatableFormOptions> = {\n fields: options.fields,\n locales: options.locales ?? [],\n formatError: options.formatError ?? formatRuleFailure,\n onSubmit: options.onSubmit ?? (() => undefined),\n };\n const mode: FormMode =\n options.mode ??\n (options.version !== undefined && options.version !== null ? 'update' : 'create');\n const startValues =\n mode === 'create'\n ? getDefaultValues(options.fields, options.values)\n : (options.values ?? {});\n const store = options.store ?? createLocalStore(startValues);\n if (options.store !== undefined && options.values !== undefined) {\n store.setValues(startValues);\n }\n\n let initialValues = store.getValues();\n let version = options.version ?? null;\n let touched: ReadonlySet<string> = new Set();\n let serverErrors: Record<string, string[]> = {};\n let status: FormStatus = 'idle';\n let conflict: FormConflict | null = null;\n let error: unknown = null;\n let submitCount = 0;\n let pending: Promise<SubmitResult> | null = null;\n\n const listeners = new Set<() => void>();\n let unsubscribeStore: (() => void) | null = null;\n\n const clientErrors = (values: Values, all: boolean): Record<string, string[]> => {\n const failures = checkValues(current.fields, values, { mode, locales: current.locales });\n return Object.fromEntries(\n Object.entries(failures)\n .filter(\n ([path]) => all || [...touched].some((parent) => isPathWithin(path, parent)),\n )\n .map(([path, list]) => [\n path,\n list.map((failure) => current.formatError(failure, path)),\n ]),\n );\n };\n\n const compute = (values: Values): FormState => ({\n values,\n initialValues,\n version,\n dirty: !isEqual(values, initialValues),\n errors: mergeErrors(clientErrors(values, submitCount > 0), serverErrors),\n touched,\n status,\n conflict,\n error,\n submitCount,\n });\n\n let state = compute(store.getValues());\n\n const update = () => {\n state = compute(store.getValues());\n listeners.forEach((listener) => listener());\n };\n\n /** Server errors go away when their value changes. */\n const onStoreChange = () => {\n const previous = state.values;\n const values = store.getValues();\n if (values === previous) {\n return;\n }\n serverErrors = Object.fromEntries(\n Object.entries(serverErrors).filter(([path]) =>\n isEqual(getValue(previous, path), getValue(values, path)),\n ),\n );\n update();\n };\n\n const changes = (values: Values): Values =>\n Object.fromEntries(\n Object.entries({ ...initialValues, ...values }).flatMap(([key]) =>\n isEqual(values[key], initialValues[key]) ? [] : [[key, values[key]]],\n ),\n );\n\n const fieldNames = () => current.fields.map((field) => field.name);\n\n const reset = (values?: Values, nextVersion?: string | null) => {\n if (nextVersion !== undefined) {\n version = nextVersion;\n }\n touched = new Set();\n serverErrors = {};\n status = 'idle';\n conflict = null;\n error = null;\n submitCount = 0;\n if (values !== undefined) {\n initialValues = values;\n store.setValues(values);\n } else {\n store.setValues(initialValues);\n }\n update();\n };\n\n const runSubmit = async (): Promise<SubmitResult> => {\n submitCount += 1;\n serverErrors = {};\n const values = store.getValues();\n const errors = clientErrors(values, true);\n if (Object.keys(errors).length > 0) {\n status = 'invalid';\n update();\n return { status: 'invalid', errors };\n }\n status = 'submitting';\n conflict = null;\n error = null;\n update();\n try {\n const result = await current.onSubmit(values, {\n mode,\n version,\n changes: changes(values),\n });\n if (isItem(result)) {\n const saved = getItemValues(result, fieldNames());\n version = result.version;\n initialValues = saved;\n // Keep what was typed while saving; otherwise take the saved values.\n if (store.getValues() === values) {\n store.setValues(saved);\n }\n } else {\n initialValues = values;\n }\n touched = new Set();\n submitCount = 0;\n status = 'submitted';\n update();\n return { status: 'submitted', result };\n } catch (caught) {\n const problem = getProblem(caught);\n if (problem?.status === 412) {\n status = 'conflict';\n conflict = { current: problem.current ?? null };\n update();\n return { status: 'conflict', current: conflict.current };\n }\n if (problem?.status === 422 && problem.errors !== undefined) {\n status = 'invalid';\n serverErrors = problem.errors;\n update();\n return { status: 'invalid', errors: problem.errors };\n }\n status = 'error';\n error = caught;\n update();\n return { status: 'error', error: caught };\n }\n };\n\n const form: Form = {\n getState() {\n if (unsubscribeStore === null) {\n onStoreChange();\n }\n return state;\n },\n subscribe(listener) {\n listeners.add(listener);\n unsubscribeStore ??= store.subscribe(onStoreChange);\n onStoreChange();\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0 && unsubscribeStore !== null) {\n unsubscribeStore();\n unsubscribeStore = null;\n }\n };\n },\n setOptions(next) {\n const { fields, locales, formatError, onSubmit } = next;\n if (onSubmit !== undefined) {\n current.onSubmit = onSubmit;\n }\n if (formatError !== undefined) {\n current.formatError = formatError;\n }\n // Fields and locales change what is valid: compare them by value, since a render can\n // create new arrays with the same content.\n const changed =\n (fields !== undefined && !isEqual(fields, current.fields)) ||\n (locales !== undefined && !isEqual(locales, current.locales));\n if (fields !== undefined) {\n current.fields = fields;\n }\n if (locales !== undefined) {\n current.locales = locales;\n }\n if (changed) {\n update();\n }\n },\n getValue: (path) => selectValue(form.getState(), path),\n setValue(path, value) {\n store.setValue(path, value);\n if (unsubscribeStore === null) {\n onStoreChange();\n }\n },\n blur(path) {\n if (touched.has(path)) {\n return;\n }\n touched = new Set([...touched, path]);\n update();\n },\n getErrors: (path, getErrorsOptions) =>\n selectErrors(form.getState(), path, getErrorsOptions),\n countErrors: (paths) => selectErrorCount(form.getState(), paths),\n isVisible: (target, parentPath) => selectVisible(form.getState(), target, parentPath),\n validate() {\n submitCount = Math.max(submitCount, 1);\n update();\n return Object.keys(clientErrors(store.getValues(), true)).length === 0;\n },\n setServerErrors(errors) {\n serverErrors = errors;\n update();\n },\n submit() {\n pending ??= runSubmit().finally(() => {\n pending = null;\n });\n return pending;\n },\n reset,\n async resolveConflict(choice) {\n if (status !== 'conflict' || conflict === null) {\n return null;\n }\n const latest = conflict.current;\n if (choice === 'reload') {\n if (latest !== null) {\n reset(getItemValues(latest, fieldNames()), latest.version);\n } else {\n status = 'idle';\n conflict = null;\n update();\n }\n return null;\n }\n if (latest !== null) {\n version = latest.version;\n }\n conflict = null;\n return form.submit();\n },\n };\n return form;\n}\n"],"mappings":";;;;;;;;AAwJA,SAAgB,iBAAiB,QAA0B,SAAiB,CAAC,GAAW;CACpF,OAAO,OAAO,QACT,QAAQ,UACL,MAAM,YAAY,KAAA,KAAa,OAAO,MAAM,UAAU,KAAA,IAChD;EAAE,GAAG;GAAS,MAAM,OAAO,MAAM;CAAQ,IACzC,QACV,MACJ;AACJ;AAEA,SAAS,YAAY,GAAG,SAA+D;CACnF,MAAM,SAAmC,CAAC;CAC1C,QAAQ,SAAS,WACb,OAAO,QAAQ,MAAM,CAAC,CAAC,SAAS,CAAC,MAAM,cAAc;EACjD,OAAO,QAAQ,CA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M,SAAS,SAAS;GACxB,IAAI,WAAW,UAAU;IACrB,IAAI,WAAW,MACX,MAAM,cAAc,QAAQ,WAAW,CAAC,GAAG,OAAO,OAAO;SACtD;KACH,SAAS;KACT,WAAW;KACX,OAAO;IACX;IACA,OAAO;GACX;GACA,IAAI,WAAW,MACX,UAAU,OAAO;GAErB,WAAW;GACX,OAAO,KAAK,OAAO;EACvB;CACJ;CACA,OAAO;AACX"}
1
+ {"version":3,"file":"form.js","names":["Condition","Field","Item","RuleFailure","checkValues","getValue","FormMode","Values","isEqual","isPathWithin","formatRuleFailure","getItemValues","getProblem","isItem","selectErrorCount","selectErrors","selectValue","selectVisible","FormStore","createLocalStore","FormStatus","FormConflict","current","FormState","values","initialValues","version","dirty","errors","Record","touched","ReadonlySet","status","conflict","error","submitCount","SubmitContext","mode","changes","SubmitResult","result","FormOptions","fields","locales","store","formatError","failure","path","onSubmit","context","UpdatableFormOptions","Pick","GetErrorsOptions","nested","Form","getState","subscribe","listener","setOptions","options","Partial","setValue","value","blur","getErrors","countErrors","paths","isVisible","target","visibleWhen","parentPath","validate","setServerErrors","submit","Promise","reset","resolveConflict","choice","getDefaultValues","reduce","field","default","undefined","name","mergeErrors","sources","merged","forEach","source","Object","entries","messages","createForm","Required","startValues","setValues","getValues","Set","serverErrors","pending","listeners","unsubscribeStore","clientErrors","all","failures","fromEntries","filter","some","parent","map","list","compute","state","update","onStoreChange","previous","flatMap","key","fieldNames","nextVersion","runSubmit","keys","length","saved","caught","problem","form","add","delete","size","next","changed","has","getErrorsOptions","Math","max","finally","latest"],"sources":["../../src/form/form.ts"],"sourcesContent":["import type { Condition, Field, Item, RuleFailure } from '@panneau/protocol';\nimport { checkValues, getValue } from '@panneau/protocol/runtime';\n\nimport type { FormMode } from '../definition/form';\nimport { type Values, isEqual, isPathWithin } from '../values';\nimport { formatRuleFailure } from './messages';\nimport { getItemValues, getProblem, isItem } from './problem';\nimport { selectErrorCount, selectErrors, selectValue, selectVisible } from './selectors';\nimport { type FormStore, createLocalStore } from './store';\n\n/**\n * - `idle`: nothing submitted yet, or after a reset;\n * - `submitting`: waiting for `onSubmit`;\n * - `submitted`: the last submit succeeded;\n * - `invalid`: client validation or the server (`422`) found errors;\n * - `conflict`: the item changed since the form's version (`412`), see `resolveConflict()`;\n * - `error`: the last submit failed for another reason (network, `403`, `500`…), see `error`.\n */\nexport type FormStatus = 'idle' | 'submitting' | 'submitted' | 'invalid' | 'conflict' | 'error';\n\nexport interface FormConflict {\n /** The current version of the item, when the backend sent it. */\n current: Item | null;\n}\n\n/** A snapshot of a form. A new object is created on every change. */\nexport interface FormState {\n values: Values;\n /** The values the form started from, or was last saved with. `dirty` compares to them. */\n initialValues: Values;\n /** The version of the item the values were edited from, sent with the submit. */\n version: string | null;\n /** Whether the values differ from the initial values. */\n dirty: boolean;\n /**\n * Errors shown, by dot path (`title.fr`): client errors of touched fields (all of them after a\n * submit), then server errors. A server error goes away when its value changes.\n */\n errors: Record<string, string[]>;\n /** Paths of the fields that lost focus at least once. */\n touched: ReadonlySet<string>;\n status: FormStatus;\n /** With the `conflict` status: what the backend says is current. */\n conflict: FormConflict | null;\n /** With the `error` status: what `onSubmit` threw. */\n error: unknown;\n submitCount: number;\n}\n\nexport interface SubmitContext {\n mode: FormMode;\n /** The version to send as `If-Match`. */\n version: string | null;\n /** The top-level values that differ from the initial values, for partial updates. */\n changes: Values;\n}\n\nexport type SubmitResult =\n | { status: 'submitted'; result: unknown }\n | { status: 'invalid'; errors: Record<string, string[]> }\n | { status: 'conflict'; current: Item | null }\n | { status: 'error'; error: unknown };\n\nexport interface FormOptions {\n /** The fields of the form, as resolved by `resolveForm()`. */\n fields: Field[];\n /** Initial values. In `create` mode, fields without a value get their `default`. */\n values?: Values;\n /** The version of the item the values come from. */\n version?: string | null;\n /** Defaults to `update` when a version is given, `create` otherwise. */\n mode?: FormMode;\n /** Locales a `required` localized field must be filled in (all of them, usually). */\n locales?: string[];\n /** Where the values live. Defaults to a local store. */\n store?: FormStore;\n /** Message of a failed rule. Defaults to `formatRuleFailure()`. */\n formatError?: (failure: RuleFailure, path: string) => string;\n /**\n * Saves the values. When it returns an item, the form continues from that item. When it\n * throws an error that carries problem details (`getProblem()`), `422` errors are shown by\n * path and `412` puts the form in the `conflict` status.\n */\n onSubmit?: (values: Values, context: SubmitContext) => unknown;\n}\n\n/** Form options that can change after the form is created. */\nexport type UpdatableFormOptions = Pick<\n FormOptions,\n 'fields' | 'locales' | 'formatError' | 'onSubmit'\n>;\n\nexport interface GetErrorsOptions {\n /** Also return the errors of nested paths (`title.fr` for `title`). */\n nested?: boolean;\n}\n\n/**\n * A headless form: values, errors, visibility and submit. React components use `useForm()`.\n *\n * The methods that read the state (`getValue()`, `getErrors()`, `countErrors()`, `isVisible()`)\n * are not React APIs: the React Compiler memoizes their calls by their arguments, so they return\n * stale results in components. Components read the state they subscribed to with the selectors\n * (`selectValue()`, `selectErrors()`, `selectErrorCount()`, `selectVisible()`).\n */\nexport interface Form {\n /**\n * Whether the form creates or updates an item: its `mode` option, or `update` with a version\n * and `create` without. Rules limited to a mode apply in this one.\n */\n readonly mode: FormMode;\n getState(): FormState;\n subscribe(listener: () => void): () => void;\n /** Updates the options that can change between renders. */\n setOptions(options: Partial<UpdatableFormOptions>): void;\n /**\n * The value at a dot path. Not a React API: components use `selectValue(state, path)` (see\n * {@link Form}).\n */\n getValue(path: string): unknown;\n setValue(path: string, value: unknown): void;\n /** Marks a field as touched, which shows its client errors. */\n blur(path: string): void;\n /**\n * Errors at a path. Not a React API: components use `selectErrors(state, path, options)` (see\n * {@link Form}).\n */\n getErrors(path: string, options?: GetErrorsOptions): string[];\n /**\n * The number of paths with errors within the given paths, for counts on tabs and sections. Not\n * a React API: components use `selectErrorCount(state, paths)` (see {@link Form}).\n */\n countErrors(paths: readonly string[]): number;\n /**\n * Whether a field or a layout node is visible, from its `visibleWhen`. For nested fields, pass\n * the path of the object they belong to (`blocks.2`): conditions are relative to it. Not a\n * React API: components use `selectVisible(state, target, parentPath)` (see {@link Form}).\n */\n isVisible(target: { visibleWhen?: Condition | undefined }, parentPath?: string): boolean;\n /** Checks every value with the portable rules and shows every error. Returns whether valid. */\n validate(): boolean;\n /** Shows server errors, by dot path. */\n setServerErrors(errors: Record<string, string[]>): void;\n /** Validates, then calls `onSubmit`. */\n submit(): Promise<SubmitResult>;\n /** Starts over from new values (or the initial ones), and a new version. */\n reset(values?: Values, version?: string | null): void;\n /**\n * Leaves the `conflict` status:\n *\n * - `reload` drops the local changes and continues from the current item;\n * - `overwrite` keeps the local changes and submits them again over the current version.\n */\n resolveConflict(choice: 'reload' | 'overwrite'): Promise<SubmitResult | null>;\n}\n\n/** Initial values of fields that have a `default` and no value. */\nexport function getDefaultValues(fields: readonly Field[], values: Values = {}): Values {\n return fields.reduce<Values>(\n (result, field) =>\n field.default !== undefined && result[field.name] === undefined\n ? { ...result, [field.name]: field.default }\n : result,\n values,\n );\n}\n\nfunction mergeErrors(...sources: Record<string, string[]>[]): Record<string, string[]> {\n const merged: Record<string, string[]> = {};\n sources.forEach((source) =>\n Object.entries(source).forEach(([path, messages]) => {\n merged[path] = [...(merged[path] ?? []), ...messages];\n }),\n );\n return merged;\n}\n\n/** Creates a headless form. */\nexport function createForm(options: FormOptions): Form {\n const current: Required<UpdatableFormOptions> = {\n fields: options.fields,\n locales: options.locales ?? [],\n formatError: options.formatError ?? formatRuleFailure,\n onSubmit: options.onSubmit ?? (() => undefined),\n };\n const mode: FormMode =\n options.mode ??\n (options.version !== undefined && options.version !== null ? 'update' : 'create');\n const startValues =\n mode === 'create'\n ? getDefaultValues(options.fields, options.values)\n : (options.values ?? {});\n const store = options.store ?? createLocalStore(startValues);\n if (options.store !== undefined && options.values !== undefined) {\n store.setValues(startValues);\n }\n\n let initialValues = store.getValues();\n let version = options.version ?? null;\n let touched: ReadonlySet<string> = new Set();\n let serverErrors: Record<string, string[]> = {};\n let status: FormStatus = 'idle';\n let conflict: FormConflict | null = null;\n let error: unknown = null;\n let submitCount = 0;\n let pending: Promise<SubmitResult> | null = null;\n\n const listeners = new Set<() => void>();\n let unsubscribeStore: (() => void) | null = null;\n\n const clientErrors = (values: Values, all: boolean): Record<string, string[]> => {\n const failures = checkValues(current.fields, values, { mode, locales: current.locales });\n return Object.fromEntries(\n Object.entries(failures)\n .filter(\n ([path]) => all || [...touched].some((parent) => isPathWithin(path, parent)),\n )\n .map(([path, list]) => [\n path,\n list.map((failure) => current.formatError(failure, path)),\n ]),\n );\n };\n\n const compute = (values: Values): FormState => ({\n values,\n initialValues,\n version,\n dirty: !isEqual(values, initialValues),\n errors: mergeErrors(clientErrors(values, submitCount > 0), serverErrors),\n touched,\n status,\n conflict,\n error,\n submitCount,\n });\n\n let state = compute(store.getValues());\n\n const update = () => {\n state = compute(store.getValues());\n listeners.forEach((listener) => listener());\n };\n\n /** Server errors go away when their value changes. */\n const onStoreChange = () => {\n const previous = state.values;\n const values = store.getValues();\n if (values === previous) {\n return;\n }\n serverErrors = Object.fromEntries(\n Object.entries(serverErrors).filter(([path]) =>\n isEqual(getValue(previous, path), getValue(values, path)),\n ),\n );\n update();\n };\n\n const changes = (values: Values): Values =>\n Object.fromEntries(\n Object.entries({ ...initialValues, ...values }).flatMap(([key]) =>\n isEqual(values[key], initialValues[key]) ? [] : [[key, values[key]]],\n ),\n );\n\n const fieldNames = () => current.fields.map((field) => field.name);\n\n const reset = (values?: Values, nextVersion?: string | null) => {\n if (nextVersion !== undefined) {\n version = nextVersion;\n }\n touched = new Set();\n serverErrors = {};\n status = 'idle';\n conflict = null;\n error = null;\n submitCount = 0;\n if (values !== undefined) {\n initialValues = values;\n store.setValues(values);\n } else {\n store.setValues(initialValues);\n }\n update();\n };\n\n const runSubmit = async (): Promise<SubmitResult> => {\n submitCount += 1;\n serverErrors = {};\n const values = store.getValues();\n const errors = clientErrors(values, true);\n if (Object.keys(errors).length > 0) {\n status = 'invalid';\n update();\n return { status: 'invalid', errors };\n }\n status = 'submitting';\n conflict = null;\n error = null;\n update();\n try {\n const result = await current.onSubmit(values, {\n mode,\n version,\n changes: changes(values),\n });\n if (isItem(result)) {\n const saved = getItemValues(result, fieldNames());\n version = result.version;\n initialValues = saved;\n // Keep what was typed while saving; otherwise take the saved values.\n if (store.getValues() === values) {\n store.setValues(saved);\n }\n } else {\n initialValues = values;\n }\n touched = new Set();\n submitCount = 0;\n status = 'submitted';\n update();\n return { status: 'submitted', result };\n } catch (caught) {\n const problem = getProblem(caught);\n if (problem?.status === 412) {\n status = 'conflict';\n conflict = { current: problem.current ?? null };\n update();\n return { status: 'conflict', current: conflict.current };\n }\n if (problem?.status === 422 && problem.errors !== undefined) {\n status = 'invalid';\n serverErrors = problem.errors;\n update();\n return { status: 'invalid', errors: problem.errors };\n }\n status = 'error';\n error = caught;\n update();\n return { status: 'error', error: caught };\n }\n };\n\n const form: Form = {\n mode,\n getState() {\n if (unsubscribeStore === null) {\n onStoreChange();\n }\n return state;\n },\n subscribe(listener) {\n listeners.add(listener);\n unsubscribeStore ??= store.subscribe(onStoreChange);\n onStoreChange();\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0 && unsubscribeStore !== null) {\n unsubscribeStore();\n unsubscribeStore = null;\n }\n };\n },\n setOptions(next) {\n const { fields, locales, formatError, onSubmit } = next;\n if (onSubmit !== undefined) {\n current.onSubmit = onSubmit;\n }\n if (formatError !== undefined) {\n current.formatError = formatError;\n }\n // Fields and locales change what is valid: compare them by value, since a render can\n // create new arrays with the same content.\n const changed =\n (fields !== undefined && !isEqual(fields, current.fields)) ||\n (locales !== undefined && !isEqual(locales, current.locales));\n if (fields !== undefined) {\n current.fields = fields;\n }\n if (locales !== undefined) {\n current.locales = locales;\n }\n if (changed) {\n update();\n }\n },\n getValue: (path) => selectValue(form.getState(), path),\n setValue(path, value) {\n store.setValue(path, value);\n if (unsubscribeStore === null) {\n onStoreChange();\n }\n },\n blur(path) {\n if (touched.has(path)) {\n return;\n }\n touched = new Set([...touched, path]);\n update();\n },\n getErrors: (path, getErrorsOptions) =>\n selectErrors(form.getState(), path, getErrorsOptions),\n countErrors: (paths) => selectErrorCount(form.getState(), paths),\n isVisible: (target, parentPath) => selectVisible(form.getState(), target, parentPath),\n validate() {\n submitCount = Math.max(submitCount, 1);\n update();\n return Object.keys(clientErrors(store.getValues(), true)).length === 0;\n },\n setServerErrors(errors) {\n serverErrors = errors;\n update();\n },\n submit() {\n pending ??= runSubmit().finally(() => {\n pending = null;\n });\n return pending;\n },\n reset,\n async resolveConflict(choice) {\n if (status !== 'conflict' || conflict === null) {\n return null;\n }\n const latest = conflict.current;\n if (choice === 'reload') {\n if (latest !== null) {\n reset(getItemValues(latest, fieldNames()), latest.version);\n } else {\n status = 'idle';\n conflict = null;\n update();\n }\n return null;\n }\n if (latest !== null) {\n version = latest.version;\n }\n conflict = null;\n return form.submit();\n },\n };\n return form;\n}\n"],"mappings":";;;;;;;;AA6JA,SAAgB8E,iBAAiBpC,QAA0BlB,SAAiB,CAAC,GAAW;CACpF,OAAOkB,OAAOqC,QACTvC,QAAQwC,UACLA,MAAMC,YAAYC,KAAAA,KAAa1C,OAAOwC,MAAMG,UAAUD,KAAAA,IAChD;EAAE,GAAG1C;GAASwC,MAAMG,OAAOH,MAAMC;CAAQ,IACzCzC,QACVhB,MACJ;AACJ;AAEA,SAAS4D,YAAY,GAAGC,SAA+D;CACnF,MAAMC,SAAmC,CAAC;CAC1CD,QAAQE,SAASC,WACbC,OAAOC,QAAQF,MAAM,CAAC,CAACD,SAAS,CAACxC,MAAM4C,cAAc;EACjDL,OAAOvC,QAAQ,CAAC,GAAIuC,OAAOvC,SAAS,CAAA,GAAK,GAAG4C,QAAQ;CACxD,CAAC,CACL;CACA,OAAOL;AACX;;AAGA,SAAgBM,WAAWjC,SAA4B;CACnD,MAAMrC,UAA0C;EAC5CoB,QAAQiB,QAAQjB;EAChBC,SAASgB,QAAQhB,WAAW,CAAA;EAC5BE,aAAac,QAAQd,eAAenC;EACpCsC,UAAUW,QAAQX,mBAAmBkC,KAAAA;CACzC;CACA,MAA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gH,KAAKvE,SAAS,GAAGW,KAAK;EAC/DC,YAAYC,QAAQE,eAAerD,cAAc6G,KAAKvE,SAAS,GAAGa,QAAQE,UAAU;EACpFC,WAAW;GACPpC,cAAcmG,KAAKC,IAAIpG,aAAa,CAAC;GACrC8E,OAAO;GACP,OAAOxB,OAAOgC,KAAKnB,aAAa1D,MAAMoD,UAAU,GAAG,IAAI,CAAC,CAAC,CAAC0B,WAAW;EACzE;EACAlD,gBAAgB5C,QAAQ;GACpBsE,eAAetE;GACfqF,OAAO;EACX;EACAxC,SAAS;GACL0B,YAAYqB,UAAU,CAAC,CAACgB,cAAc;IAClCrC,UAAU;GACd,CAAC;GACD,OAAOA;EACX;EACAxB;EACA,MAAMC,gBAAgBC,QAAQ;GAC1B,IAAI7C,WAAW,cAAcC,aAAa,MACtC,OAAO;GAEX,MAAMwG,SAASxG,SAASX;GACxB,IAAIuD,WAAW,UAAU;IACrB,IAAI4D,WAAW,MACX9D,MAAMhE,cAAc8H,QAAQnB,WAAW,CAAC,GAAGmB,OAAO/G,OAAO;SACtD;KACHM,SAAS;KACTC,WAAW;KACXgF,OAAO;IACX;IACA,OAAO;GACX;GACA,IAAIwB,WAAW,MACX/G,UAAU+G,OAAO/G;GAErBO,WAAW;GACX,OAAO6F,KAAKrD,OAAO;EACvB;CACJ;CACA,OAAOqD;AACX"}
@@ -1 +1 @@
1
- {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/form/messages.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAgBrD;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,WAAW,GAAG,MAAM,CAE9D"}
1
+ {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/form/messages.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAmCrD;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,WAAW,GAAG,MAAM,CAE9D"}
@@ -1,4 +1,8 @@
1
1
  //#region src/form/messages.ts
2
+ /** `YouTube, Vimeo or Spotify`. */
3
+ function orList(items) {
4
+ return items.length > 1 ? `${items.slice(0, -1).join(", ")} or ${String(items.at(-1))}` : items[0] ?? "";
5
+ }
2
6
  var MESSAGES = {
3
7
  required: () => "This field is required.",
4
8
  min: (failure) => `This value must be at least ${String(failure.value)}.`,
@@ -6,11 +10,17 @@ var MESSAGES = {
6
10
  pattern: () => "This value has an invalid format.",
7
11
  email: () => "This value must be an email address.",
8
12
  url: () => "This value must be a URL.",
13
+ json: () => "This value must be valid JSON: an object or an array.",
14
+ tel: () => "This value must be a complete phone number.",
15
+ postalCode: () => "This value must be a postal code of its country.",
16
+ daterange: (failure) => failure.value === "start" ? "Give the start of this range." : failure.value === "end" ? "Give the end of this range." : "The end can’t be before the start.",
17
+ money: () => "This value must be an amount in one of the allowed currencies.",
9
18
  in: () => "This value is not one of the choices.",
10
19
  accept: () => "This file type is not accepted.",
11
20
  maxSize: () => "This file is too large.",
12
21
  before: () => "This date is too late.",
13
- after: () => "This date is too early."
22
+ after: () => "This date is too early.",
23
+ providers: (failure) => `This embed must come from ${orList(Array.isArray(failure.value) ? failure.value.map(String) : [])}.`
14
24
  };
15
25
  /**
16
26
  * The message of a failed rule: the rule's own `message`, or a default English message. Forms
@@ -1 +1 @@
1
- {"version":3,"file":"messages.js","names":[],"sources":["../../src/form/messages.ts"],"sourcesContent":["import type { RuleFailure } from '@panneau/protocol';\n\nconst MESSAGES: Record<string, (failure: RuleFailure) => string> = {\n required: () => 'This field is required.',\n min: (failure) => `This value must be at least ${String(failure.value)}.`,\n max: (failure) => `This value must be at most ${String(failure.value)}.`,\n pattern: () => 'This value has an invalid format.',\n email: () => 'This value must be an email address.',\n url: () => 'This value must be a URL.',\n in: () => 'This value is not one of the choices.',\n accept: () => 'This file type is not accepted.',\n maxSize: () => 'This file is too large.',\n before: () => 'This date is too late.',\n after: () => 'This date is too early.',\n};\n\n/**\n * The message of a failed rule: the rule's own `message`, or a default English message. Forms\n * take a `formatError` option to translate them.\n */\nexport function formatRuleFailure(failure: RuleFailure): string {\n return failure.message ?? MESSAGES[failure.rule]?.(failure) ?? 'This value is invalid.';\n}\n"],"mappings":";AAEA,IAAM,WAA6D;CAC/D,gBAAgB;CAChB,MAAM,YAAY,+BAA+B,OAAO,QAAQ,KAAK,EAAC;CACtE,MAAM,YAAY,8BAA8B,OAAO,QAAQ,KAAK,EAAC;CACrE,eAAe;CACf,aAAa;CACb,WAAW;CACX,UAAU;CACV,cAAc;CACd,eAAe;CACf,cAAc;CACd,aAAa;AACjB;;;;;AAMA,SAAgB,kBAAkB,SAA8B;CAC5D,OAAO,QAAQ,WAAW,SAAS,QAAQ,KAAK,GAAG,OAAO,KAAK;AACnE"}
1
+ {"version":3,"file":"messages.js","names":["RuleFailure","orList","items","length","slice","join","String","at","MESSAGES","Record","failure","required","min","value","max","pattern","email","url","json","tel","postalCode","daterange","money","in","accept","maxSize","before","after","providers","Array","isArray","map","formatRuleFailure","message","rule"],"sources":["../../src/form/messages.ts"],"sourcesContent":["import type { RuleFailure } from '@panneau/protocol';\n\n/** `YouTube, Vimeo or Spotify`. */\nfunction orList(items: readonly string[]): string {\n return items.length > 1\n ? `${items.slice(0, -1).join(', ')} or ${String(items.at(-1))}`\n : (items[0] ?? '');\n}\n\nconst MESSAGES: Record<string, (failure: RuleFailure) => string> = {\n required: () => 'This field is required.',\n min: (failure) => `This value must be at least ${String(failure.value)}.`,\n max: (failure) => `This value must be at most ${String(failure.value)}.`,\n pattern: () => 'This value has an invalid format.',\n email: () => 'This value must be an email address.',\n url: () => 'This value must be a URL.',\n json: () => 'This value must be valid JSON: an object or an array.',\n tel: () => 'This value must be a complete phone number.',\n postalCode: () => 'This value must be a postal code of its country.',\n daterange: (failure) =>\n failure.value === 'start'\n ? 'Give the start of this range.'\n : failure.value === 'end'\n ? 'Give the end of this range.'\n : 'The end can’t be before the start.',\n money: () => 'This value must be an amount in one of the allowed currencies.',\n in: () => 'This value is not one of the choices.',\n accept: () => 'This file type is not accepted.',\n maxSize: () => 'This file is too large.',\n before: () => 'This date is too late.',\n after: () => 'This date is too early.',\n providers: (failure) =>\n `This embed must come from ${orList(Array.isArray(failure.value) ? failure.value.map(String) : [])}.`,\n};\n\n/**\n * The message of a failed rule: the rule's own `message`, or a default English message. Forms\n * take a `formatError` option to translate them.\n */\nexport function formatRuleFailure(failure: RuleFailure): string {\n return failure.message ?? MESSAGES[failure.rule]?.(failure) ?? 'This value is invalid.';\n}\n"],"mappings":";;AAGA,SAASC,OAAOC,OAAkC;CAC9C,OAAOA,MAAMC,SAAS,IAChB,GAAGD,MAAME,MAAM,GAAG,EAAE,CAAC,CAACC,KAAK,IAAI,EAAC,MAAOC,OAAOJ,MAAMK,GAAG,EAAE,CAAC,MACzDL,MAAM,MAAM;AACvB;AAEA,IAAMM,WAA6D;CAC/DG,gBAAgB;CAChBC,MAAMF,YAAY,+BAA+BJ,OAAOI,QAAQG,KAAK,EAAC;CACtEC,MAAMJ,YAAY,8BAA8BJ,OAAOI,QAAQG,KAAK,EAAC;CACrEE,eAAe;CACfC,aAAa;CACbC,WAAW;CACXC,YAAY;CACZC,WAAW;CACXC,kBAAkB;CAClBC,YAAYX,YACRA,QAAQG,UAAU,UACZ,kCACAH,QAAQG,UAAU,QAChB,gCACA;CACZS,aAAa;CACbC,UAAU;CACVC,cAAc;CACdC,eAAe;CACfC,cAAc;CACdC,aAAa;CACbC,YAAYlB,YACR,6BAA6BT,OAAO4B,MAAMC,QAAQpB,QAAQG,KAAK,IAAIH,QAAQG,MAAMkB,IAAIzB,MAAM,IAAI,CAAA,CAAE,EAAC;AAC1G;;;;;AAMA,SAAgB0B,kBAAkBtB,SAA8B;CAC5D,OAAOA,QAAQuB,WAAWzB,SAASE,QAAQwB,KAAK,GAAGxB,OAAO,KAAK;AACnE"}
@@ -1,5 +1,5 @@
1
1
  import type { Item, Problem } from '@panneau/protocol';
2
- import type { Values } from '../values';
2
+ import type { Values } from '../values.js';
3
3
  /**
4
4
  * The problem details carried by an error: the error itself when it is a problem, or its
5
5
  * `problem` property, as on the errors of `@panneau/data`. A custom adapter only needs to throw
@@ -1 +1 @@
1
- {"version":3,"file":"problem.js","names":[],"sources":["../../src/form/problem.ts"],"sourcesContent":["import type { Item, Problem } from '@panneau/protocol';\nimport { isProblem } from '@panneau/protocol/runtime';\n\nimport type { Values } from '../values';\n\n/**\n * The problem details carried by an error: the error itself when it is a problem, or its\n * `problem` property, as on the errors of `@panneau/data`. A custom adapter only needs to throw\n * errors with a `problem` for forms to show validation errors and conflicts.\n */\nexport function getProblem(error: unknown): Problem | null {\n if (isProblem(error)) {\n return error;\n }\n if (error !== null && typeof error === 'object' && 'problem' in error) {\n return isProblem(error.problem) ? error.problem : null;\n }\n return null;\n}\n\nconst ITEM_KEYS = new Set(['id', 'version', 'abilities']);\n\n/** Whether a value looks like an item of the protocol (`id`, `version`, `abilities`). */\nexport function isItem(value: unknown): value is Item {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const item = value as Record<string, unknown>;\n return (\n typeof item.id === 'string' &&\n (typeof item.version === 'string' || item.version === null) &&\n item.abilities !== null &&\n typeof item.abilities === 'object'\n );\n}\n\n/**\n * The values of an item: every property except `id`, `version` and `abilities`, or only the\n * given field names.\n */\nexport function getItemValues(item: Item, names?: readonly string[]): Values {\n return Object.fromEntries(\n Object.entries(item).filter(([key]) =>\n names !== undefined ? names.includes(key) : !ITEM_KEYS.has(key),\n ),\n );\n}\n"],"mappings":";;;;;;;AAUA,SAAgB,WAAW,OAAgC;CACvD,IAAI,UAAU,KAAK,GACf,OAAO;CAEX,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,aAAa,OAC5D,OAAO,UAAU,MAAM,OAAO,IAAI,MAAM,UAAU;CAEtD,OAAO;AACX;AAEA,IAAM,4BAAY,IAAI,IAAI;CAAC;CAAM;CAAW;AAAW,CAAC;;AAGxD,SAAgB,OAAO,OAA+B;CAClD,IAAI,UAAU,QAAQ,OAAO,UAAU,UACnC,OAAO;CAEX,MAAM,OAAO;CACb,OACI,OAAO,KAAK,OAAO,aAClB,OAAO,KAAK,YAAY,YAAY,KAAK,YAAY,SACtD,KAAK,cAAc,QACnB,OAAO,KAAK,cAAc;AAElC;;;;;AAMA,SAAgB,cAAc,MAAY,OAAmC;CACzE,OAAO,OAAO,YACV,OAAO,QAAQ,IAAI,CAAC,CAAC,QAAQ,CAAC,SAC1B,UAAU,KAAA,IAAY,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,IAAI,GAAG,CAClE,CACJ;AACJ"}
1
+ {"version":3,"file":"problem.js","names":["Item","Problem","isProblem","Values","getProblem","error","problem","ITEM_KEYS","Set","isItem","value","item","Record","id","version","abilities","getItemValues","names","Object","fromEntries","entries","filter","key","undefined","includes","has"],"sources":["../../src/form/problem.ts"],"sourcesContent":["import type { Item, Problem } from '@panneau/protocol';\nimport { isProblem } from '@panneau/protocol/runtime';\n\nimport type { Values } from '../values';\n\n/**\n * The problem details carried by an error: the error itself when it is a problem, or its\n * `problem` property, as on the errors of `@panneau/data`. A custom adapter only needs to throw\n * errors with a `problem` for forms to show validation errors and conflicts.\n */\nexport function getProblem(error: unknown): Problem | null {\n if (isProblem(error)) {\n return error;\n }\n if (error !== null && typeof error === 'object' && 'problem' in error) {\n return isProblem(error.problem) ? error.problem : null;\n }\n return null;\n}\n\nconst ITEM_KEYS = new Set(['id', 'version', 'abilities']);\n\n/** Whether a value looks like an item of the protocol (`id`, `version`, `abilities`). */\nexport function isItem(value: unknown): value is Item {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const item = value as Record<string, unknown>;\n return (\n typeof item.id === 'string' &&\n (typeof item.version === 'string' || item.version === null) &&\n item.abilities !== null &&\n typeof item.abilities === 'object'\n );\n}\n\n/**\n * The values of an item: every property except `id`, `version` and `abilities`, or only the\n * given field names.\n */\nexport function getItemValues(item: Item, names?: readonly string[]): Values {\n return Object.fromEntries(\n Object.entries(item).filter(([key]) =>\n names !== undefined ? names.includes(key) : !ITEM_KEYS.has(key),\n ),\n );\n}\n"],"mappings":";;;;;;;AAUA,SAAgBI,WAAWC,OAAgC;CACvD,IAAIH,UAAUG,KAAK,GACf,OAAOA;CAEX,IAAIA,UAAU,QAAQ,OAAOA,UAAU,YAAY,aAAaA,OAC5D,OAAOH,UAAUG,MAAMC,OAAO,IAAID,MAAMC,UAAU;CAEtD,OAAO;AACX;AAEA,IAAMC,4BAAY,IAAIC,IAAI;CAAC;CAAM;CAAW;AAAW,CAAC;;AAGxD,SAAgBC,OAAOC,OAA+B;CAClD,IAAIA,UAAU,QAAQ,OAAOA,UAAU,UACnC,OAAO;CAEX,MAAMC,OAAOD;CACb,OACI,OAAOC,KAAKE,OAAO,aAClB,OAAOF,KAAKG,YAAY,YAAYH,KAAKG,YAAY,SACtDH,KAAKI,cAAc,QACnB,OAAOJ,KAAKI,cAAc;AAElC;;;;;AAMA,SAAgBC,cAAcL,MAAYM,OAAmC;CACzE,OAAOC,OAAOC,YACVD,OAAOE,QAAQT,IAAI,CAAC,CAACU,QAAQ,CAACC,SAC1BL,UAAUM,KAAAA,IAAYN,MAAMO,SAASF,GAAG,IAAI,CAACf,UAAUkB,IAAIH,GAAG,CAClE,CACJ;AACJ"}
@@ -1,5 +1,5 @@
1
1
  import type { Condition } from '@panneau/protocol';
2
- import type { FormState, GetErrorsOptions } from './form';
2
+ import type { FormState, GetErrorsOptions } from './form.js';
3
3
  /** The value at a dot path (`title.fr`). */
4
4
  export declare function selectValue(state: FormState, path: string): unknown;
5
5
  /** Errors at a path, and with `nested` at the paths inside it (`title.fr` for `title`). */