@rebasepro/cms 0.26.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/collection_editor/serializable_utils.js +5 -2
  2. package/dist/collection_editor/serializable_utils.js.map +1 -1
  3. package/dist/collection_editor/ui/collection_editor/EnumForm.d.ts +17 -0
  4. package/dist/collection_editor/ui/collection_editor/EnumForm.js +31 -17
  5. package/dist/collection_editor/ui/collection_editor/EnumForm.js.map +1 -1
  6. package/dist/collection_editor/ui/collection_editor/properties/EnumPropertyField.js +6 -5
  7. package/dist/collection_editor/ui/collection_editor/properties/EnumPropertyField.js.map +1 -1
  8. package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js +3 -2
  9. package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js.map +1 -1
  10. package/dist/components/CollectionViewBinding/CollectionListViewBinding.js +32 -16
  11. package/dist/components/CollectionViewBinding/CollectionListViewBinding.js.map +1 -1
  12. package/dist/components/DefaultDrawer.js +3 -2
  13. package/dist/components/DefaultDrawer.js.map +1 -1
  14. package/dist/components/DetailViewBinding.js +4 -3
  15. package/dist/components/DetailViewBinding.js.map +1 -1
  16. package/dist/components/EditViewBinding.js +23 -5
  17. package/dist/components/EditViewBinding.js.map +1 -1
  18. package/dist/components/EntityPreviewBinding.js +1 -0
  19. package/dist/components/EntityPreviewBinding.js.map +1 -1
  20. package/dist/components/HomePage/ContentHomePage.js +3 -2
  21. package/dist/components/HomePage/ContentHomePage.js.map +1 -1
  22. package/dist/components/SelectableTable/filters/StringNumberFilterField.js +3 -3
  23. package/dist/components/SelectableTable/filters/StringNumberFilterField.js.map +1 -1
  24. package/dist/components/SidePanelBinding.js +7 -6
  25. package/dist/components/SidePanelBinding.js.map +1 -1
  26. package/dist/components/app/Scaffold.js +16 -1
  27. package/dist/components/app/Scaffold.js.map +1 -1
  28. package/dist/components/history/EntityHistoryView.js +2 -1
  29. package/dist/components/history/EntityHistoryView.js.map +1 -1
  30. package/dist/data_export/export/export.js +3 -3
  31. package/dist/data_export/export/export.js.map +1 -1
  32. package/dist/data_import/import/ImportCollectionAction.js +10 -12
  33. package/dist/data_import/import/ImportCollectionAction.js.map +1 -1
  34. package/dist/data_import/utils/id_column.d.ts +19 -0
  35. package/dist/data_import/utils/id_column.js +19 -1
  36. package/dist/data_import/utils/id_column.js.map +1 -1
  37. package/dist/data_import/utils/transforms.js +24 -7
  38. package/dist/data_import/utils/transforms.js.map +1 -1
  39. package/dist/form/EntityForm.d.ts +1 -1
  40. package/dist/form/EntityForm.js +14 -4
  41. package/dist/form/EntityForm.js.map +1 -1
  42. package/dist/form/EntityFormBinding.js +12 -8
  43. package/dist/form/EntityFormBinding.js.map +1 -1
  44. package/dist/form/components/FieldBlock.js +2 -1
  45. package/dist/form/components/FieldBlock.js.map +1 -1
  46. package/dist/form/field_bindings/KeyValueFieldBinding.js +3 -1
  47. package/dist/form/field_bindings/KeyValueFieldBinding.js.map +1 -1
  48. package/dist/form/field_bindings/ReadOnlyFieldBinding.js +0 -2
  49. package/dist/form/field_bindings/ReadOnlyFieldBinding.js.map +1 -1
  50. package/dist/form/field_bindings/TextFieldBinding.js +3 -2
  51. package/dist/form/field_bindings/TextFieldBinding.js.map +1 -1
  52. package/dist/form/validation.js +12 -1
  53. package/dist/form/validation.js.map +1 -1
  54. package/dist/hooks/navigation/url_segments.d.ts +33 -0
  55. package/dist/hooks/navigation/url_segments.js +56 -0
  56. package/dist/hooks/navigation/url_segments.js.map +1 -0
  57. package/dist/hooks/navigation/useBuildUrlController.js +4 -2
  58. package/dist/hooks/navigation/useBuildUrlController.js.map +1 -1
  59. package/dist/hooks/useBuildSidePanel.js +6 -5
  60. package/dist/hooks/useBuildSidePanel.js.map +1 -1
  61. package/dist/hooks/useHistory.js +4 -3
  62. package/dist/hooks/useHistory.js.map +1 -1
  63. package/dist/routes/RebaseRoute.js +20 -30
  64. package/dist/routes/RebaseRoute.js.map +1 -1
  65. package/dist/util/navigation_utils.js +4 -3
  66. package/dist/util/navigation_utils.js.map +1 -1
  67. package/package.json +9 -9
@@ -21,7 +21,25 @@ function guessIdColumn(headers, headersMapping, properties) {
21
21
  const mappedProperty = mappedKey ? properties?.[mappedKey] : void 0;
22
22
  if (mappedProperty && "isId" in mappedProperty && mappedProperty.isId) return firstKey;
23
23
  }
24
+ /**
25
+ * The mapping and id column after the person importing picks where one column
26
+ * goes, in that column's row of the mapping step: a property (`targetKey`), or
27
+ * nothing (`null`, "Do not import this property").
28
+ *
29
+ * A property holds one column, so a column that held `targetKey` before lets
30
+ * it go. And a column picked for a property, or for nothing, is no longer the
31
+ * id: the row's select shows "Use this column as ID" while it is, and the
32
+ * conversion takes the id column out of the values, so the pick was dropped.
33
+ */
34
+ function remapImportColumn({ headersMapping, idColumn, column, targetKey }) {
35
+ const remapped = {};
36
+ for (const [currentColumn, currentKey] of Object.entries(headersMapping)) remapped[currentColumn] = currentColumn === column ? targetKey : targetKey !== null && currentKey === targetKey ? null : currentKey;
37
+ return {
38
+ headersMapping: remapped,
39
+ idColumn: idColumn === column ? void 0 : idColumn
40
+ };
41
+ }
24
42
  //#endregion
25
- export { guessIdColumn };
43
+ export { guessIdColumn, remapImportColumn };
26
44
 
27
45
  //# sourceMappingURL=id_column.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"id_column.js","names":[],"sources":["../../../src/data_import/utils/id_column.ts"],"sourcesContent":["import { Properties } from \"@rebasepro/types\";\n\n/**\n * The column an import uses as the row id before the user touches the mapping.\n *\n * The guess decides something destructive: the chosen column is taken out of\n * the values and sent as the id of an upsert, so every row overwrites the record\n * that already has that id. A header that merely *contained* \"id\" or \"key\" used\n * to qualify, so a file starting with `width`, `video` or `provider` wrote its\n * widths over the records whose ids they happened to equal.\n *\n * Only the first column is a candidate — the one the export writes the id to —\n * and only when its name says it is the id: the header is `id` (in any case),\n * or it maps onto a property the collection declares with `isId`. Anything else\n * is left for the user to choose in the mapping step.\n */\nexport function guessIdColumn(headers: string[],\n headersMapping: Record<string, string | null>,\n properties?: Properties): string | undefined {\n const firstKey = headers[0];\n if (firstKey === undefined) return undefined;\n\n if (firstKey.trim().toLowerCase() === \"id\") return firstKey;\n\n const mappedKey = headersMapping[firstKey];\n const mappedProperty = mappedKey ? properties?.[mappedKey] : undefined;\n if (mappedProperty && \"isId\" in mappedProperty && mappedProperty.isId) return firstKey;\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,SAAgB,cAAc,SAC1B,gBACA,YAA6C;CAC7C,MAAM,WAAW,QAAQ;CACzB,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;CAEnC,IAAI,SAAS,KAAK,CAAC,CAAC,YAAY,MAAM,MAAM,OAAO;CAEnD,MAAM,YAAY,eAAe;CACjC,MAAM,iBAAiB,YAAY,aAAa,aAAa,KAAA;CAC7D,IAAI,kBAAkB,UAAU,kBAAkB,eAAe,MAAM,OAAO;AAGlF"}
1
+ {"version":3,"file":"id_column.js","names":[],"sources":["../../../src/data_import/utils/id_column.ts"],"sourcesContent":["import { Properties } from \"@rebasepro/types\";\n\n/**\n * The column an import uses as the row id before the user touches the mapping.\n *\n * The guess decides something destructive: the chosen column is taken out of\n * the values and sent as the id of an upsert, so every row overwrites the record\n * that already has that id. A header that merely *contained* \"id\" or \"key\" used\n * to qualify, so a file starting with `width`, `video` or `provider` wrote its\n * widths over the records whose ids they happened to equal.\n *\n * Only the first column is a candidate — the one the export writes the id to —\n * and only when its name says it is the id: the header is `id` (in any case),\n * or it maps onto a property the collection declares with `isId`. Anything else\n * is left for the user to choose in the mapping step.\n */\nexport function guessIdColumn(headers: string[],\n headersMapping: Record<string, string | null>,\n properties?: Properties): string | undefined {\n const firstKey = headers[0];\n if (firstKey === undefined) return undefined;\n\n if (firstKey.trim().toLowerCase() === \"id\") return firstKey;\n\n const mappedKey = headersMapping[firstKey];\n const mappedProperty = mappedKey ? properties?.[mappedKey] : undefined;\n if (mappedProperty && \"isId\" in mappedProperty && mappedProperty.isId) return firstKey;\n\n return undefined;\n}\n\n/**\n * The mapping and id column after the person importing picks where one column\n * goes, in that column's row of the mapping step: a property (`targetKey`), or\n * nothing (`null`, \"Do not import this property\").\n *\n * A property holds one column, so a column that held `targetKey` before lets\n * it go. And a column picked for a property, or for nothing, is no longer the\n * id: the row's select shows \"Use this column as ID\" while it is, and the\n * conversion takes the id column out of the values, so the pick was dropped.\n */\nexport function remapImportColumn({\n headersMapping,\n idColumn,\n column,\n targetKey\n}: {\n headersMapping: Record<string, string | null>;\n idColumn: string | undefined;\n column: string;\n targetKey: string | null;\n}): { headersMapping: Record<string, string | null>; idColumn: string | undefined } {\n const remapped: Record<string, string | null> = {};\n for (const [currentColumn, currentKey] of Object.entries(headersMapping)) {\n remapped[currentColumn] = currentColumn === column\n ? targetKey\n : targetKey !== null && currentKey === targetKey ? null : currentKey;\n }\n return {\n headersMapping: remapped,\n idColumn: idColumn === column ? undefined : idColumn\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,SAAgB,cAAc,SAC1B,gBACA,YAA6C;CAC7C,MAAM,WAAW,QAAQ;CACzB,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;CAEnC,IAAI,SAAS,KAAK,CAAC,CAAC,YAAY,MAAM,MAAM,OAAO;CAEnD,MAAM,YAAY,eAAe;CACjC,MAAM,iBAAiB,YAAY,aAAa,aAAa,KAAA;CAC7D,IAAI,kBAAkB,UAAU,kBAAkB,eAAe,MAAM,OAAO;AAGlF;;;;;;;;;;;AAYA,SAAgB,kBAAkB,EAC9B,gBACA,UACA,QACA,aAMgF;CAChF,MAAM,WAA0C,CAAC;CACjD,KAAK,MAAM,CAAC,eAAe,eAAe,OAAO,QAAQ,cAAc,GACnE,SAAS,iBAAiB,kBAAkB,SACtC,YACA,cAAc,QAAQ,eAAe,YAAY,OAAO;CAElE,OAAO;EACH,gBAAgB;EAChB,UAAU,aAAa,SAAS,KAAA,IAAY;CAChD;AACJ"}
@@ -1,6 +1,21 @@
1
1
  import { isPrototypePollutingKey, pathTraversesPrototype } from "@rebasepro/utils";
2
2
  //#region src/data_import/utils/transforms.ts
3
3
  /**
4
+ * Make `holder[slot]` an array or an object to write into, unless it is one.
5
+ *
6
+ * A file can carry a plain column and nested ones under the same name — `tags`
7
+ * beside `tags[0]`, `address` beside `address.city`. The nested columns win:
8
+ * they say what shape the value has, and writing an index or a key into the
9
+ * text a plain column left there threw (strict mode), which failed the whole
10
+ * file.
11
+ */
12
+ function containerAt(holder, slot, kind, column) {
13
+ const existing = holder[slot];
14
+ if (existing !== null && typeof existing === "object") return;
15
+ if (existing !== void 0 && existing !== null && existing !== "") console.warn(`Column "${column}" nests under "${String(slot)}", which another column set to a plain value; the nested columns are kept`);
16
+ holder[slot] = kind === "array" ? [] : {};
17
+ }
18
+ /**
4
19
  * Take an object with keys of type `address.street`, `address.city` and
5
20
  * convert it to an object with nested objects like `{ address: { street: ..., city: ... } }`
6
21
  *
@@ -23,18 +38,20 @@ function unflattenObject(flatObj) {
23
38
  let currentObj = nestedObj;
24
39
  const keyParts = key.split(".");
25
40
  keyParts.forEach((keyPart, i) => {
26
- if (/^[\w]+\[\d+\]$/.test(keyPart)) {
27
- const mainPropertyName = keyPart.slice(0, keyPart.indexOf("["));
28
- const index = parseInt(keyPart.slice(keyPart.indexOf("[") + 1, keyPart.indexOf("]")));
29
- if (!currentObj[mainPropertyName]) currentObj[mainPropertyName] = [];
41
+ const indexed = /^(.+)\[(\d+)\]$/.exec(keyPart);
42
+ if (indexed) {
43
+ const mainPropertyName = indexed[1];
44
+ const index = parseInt(indexed[2], 10);
45
+ containerAt(currentObj, mainPropertyName, "array", key);
30
46
  if (i !== keyParts.length - 1) {
31
- currentObj[mainPropertyName][index] = currentObj[mainPropertyName][index] || {};
47
+ containerAt(currentObj[mainPropertyName], index, "object", key);
32
48
  currentObj = currentObj[mainPropertyName][index];
33
49
  } else currentObj[mainPropertyName][index] = flatObj[key];
34
50
  } else if (i !== keyParts.length - 1) {
35
- currentObj[keyPart] = currentObj[keyPart] || {};
51
+ containerAt(currentObj, keyPart, "object", key);
36
52
  currentObj = currentObj[keyPart];
37
- } else currentObj[keyPart] = flatObj[key];
53
+ } else if (currentObj[keyPart] !== null && typeof currentObj[keyPart] === "object") console.warn(`Column "${key}" is a plain value where nested columns already are; the nested columns are kept`);
54
+ else currentObj[keyPart] = flatObj[key];
38
55
  });
39
56
  return nestedObj;
40
57
  }, {});
@@ -1 +1 @@
1
- {"version":3,"file":"transforms.js","names":[],"sources":["../../../src/data_import/utils/transforms.ts"],"sourcesContent":["import { isPrototypePollutingKey, pathTraversesPrototype } from \"@rebasepro/utils\";\n\n/**\n * Take an object with keys of type `address.street`, `address.city` and\n * convert it to an object with nested objects like `{ address: { street: ..., city: ... } }`\n *\n * Keys here are the **header row of an uploaded file**, so they are attacker\n * data. `res[\"__proto__\"] = …` is the prototype setter rather than an own\n * property, so a column named `__proto__.polluted` walked out of the accumulator\n * and wrote onto `Object.prototype` for the life of the tab — and\n * `constructor.prototype.x` threw a `TypeError` that surfaced as an unreadable\n * file. Such a column is refused, not sanitised, the way `setIn` settled it\n * (`docs/bug-classes.md` class 22).\n *\n * @param flatObj\n */\nexport function unflattenObject(flatObj: { [key: string]: any }) {\n return Object.keys(flatObj).reduce((nestedObj, key) => {\n // The string form, so `toPath` rewrites `__proto__[0]` to a `__proto__`\n // segment too — the bracket branch below writes through the same setter.\n if (pathTraversesPrototype(key)) {\n console.warn(`Skipping column \"${key}\": a header may not reach the prototype chain`);\n return nestedObj;\n }\n let currentObj = nestedObj;\n const keyParts = key.split(\".\");\n keyParts.forEach((keyPart, i) => {\n\n if (/^[\\w]+\\[\\d+\\]$/.test(keyPart)) {\n const mainPropertyName = keyPart.slice(0, keyPart.indexOf(\"[\"));\n const index = parseInt(keyPart.slice(keyPart.indexOf(\"[\") + 1, keyPart.indexOf(\"]\")));\n\n if (!currentObj[mainPropertyName]) {\n currentObj[mainPropertyName] = []\n }\n\n if (i !== keyParts.length - 1) {\n currentObj[mainPropertyName][index] = currentObj[mainPropertyName][index] || {};\n currentObj = currentObj[mainPropertyName][index];\n } else {\n currentObj[mainPropertyName][index] = flatObj[key];\n }\n } else if (i !== keyParts.length - 1) {\n currentObj[keyPart] = currentObj[keyPart] || {};\n currentObj = currentObj[keyPart];\n } else {\n currentObj[keyPart] = flatObj[key];\n }\n\n });\n return nestedObj;\n }, {} as { [key: string]: any });\n}\n\n/**\n * Read a text cell as the number, boolean or array it spells, when it spells\n * one exactly — so the type inference sees `12`, `true` and the export's\n * `[\"a\",\"b\"]` for what they are.\n *\n * Only a cell that is the canonical JSON of its value is read: `JSON.stringify`\n * of the result must give back the cell's text. That makes the read lossless,\n * and the import coerces each value against the property it lands in only\n * later — a string property turns it back into exactly the text in the file.\n * Anything else stays the text it was: `1.10`, `00123`, `1E3`, a twenty-digit\n * SKU that a double cannot hold, the word `null`, and a cell with quotes in it.\n * So does an object: the import flattens objects into `a.b` columns, which\n * would scatter a string property's JSON text into columns that do not exist.\n */\nfunction parseCanonicalJsonCell(cell: unknown): unknown {\n if (typeof cell !== \"string\") return cell;\n // The canonical JSON of a number, boolean or array starts with `-`, a\n // digit, `t`, `f` or `[` — nothing else can pass the round trip below. Text\n // is most of a file, and `JSON.parse` on text throws: the throw was over\n // half of the main-thread time of reading one.\n if (!couldBeCanonicalJson(cell.charCodeAt(0))) return cell;\n let parsed: unknown;\n try {\n parsed = JSON.parse(cell);\n } catch (e) {\n return cell;\n }\n const readable = typeof parsed === \"number\" || typeof parsed === \"boolean\" || Array.isArray(parsed);\n return readable && JSON.stringify(parsed) === cell ? parsed : cell;\n}\n\nfunction couldBeCanonicalJson(firstChar: number): boolean {\n return firstChar === 45 /* - */\n || (firstChar >= 48 && firstChar <= 57) /* 0-9 */\n || firstChar === 116 /* t */\n || firstChar === 102 /* f */\n || firstChar === 91; /* [ */\n}\n\nexport function mapJsonParse(obj: Record<string, any>) {\n return Object.keys(obj).reduce((acc: Record<string, any>, key) => {\n // Same header row, same setter: `acc[\"__proto__\"] = value` replaces the\n // accumulator's prototype instead of adding a column.\n if (isPrototypePollutingKey(key)) {\n console.warn(`Skipping column \"${key}\": a header may not reach the prototype chain`);\n return acc;\n }\n acc[key] = parseCanonicalJsonCell(obj[key]);\n return acc;\n }, {});\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,SAAgB,gBAAgB,SAAiC;CAC7D,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,QAAQ,WAAW,QAAQ;EAGnD,IAAI,uBAAuB,GAAG,GAAG;GAC7B,QAAQ,KAAK,oBAAoB,IAAI,8CAA8C;GACnF,OAAO;EACX;EACA,IAAI,aAAa;EACjB,MAAM,WAAW,IAAI,MAAM,GAAG;EAC9B,SAAS,SAAS,SAAS,MAAM;GAE7B,IAAI,iBAAiB,KAAK,OAAO,GAAG;IAChC,MAAM,mBAAmB,QAAQ,MAAM,GAAG,QAAQ,QAAQ,GAAG,CAAC;IAC9D,MAAM,QAAQ,SAAS,QAAQ,MAAM,QAAQ,QAAQ,GAAG,IAAI,GAAG,QAAQ,QAAQ,GAAG,CAAC,CAAC;IAEpF,IAAI,CAAC,WAAW,mBACZ,WAAW,oBAAoB,CAAC;IAGpC,IAAI,MAAM,SAAS,SAAS,GAAG;KAC3B,WAAW,iBAAiB,CAAC,SAAS,WAAW,iBAAiB,CAAC,UAAU,CAAC;KAC9E,aAAa,WAAW,iBAAiB,CAAC;IAC9C,OACI,WAAW,iBAAiB,CAAC,SAAS,QAAQ;GAEtD,OAAO,IAAI,MAAM,SAAS,SAAS,GAAG;IAClC,WAAW,WAAW,WAAW,YAAY,CAAC;IAC9C,aAAa,WAAW;GAC5B,OACI,WAAW,WAAW,QAAQ;EAGtC,CAAC;EACD,OAAO;CACX,GAAG,CAAC,CAA2B;AACnC;;;;;;;;;;;;;;;AAgBA,SAAS,uBAAuB,MAAwB;CACpD,IAAI,OAAO,SAAS,UAAU,OAAO;CAKrC,IAAI,CAAC,qBAAqB,KAAK,WAAW,CAAC,CAAC,GAAG,OAAO;CACtD,IAAI;CACJ,IAAI;EACA,SAAS,KAAK,MAAM,IAAI;CAC5B,SAAS,GAAG;EACR,OAAO;CACX;CAEA,QADiB,OAAO,WAAW,YAAY,OAAO,WAAW,aAAa,MAAM,QAAQ,MAAM,MAC/E,KAAK,UAAU,MAAM,MAAM,OAAO,SAAS;AAClE;AAEA,SAAS,qBAAqB,WAA4B;CACtD,OAAO,cAAc,MACb,aAAa,MAAM,aAAa,MACjC,cAAc,OACd,cAAc,OACd,cAAc;AACzB;AAEA,SAAgB,aAAa,KAA0B;CACnD,OAAO,OAAO,KAAK,GAAG,CAAC,CAAC,QAAQ,KAA0B,QAAQ;EAG9D,IAAI,wBAAwB,GAAG,GAAG;GAC9B,QAAQ,KAAK,oBAAoB,IAAI,8CAA8C;GACnF,OAAO;EACX;EACA,IAAI,OAAO,uBAAuB,IAAI,IAAI;EAC1C,OAAO;CACX,GAAG,CAAC,CAAC;AACT"}
1
+ {"version":3,"file":"transforms.js","names":[],"sources":["../../../src/data_import/utils/transforms.ts"],"sourcesContent":["import { isPrototypePollutingKey, pathTraversesPrototype } from \"@rebasepro/utils\";\n\n/**\n * Make `holder[slot]` an array or an object to write into, unless it is one.\n *\n * A file can carry a plain column and nested ones under the same name — `tags`\n * beside `tags[0]`, `address` beside `address.city`. The nested columns win:\n * they say what shape the value has, and writing an index or a key into the\n * text a plain column left there threw (strict mode), which failed the whole\n * file.\n */\nfunction containerAt(holder: { [key: string]: any }, slot: string | number, kind: \"array\" | \"object\", column: string): void {\n const existing = holder[slot];\n if (existing !== null && typeof existing === \"object\") return;\n if (existing !== undefined && existing !== null && existing !== \"\") {\n console.warn(`Column \"${column}\" nests under \"${String(slot)}\", which another column set to a plain value; the nested columns are kept`);\n }\n holder[slot] = kind === \"array\" ? [] : {};\n}\n\n/**\n * Take an object with keys of type `address.street`, `address.city` and\n * convert it to an object with nested objects like `{ address: { street: ..., city: ... } }`\n *\n * Keys here are the **header row of an uploaded file**, so they are attacker\n * data. `res[\"__proto__\"] = …` is the prototype setter rather than an own\n * property, so a column named `__proto__.polluted` walked out of the accumulator\n * and wrote onto `Object.prototype` for the life of the tab — and\n * `constructor.prototype.x` threw a `TypeError` that surfaced as an unreadable\n * file. Such a column is refused, not sanitised, the way `setIn` settled it\n * (`docs/bug-classes.md` class 22).\n *\n * @param flatObj\n */\nexport function unflattenObject(flatObj: { [key: string]: any }) {\n return Object.keys(flatObj).reduce((nestedObj, key) => {\n // The string form, so `toPath` rewrites `__proto__[0]` to a `__proto__`\n // segment too — the bracket branch below writes through the same setter.\n if (pathTraversesPrototype(key)) {\n console.warn(`Skipping column \"${key}\": a header may not reach the prototype chain`);\n return nestedObj;\n }\n let currentObj = nestedObj;\n const keyParts = key.split(\".\");\n keyParts.forEach((keyPart, i) => {\n\n const indexed = /^(.+)\\[(\\d+)\\]$/.exec(keyPart);\n if (indexed) {\n const mainPropertyName = indexed[1];\n const index = parseInt(indexed[2], 10);\n\n containerAt(currentObj, mainPropertyName, \"array\", key);\n\n if (i !== keyParts.length - 1) {\n containerAt(currentObj[mainPropertyName], index, \"object\", key);\n currentObj = currentObj[mainPropertyName][index];\n } else {\n currentObj[mainPropertyName][index] = flatObj[key];\n }\n } else if (i !== keyParts.length - 1) {\n containerAt(currentObj, keyPart, \"object\", key);\n currentObj = currentObj[keyPart];\n } else if (currentObj[keyPart] !== null && typeof currentObj[keyPart] === \"object\") {\n // Nested columns already gave this name its shape; see `containerAt`.\n console.warn(`Column \"${key}\" is a plain value where nested columns already are; the nested columns are kept`);\n } else {\n currentObj[keyPart] = flatObj[key];\n }\n\n });\n return nestedObj;\n }, {} as { [key: string]: any });\n}\n\n/**\n * Read a text cell as the number, boolean or array it spells, when it spells\n * one exactly — so the type inference sees `12`, `true` and the export's\n * `[\"a\",\"b\"]` for what they are.\n *\n * Only a cell that is the canonical JSON of its value is read: `JSON.stringify`\n * of the result must give back the cell's text. That makes the read lossless,\n * and the import coerces each value against the property it lands in only\n * later — a string property turns it back into exactly the text in the file.\n * Anything else stays the text it was: `1.10`, `00123`, `1E3`, a twenty-digit\n * SKU that a double cannot hold, the word `null`, and a cell with quotes in it.\n * So does an object: the import flattens objects into `a.b` columns, which\n * would scatter a string property's JSON text into columns that do not exist.\n */\nfunction parseCanonicalJsonCell(cell: unknown): unknown {\n if (typeof cell !== \"string\") return cell;\n // The canonical JSON of a number, boolean or array starts with `-`, a\n // digit, `t`, `f` or `[` — nothing else can pass the round trip below. Text\n // is most of a file, and `JSON.parse` on text throws: the throw was over\n // half of the main-thread time of reading one.\n if (!couldBeCanonicalJson(cell.charCodeAt(0))) return cell;\n let parsed: unknown;\n try {\n parsed = JSON.parse(cell);\n } catch (e) {\n return cell;\n }\n const readable = typeof parsed === \"number\" || typeof parsed === \"boolean\" || Array.isArray(parsed);\n return readable && JSON.stringify(parsed) === cell ? parsed : cell;\n}\n\nfunction couldBeCanonicalJson(firstChar: number): boolean {\n return firstChar === 45 /* - */\n || (firstChar >= 48 && firstChar <= 57) /* 0-9 */\n || firstChar === 116 /* t */\n || firstChar === 102 /* f */\n || firstChar === 91; /* [ */\n}\n\nexport function mapJsonParse(obj: Record<string, any>) {\n return Object.keys(obj).reduce((acc: Record<string, any>, key) => {\n // Same header row, same setter: `acc[\"__proto__\"] = value` replaces the\n // accumulator's prototype instead of adding a column.\n if (isPrototypePollutingKey(key)) {\n console.warn(`Skipping column \"${key}\": a header may not reach the prototype chain`);\n return acc;\n }\n acc[key] = parseCanonicalJsonCell(obj[key]);\n return acc;\n }, {});\n}\n"],"mappings":";;;;;;;;;;;AAWA,SAAS,YAAY,QAAgC,MAAuB,MAA0B,QAAsB;CACxH,MAAM,WAAW,OAAO;CACxB,IAAI,aAAa,QAAQ,OAAO,aAAa,UAAU;CACvD,IAAI,aAAa,KAAA,KAAa,aAAa,QAAQ,aAAa,IAC5D,QAAQ,KAAK,WAAW,OAAO,iBAAiB,OAAO,IAAI,EAAE,0EAA0E;CAE3I,OAAO,QAA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MAAM,MAC/E,KAAK,UAAU,MAAM,MAAM,OAAO,SAAS;AAClE;AAEA,SAAS,qBAAqB,WAA4B;CACtD,OAAO,cAAc,MACb,aAAa,MAAM,aAAa,MACjC,cAAc,OACd,cAAc,OACd,cAAc;AACzB;AAEA,SAAgB,aAAa,KAA0B;CACnD,OAAO,OAAO,KAAK,GAAG,CAAC,CAAC,QAAQ,KAA0B,QAAQ;EAG9D,IAAI,wBAAwB,GAAG,GAAG;GAC9B,QAAQ,KAAK,oBAAoB,IAAI,8CAA8C;GACnF,OAAO;EACX;EACA,IAAI,OAAO,uBAAuB,IAAI,IAAI;EAC1C,OAAO;CACX,GAAG,CAAC,CAAC;AACT"}
@@ -9,4 +9,4 @@ import type { EntityFormProps } from "../types/components/EntityFormProps.js";
9
9
  *
10
10
  * @group Components
11
11
  */
12
- export declare function EntityForm<M extends Record<string, unknown>>({ path, entityId: entityIdProp, collection, onValuesModified, onIdChange, onSaved, entity, initialDirtyValues, onFormContextReady, initialStatus, className, onStatusChange, onEntityChange, openEntityMode, formex: formexProp, disabled: disabledProp, Builder, parentCollectionSlugs, parentEntityIds, EntityFormActionsComponent, showDefaultActions, navigateBack: navigateBackProp, children, onSubmit: onSubmitProp, onValuesChangeDeferred: onValuesChangeDeferredProp, onReset: onResetProp, uniqueFieldValidator: uniqueFieldValidatorProp, lockedPropertyKeys, beforeFields, afterFields, pluginActions: pluginActionsProp, computedInitialValues, hasLocalChanges: hasLocalChangesProp, localChangesData, manualApplyLocalChanges, localChangesCacheKey, onClearLocalChanges }: EntityFormProps<M>): React.JSX.Element;
12
+ export declare function EntityForm<M extends Record<string, unknown>>({ path, entityId: entityIdProp, collection, onValuesModified, onIdChange, onSaved, entity: entityProp, initialDirtyValues, onFormContextReady, initialStatus, className, onStatusChange, onEntityChange, openEntityMode, formex: formexProp, disabled: disabledProp, Builder, parentCollectionSlugs, parentEntityIds, EntityFormActionsComponent, showDefaultActions, navigateBack: navigateBackProp, children, onSubmit: onSubmitProp, onValuesChangeDeferred: onValuesChangeDeferredProp, onReset: onResetProp, uniqueFieldValidator: uniqueFieldValidatorProp, lockedPropertyKeys, beforeFields, afterFields, pluginActions: pluginActionsProp, computedInitialValues, hasLocalChanges: hasLocalChangesProp, localChangesData, manualApplyLocalChanges, localChangesCacheKey, onClearLocalChanges }: EntityFormProps<M>): React.JSX.Element;
@@ -18,7 +18,7 @@ import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "rea
18
18
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
19
19
  import { deepEqual } from "fast-equals";
20
20
  import { Alert, AlignLeftIcon, Button, CircularProgressCenter, Dialog, DialogActions, DialogContent, DialogTitle, ErrorBoundary, Typography, cls, defaultBorderMixin, isKeyHandled, paperMixin, useDebouncedCallback } from "@rebasepro/ui";
21
- import { effectiveAccess, getCopyValues, getDefaultValuesFor } from "@rebasepro/common";
21
+ import { effectiveAccess, getCopyValues, getDefaultValuesFor, hasEntityId } from "@rebasepro/common";
22
22
  import { flattenKeys, getFormFieldKeys, isDisabled, isHidden, isReadOnly, resolveFormLayout, useAuthController, useCustomizationController, useRebaseContext, useTranslation } from "@rebasepro/app";
23
23
  import { Formex, useCreateFormex } from "@rebasepro/forms";
24
24
  //#region src/form/EntityForm.tsx
@@ -31,12 +31,21 @@ import { Formex, useCreateFormex } from "@rebasepro/forms";
31
31
  *
32
32
  * @group Components
33
33
  */
34
- function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified, onIdChange, onSaved, entity, initialDirtyValues, onFormContextReady, initialStatus, className, onStatusChange, onEntityChange, openEntityMode = "full_screen", formex: formexProp, disabled: disabledProp, Builder, parentCollectionSlugs, parentEntityIds, EntityFormActionsComponent = EntityFormActions, showDefaultActions = true, navigateBack: navigateBackProp, children, onSubmit: onSubmitProp, onValuesChangeDeferred: onValuesChangeDeferredProp, onReset: onResetProp, uniqueFieldValidator: uniqueFieldValidatorProp, lockedPropertyKeys, beforeFields, afterFields, pluginActions: pluginActionsProp, computedInitialValues, hasLocalChanges: hasLocalChangesProp, localChangesData, manualApplyLocalChanges, localChangesCacheKey, onClearLocalChanges }) {
34
+ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified, onIdChange, onSaved, entity: entityProp, initialDirtyValues, onFormContextReady, initialStatus, className, onStatusChange, onEntityChange, openEntityMode = "full_screen", formex: formexProp, disabled: disabledProp, Builder, parentCollectionSlugs, parentEntityIds, EntityFormActionsComponent = EntityFormActions, showDefaultActions = true, navigateBack: navigateBackProp, children, onSubmit: onSubmitProp, onValuesChangeDeferred: onValuesChangeDeferredProp, onReset: onResetProp, uniqueFieldValidator: uniqueFieldValidatorProp, lockedPropertyKeys, beforeFields, afterFields, pluginActions: pluginActionsProp, computedInitialValues, hasLocalChanges: hasLocalChangesProp, localChangesData, manualApplyLocalChanges, localChangesCacheKey, onClearLocalChanges }) {
35
35
  const navigateBack = useCallback(() => {
36
36
  if (navigateBackProp) navigateBackProp();
37
37
  }, [navigateBackProp]);
38
38
  const authController = useAuthController();
39
39
  const [status, setStatus] = useState(initialStatus);
40
+ /**
41
+ * The record as this form last saved it. A create turns the form into the
42
+ * editor of the record it made, and the `entity` prop names that record
43
+ * only once the caller has caught up — a caller that never does (the form
44
+ * used on its own) left an "existing" form with no record: it re-seeded
45
+ * itself with the defaults and refused the next Save.
46
+ */
47
+ const [savedEntity, setSavedEntity] = useState(void 0);
48
+ const entity = entityProp ?? (status === "existing" ? savedEntity : void 0);
40
49
  const updateStatus = (status) => {
41
50
  setStatus(status);
42
51
  onStatusChange?.(status);
@@ -214,6 +223,7 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
214
223
  return () => window.removeEventListener("keydown", handleKeyDown);
215
224
  }, [formex]);
216
225
  const afterSave = (updatedEntity) => {
226
+ setSavedEntity(updatedEntity);
217
227
  onResetProp?.();
218
228
  onValuesModified?.(false, updatedEntity.values);
219
229
  onEntityChange?.(updatedEntity);
@@ -582,7 +592,7 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
582
592
  children: t("entity_does_not_exist")
583
593
  }),
584
594
  children,
585
- initialEntityId && !entity && initialStatus !== "new" && /* @__PURE__ */ jsx(Alert, {
595
+ hasEntityId(initialEntityId) && !entity && initialStatus !== "new" && /* @__PURE__ */ jsx(Alert, {
586
596
  color: "info",
587
597
  size: "small",
588
598
  children: t("entity_does_not_exist")
@@ -638,7 +648,7 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
638
648
  })
639
649
  ] }) });
640
650
  useEffect(() => {
641
- if (entityId && onIdChange) onIdChange(entityId);
651
+ if (hasEntityId(entityId) && onIdChange) onIdChange(entityId);
642
652
  }, [entityId, onIdChange]);
643
653
  if (!collection || !path) throw Error("INTERNAL: Collection and path must be defined in form context");
644
654
  const dialogActions = /* @__PURE__ */ jsx(EntityFormActionsComponent, {
@@ -1 +1 @@
1
- {"version":3,"file":"EntityForm.js","names":[],"sources":["../../src/form/EntityForm.tsx"],"sourcesContent":["\nimport type { AdditionalFieldDelegateProps } from \"@rebasepro/cms-types\";\nimport type { FormContext, PropertyFieldBindingProps } from \"../types/fields\";\nimport React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { Entity, EntityStatus, EntityValues } from \"@rebasepro/types\";\nimport type { Properties, Property } from \"@rebasepro/types\";\nimport type { EntityFormProps } from \"../types/components/EntityFormProps\";\nimport { deepEqual as equal } from \"fast-equals\";\n\nimport { ErrorBoundary, isKeyHandled } from \"@rebasepro/ui\";\nimport { AlignLeftIcon, useDebouncedCallback } from \"@rebasepro/ui\";\nimport { effectiveAccess, getCopyValues, getDefaultValuesFor } from \"@rebasepro/common\";\nimport { isDisabled, isHidden, isReadOnly } from \"@rebasepro/app\";\nimport { useAuthController, useCustomizationController, useRebaseContext, useTranslation } from \"@rebasepro/app\";\n\nimport { getFormFieldKeys, resolveFormLayout } from \"@rebasepro/app\";\nimport type { ResolvedFormField } from \"@rebasepro/app\";\nimport { Alert, Button, CircularProgressCenter, cls, defaultBorderMixin, Dialog, DialogActions, DialogContent, DialogTitle, paperMixin, Typography } from \"@rebasepro/ui\";\nimport { Formex, FormexController, useCreateFormex } from \"@rebasepro/forms\";\n\nimport { FieldBlock, isSelfLabellingProperty, LABEL_ICON_SIZE, spanClass } from \"./components/FieldBlock\";\nimport { labelsInsideControl } from \"./label_placement\";\nimport { AdditionalFieldValue } from \"../components/AdditionalFieldValue\";\nimport { FormRail, RecordMeta } from \"./components/FormRail\";\nimport { FormSections } from \"./components/FormSections\";\nimport { useRailVisible } from \"./components/useRailVisible\";\nimport { PropertyFieldBinding } from \"./PropertyFieldBinding\";\nimport { flattenKeys } from \"@rebasepro/app\";\nimport { ErrorFocus } from \"./components/ErrorFocus\";\nimport { applyValueTransforms, CustomFieldValidator, getEntitySchema, uniqueValueErrors } from \"./validation\";\nimport { formViewer, resolveFormProperty, resolvePropertiesForValidation, withoutUnwritableDefaults } from \"./resolve_form_properties\";\nimport { EntityFormActions } from \"./EntityFormActions\";\nimport type { EntityFormActionsProps } from \"../types/components/EntityFormActionsProps\";\nimport { LocalChangesMenu } from \"./components/LocalChangesMenu\";\nimport { useUndoableDiscard } from \"./useUndoableDiscard\";\nimport { ownsKeystroke, registerKeyboardScope } from \"./form_keyboard_scope\";\nimport { createFormUploadTracker, FormUploadsContext } from \"./form_uploads\";\n\nimport {\n getChangedProperties,\n overlayEdit,\n serverViolationErrors,\n withoutUnsetNulls,\n zodToFormErrors\n} from \"./form_utils\";\n\n/**\n * Headless entity form component.\n *\n * Renders a form for a entity collection without any admin or backend dependencies.\n * All backend concerns (save, caching, analytics, plugin slots) are provided via\n * callback props. For admin-connected usage, use {@link EntityFormBinding} instead.\n *\n * @group Components\n */\nexport function EntityForm<M extends Record<string, unknown>>({\n path,\n entityId: entityIdProp,\n collection,\n onValuesModified,\n onIdChange,\n onSaved,\n entity,\n initialDirtyValues,\n onFormContextReady,\n initialStatus,\n className,\n onStatusChange,\n onEntityChange,\n openEntityMode = \"full_screen\",\n formex: formexProp,\n disabled: disabledProp,\n Builder,\n parentCollectionSlugs,\n parentEntityIds,\n EntityFormActionsComponent = EntityFormActions,\n showDefaultActions = true,\n navigateBack: navigateBackProp,\n children,\n // Headless callback props\n onSubmit: onSubmitProp,\n onValuesChangeDeferred: onValuesChangeDeferredProp,\n onReset: onResetProp,\n uniqueFieldValidator: uniqueFieldValidatorProp,\n lockedPropertyKeys,\n // Slots\n beforeFields,\n afterFields,\n pluginActions: pluginActionsProp,\n // Local changes (managed externally)\n computedInitialValues,\n hasLocalChanges: hasLocalChangesProp,\n localChangesData,\n manualApplyLocalChanges,\n localChangesCacheKey,\n onClearLocalChanges\n}: EntityFormProps<M>) {\n\n const navigateBack = useCallback(() => {\n if (navigateBackProp) {\n navigateBackProp();\n }\n }, [navigateBackProp]);\n\n const authController = useAuthController();\n const [status, setStatus] = useState<EntityStatus>(initialStatus);\n\n const updateStatus = (status: EntityStatus) => {\n setStatus(status);\n onStatusChange?.(status);\n };\n\n /**\n * The autosave due: what it writes, and the whole form it was taken from\n * — which is what validation judges.\n */\n const [valuesToBeSaved, setValuesToBeSaved] = useState<{ toSave: EntityValues<M>, values: M } | undefined>(undefined);\n useDebouncedCallback(valuesToBeSaved, () => {\n if (!valuesToBeSaved || !onSubmitProp) return;\n const pending = valuesToBeSaved;\n setIsSavingAutoSave(true);\n // An autosave is a save, and is held to what Save is held to. It\n // wrote every edit unchecked; a form that does not validate now shows\n // why, and writes nothing until it does.\n validateForSave(pending.values)\n .then((errors) => {\n if (Object.keys(errors).length > 0) {\n formex.validate();\n return;\n }\n return onSubmitProp(pending.toSave, formex);\n })\n .catch((e) => {\n console.error(e);\n setSavingError(e);\n // The fields the server refused, marked as a Save marks them;\n // an autosave has no submit to make them show, so it counts one.\n const fieldErrors = serverViolationErrors(e, Object.keys(collection.properties ?? {}));\n if (Object.keys(fieldErrors).length > 0) {\n for (const [key, message] of Object.entries(fieldErrors)) formex.setFieldError(key, message);\n formex.setSubmitCount(formex.submitCount + 1);\n }\n })\n .finally(() => setIsSavingAutoSave(false));\n }, false, 2000);\n\n /**\n * The properties the record changed underneath an edit of the user's own,\n * keyed to the value they changed to — each one shown as \"updated\n * elsewhere\" while the form still holds something else. Filled by the\n * effect that follows the baseline, below.\n */\n const [underlyingChanges, setUnderlyingChanges] = useState<Record<string, unknown>>({});\n\n /**\n * Rules the stored record already broke, on fields this edit leaves alone —\n * shown, and not held against the save. Keyed like `formex.errors`.\n */\n const [predatingViolations, setPredatingViolations] = useState<Record<string, unknown>>({});\n\n const initialEntityId: string | number | undefined = useMemo(() => {\n if (status === \"new\" || status === \"copy\") {\n return undefined;\n } else {\n return entityIdProp;\n }\n }, [entityIdProp, status]);\n\n const [entityId, setEntityId] = useState<string | number | undefined>(initialEntityId);\n const [savingError, setSavingError] = useState<Error | undefined>();\n const [isSavingAutoSave, setIsSavingAutoSave] = useState<boolean>(false);\n const [discardDialogOpen, setDiscardDialogOpen] = useState<boolean>(false);\n\n const discard = useUndoableDiscard();\n\n const autoSave = collection.formAutoSave;\n\n // Use externally computed initial values if provided, otherwise compute from entity + collection\n const baseInitialValues = useMemo(() => {\n if (computedInitialValues !== undefined) {\n return computedInitialValues;\n }\n // Fallback: compute from entity/collection (requires authController from context)\n // In headless mode without computedInitialValues, use entity values or defaults\n if (status === \"copy\" && entity) {\n return getCopyValues(collection, entity.values ?? getDefaultValuesFor(collection.properties));\n }\n if (status === \"existing\" && entity) {\n return entity.values ?? getDefaultValuesFor(collection.properties);\n }\n return getDefaultValuesFor(collection.properties);\n }, [computedInitialValues, collection, status, entity]);\n\n const [localChangesCleared, setLocalChangesCleared] = useState<boolean>(false);\n\n const hasLocalChanges = hasLocalChangesProp !== undefined\n ? (hasLocalChangesProp && !localChangesCleared)\n : false;\n\n const onSubmit = (values: EntityValues<M>, formexController: FormexController<EntityValues<M>>) => {\n\n setSavingError(undefined);\n\n if (status === \"existing\") {\n if (!entity?.id) throw Error(\"Form misconfiguration when saving, no id for existing entity\");\n } else if (status !== \"new\" && status !== \"copy\") {\n throw Error(\"New FormType added, check EntityForm\");\n }\n\n if (!onSubmitProp) {\n console.warn(\"EntityForm: no onSubmit callback provided. Form submission has no effect.\");\n formexController.setSubmitting(false);\n return;\n }\n\n return Promise.resolve(save(values))\n ?.then((savedEntity) => {\n if (savedEntity) {\n formexController.resetForm({\n values: savedEntity.values || values,\n submitCount: 0,\n touched: {}\n });\n }\n })\n .finally(() => {\n formexController.setSubmitting(false);\n });\n };\n\n /**\n * What the form opens showing, when that is not what is stored — an edit\n * carried over from the side panel's \"open full screen\", or a draft\n * restored from the local-changes backup.\n *\n * The merge is deliberately *not* folded into the baseline. `mergeDeep`\n * used to produce a single `initialValues` that served as both, with a\n * `initialDirty: true` bolted on beside it to say what the baseline could\n * no longer show — and that flag survived exactly one render, because the\n * record's data arriving replaced the baseline and the form recomputed\n * dirty as false against a baseline that already contained the edit.\n *\n * Read once, at mount: this is a handoff, and re-reading it every render\n * tied the form to a cache that is cleared as soon as it has been consumed.\n */\n const initialModifiedValues = useRef(\n initialDirtyValues && Object.keys(initialDirtyValues).length > 0\n ? overlayEdit(baseInitialValues as Partial<M>, initialDirtyValues as Partial<M>)\n : undefined\n ).current;\n\n /**\n * Every key of the handed-over edit, marked touched. Read once, at mount,\n * like the edit itself: it was rebuilt on every render — a key-value map\n * of 1,000 entries cost ~60 ms per keystroke — by a spread that copied the\n * map once per key.\n */\n const [initialTouched] = useState<Record<string, boolean>>(() => {\n const touched: Record<string, boolean> = {};\n if (initialDirtyValues) {\n for (const key of flattenKeys(initialDirtyValues)) touched[key] = true;\n }\n return touched;\n });\n\n // A Save waits for a file still uploading: its path reaches the values\n // only when the upload ends. See `form_uploads.ts`.\n const [uploadTracker] = useState(createFormUploadTracker);\n\n const internalFormex = useCreateFormex<M>({\n initialValues: baseInitialValues as M,\n beforeSubmit: uploadTracker.wait,\n initialModifiedValues: initialModifiedValues as M | undefined,\n debugId: `EntityForm:${path}/${entityIdProp}`,\n initialTouched,\n onSubmit,\n onReset: () => {\n setUnderlyingChanges({});\n onResetProp?.();\n // The stored values — a reset returns the form to them, and by now\n // that is the baseline whether or not it was at mount.\n onValuesModified?.(false, baseInitialValues as M);\n },\n onValuesChangeDeferred: onValuesChangeDeferredProp,\n validation: (values) => validateForSave(values)\n });\n const formex: FormexController<M> = formexProp ?? internalFormex;\n\n /**\n * The errors that stop a save of `values`. Formex runs it on submit, and\n * the autosave runs it before each write.\n */\n async function validateForSave(values: M): Promise<Record<string, string>> {\n const errors = await validationErrorsFor(values);\n if (status !== \"existing\" || !entity?.values || Object.keys(errors).length === 0) {\n setPredatingViolations({});\n return errors;\n }\n // A record stored before a rule existed still breaks it, and the\n // server — which judges only what is sent — would take an\n // unrelated edit. So a field the user did not change, that the\n // stored record already broke, is a warning and not a refusal. A\n // field they changed must be valid, and so must one their edit\n // made invalid: a rule that reads the edited value is the edit's.\n const edited = getChangedProperties<M>(values, entity.values as Partial<M>);\n const storedErrors = await validationErrorsFor(entity.values as M);\n const blocking: Record<string, string> = {};\n const predating: Record<string, string> = {};\n for (const [key, error] of Object.entries(errors)) {\n if (!(key in edited) && key in storedErrors) predating[key] = error;\n else blocking[key] = error;\n }\n setPredatingViolations(predating);\n return blocking;\n }\n\n // One form takes a shortcut: the one the focus is in, else the one\n // mounted last (the top panel). Registered once per mount, so the order\n // is the order the forms opened in. See `form_keyboard_scope.ts`.\n const keyboardScope = useRef<ReturnType<typeof registerKeyboardScope> | undefined>(undefined);\n useEffect(() => {\n const scope = registerKeyboardScope(() => formElementRef.current);\n keyboardScope.current = scope;\n return () => {\n scope.unregister();\n keyboardScope.current = undefined;\n };\n }, []);\n\n useEffect(() => {\n\n const handleKeyDown = (e: KeyboardEvent) => {\n // A layer above the form (a dialog, a menu) already acted on it.\n if (isKeyHandled(e)) return;\n if (!keyboardScope.current || !ownsKeystroke(keyboardScope.current, e)) return;\n const isUndo = (e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === \"z\";\n const isRedo =\n ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key.toLowerCase() === \"z\") ||\n ((e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === \"y\");\n const isSave = (e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"s\";\n\n if (isSave && !disabled && formex.dirty) {\n e.preventDefault();\n formex.handleSubmit();\n } else if (isUndo && formex.canUndo) {\n e.preventDefault();\n formex.undo();\n } else if (isRedo && formex.canRedo) {\n e.preventDefault();\n formex.redo();\n }\n };\n\n window.addEventListener(\"keydown\", handleKeyDown);\n return () => window.removeEventListener(\"keydown\", handleKeyDown);\n\n }, [formex]);\n\n const afterSave = (updatedEntity: Entity<M>) => {\n onResetProp?.();\n onValuesModified?.(false, updatedEntity.values);\n onEntityChange?.(updatedEntity);\n updateStatus(\"existing\");\n setEntityId(updatedEntity.id);\n\n if (onSaved) {\n onSaved({\n entity: updatedEntity,\n status,\n path,\n entityId: updatedEntity.id,\n collection\n });\n }\n };\n\n // What the form opened with counts as saved: a New form nobody touched\n // has nothing to autosave. Seeded with `entity?.values`, which a new\n // record does not have, the first autosave wrote a record of defaults.\n const lastSavedValues = useRef<EntityValues<M> | undefined>(baseInitialValues as EntityValues<M>);\n const save = async (values: EntityValues<M>): Promise<Entity<M> | void> => {\n // The string transforms a property declares change what is written;\n // validation has already judged the transformed value.\n const writtenValues = applyValueTransforms(values, collection.properties);\n // An existing record sends only what changed; a new one or a copy\n // sends what it holds, less what the user could not have written.\n const valuesToSave = status === \"existing\"\n ? getChangedProperties<M>(writtenValues, entity?.values || {}) as EntityValues<M>\n : withoutUnwritableDefaults<M>(\n status === \"new\"\n ? withoutUnsetNulls(writtenValues, baseInitialValues as Partial<M>)\n : writtenValues,\n baseInitialValues as Partial<M>,\n collection.properties,\n formViewer(authController)\n ) as EntityValues<M>;\n\n if (status === \"existing\" && Object.keys(valuesToSave).length === 0 && entity) {\n return Promise.resolve(entity);\n }\n\n lastSavedValues.current = values;\n\n if (!onSubmitProp) {\n return;\n }\n\n const autoSaveEnabled = autoSave ?? false;\n\n if (autoSaveEnabled) {\n setValuesToBeSaved({ toSave: valuesToSave, values: values as M });\n return Promise.resolve();\n }\n\n return Promise.resolve(onSubmitProp(valuesToSave as M, formex))\n .then((result) => {\n if (result) {\n afterSave(result as Entity<M>);\n }\n return result as Entity<M> | void;\n })\n .catch(e => {\n console.error(e);\n setSavingError(e);\n // The fields the server refused, marked where the user can\n // see them — not only the sentence in the footer.\n const fieldErrors = serverViolationErrors(e, Object.keys(collection.properties ?? {}));\n for (const [key, message] of Object.entries(fieldErrors)) formex.setFieldError(key, message);\n });\n };\n\n const disabled = formex.isSubmitting || Boolean(disabledProp);\n\n // The context an `additionalFields` Builder is documented to receive, and\n // the one `CollectionTableBinding` already hands it. This form used to pass\n // its own `FormContext` instead, laundered through\n // `formContext as unknown as AdditionalFieldDelegateProps[\"context\"]` —\n // two unrelated types, so a Builder reading anything off `RebaseContext`\n // worked in the table view and read `undefined` in the form.\n const rebaseContext = useRebaseContext();\n\n const formContext: FormContext<M> = {\n setFieldValue: useCallback((key: string, value: unknown) => formex.setFieldValue(key, value), []),\n values: formex.values,\n collection,\n entityId: entityId as string,\n path,\n save,\n submit: formex.handleSubmit,\n formex,\n entity,\n savingError,\n status,\n openEntityMode,\n disabled,\n isSaving: formex.isSubmitting || isSavingAutoSave\n };\n\n /**\n * The context the fields get. Not `formContext`: that one is a new object\n * per render, and a field memoised on its own value would re-render for it\n * on every keystroke anywhere in the form.\n *\n * This one changes identity only with what a field may draw from it — the\n * record, its status, the form's `version` (a reset or re-seed) — and reads\n * `values`, `formex` and `save` through a ref, so a field that did not\n * re-render still sees the current ones from its callbacks (a storage path\n * builder, a markdown file name). A field that reads another field's value\n * *while rendering* has to re-render with it; `PropertyFieldBinding` keeps\n * those — custom `Field`s, `dynamicProps`, `conditions` — on that path.\n */\n const latestRef = useRef({ formex, save });\n latestRef.current = { formex, save };\n const isSaving = formex.isSubmitting || isSavingAutoSave;\n const fieldContext: FormContext<M> = useMemo(() => ({\n get values() {\n return latestRef.current.formex.values;\n },\n get formex() {\n return latestRef.current.formex;\n },\n setFieldValue: formContext.setFieldValue,\n save: (values: M) => latestRef.current.save(values),\n submit: () => latestRef.current.formex.handleSubmit(),\n collection,\n entityId: entityId as string,\n path,\n entity,\n savingError,\n status,\n openEntityMode,\n disabled,\n isSaving\n // `formex.version` is a key, not an input: a reset or re-seed has to\n // hand the fields a new context even though nothing above reads it.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [formContext.setFieldValue, collection, entityId, path, entity, savingError, status, openEntityMode, disabled, isSaving, formex.version]);\n\n useEffect(() => {\n onFormContextReady?.(formContext);\n // `formex.version` only moves on `resetForm`, so these deps used to hand\n // the container one snapshot at mount and never another. That was\n // invisible while Save lived inside the form and read `formex` directly;\n // once the identity bar owned Save, its `dirty` was frozen false and the\n // button never enabled — for any field, not just the one that exposed\n // it. Custom entity views read `formContext.values` through the same\n // channel and were reading a stale copy too.\n //\n // Deps are the state *transitions* a container cares about, not\n // `formex.values`: re-publishing on every keystroke would re-render the\n // whole entity view per character.\n }, [\n formex.version, collection, entityId, path,\n formex.dirty, formex.isSubmitting, formex.submitCount, isSavingAutoSave\n ]);\n\n const actionsDisabled = disabled || formex.isSubmitting || (status === \"existing\" && !formex.dirty) || Boolean(disabledProp);\n\n // The record's title is resolved by the container that renders the identity\n // bar (see `useEntityDisplayTitle`), not here — the form no longer draws a\n // heading of its own.\n\n const modified = formex.dirty;\n\n useEffect(() => {\n if (!autoSave) {\n onValuesModified?.(modified, formex.values);\n }\n }, [formex.dirty]);\n\n // Default no-op unique field validator — always passes\n const defaultUniqueFieldValidator: CustomFieldValidator = useCallback(async () => true, []);\n\n const uniqueFieldValidator: CustomFieldValidator = useMemo(() => {\n if (uniqueFieldValidatorProp) {\n return uniqueFieldValidatorProp as CustomFieldValidator;\n }\n return defaultUniqueFieldValidator;\n }, [uniqueFieldValidatorProp, defaultUniqueFieldValidator]);\n\n const customizationController = useCustomizationController();\n const { t } = useTranslation();\n\n async function validationErrorsFor(values: M): Promise<Record<string, string>> {\n const properties = validationPropertiesFor(values);\n const result = await getEntitySchema(entityId, properties, uniqueFieldValidator).safeParseAsync(values);\n const errors: Record<string, string> = result.success ? {} : zodToFormErrors(result.error);\n // `validation.unique` asks the data source, so it runs here — on\n // submit — and only for values this edit changed that are otherwise\n // valid. It was built and threaded through, and never called.\n const notUnique = await uniqueValueErrors({\n properties,\n values,\n storedValues: status === \"existing\" ? entity?.values : undefined,\n entityId,\n errors,\n validator: uniqueFieldValidator\n });\n return { ...errors, ...notUnique };\n }\n\n /**\n * What the save is judged against: the properties as the form shows them\n * for these values — `dynamicProps` and `conditions` applied — and only\n * the ones the user can change. Built per call because both depend on the\n * values being judged.\n */\n function validationPropertiesFor(values: M) {\n return resolvePropertiesForValidation<M>({\n properties: collection.properties,\n isNew: status === \"new\" || status === \"copy\",\n values,\n previousValues: baseInitialValues as Partial<M>,\n path,\n entityId,\n propertyConfigs: customizationController.propertyConfigs,\n authController\n });\n }\n\n useOnAutoSave(autoSave, formex, lastSavedValues, save);\n\n /**\n * The record changed while the form was open: someone else saved it, and\n * the listener delivered the new version as a new baseline.\n *\n * An unmodified form follows it whole — formex does that. A modified one\n * keeps the edit, and formex keeps *everything* it holds: a property the\n * user never changed would still show the old value, differ from the new\n * stored one, and be written back by the next save, reverting the other\n * change without a word.\n *\n * So each top-level property that changed underneath is judged on its own,\n * against the baseline the form last followed. One the user has not changed\n * follows the record. One the user has changed keeps the edit — that is\n * what a save writes — and is marked as updated elsewhere, so the overwrite\n * is not a surprise.\n */\n const followedBaseline = useRef(baseInitialValues);\n useEffect(() => {\n const previous: Record<string, unknown> = followedBaseline.current ?? {};\n const next: Record<string, unknown> = baseInitialValues ?? {};\n followedBaseline.current = baseInitialValues;\n if (previous === next) return;\n\n const current: Record<string, unknown> = formex.values;\n if (equal(previous, current)) return;\n\n const conflicts: Record<string, unknown> = {};\n const changedUnderneath = new Set([...Object.keys(previous), ...Object.keys(next)]);\n for (const key of changedUnderneath) {\n if (equal(previous[key], next[key])) {\n changedUnderneath.delete(key);\n } else if (equal(current[key], previous[key])) {\n formex.setFieldValue(key, next[key]);\n } else if (!equal(current[key], next[key])) {\n conflicts[key] = next[key];\n }\n }\n if (changedUnderneath.size === 0) return;\n\n setUnderlyingChanges(prev => {\n const updated = { ...prev };\n changedUnderneath.forEach(key => {\n if (key in conflicts) updated[key] = conflicts[key];\n else delete updated[key];\n });\n return updated;\n });\n }, [baseInitialValues]);\n\n const formFieldKeys = getFormFieldKeys(collection);\n\n const layout = useMemo(() => resolveFormLayout({\n collection,\n fieldKeys: formFieldKeys,\n status\n }), [collection, formFieldKeys.join(\",\"), status]);\n\n const formElementRef = useRef<HTMLFormElement>(null);\n // Measured, not a breakpoint: the rail holds fields the resolver moved\n // out of the column, so when it cannot be shown they have to come back.\n const railVisible = useRailVisible(formElementRef);\n const showRail = !Builder && layout.hasRail && railVisible;\n\n // Collapsed sections are per-section-key so a renamed title keeps its state,\n // and initial state comes from the config rather than being forced open.\n const [collapsedSections, setCollapsedSections] = useState<Set<string>>(\n () => new Set(layout.sections.filter(s => s.collapsed).map(s => s.key))\n );\n const toggleSection = useCallback((key: string) => {\n setCollapsedSections(prev => {\n const next = new Set(prev);\n if (next.has(key)) next.delete(key); else next.add(key);\n return next;\n });\n }, []);\n\n const errorKeys = useMemo(\n () => new Set(formex.submitCount > 0 ? Object.keys(formex.errors) : []),\n [formex.errors, formex.submitCount]\n );\n\n // Autofocus lands on the first field the user can actually type into. Tracked\n // across the whole layout rather than per section, so a collapsed leading\n // group does not steal it.\n const autoFocusKey = useMemo(() => {\n if (status !== \"new\" && status !== \"copy\") return undefined;\n const ordered = [...layout.sections.flatMap(s => s.fields), ...layout.sidebar];\n return ordered.find(field => {\n const property = collection.properties?.[field.key];\n return property ? !isFieldDisabled(field.key, property) : false;\n })?.key;\n }, [layout, collection, status, disabledProp, lockedPropertyKeys]);\n\n function isFieldDisabled(key: string, property: NonNullable<typeof collection.properties[string]>): boolean {\n const isNew = status === \"new\" || status === \"copy\";\n const isStringOrNumber = property.type === \"string\" || property.type === \"number\";\n const isIdAndAuto = isStringOrNumber && \"isId\" in property && typeof property.isId === \"string\" && property.isId !== \"manual\";\n return Boolean(\n disabledProp\n || (!autoSave && formex.isSubmitting)\n || isReadOnly(property)\n || isDisabled(property)\n || (!isNew && \"isId\" in property && Boolean(property.isId))\n || (isNew && isIdAndAuto)\n || (isNew && lockedPropertyKeys?.includes(key))\n );\n }\n\n const renderField = (field: ResolvedFormField): React.ReactNode => {\n\n if (field.additional) {\n const additionalField = collection.additionalFields?.find(f => f.key === field.key);\n if (!additionalField || !entity) return null;\n\n const AdditionalFieldBuilder = additionalField.Builder;\n if (!AdditionalFieldBuilder && !additionalField.value) {\n throw new Error(\"When using additional fields you need to provide a Builder or a value\");\n }\n const child = AdditionalFieldBuilder\n ? <AdditionalFieldBuilder entity={entity} context={rebaseContext}/>\n : <div className={\"w-full\"}>\n <AdditionalFieldValue\n field={additionalField}\n entity={entity}\n context={rebaseContext}/>\n </div>;\n\n return (\n // Through FieldBlock like every other cell, so a computed\n // column is labelled at the same size, with the same gap to its\n // box, as the property next to it on the grid.\n <div key={`additional_${field.key}`}\n className={spanClass(field.span)}>\n <FieldBlock propertyKey={field.key}\n showLabel={true}\n label={additionalField.name}\n icon={<AlignLeftIcon size={LABEL_ICON_SIZE}/>}>\n <div className={cls(paperMixin, \"w-full min-h-12 p-4 md:p-6 overflow-x-auto no-scrollbar\")}>\n {child}\n </div>\n </FieldBlock>\n </div>\n );\n }\n\n const property = collection.properties?.[field.key];\n if (!property) {\n console.warn(`Property ${field.key} not found in collection ${collection.name} in properties or additional fields. Skipping.`);\n return null;\n }\n // A field a rule hides for these values, or that this user may not\n // read, takes its label with it: the binding renders nothing, and a\n // heading over nothing is worse.\n if (property.conditions?.hidden || effectiveAccess(property)) {\n const shown = resolveFormProperty({\n propertyKey: field.key,\n property,\n values: formex.values,\n previousValues: baseInitialValues as Partial<M>,\n path,\n entityId,\n propertyConfigs: customizationController.propertyConfigs,\n ignoreMissingFields: true,\n authController\n });\n if (!shown || isHidden(shown)) return null;\n }\n\n const underlyingValueHasChanged: boolean =\n field.key in underlyingChanges &&\n !equal(formex.values[field.key], underlyingChanges[field.key]);\n\n const disabled = isFieldDisabled(field.key, property);\n // Three places a label can be. The panel-style editors carry their own\n // header. The one-line controls draw it inside their box, FireCMS-style,\n // so they all stand the same height. Everything else — multi-selects,\n // uploads, markdown, relations — is labelled above by FieldBlock.\n const selfLabelling = isSelfLabellingProperty(property);\n const labelInside = !selfLabelling\n && labelsInsideControl(property, customizationController.propertyConfigs);\n\n const cmsFormFieldProps: PropertyFieldBindingProps<M> = {\n propertyKey: field.key,\n disabled,\n property,\n // FieldBlock owns the description now, so the binding must not\n // repeat it — it still renders validation errors, which belong\n // against the control rather than under the label.\n includeDescription: false,\n hideLabel: !selfLabelling && !labelInside,\n underlyingValueHasChanged: underlyingValueHasChanged && !autoSave,\n context: fieldContext,\n partOfArray: false,\n minimalistView: false,\n // One height for every control in the form. Left to their own\n // defaults, a text field came out 48px, a select 44 and a switch 64.\n // `large`: the record-form density — a 64px box with the label\n // inside and a 16px value, or a 48px box under a label. 0.20.0 took\n // the form to `small` (32px) to match the reference, and the fields\n // read as cramped next to what they had been; see DESIGN.md \"Form\n // density\".\n size: \"large\",\n autoFocus: autoFocusKey === field.key\n };\n\n return (\n <div key={`field_${field.key}`} className={spanClass(field.span)}>\n <FieldBlock propertyKey={field.key}\n property={property}\n showLabel={!selfLabelling && !labelInside}\n labelInside={labelInside}>\n <PropertyFieldBinding {...cmsFormFieldProps}/>\n </FieldBlock>\n </div>\n );\n };\n\n const formFields = () => {\n\n if (Builder) {\n // Its own boundary: a Builder is usually a lazy chunk, and without\n // one, loading it suspends the nearest boundary above the record\n // view — which takes the identity bar down with the form.\n return <Suspense fallback={<CircularProgressCenter/>}>\n <Builder\n collection={collection}\n parentCollectionSlugs={parentCollectionSlugs}\n parentEntityIds={parentEntityIds}\n entity={entity}\n modifiedValues={formex.values}\n formContext={formContext}\n />\n </Suspense>;\n }\n\n const sections = showRail || !layout.sidebar.length\n ? layout.sections\n : [\n ...layout.sections,\n // Trailing, not leading. Beside the column these read as\n // peripheral; stacked above it they pushed the record's own name\n // below its status, which is the wrong thing to meet first.\n // Settings come after the content they apply to.\n {\n key: \"__rail\",\n title: \"Settings\",\n collapsible: false,\n collapsed: false,\n fields: layout.sidebar\n }\n ];\n\n return <>\n <FormSections\n sections={sections}\n collapsed={collapsedSections}\n onToggle={toggleSection}\n errorKeys={errorKeys}\n renderField={renderField}/>\n\n {/* Folded back with the rail's fields, and for the same reason. The\n rail renders only where it has been measured to fit, so on the\n split pane, the side panel and the dialog this block was dropped\n outright and the record's id was nowhere on screen but the\n truncated chip in the bar. */}\n {!showRail && layout.showRecordMeta && status === \"existing\" && entity && (\n <div className={cls(\"mt-8 pt-5 border-t max-w-sm\", defaultBorderMixin)}>\n <RecordMeta entity={entity as Entity<Record<string, unknown>>}/>\n </div>\n )}\n </>;\n };\n\n const formRef = useRef<HTMLDivElement>(null);\n\n const hasFormErrors = Object.keys(formex.errors).length > 0 && formex.submitCount > 0;\n\n const predatingViolationLines = useMemo(\n () => errorLines(predatingViolations, collection.properties),\n [predatingViolations, collection.properties]\n );\n\n const formView = <ErrorBoundary>\n <>\n {beforeFields}\n\n {/* The title, the `path/id` chip and the 72px gap under them used to\n live here — 219px above the first field, carrying nothing, and\n scrolling the record's identity away on the first wheel click.\n It is now in the persistent bar, where it stays put. */}\n\n {!entity?.values && initialStatus === \"existing\" &&\n <Alert color={\"warning\"} size={\"small\"} outerClassName={\"w-full mb-4 text-xs\"}>\n {t(\"entity_does_not_exist\")}\n </Alert>}\n\n {children}\n\n {initialEntityId && !entity && initialStatus !== \"new\" && <Alert color={\"info\"} size={\"small\"}>\n {t(\"entity_does_not_exist\")}\n </Alert>}\n\n {hasFormErrors && <Alert color={\"error\"} size={\"small\"} outerClassName={\"w-full mt-2\"}>\n {t(\"fix_errors_before_saving\")}\n </Alert>}\n\n {predatingViolationLines.length > 0 &&\n <Alert color={\"warning\"} size={\"small\"} outerClassName={\"w-full mt-2\"}>\n <Typography variant={\"caption\"} component={\"div\"}>\n {t(\"form_predating_rule_violations\")}\n </Typography>\n <ul className={\"list-disc pl-5 mt-1\"}>\n {predatingViolationLines.map(({ path: errorPath, label, message }) =>\n <li key={errorPath}><Typography variant={\"caption\"}>{`${label}: ${message}`}</Typography></li>)}\n </ul>\n </Alert>}\n\n {formContext && <>\n <div ref={formRef}>\n {formFields()}\n <ErrorFocus containerRef={formRef}/>\n </div>\n </>}\n\n {afterFields}\n\n <Dialog open={discardDialogOpen} onOpenChange={setDiscardDialogOpen} maxWidth={\"sm\"}>\n <DialogTitle>{status === \"existing\" ? \"Discard changes?\" : \"Clear form?\"}</DialogTitle>\n <DialogContent>\n <Typography>\n {status === \"existing\"\n ? \"All unsaved changes will be lost. \"\n : \"All entered values will be cleared. \"}\n You can bring them back with Undo (⌘Z / Ctrl+Z), or from\n the notification, for as long as this form stays open.\n </Typography>\n </DialogContent>\n <DialogActions>\n <Button variant={\"text\"} onClick={() => setDiscardDialogOpen(false)}>\n Cancel\n </Button>\n <Button variant={\"filled\"} color={\"error\"} onClick={() => {\n setDiscardDialogOpen(false);\n discard(formex, status, baseInitialValues);\n }}>\n {status === \"existing\" ? \"Discard\" : \"Clear\"}\n </Button>\n </DialogActions>\n </Dialog>\n </>\n </ErrorBoundary>;\n\n useEffect(() => {\n if (entityId && onIdChange)\n onIdChange(entityId);\n }, [entityId, onIdChange]);\n\n if (!collection || !path) {\n throw Error(\"INTERNAL: Collection and path must be defined in form context\");\n }\n\n const EntityFormActionsRender = EntityFormActionsComponent as React.FC<EntityFormActionsProps>;\n\n const dialogActions = <EntityFormActionsRender\n collection={collection}\n path={path}\n entity={entity}\n savingError={savingError}\n formex={formex as FormexController<Record<string, unknown>>}\n disabled={actionsDisabled}\n status={status}\n pluginActions={pluginActionsProp ?? []}\n openEntityMode={openEntityMode}\n showDefaultActions={showDefaultActions}\n navigateBack={navigateBack}\n formContext={formContext as FormContext<Record<string, unknown>>}\n />;\n\n return (\n <Formex value={formex}>\n <FormUploadsContext.Provider value={uploadTracker}>\n <form\n ref={formElementRef}\n onSubmit={formex.handleSubmit}\n onReset={(e) => {\n e.preventDefault();\n if (formex.dirty) {\n setDiscardDialogOpen(true);\n } else {\n formex.resetForm({ values: baseInitialValues as M });\n }\n }}\n noValidate\n className={cls(\"@container/form flex-1 flex flex-col w-full min-h-0\", className)}>\n\n {/* The actions bar is a sibling of this row rather than absolutely\n positioned over it, so the scroll area ends where the bar\n begins. As an overlay it hid the last field, and the bottom\n padding that compensated was a guess at its height. */}\n <div className={\"flex-1 min-h-0 flex flex-row w-full\"}>\n\n {/* Main column. Its own container scope, so a field's span\n answers to the column it sits in rather than to the window —\n the same form renders at four very different widths. */}\n {/* `items-start`: the column is a flex item, so without it the cross-axis\n default stretches it to the scroller's height. Its content then\n overflows its own box and the bottom padding sits at the bottom of\n the *viewport* instead of after the last field — which is why the\n form appeared to have no padding however large `pb-*` grew. */}\n <div className={\"flex-1 min-w-0 overflow-y-auto flex justify-center items-start\"}>\n <div\n id={`form_${path}`}\n className={cls(\n // Two rules widen the column, and they answer to\n // different things on purpose. `@7xl/form` measures\n // the form itself: full screen on a laptop is ~1400px\n // of form, which after the 304px rail leaves room for\n // the wider column with real gutters either side — and\n // it stays 768 in the split pane and the side panel,\n // which never get that wide. `2xl` is the older\n // viewport rule, kept so a panel on a large monitor\n // does not get *narrower* than it is today.\n \"@container/col w-full max-w-3xl @7xl/form:max-w-4xl 2xl:max-w-4xl flex flex-col\",\n openEntityMode === \"dialog\"\n ? \"pt-5 pb-8 px-6 sm:px-8\"\n : \"pt-6 pb-12 px-5 sm:px-8\"\n )}>\n\n {manualApplyLocalChanges && hasLocalChanges && localChangesCacheKey &&\n <div className={\"flex justify-end mb-3\"}>\n <LocalChangesMenu<M>\n cacheKey={localChangesCacheKey}\n properties={collection.properties}\n cachedData={localChangesData as Partial<M>}\n formex={formex}\n onClearLocalChanges={() => {\n setLocalChangesCleared(true);\n onClearLocalChanges?.();\n }}\n />\n </div>}\n\n {formView}\n\n </div>\n </div>\n\n {showRail && <FormRail\n fields={layout.sidebar}\n showRecordMeta={layout.showRecordMeta && status === \"existing\"}\n entity={entity as Entity<Record<string, unknown>> | undefined}\n renderField={renderField}/>}\n </div>\n\n {dialogActions}\n\n </form>\n </FormUploadsContext.Provider>\n\n </Formex>\n );\n}\n\nfunction useOnAutoSave<M extends Record<string, unknown>>(autoSave: undefined | boolean, formex: FormexController<M>, lastSavedValues: React.MutableRefObject<EntityValues<M> | undefined>, save: (values: EntityValues<M>) => Promise<Entity<M> | void>) {\n useEffect(() => {\n if (!autoSave) return;\n if (formex.values && !equal(formex.values, lastSavedValues.current)) {\n save(formex.values);\n }\n }, [autoSave, formex.values]);\n}\n\n/**\n * A nested error map — the shape `zodToFormErrors` builds — as one line per\n * failing field, labelled with the property's name.\n */\nfunction errorLines(\n errors: Record<string, unknown>,\n properties: Properties\n): { path: string; label: string; message: string }[] {\n const lines: { path: string; label: string; message: string }[] = [];\n const walk = (value: unknown, path: string[], label: string[], props: Properties | undefined) => {\n if (typeof value === \"string\") {\n lines.push({ path: path.join(\".\"), label: label.join(\" › \"), message: value });\n return;\n }\n if (!value || typeof value !== \"object\") return;\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n const property = props?.[key] as Property | undefined;\n const childProps = property?.type === \"map\" ? property.properties as Properties | undefined : undefined;\n walk(child, [...path, key], [...label, property?.name ?? key], childProps);\n }\n };\n walk(errors, [], [], properties);\n return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,SAAgB,WAA8C,EAC1D,MACA,UAAU,cACV,YACA,kBACA,YACA,SACA,QACA,oBACA,oBACA,eACA,WACA,gBACA,gBACA,iBAAiB,eACjB,QAAQ,YACR,UAAU,cACV,SACA,uBACA,iBACA,6BA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S,aAAuC,KAAA;GAC9F,KAAK,OAAO,CAAC,GAAG,MAAM,GAAG,GAAG,CAAC,GAAG,OAAO,UAAU,QAAQ,GAAG,GAAG,UAAU;EAC7E;CACJ;CACA,KAAK,QAAQ,CAAC,GAAG,CAAC,GAAG,UAAU;CAC/B,OAAO;AACX"}
1
+ {"version":3,"file":"EntityForm.js","names":[],"sources":["../../src/form/EntityForm.tsx"],"sourcesContent":["\nimport type { AdditionalFieldDelegateProps } from \"@rebasepro/cms-types\";\nimport type { FormContext, PropertyFieldBindingProps } from \"../types/fields\";\nimport React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { Entity, EntityStatus, EntityValues } from \"@rebasepro/types\";\nimport type { Properties, Property } from \"@rebasepro/types\";\nimport type { EntityFormProps } from \"../types/components/EntityFormProps\";\nimport { deepEqual as equal } from \"fast-equals\";\n\nimport { ErrorBoundary, isKeyHandled } from \"@rebasepro/ui\";\nimport { AlignLeftIcon, useDebouncedCallback } from \"@rebasepro/ui\";\nimport { effectiveAccess, getCopyValues, getDefaultValuesFor, hasEntityId } from \"@rebasepro/common\";\nimport { isDisabled, isHidden, isReadOnly } from \"@rebasepro/app\";\nimport { useAuthController, useCustomizationController, useRebaseContext, useTranslation } from \"@rebasepro/app\";\n\nimport { getFormFieldKeys, resolveFormLayout } from \"@rebasepro/app\";\nimport type { ResolvedFormField } from \"@rebasepro/app\";\nimport { Alert, Button, CircularProgressCenter, cls, defaultBorderMixin, Dialog, DialogActions, DialogContent, DialogTitle, paperMixin, Typography } from \"@rebasepro/ui\";\nimport { Formex, FormexController, useCreateFormex } from \"@rebasepro/forms\";\n\nimport { FieldBlock, isSelfLabellingProperty, LABEL_ICON_SIZE, spanClass } from \"./components/FieldBlock\";\nimport { labelsInsideControl } from \"./label_placement\";\nimport { AdditionalFieldValue } from \"../components/AdditionalFieldValue\";\nimport { FormRail, RecordMeta } from \"./components/FormRail\";\nimport { FormSections } from \"./components/FormSections\";\nimport { useRailVisible } from \"./components/useRailVisible\";\nimport { PropertyFieldBinding } from \"./PropertyFieldBinding\";\nimport { flattenKeys } from \"@rebasepro/app\";\nimport { ErrorFocus } from \"./components/ErrorFocus\";\nimport { applyValueTransforms, CustomFieldValidator, getEntitySchema, uniqueValueErrors } from \"./validation\";\nimport { formViewer, resolveFormProperty, resolvePropertiesForValidation, withoutUnwritableDefaults } from \"./resolve_form_properties\";\nimport { EntityFormActions } from \"./EntityFormActions\";\nimport type { EntityFormActionsProps } from \"../types/components/EntityFormActionsProps\";\nimport { LocalChangesMenu } from \"./components/LocalChangesMenu\";\nimport { useUndoableDiscard } from \"./useUndoableDiscard\";\nimport { ownsKeystroke, registerKeyboardScope } from \"./form_keyboard_scope\";\nimport { createFormUploadTracker, FormUploadsContext } from \"./form_uploads\";\n\nimport {\n getChangedProperties,\n overlayEdit,\n serverViolationErrors,\n withoutUnsetNulls,\n zodToFormErrors\n} from \"./form_utils\";\n\n/**\n * Headless entity form component.\n *\n * Renders a form for a entity collection without any admin or backend dependencies.\n * All backend concerns (save, caching, analytics, plugin slots) are provided via\n * callback props. For admin-connected usage, use {@link EntityFormBinding} instead.\n *\n * @group Components\n */\nexport function EntityForm<M extends Record<string, unknown>>({\n path,\n entityId: entityIdProp,\n collection,\n onValuesModified,\n onIdChange,\n onSaved,\n entity: entityProp,\n initialDirtyValues,\n onFormContextReady,\n initialStatus,\n className,\n onStatusChange,\n onEntityChange,\n openEntityMode = \"full_screen\",\n formex: formexProp,\n disabled: disabledProp,\n Builder,\n parentCollectionSlugs,\n parentEntityIds,\n EntityFormActionsComponent = EntityFormActions,\n showDefaultActions = true,\n navigateBack: navigateBackProp,\n children,\n // Headless callback props\n onSubmit: onSubmitProp,\n onValuesChangeDeferred: onValuesChangeDeferredProp,\n onReset: onResetProp,\n uniqueFieldValidator: uniqueFieldValidatorProp,\n lockedPropertyKeys,\n // Slots\n beforeFields,\n afterFields,\n pluginActions: pluginActionsProp,\n // Local changes (managed externally)\n computedInitialValues,\n hasLocalChanges: hasLocalChangesProp,\n localChangesData,\n manualApplyLocalChanges,\n localChangesCacheKey,\n onClearLocalChanges\n}: EntityFormProps<M>) {\n\n const navigateBack = useCallback(() => {\n if (navigateBackProp) {\n navigateBackProp();\n }\n }, [navigateBackProp]);\n\n const authController = useAuthController();\n const [status, setStatus] = useState<EntityStatus>(initialStatus);\n\n /**\n * The record as this form last saved it. A create turns the form into the\n * editor of the record it made, and the `entity` prop names that record\n * only once the caller has caught up — a caller that never does (the form\n * used on its own) left an \"existing\" form with no record: it re-seeded\n * itself with the defaults and refused the next Save.\n */\n const [savedEntity, setSavedEntity] = useState<Entity<M> | undefined>(undefined);\n const entity = entityProp ?? (status === \"existing\" ? savedEntity : undefined);\n\n const updateStatus = (status: EntityStatus) => {\n setStatus(status);\n onStatusChange?.(status);\n };\n\n /**\n * The autosave due: what it writes, and the whole form it was taken from\n * — which is what validation judges.\n */\n const [valuesToBeSaved, setValuesToBeSaved] = useState<{ toSave: EntityValues<M>, values: M } | undefined>(undefined);\n useDebouncedCallback(valuesToBeSaved, () => {\n if (!valuesToBeSaved || !onSubmitProp) return;\n const pending = valuesToBeSaved;\n setIsSavingAutoSave(true);\n // An autosave is a save, and is held to what Save is held to. It\n // wrote every edit unchecked; a form that does not validate now shows\n // why, and writes nothing until it does.\n validateForSave(pending.values)\n .then((errors) => {\n if (Object.keys(errors).length > 0) {\n formex.validate();\n return;\n }\n return onSubmitProp(pending.toSave, formex);\n })\n .catch((e) => {\n console.error(e);\n setSavingError(e);\n // The fields the server refused, marked as a Save marks them;\n // an autosave has no submit to make them show, so it counts one.\n const fieldErrors = serverViolationErrors(e, Object.keys(collection.properties ?? {}));\n if (Object.keys(fieldErrors).length > 0) {\n for (const [key, message] of Object.entries(fieldErrors)) formex.setFieldError(key, message);\n formex.setSubmitCount(formex.submitCount + 1);\n }\n })\n .finally(() => setIsSavingAutoSave(false));\n }, false, 2000);\n\n /**\n * The properties the record changed underneath an edit of the user's own,\n * keyed to the value they changed to — each one shown as \"updated\n * elsewhere\" while the form still holds something else. Filled by the\n * effect that follows the baseline, below.\n */\n const [underlyingChanges, setUnderlyingChanges] = useState<Record<string, unknown>>({});\n\n /**\n * Rules the stored record already broke, on fields this edit leaves alone —\n * shown, and not held against the save. Keyed like `formex.errors`.\n */\n const [predatingViolations, setPredatingViolations] = useState<Record<string, unknown>>({});\n\n const initialEntityId: string | number | undefined = useMemo(() => {\n if (status === \"new\" || status === \"copy\") {\n return undefined;\n } else {\n return entityIdProp;\n }\n }, [entityIdProp, status]);\n\n const [entityId, setEntityId] = useState<string | number | undefined>(initialEntityId);\n const [savingError, setSavingError] = useState<Error | undefined>();\n const [isSavingAutoSave, setIsSavingAutoSave] = useState<boolean>(false);\n const [discardDialogOpen, setDiscardDialogOpen] = useState<boolean>(false);\n\n const discard = useUndoableDiscard();\n\n const autoSave = collection.formAutoSave;\n\n // Use externally computed initial values if provided, otherwise compute from entity + collection\n const baseInitialValues = useMemo(() => {\n if (computedInitialValues !== undefined) {\n return computedInitialValues;\n }\n // Fallback: compute from entity/collection (requires authController from context)\n // In headless mode without computedInitialValues, use entity values or defaults\n if (status === \"copy\" && entity) {\n return getCopyValues(collection, entity.values ?? getDefaultValuesFor(collection.properties));\n }\n if (status === \"existing\" && entity) {\n return entity.values ?? getDefaultValuesFor(collection.properties);\n }\n return getDefaultValuesFor(collection.properties);\n }, [computedInitialValues, collection, status, entity]);\n\n const [localChangesCleared, setLocalChangesCleared] = useState<boolean>(false);\n\n const hasLocalChanges = hasLocalChangesProp !== undefined\n ? (hasLocalChangesProp && !localChangesCleared)\n : false;\n\n const onSubmit = (values: EntityValues<M>, formexController: FormexController<EntityValues<M>>) => {\n\n setSavingError(undefined);\n\n if (status === \"existing\") {\n if (!entity?.id) throw Error(\"Form misconfiguration when saving, no id for existing entity\");\n } else if (status !== \"new\" && status !== \"copy\") {\n throw Error(\"New FormType added, check EntityForm\");\n }\n\n if (!onSubmitProp) {\n console.warn(\"EntityForm: no onSubmit callback provided. Form submission has no effect.\");\n formexController.setSubmitting(false);\n return;\n }\n\n return Promise.resolve(save(values))\n ?.then((savedEntity) => {\n if (savedEntity) {\n formexController.resetForm({\n values: savedEntity.values || values,\n submitCount: 0,\n touched: {}\n });\n }\n })\n .finally(() => {\n formexController.setSubmitting(false);\n });\n };\n\n /**\n * What the form opens showing, when that is not what is stored — an edit\n * carried over from the side panel's \"open full screen\", or a draft\n * restored from the local-changes backup.\n *\n * The merge is deliberately *not* folded into the baseline. `mergeDeep`\n * used to produce a single `initialValues` that served as both, with a\n * `initialDirty: true` bolted on beside it to say what the baseline could\n * no longer show — and that flag survived exactly one render, because the\n * record's data arriving replaced the baseline and the form recomputed\n * dirty as false against a baseline that already contained the edit.\n *\n * Read once, at mount: this is a handoff, and re-reading it every render\n * tied the form to a cache that is cleared as soon as it has been consumed.\n */\n const initialModifiedValues = useRef(\n initialDirtyValues && Object.keys(initialDirtyValues).length > 0\n ? overlayEdit(baseInitialValues as Partial<M>, initialDirtyValues as Partial<M>)\n : undefined\n ).current;\n\n /**\n * Every key of the handed-over edit, marked touched. Read once, at mount,\n * like the edit itself: it was rebuilt on every render — a key-value map\n * of 1,000 entries cost ~60 ms per keystroke — by a spread that copied the\n * map once per key.\n */\n const [initialTouched] = useState<Record<string, boolean>>(() => {\n const touched: Record<string, boolean> = {};\n if (initialDirtyValues) {\n for (const key of flattenKeys(initialDirtyValues)) touched[key] = true;\n }\n return touched;\n });\n\n // A Save waits for a file still uploading: its path reaches the values\n // only when the upload ends. See `form_uploads.ts`.\n const [uploadTracker] = useState(createFormUploadTracker);\n\n const internalFormex = useCreateFormex<M>({\n initialValues: baseInitialValues as M,\n beforeSubmit: uploadTracker.wait,\n initialModifiedValues: initialModifiedValues as M | undefined,\n debugId: `EntityForm:${path}/${entityIdProp}`,\n initialTouched,\n onSubmit,\n onReset: () => {\n setUnderlyingChanges({});\n onResetProp?.();\n // The stored values — a reset returns the form to them, and by now\n // that is the baseline whether or not it was at mount.\n onValuesModified?.(false, baseInitialValues as M);\n },\n onValuesChangeDeferred: onValuesChangeDeferredProp,\n validation: (values) => validateForSave(values)\n });\n const formex: FormexController<M> = formexProp ?? internalFormex;\n\n /**\n * The errors that stop a save of `values`. Formex runs it on submit, and\n * the autosave runs it before each write.\n */\n async function validateForSave(values: M): Promise<Record<string, string>> {\n const errors = await validationErrorsFor(values);\n if (status !== \"existing\" || !entity?.values || Object.keys(errors).length === 0) {\n setPredatingViolations({});\n return errors;\n }\n // A record stored before a rule existed still breaks it, and the\n // server — which judges only what is sent — would take an\n // unrelated edit. So a field the user did not change, that the\n // stored record already broke, is a warning and not a refusal. A\n // field they changed must be valid, and so must one their edit\n // made invalid: a rule that reads the edited value is the edit's.\n const edited = getChangedProperties<M>(values, entity.values as Partial<M>);\n const storedErrors = await validationErrorsFor(entity.values as M);\n const blocking: Record<string, string> = {};\n const predating: Record<string, string> = {};\n for (const [key, error] of Object.entries(errors)) {\n if (!(key in edited) && key in storedErrors) predating[key] = error;\n else blocking[key] = error;\n }\n setPredatingViolations(predating);\n return blocking;\n }\n\n // One form takes a shortcut: the one the focus is in, else the one\n // mounted last (the top panel). Registered once per mount, so the order\n // is the order the forms opened in. See `form_keyboard_scope.ts`.\n const keyboardScope = useRef<ReturnType<typeof registerKeyboardScope> | undefined>(undefined);\n useEffect(() => {\n const scope = registerKeyboardScope(() => formElementRef.current);\n keyboardScope.current = scope;\n return () => {\n scope.unregister();\n keyboardScope.current = undefined;\n };\n }, []);\n\n useEffect(() => {\n\n const handleKeyDown = (e: KeyboardEvent) => {\n // A layer above the form (a dialog, a menu) already acted on it.\n if (isKeyHandled(e)) return;\n if (!keyboardScope.current || !ownsKeystroke(keyboardScope.current, e)) return;\n const isUndo = (e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === \"z\";\n const isRedo =\n ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key.toLowerCase() === \"z\") ||\n ((e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === \"y\");\n const isSave = (e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"s\";\n\n if (isSave && !disabled && formex.dirty) {\n e.preventDefault();\n formex.handleSubmit();\n } else if (isUndo && formex.canUndo) {\n e.preventDefault();\n formex.undo();\n } else if (isRedo && formex.canRedo) {\n e.preventDefault();\n formex.redo();\n }\n };\n\n window.addEventListener(\"keydown\", handleKeyDown);\n return () => window.removeEventListener(\"keydown\", handleKeyDown);\n\n }, [formex]);\n\n const afterSave = (updatedEntity: Entity<M>) => {\n setSavedEntity(updatedEntity);\n onResetProp?.();\n onValuesModified?.(false, updatedEntity.values);\n onEntityChange?.(updatedEntity);\n updateStatus(\"existing\");\n setEntityId(updatedEntity.id);\n\n if (onSaved) {\n onSaved({\n entity: updatedEntity,\n status,\n path,\n entityId: updatedEntity.id,\n collection\n });\n }\n };\n\n // What the form opened with counts as saved: a New form nobody touched\n // has nothing to autosave. Seeded with `entity?.values`, which a new\n // record does not have, the first autosave wrote a record of defaults.\n const lastSavedValues = useRef<EntityValues<M> | undefined>(baseInitialValues as EntityValues<M>);\n const save = async (values: EntityValues<M>): Promise<Entity<M> | void> => {\n // The string transforms a property declares change what is written;\n // validation has already judged the transformed value.\n const writtenValues = applyValueTransforms(values, collection.properties);\n // An existing record sends only what changed; a new one or a copy\n // sends what it holds, less what the user could not have written.\n const valuesToSave = status === \"existing\"\n ? getChangedProperties<M>(writtenValues, entity?.values || {}) as EntityValues<M>\n : withoutUnwritableDefaults<M>(\n status === \"new\"\n ? withoutUnsetNulls(writtenValues, baseInitialValues as Partial<M>)\n : writtenValues,\n baseInitialValues as Partial<M>,\n collection.properties,\n formViewer(authController)\n ) as EntityValues<M>;\n\n if (status === \"existing\" && Object.keys(valuesToSave).length === 0 && entity) {\n return Promise.resolve(entity);\n }\n\n lastSavedValues.current = values;\n\n if (!onSubmitProp) {\n return;\n }\n\n const autoSaveEnabled = autoSave ?? false;\n\n if (autoSaveEnabled) {\n setValuesToBeSaved({ toSave: valuesToSave, values: values as M });\n return Promise.resolve();\n }\n\n return Promise.resolve(onSubmitProp(valuesToSave as M, formex))\n .then((result) => {\n if (result) {\n afterSave(result as Entity<M>);\n }\n return result as Entity<M> | void;\n })\n .catch(e => {\n console.error(e);\n setSavingError(e);\n // The fields the server refused, marked where the user can\n // see them — not only the sentence in the footer.\n const fieldErrors = serverViolationErrors(e, Object.keys(collection.properties ?? {}));\n for (const [key, message] of Object.entries(fieldErrors)) formex.setFieldError(key, message);\n });\n };\n\n const disabled = formex.isSubmitting || Boolean(disabledProp);\n\n // The context an `additionalFields` Builder is documented to receive, and\n // the one `CollectionTableBinding` already hands it. This form used to pass\n // its own `FormContext` instead, laundered through\n // `formContext as unknown as AdditionalFieldDelegateProps[\"context\"]` —\n // two unrelated types, so a Builder reading anything off `RebaseContext`\n // worked in the table view and read `undefined` in the form.\n const rebaseContext = useRebaseContext();\n\n const formContext: FormContext<M> = {\n setFieldValue: useCallback((key: string, value: unknown) => formex.setFieldValue(key, value), []),\n values: formex.values,\n collection,\n entityId: entityId as string,\n path,\n save,\n submit: formex.handleSubmit,\n formex,\n entity,\n savingError,\n status,\n openEntityMode,\n disabled,\n isSaving: formex.isSubmitting || isSavingAutoSave\n };\n\n /**\n * The context the fields get. Not `formContext`: that one is a new object\n * per render, and a field memoised on its own value would re-render for it\n * on every keystroke anywhere in the form.\n *\n * This one changes identity only with what a field may draw from it — the\n * record, its status, the form's `version` (a reset or re-seed) — and reads\n * `values`, `formex` and `save` through a ref, so a field that did not\n * re-render still sees the current ones from its callbacks (a storage path\n * builder, a markdown file name). A field that reads another field's value\n * *while rendering* has to re-render with it; `PropertyFieldBinding` keeps\n * those — custom `Field`s, `dynamicProps`, `conditions` — on that path.\n */\n const latestRef = useRef({ formex, save });\n latestRef.current = { formex, save };\n const isSaving = formex.isSubmitting || isSavingAutoSave;\n const fieldContext: FormContext<M> = useMemo(() => ({\n get values() {\n return latestRef.current.formex.values;\n },\n get formex() {\n return latestRef.current.formex;\n },\n setFieldValue: formContext.setFieldValue,\n save: (values: M) => latestRef.current.save(values),\n submit: () => latestRef.current.formex.handleSubmit(),\n collection,\n entityId: entityId as string,\n path,\n entity,\n savingError,\n status,\n openEntityMode,\n disabled,\n isSaving\n // `formex.version` is a key, not an input: a reset or re-seed has to\n // hand the fields a new context even though nothing above reads it.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [formContext.setFieldValue, collection, entityId, path, entity, savingError, status, openEntityMode, disabled, isSaving, formex.version]);\n\n useEffect(() => {\n onFormContextReady?.(formContext);\n // `formex.version` only moves on `resetForm`, so these deps used to hand\n // the container one snapshot at mount and never another. That was\n // invisible while Save lived inside the form and read `formex` directly;\n // once the identity bar owned Save, its `dirty` was frozen false and the\n // button never enabled — for any field, not just the one that exposed\n // it. Custom entity views read `formContext.values` through the same\n // channel and were reading a stale copy too.\n //\n // Deps are the state *transitions* a container cares about, not\n // `formex.values`: re-publishing on every keystroke would re-render the\n // whole entity view per character.\n }, [\n formex.version, collection, entityId, path,\n formex.dirty, formex.isSubmitting, formex.submitCount, isSavingAutoSave\n ]);\n\n const actionsDisabled = disabled || formex.isSubmitting || (status === \"existing\" && !formex.dirty) || Boolean(disabledProp);\n\n // The record's title is resolved by the container that renders the identity\n // bar (see `useEntityDisplayTitle`), not here — the form no longer draws a\n // heading of its own.\n\n const modified = formex.dirty;\n\n useEffect(() => {\n if (!autoSave) {\n onValuesModified?.(modified, formex.values);\n }\n }, [formex.dirty]);\n\n // Default no-op unique field validator — always passes\n const defaultUniqueFieldValidator: CustomFieldValidator = useCallback(async () => true, []);\n\n const uniqueFieldValidator: CustomFieldValidator = useMemo(() => {\n if (uniqueFieldValidatorProp) {\n return uniqueFieldValidatorProp as CustomFieldValidator;\n }\n return defaultUniqueFieldValidator;\n }, [uniqueFieldValidatorProp, defaultUniqueFieldValidator]);\n\n const customizationController = useCustomizationController();\n const { t } = useTranslation();\n\n async function validationErrorsFor(values: M): Promise<Record<string, string>> {\n const properties = validationPropertiesFor(values);\n const result = await getEntitySchema(entityId, properties, uniqueFieldValidator).safeParseAsync(values);\n const errors: Record<string, string> = result.success ? {} : zodToFormErrors(result.error);\n // `validation.unique` asks the data source, so it runs here — on\n // submit — and only for values this edit changed that are otherwise\n // valid. It was built and threaded through, and never called.\n const notUnique = await uniqueValueErrors({\n properties,\n values,\n storedValues: status === \"existing\" ? entity?.values : undefined,\n entityId,\n errors,\n validator: uniqueFieldValidator\n });\n return { ...errors, ...notUnique };\n }\n\n /**\n * What the save is judged against: the properties as the form shows them\n * for these values — `dynamicProps` and `conditions` applied — and only\n * the ones the user can change. Built per call because both depend on the\n * values being judged.\n */\n function validationPropertiesFor(values: M) {\n return resolvePropertiesForValidation<M>({\n properties: collection.properties,\n isNew: status === \"new\" || status === \"copy\",\n values,\n previousValues: baseInitialValues as Partial<M>,\n path,\n entityId,\n propertyConfigs: customizationController.propertyConfigs,\n authController\n });\n }\n\n useOnAutoSave(autoSave, formex, lastSavedValues, save);\n\n /**\n * The record changed while the form was open: someone else saved it, and\n * the listener delivered the new version as a new baseline.\n *\n * An unmodified form follows it whole — formex does that. A modified one\n * keeps the edit, and formex keeps *everything* it holds: a property the\n * user never changed would still show the old value, differ from the new\n * stored one, and be written back by the next save, reverting the other\n * change without a word.\n *\n * So each top-level property that changed underneath is judged on its own,\n * against the baseline the form last followed. One the user has not changed\n * follows the record. One the user has changed keeps the edit — that is\n * what a save writes — and is marked as updated elsewhere, so the overwrite\n * is not a surprise.\n */\n const followedBaseline = useRef(baseInitialValues);\n useEffect(() => {\n const previous: Record<string, unknown> = followedBaseline.current ?? {};\n const next: Record<string, unknown> = baseInitialValues ?? {};\n followedBaseline.current = baseInitialValues;\n if (previous === next) return;\n\n const current: Record<string, unknown> = formex.values;\n if (equal(previous, current)) return;\n\n const conflicts: Record<string, unknown> = {};\n const changedUnderneath = new Set([...Object.keys(previous), ...Object.keys(next)]);\n for (const key of changedUnderneath) {\n if (equal(previous[key], next[key])) {\n changedUnderneath.delete(key);\n } else if (equal(current[key], previous[key])) {\n formex.setFieldValue(key, next[key]);\n } else if (!equal(current[key], next[key])) {\n conflicts[key] = next[key];\n }\n }\n if (changedUnderneath.size === 0) return;\n\n setUnderlyingChanges(prev => {\n const updated = { ...prev };\n changedUnderneath.forEach(key => {\n if (key in conflicts) updated[key] = conflicts[key];\n else delete updated[key];\n });\n return updated;\n });\n }, [baseInitialValues]);\n\n const formFieldKeys = getFormFieldKeys(collection);\n\n const layout = useMemo(() => resolveFormLayout({\n collection,\n fieldKeys: formFieldKeys,\n status\n }), [collection, formFieldKeys.join(\",\"), status]);\n\n const formElementRef = useRef<HTMLFormElement>(null);\n // Measured, not a breakpoint: the rail holds fields the resolver moved\n // out of the column, so when it cannot be shown they have to come back.\n const railVisible = useRailVisible(formElementRef);\n const showRail = !Builder && layout.hasRail && railVisible;\n\n // Collapsed sections are per-section-key so a renamed title keeps its state,\n // and initial state comes from the config rather than being forced open.\n const [collapsedSections, setCollapsedSections] = useState<Set<string>>(\n () => new Set(layout.sections.filter(s => s.collapsed).map(s => s.key))\n );\n const toggleSection = useCallback((key: string) => {\n setCollapsedSections(prev => {\n const next = new Set(prev);\n if (next.has(key)) next.delete(key); else next.add(key);\n return next;\n });\n }, []);\n\n const errorKeys = useMemo(\n () => new Set(formex.submitCount > 0 ? Object.keys(formex.errors) : []),\n [formex.errors, formex.submitCount]\n );\n\n // Autofocus lands on the first field the user can actually type into. Tracked\n // across the whole layout rather than per section, so a collapsed leading\n // group does not steal it.\n const autoFocusKey = useMemo(() => {\n if (status !== \"new\" && status !== \"copy\") return undefined;\n const ordered = [...layout.sections.flatMap(s => s.fields), ...layout.sidebar];\n return ordered.find(field => {\n const property = collection.properties?.[field.key];\n return property ? !isFieldDisabled(field.key, property) : false;\n })?.key;\n }, [layout, collection, status, disabledProp, lockedPropertyKeys]);\n\n function isFieldDisabled(key: string, property: NonNullable<typeof collection.properties[string]>): boolean {\n const isNew = status === \"new\" || status === \"copy\";\n const isStringOrNumber = property.type === \"string\" || property.type === \"number\";\n const isIdAndAuto = isStringOrNumber && \"isId\" in property && typeof property.isId === \"string\" && property.isId !== \"manual\";\n return Boolean(\n disabledProp\n || (!autoSave && formex.isSubmitting)\n || isReadOnly(property)\n || isDisabled(property)\n || (!isNew && \"isId\" in property && Boolean(property.isId))\n || (isNew && isIdAndAuto)\n || (isNew && lockedPropertyKeys?.includes(key))\n );\n }\n\n const renderField = (field: ResolvedFormField): React.ReactNode => {\n\n if (field.additional) {\n const additionalField = collection.additionalFields?.find(f => f.key === field.key);\n if (!additionalField || !entity) return null;\n\n const AdditionalFieldBuilder = additionalField.Builder;\n if (!AdditionalFieldBuilder && !additionalField.value) {\n throw new Error(\"When using additional fields you need to provide a Builder or a value\");\n }\n const child = AdditionalFieldBuilder\n ? <AdditionalFieldBuilder entity={entity} context={rebaseContext}/>\n : <div className={\"w-full\"}>\n <AdditionalFieldValue\n field={additionalField}\n entity={entity}\n context={rebaseContext}/>\n </div>;\n\n return (\n // Through FieldBlock like every other cell, so a computed\n // column is labelled at the same size, with the same gap to its\n // box, as the property next to it on the grid.\n <div key={`additional_${field.key}`}\n className={spanClass(field.span)}>\n <FieldBlock propertyKey={field.key}\n showLabel={true}\n label={additionalField.name}\n icon={<AlignLeftIcon size={LABEL_ICON_SIZE}/>}>\n <div className={cls(paperMixin, \"w-full min-h-12 p-4 md:p-6 overflow-x-auto no-scrollbar\")}>\n {child}\n </div>\n </FieldBlock>\n </div>\n );\n }\n\n const property = collection.properties?.[field.key];\n if (!property) {\n console.warn(`Property ${field.key} not found in collection ${collection.name} in properties or additional fields. Skipping.`);\n return null;\n }\n // A field a rule hides for these values, or that this user may not\n // read, takes its label with it: the binding renders nothing, and a\n // heading over nothing is worse.\n if (property.conditions?.hidden || effectiveAccess(property)) {\n const shown = resolveFormProperty({\n propertyKey: field.key,\n property,\n values: formex.values,\n previousValues: baseInitialValues as Partial<M>,\n path,\n entityId,\n propertyConfigs: customizationController.propertyConfigs,\n ignoreMissingFields: true,\n authController\n });\n if (!shown || isHidden(shown)) return null;\n }\n\n const underlyingValueHasChanged: boolean =\n field.key in underlyingChanges &&\n !equal(formex.values[field.key], underlyingChanges[field.key]);\n\n const disabled = isFieldDisabled(field.key, property);\n // Three places a label can be. The panel-style editors carry their own\n // header. The one-line controls draw it inside their box, FireCMS-style,\n // so they all stand the same height. Everything else — multi-selects,\n // uploads, markdown, relations — is labelled above by FieldBlock.\n const selfLabelling = isSelfLabellingProperty(property);\n const labelInside = !selfLabelling\n && labelsInsideControl(property, customizationController.propertyConfigs);\n\n const cmsFormFieldProps: PropertyFieldBindingProps<M> = {\n propertyKey: field.key,\n disabled,\n property,\n // FieldBlock owns the description now, so the binding must not\n // repeat it — it still renders validation errors, which belong\n // against the control rather than under the label.\n includeDescription: false,\n hideLabel: !selfLabelling && !labelInside,\n underlyingValueHasChanged: underlyingValueHasChanged && !autoSave,\n context: fieldContext,\n partOfArray: false,\n minimalistView: false,\n // One height for every control in the form. Left to their own\n // defaults, a text field came out 48px, a select 44 and a switch 64.\n // `large`: the record-form density — a 64px box with the label\n // inside and a 16px value, or a 48px box under a label. 0.20.0 took\n // the form to `small` (32px) to match the reference, and the fields\n // read as cramped next to what they had been; see DESIGN.md \"Form\n // density\".\n size: \"large\",\n autoFocus: autoFocusKey === field.key\n };\n\n return (\n <div key={`field_${field.key}`} className={spanClass(field.span)}>\n <FieldBlock propertyKey={field.key}\n property={property}\n showLabel={!selfLabelling && !labelInside}\n labelInside={labelInside}>\n <PropertyFieldBinding {...cmsFormFieldProps}/>\n </FieldBlock>\n </div>\n );\n };\n\n const formFields = () => {\n\n if (Builder) {\n // Its own boundary: a Builder is usually a lazy chunk, and without\n // one, loading it suspends the nearest boundary above the record\n // view — which takes the identity bar down with the form.\n return <Suspense fallback={<CircularProgressCenter/>}>\n <Builder\n collection={collection}\n parentCollectionSlugs={parentCollectionSlugs}\n parentEntityIds={parentEntityIds}\n entity={entity}\n modifiedValues={formex.values}\n formContext={formContext}\n />\n </Suspense>;\n }\n\n const sections = showRail || !layout.sidebar.length\n ? layout.sections\n : [\n ...layout.sections,\n // Trailing, not leading. Beside the column these read as\n // peripheral; stacked above it they pushed the record's own name\n // below its status, which is the wrong thing to meet first.\n // Settings come after the content they apply to.\n {\n key: \"__rail\",\n title: \"Settings\",\n collapsible: false,\n collapsed: false,\n fields: layout.sidebar\n }\n ];\n\n return <>\n <FormSections\n sections={sections}\n collapsed={collapsedSections}\n onToggle={toggleSection}\n errorKeys={errorKeys}\n renderField={renderField}/>\n\n {/* Folded back with the rail's fields, and for the same reason. The\n rail renders only where it has been measured to fit, so on the\n split pane, the side panel and the dialog this block was dropped\n outright and the record's id was nowhere on screen but the\n truncated chip in the bar. */}\n {!showRail && layout.showRecordMeta && status === \"existing\" && entity && (\n <div className={cls(\"mt-8 pt-5 border-t max-w-sm\", defaultBorderMixin)}>\n <RecordMeta entity={entity as Entity<Record<string, unknown>>}/>\n </div>\n )}\n </>;\n };\n\n const formRef = useRef<HTMLDivElement>(null);\n\n const hasFormErrors = Object.keys(formex.errors).length > 0 && formex.submitCount > 0;\n\n const predatingViolationLines = useMemo(\n () => errorLines(predatingViolations, collection.properties),\n [predatingViolations, collection.properties]\n );\n\n const formView = <ErrorBoundary>\n <>\n {beforeFields}\n\n {/* The title, the `path/id` chip and the 72px gap under them used to\n live here — 219px above the first field, carrying nothing, and\n scrolling the record's identity away on the first wheel click.\n It is now in the persistent bar, where it stays put. */}\n\n {!entity?.values && initialStatus === \"existing\" &&\n <Alert color={\"warning\"} size={\"small\"} outerClassName={\"w-full mb-4 text-xs\"}>\n {t(\"entity_does_not_exist\")}\n </Alert>}\n\n {children}\n\n {hasEntityId(initialEntityId) && !entity && initialStatus !== \"new\" && <Alert color={\"info\"} size={\"small\"}>\n {t(\"entity_does_not_exist\")}\n </Alert>}\n\n {hasFormErrors && <Alert color={\"error\"} size={\"small\"} outerClassName={\"w-full mt-2\"}>\n {t(\"fix_errors_before_saving\")}\n </Alert>}\n\n {predatingViolationLines.length > 0 &&\n <Alert color={\"warning\"} size={\"small\"} outerClassName={\"w-full mt-2\"}>\n <Typography variant={\"caption\"} component={\"div\"}>\n {t(\"form_predating_rule_violations\")}\n </Typography>\n <ul className={\"list-disc pl-5 mt-1\"}>\n {predatingViolationLines.map(({ path: errorPath, label, message }) =>\n <li key={errorPath}><Typography variant={\"caption\"}>{`${label}: ${message}`}</Typography></li>)}\n </ul>\n </Alert>}\n\n {formContext && <>\n <div ref={formRef}>\n {formFields()}\n <ErrorFocus containerRef={formRef}/>\n </div>\n </>}\n\n {afterFields}\n\n <Dialog open={discardDialogOpen} onOpenChange={setDiscardDialogOpen} maxWidth={\"sm\"}>\n <DialogTitle>{status === \"existing\" ? \"Discard changes?\" : \"Clear form?\"}</DialogTitle>\n <DialogContent>\n <Typography>\n {status === \"existing\"\n ? \"All unsaved changes will be lost. \"\n : \"All entered values will be cleared. \"}\n You can bring them back with Undo (⌘Z / Ctrl+Z), or from\n the notification, for as long as this form stays open.\n </Typography>\n </DialogContent>\n <DialogActions>\n <Button variant={\"text\"} onClick={() => setDiscardDialogOpen(false)}>\n Cancel\n </Button>\n <Button variant={\"filled\"} color={\"error\"} onClick={() => {\n setDiscardDialogOpen(false);\n discard(formex, status, baseInitialValues);\n }}>\n {status === \"existing\" ? \"Discard\" : \"Clear\"}\n </Button>\n </DialogActions>\n </Dialog>\n </>\n </ErrorBoundary>;\n\n useEffect(() => {\n if (hasEntityId(entityId) && onIdChange)\n onIdChange(entityId);\n }, [entityId, onIdChange]);\n\n if (!collection || !path) {\n throw Error(\"INTERNAL: Collection and path must be defined in form context\");\n }\n\n const EntityFormActionsRender = EntityFormActionsComponent as React.FC<EntityFormActionsProps>;\n\n const dialogActions = <EntityFormActionsRender\n collection={collection}\n path={path}\n entity={entity}\n savingError={savingError}\n formex={formex as FormexController<Record<string, unknown>>}\n disabled={actionsDisabled}\n status={status}\n pluginActions={pluginActionsProp ?? []}\n openEntityMode={openEntityMode}\n showDefaultActions={showDefaultActions}\n navigateBack={navigateBack}\n formContext={formContext as FormContext<Record<string, unknown>>}\n />;\n\n return (\n <Formex value={formex}>\n <FormUploadsContext.Provider value={uploadTracker}>\n <form\n ref={formElementRef}\n onSubmit={formex.handleSubmit}\n onReset={(e) => {\n e.preventDefault();\n if (formex.dirty) {\n setDiscardDialogOpen(true);\n } else {\n formex.resetForm({ values: baseInitialValues as M });\n }\n }}\n noValidate\n className={cls(\"@container/form flex-1 flex flex-col w-full min-h-0\", className)}>\n\n {/* The actions bar is a sibling of this row rather than absolutely\n positioned over it, so the scroll area ends where the bar\n begins. As an overlay it hid the last field, and the bottom\n padding that compensated was a guess at its height. */}\n <div className={\"flex-1 min-h-0 flex flex-row w-full\"}>\n\n {/* Main column. Its own container scope, so a field's span\n answers to the column it sits in rather than to the window —\n the same form renders at four very different widths. */}\n {/* `items-start`: the column is a flex item, so without it the cross-axis\n default stretches it to the scroller's height. Its content then\n overflows its own box and the bottom padding sits at the bottom of\n the *viewport* instead of after the last field — which is why the\n form appeared to have no padding however large `pb-*` grew. */}\n <div className={\"flex-1 min-w-0 overflow-y-auto flex justify-center items-start\"}>\n <div\n id={`form_${path}`}\n className={cls(\n // Two rules widen the column, and they answer to\n // different things on purpose. `@7xl/form` measures\n // the form itself: full screen on a laptop is ~1400px\n // of form, which after the 304px rail leaves room for\n // the wider column with real gutters either side — and\n // it stays 768 in the split pane and the side panel,\n // which never get that wide. `2xl` is the older\n // viewport rule, kept so a panel on a large monitor\n // does not get *narrower* than it is today.\n \"@container/col w-full max-w-3xl @7xl/form:max-w-4xl 2xl:max-w-4xl flex flex-col\",\n openEntityMode === \"dialog\"\n ? \"pt-5 pb-8 px-6 sm:px-8\"\n : \"pt-6 pb-12 px-5 sm:px-8\"\n )}>\n\n {manualApplyLocalChanges && hasLocalChanges && localChangesCacheKey &&\n <div className={\"flex justify-end mb-3\"}>\n <LocalChangesMenu<M>\n cacheKey={localChangesCacheKey}\n properties={collection.properties}\n cachedData={localChangesData as Partial<M>}\n formex={formex}\n onClearLocalChanges={() => {\n setLocalChangesCleared(true);\n onClearLocalChanges?.();\n }}\n />\n </div>}\n\n {formView}\n\n </div>\n </div>\n\n {showRail && <FormRail\n fields={layout.sidebar}\n showRecordMeta={layout.showRecordMeta && status === \"existing\"}\n entity={entity as Entity<Record<string, unknown>> | undefined}\n renderField={renderField}/>}\n </div>\n\n {dialogActions}\n\n </form>\n </FormUploadsContext.Provider>\n\n </Formex>\n );\n}\n\nfunction useOnAutoSave<M extends Record<string, unknown>>(autoSave: undefined | boolean, formex: FormexController<M>, lastSavedValues: React.MutableRefObject<EntityValues<M> | undefined>, save: (values: EntityValues<M>) => Promise<Entity<M> | void>) {\n useEffect(() => {\n if (!autoSave) return;\n if (formex.values && !equal(formex.values, lastSavedValues.current)) {\n save(formex.values);\n }\n }, [autoSave, formex.values]);\n}\n\n/**\n * A nested error map — the shape `zodToFormErrors` builds — as one line per\n * failing field, labelled with the property's name.\n */\nfunction errorLines(\n errors: Record<string, unknown>,\n properties: Properties\n): { path: string; label: string; message: string }[] {\n const lines: { path: string; label: string; message: string }[] = [];\n const walk = (value: unknown, path: string[], label: string[], props: Properties | undefined) => {\n if (typeof value === \"string\") {\n lines.push({ path: path.join(\".\"), label: label.join(\" › \"), message: value });\n return;\n }\n if (!value || typeof value !== \"object\") return;\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n const property = props?.[key] as Property | undefined;\n const childProps = property?.type === \"map\" ? property.properties as Properties | undefined : undefined;\n walk(child, [...path, key], [...label, property?.name ?? key], childProps);\n }\n };\n walk(errors, [], [], properties);\n return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,SAAgB,WAA8C,EAC1D,MACA,UAAU,cACV,YACA,kBACA,YACA,SACA,QAAQ,YACR,oBACA,oBACA,eACA,WACA,gBACA,gBACA,iBAAiB,eACjB,QAAQ,YACR,UAAU,cACV,SACA,uBACA,iBACA,6BAA6B,mBAC7B,qBAAqB,MACrB,cAAc,kBAC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AAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAgC,GAAG;GACzE,MAAM,WAAW,QAAQ;GACzB,MAAM,aAAa,UAAU,SAAS,QAAQ,SAAS,aAAuC,KAAA;GAC9F,KAAK,OAAO,CAAC,GAAG,MAAM,GAAG,GAAG,CAAC,GAAG,OAAO,UAAU,QAAQ,GAAG,GAAG,UAAU;EAC7E;CACJ;CACA,KAAK,QAAQ,CAAC,GAAG,CAAC,GAAG,UAAU;CAC/B,OAAO;AACX"}
@@ -5,6 +5,7 @@ import { getInitialEntityValues, getParentLinkValues, getTouchedPropertyValues,
5
5
  import { EntityForm } from "./EntityForm.js";
6
6
  import { useCallback, useMemo, useState } from "react";
7
7
  import { jsx } from "react/jsx-runtime";
8
+ import { hasEntityId } from "@rebasepro/common";
8
9
  import { getEntityFromCache, getLocalChangesBackup, removeEntityFromCache, removeEntityFromMemoryCache, saveEntityToCache, saveEntityWithCallbacks, useAnalyticsController, useAuthController, useCustomizationController, useData, useSlot, useSnackbarController, useTranslation } from "@rebasepro/app";
9
10
  //#region src/form/EntityFormBinding.tsx
10
11
  /**
@@ -35,6 +36,8 @@ function EntityFormBinding({ path, entityId: entityIdProp, collection, entity, i
35
36
  const context = useAdminContext();
36
37
  const analyticsController = useAnalyticsController();
37
38
  const [status, setStatus] = useState(initialStatus);
39
+ const [savedEntity, setSavedEntity] = useState(void 0);
40
+ const currentEntity = entity ?? (status === "existing" ? savedEntity : void 0);
38
41
  const idKeyValues = useMemo(() => newRecordIdValues(collection, status, entityIdProp), [
39
42
  collection,
40
43
  status,
@@ -62,21 +65,21 @@ function EntityFormBinding({ path, entityId: entityIdProp, collection, entity, i
62
65
  ]);
63
66
  const lockedPropertyKeys = useMemo(() => Object.keys(parentLinkValues), [parentLinkValues]);
64
67
  const baseInitialValues = useMemo(() => ({
65
- ...getInitialEntityValues(authController, collection, path, status, entity, customizationController.propertyConfigs),
68
+ ...getInitialEntityValues(authController, collection, path, status, currentEntity, customizationController.propertyConfigs),
66
69
  ...parentLinkValues
67
70
  }), [
68
71
  authController,
69
72
  collection,
70
73
  path,
71
74
  status,
72
- entity,
75
+ currentEntity,
73
76
  customizationController.propertyConfigs,
74
77
  parentLinkValues
75
78
  ]);
76
79
  const localChangesBackup = getLocalChangesBackup(collection);
77
80
  const autoApplyLocalChanges = localChangesBackup === "auto_apply";
78
81
  const manualApplyLocalChanges = localChangesBackup === "manual_apply";
79
- const localChangesDataRaw = useMemo(() => entityId ? getEntityFromCache(path + "/" + entityId) : getEntityFromCache(path + "#new"), [entityId, path]);
82
+ const localChangesDataRaw = useMemo(() => hasEntityId(entityId) ? getEntityFromCache(path + "/" + entityId) : getEntityFromCache(path + "#new"), [entityId, path]);
80
83
  const [localChangesCleared, setLocalChangesCleared] = useState(false);
81
84
  const computedInitialValues = useMemo(() => {
82
85
  return autoApplyLocalChanges && localChangesDataRaw ? overlayEdit(baseInitialValues, localChangesDataRaw) : baseInitialValues;
@@ -148,13 +151,14 @@ function EntityFormBinding({ path, entityId: entityIdProp, collection, entity, i
148
151
  path,
149
152
  entityId,
150
153
  values,
151
- previousValues: entity?.values,
154
+ previousValues: currentEntity?.values,
152
155
  collection,
153
156
  status,
154
- ifMatch: status === "existing" ? entity?.etag : void 0,
157
+ ifMatch: status === "existing" ? currentEntity?.etag : void 0,
155
158
  data: dataClient,
156
159
  context,
157
160
  afterSave: (updatedEntity) => {
161
+ setSavedEntity(updatedEntity);
158
162
  clearDirtyCache();
159
163
  onValuesModified?.(false, updatedEntity.values);
160
164
  onEntityChange?.(updatedEntity);
@@ -193,7 +197,7 @@ function EntityFormBinding({ path, entityId: entityIdProp, collection, entity, i
193
197
  }, [
194
198
  path,
195
199
  entityId,
196
- entity,
200
+ currentEntity,
197
201
  collection,
198
202
  status,
199
203
  dataClient,
@@ -213,7 +217,7 @@ function EntityFormBinding({ path, entityId: entityIdProp, collection, entity, i
213
217
  where: { [name]: ["==", value] },
214
218
  limit: 2
215
219
  });
216
- return (entityId ? data.filter((e) => e.id !== entityId) : data).length === 0;
220
+ return (hasEntityId(entityId) ? data.filter((e) => String(e.id) !== String(entityId)) : data).length === 0;
217
221
  } catch (e) {
218
222
  console.error("Error checking unique field", e);
219
223
  return true;
@@ -253,7 +257,7 @@ function EntityFormBinding({ path, entityId: entityIdProp, collection, entity, i
253
257
  path,
254
258
  entityId: entityIdProp,
255
259
  collection,
256
- entity,
260
+ entity: currentEntity,
257
261
  initialStatus,
258
262
  initialDirtyValues,
259
263
  onValuesModified,