@docengine/editor 0.0.0-stage → 0.0.106

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 (902) hide show
  1. package/README.md +116 -2
  2. package/dist/DocEnginePdfViewer.zip +0 -0
  3. package/dist/editor-lwc.css +7425 -0
  4. package/dist/editor-lwc.js +1595 -0
  5. package/dist/editor-lwc.js.map +1 -0
  6. package/dist/editor.js +89754 -0
  7. package/dist/pdf-viewer/viewer.html +40 -0
  8. package/dist/pdf-viewer/viewer.js +1 -0
  9. package/lib/.tsbuildinfo +1 -0
  10. package/lib/catalog/catalog-provider.d.ts +27 -0
  11. package/lib/catalog/catalog-provider.d.ts.map +1 -0
  12. package/lib/catalog/catalog-provider.js +88 -0
  13. package/lib/catalog/catalog-provider.js.map +1 -0
  14. package/lib/core/computed-formula.d.ts +3 -0
  15. package/lib/core/computed-formula.d.ts.map +1 -0
  16. package/lib/core/computed-formula.js +2 -0
  17. package/lib/core/computed-formula.js.map +1 -0
  18. package/lib/core/computed-formula.test.d.ts +2 -0
  19. package/lib/core/computed-formula.test.d.ts.map +1 -0
  20. package/lib/core/computed-formula.test.js +204 -0
  21. package/lib/core/computed-formula.test.js.map +1 -0
  22. package/lib/core/document-display-defaults.d.ts +2 -0
  23. package/lib/core/document-display-defaults.d.ts.map +1 -0
  24. package/lib/core/document-display-defaults.js +2 -0
  25. package/lib/core/document-display-defaults.js.map +1 -0
  26. package/lib/core/document-history.d.ts +23 -0
  27. package/lib/core/document-history.d.ts.map +1 -0
  28. package/lib/core/document-history.js +87 -0
  29. package/lib/core/document-history.js.map +1 -0
  30. package/lib/core/document-history.test.d.ts +2 -0
  31. package/lib/core/document-history.test.d.ts.map +1 -0
  32. package/lib/core/document-history.test.js +47 -0
  33. package/lib/core/document-history.test.js.map +1 -0
  34. package/lib/core/document-io.d.ts +2 -0
  35. package/lib/core/document-io.d.ts.map +1 -0
  36. package/lib/core/document-io.js +2 -0
  37. package/lib/core/document-io.js.map +1 -0
  38. package/lib/core/document-io.test.d.ts +2 -0
  39. package/lib/core/document-io.test.d.ts.map +1 -0
  40. package/lib/core/document-io.test.js +616 -0
  41. package/lib/core/document-io.test.js.map +1 -0
  42. package/lib/core/document-section-defaults.d.ts +27 -0
  43. package/lib/core/document-section-defaults.d.ts.map +1 -0
  44. package/lib/core/document-section-defaults.js +60 -0
  45. package/lib/core/document-section-defaults.js.map +1 -0
  46. package/lib/core/document-section-defaults.test.d.ts +2 -0
  47. package/lib/core/document-section-defaults.test.d.ts.map +1 -0
  48. package/lib/core/document-section-defaults.test.js +47 -0
  49. package/lib/core/document-section-defaults.test.js.map +1 -0
  50. package/lib/core/field-id.d.ts +2 -0
  51. package/lib/core/field-id.d.ts.map +1 -0
  52. package/lib/core/field-id.js +2 -0
  53. package/lib/core/field-id.js.map +1 -0
  54. package/lib/core/field-id.test.d.ts +2 -0
  55. package/lib/core/field-id.test.d.ts.map +1 -0
  56. package/lib/core/field-id.test.js +253 -0
  57. package/lib/core/field-id.test.js.map +1 -0
  58. package/lib/core/field-io/sectioned-document-io.d.ts +2 -0
  59. package/lib/core/field-io/sectioned-document-io.d.ts.map +1 -0
  60. package/lib/core/field-io/sectioned-document-io.js +2 -0
  61. package/lib/core/field-io/sectioned-document-io.js.map +1 -0
  62. package/lib/core/field-io/sectioned-document-io.test.d.ts +2 -0
  63. package/lib/core/field-io/sectioned-document-io.test.d.ts.map +1 -0
  64. package/lib/core/field-io/sectioned-document-io.test.js +511 -0
  65. package/lib/core/field-io/sectioned-document-io.test.js.map +1 -0
  66. package/lib/core/field-io/table-field-io.d.ts +2 -0
  67. package/lib/core/field-io/table-field-io.d.ts.map +1 -0
  68. package/lib/core/field-io/table-field-io.js +2 -0
  69. package/lib/core/field-io/table-field-io.js.map +1 -0
  70. package/lib/core/field-io/table-field-io.test.d.ts +2 -0
  71. package/lib/core/field-io/table-field-io.test.d.ts.map +1 -0
  72. package/lib/core/field-io/table-field-io.test.js +193 -0
  73. package/lib/core/field-io/table-field-io.test.js.map +1 -0
  74. package/lib/core/field-schemas.d.ts +2 -0
  75. package/lib/core/field-schemas.d.ts.map +1 -0
  76. package/lib/core/field-schemas.js +7 -0
  77. package/lib/core/field-schemas.js.map +1 -0
  78. package/lib/core/field-schemas.test.d.ts +2 -0
  79. package/lib/core/field-schemas.test.d.ts.map +1 -0
  80. package/lib/core/field-schemas.test.js +369 -0
  81. package/lib/core/field-schemas.test.js.map +1 -0
  82. package/lib/core/formula-field-index.d.ts +2 -0
  83. package/lib/core/formula-field-index.d.ts.map +1 -0
  84. package/lib/core/formula-field-index.js +2 -0
  85. package/lib/core/formula-field-index.js.map +1 -0
  86. package/lib/core/formula-field-index.test.d.ts +2 -0
  87. package/lib/core/formula-field-index.test.d.ts.map +1 -0
  88. package/lib/core/formula-field-index.test.js +110 -0
  89. package/lib/core/formula-field-index.test.js.map +1 -0
  90. package/lib/core/page-setup-styles.d.ts +69 -0
  91. package/lib/core/page-setup-styles.d.ts.map +1 -0
  92. package/lib/core/page-setup-styles.js +147 -0
  93. package/lib/core/page-setup-styles.js.map +1 -0
  94. package/lib/core/page-setup-styles.test.d.ts +2 -0
  95. package/lib/core/page-setup-styles.test.d.ts.map +1 -0
  96. package/lib/core/page-setup-styles.test.js +204 -0
  97. package/lib/core/page-setup-styles.test.js.map +1 -0
  98. package/lib/core/repeater-io.d.ts +2 -0
  99. package/lib/core/repeater-io.d.ts.map +1 -0
  100. package/lib/core/repeater-io.js +2 -0
  101. package/lib/core/repeater-io.js.map +1 -0
  102. package/lib/core/repeater-io.test.d.ts +2 -0
  103. package/lib/core/repeater-io.test.d.ts.map +1 -0
  104. package/lib/core/repeater-io.test.js +754 -0
  105. package/lib/core/repeater-io.test.js.map +1 -0
  106. package/lib/core/segment-tree.d.ts +2 -0
  107. package/lib/core/segment-tree.d.ts.map +1 -0
  108. package/lib/core/segment-tree.js +2 -0
  109. package/lib/core/segment-tree.js.map +1 -0
  110. package/lib/core/segment-tree.test.d.ts +2 -0
  111. package/lib/core/segment-tree.test.d.ts.map +1 -0
  112. package/lib/core/segment-tree.test.js +39 -0
  113. package/lib/core/segment-tree.test.js.map +1 -0
  114. package/lib/create-editor.d.ts +160 -0
  115. package/lib/create-editor.d.ts.map +1 -0
  116. package/lib/create-editor.js +3373 -0
  117. package/lib/create-editor.js.map +1 -0
  118. package/lib/design/collection-tree-picker.d.ts +17 -0
  119. package/lib/design/collection-tree-picker.d.ts.map +1 -0
  120. package/lib/design/collection-tree-picker.js +295 -0
  121. package/lib/design/collection-tree-picker.js.map +1 -0
  122. package/lib/design/collection-tree-picker.test.d.ts +2 -0
  123. package/lib/design/collection-tree-picker.test.d.ts.map +1 -0
  124. package/lib/design/collection-tree-picker.test.js +94 -0
  125. package/lib/design/collection-tree-picker.test.js.map +1 -0
  126. package/lib/design/design-mode.d.ts +3 -0
  127. package/lib/design/design-mode.d.ts.map +1 -0
  128. package/lib/design/design-mode.js +7 -0
  129. package/lib/design/design-mode.js.map +1 -0
  130. package/lib/design/design-shell.d.ts +16 -0
  131. package/lib/design/design-shell.d.ts.map +1 -0
  132. package/lib/design/design-shell.js +68 -0
  133. package/lib/design/design-shell.js.map +1 -0
  134. package/lib/design/display-style-form.d.ts +10 -0
  135. package/lib/design/display-style-form.d.ts.map +1 -0
  136. package/lib/design/display-style-form.js +182 -0
  137. package/lib/design/display-style-form.js.map +1 -0
  138. package/lib/design/display-style-form.test.d.ts +2 -0
  139. package/lib/design/display-style-form.test.d.ts.map +1 -0
  140. package/lib/design/display-style-form.test.js +137 -0
  141. package/lib/design/display-style-form.test.js.map +1 -0
  142. package/lib/design/field-highlight-form.d.ts +10 -0
  143. package/lib/design/field-highlight-form.d.ts.map +1 -0
  144. package/lib/design/field-highlight-form.js +160 -0
  145. package/lib/design/field-highlight-form.js.map +1 -0
  146. package/lib/design/field-highlight-form.test.d.ts +2 -0
  147. package/lib/design/field-highlight-form.test.d.ts.map +1 -0
  148. package/lib/design/field-highlight-form.test.js +58 -0
  149. package/lib/design/field-highlight-form.test.js.map +1 -0
  150. package/lib/design/field-palette.d.ts +55 -0
  151. package/lib/design/field-palette.d.ts.map +1 -0
  152. package/lib/design/field-palette.js +216 -0
  153. package/lib/design/field-palette.js.map +1 -0
  154. package/lib/design/field-palette.test.d.ts +2 -0
  155. package/lib/design/field-palette.test.d.ts.map +1 -0
  156. package/lib/design/field-palette.test.js +79 -0
  157. package/lib/design/field-palette.test.js.map +1 -0
  158. package/lib/design/formula-field-picker.d.ts +15 -0
  159. package/lib/design/formula-field-picker.d.ts.map +1 -0
  160. package/lib/design/formula-field-picker.js +170 -0
  161. package/lib/design/formula-field-picker.js.map +1 -0
  162. package/lib/design/formula-field-picker.test.d.ts +2 -0
  163. package/lib/design/formula-field-picker.test.d.ts.map +1 -0
  164. package/lib/design/formula-field-picker.test.js +136 -0
  165. package/lib/design/formula-field-picker.test.js.map +1 -0
  166. package/lib/design/palette-block-drop.d.ts +7 -0
  167. package/lib/design/palette-block-drop.d.ts.map +1 -0
  168. package/lib/design/palette-block-drop.js +62 -0
  169. package/lib/design/palette-block-drop.js.map +1 -0
  170. package/lib/design/properties-panel.d.ts +22 -0
  171. package/lib/design/properties-panel.d.ts.map +1 -0
  172. package/lib/design/properties-panel.js +848 -0
  173. package/lib/design/properties-panel.js.map +1 -0
  174. package/lib/design/schema-editor-controller.d.ts +22 -0
  175. package/lib/design/schema-editor-controller.d.ts.map +1 -0
  176. package/lib/design/schema-editor-controller.js +1033 -0
  177. package/lib/design/schema-editor-controller.js.map +1 -0
  178. package/lib/design/schema-editor-controller.test.d.ts +2 -0
  179. package/lib/design/schema-editor-controller.test.d.ts.map +1 -0
  180. package/lib/design/schema-editor-controller.test.js +259 -0
  181. package/lib/design/schema-editor-controller.test.js.map +1 -0
  182. package/lib/design/schema-editor-modal.d.ts +4 -0
  183. package/lib/design/schema-editor-modal.d.ts.map +1 -0
  184. package/lib/design/schema-editor-modal.js +68 -0
  185. package/lib/design/schema-editor-modal.js.map +1 -0
  186. package/lib/design/schema-items-designer-modal.d.ts +3 -0
  187. package/lib/design/schema-items-designer-modal.d.ts.map +1 -0
  188. package/lib/design/schema-items-designer-modal.js +187 -0
  189. package/lib/design/schema-items-designer-modal.js.map +1 -0
  190. package/lib/design/schema-items-designer.d.ts +20 -0
  191. package/lib/design/schema-items-designer.d.ts.map +1 -0
  192. package/lib/design/schema-items-designer.js +394 -0
  193. package/lib/design/schema-items-designer.js.map +1 -0
  194. package/lib/design/schema-items-designer.test.d.ts +2 -0
  195. package/lib/design/schema-items-designer.test.d.ts.map +1 -0
  196. package/lib/design/schema-items-designer.test.js +115 -0
  197. package/lib/design/schema-items-designer.test.js.map +1 -0
  198. package/lib/design/style-toolbar-shared.d.ts +53 -0
  199. package/lib/design/style-toolbar-shared.d.ts.map +1 -0
  200. package/lib/design/style-toolbar-shared.js +196 -0
  201. package/lib/design/style-toolbar-shared.js.map +1 -0
  202. package/lib/domain/ophthalmology/catalogs.d.ts +107 -0
  203. package/lib/domain/ophthalmology/catalogs.d.ts.map +1 -0
  204. package/lib/domain/ophthalmology/catalogs.js +65 -0
  205. package/lib/domain/ophthalmology/catalogs.js.map +1 -0
  206. package/lib/domain/ophthalmology/life-anamnesis-tree.d.ts +13 -0
  207. package/lib/domain/ophthalmology/life-anamnesis-tree.d.ts.map +1 -0
  208. package/lib/domain/ophthalmology/life-anamnesis-tree.js +44 -0
  209. package/lib/domain/ophthalmology/life-anamnesis-tree.js.map +1 -0
  210. package/lib/domain/ophthalmology/norm-options.d.ts +9 -0
  211. package/lib/domain/ophthalmology/norm-options.d.ts.map +1 -0
  212. package/lib/domain/ophthalmology/norm-options.js +24 -0
  213. package/lib/domain/ophthalmology/norm-options.js.map +1 -0
  214. package/lib/domain/ophthalmology/ophthalmology-complaints-tree.d.ts +13 -0
  215. package/lib/domain/ophthalmology/ophthalmology-complaints-tree.d.ts.map +1 -0
  216. package/lib/domain/ophthalmology/ophthalmology-complaints-tree.js +48 -0
  217. package/lib/domain/ophthalmology/ophthalmology-complaints-tree.js.map +1 -0
  218. package/lib/domain/ophthalmology/ophthalmology-diagnoses.d.ts +6 -0
  219. package/lib/domain/ophthalmology/ophthalmology-diagnoses.d.ts.map +1 -0
  220. package/lib/domain/ophthalmology/ophthalmology-diagnoses.js +13 -0
  221. package/lib/domain/ophthalmology/ophthalmology-diagnoses.js.map +1 -0
  222. package/lib/domain/ophthalmology/vision-values.d.ts +21 -0
  223. package/lib/domain/ophthalmology/vision-values.d.ts.map +1 -0
  224. package/lib/domain/ophthalmology/vision-values.js +55 -0
  225. package/lib/domain/ophthalmology/vision-values.js.map +1 -0
  226. package/lib/export/document-pdf.d.ts +20 -0
  227. package/lib/export/document-pdf.d.ts.map +1 -0
  228. package/lib/export/document-pdf.js +39 -0
  229. package/lib/export/document-pdf.js.map +1 -0
  230. package/lib/export/document-pdf.sf-stub.d.ts +13 -0
  231. package/lib/export/document-pdf.sf-stub.d.ts.map +1 -0
  232. package/lib/export/document-pdf.sf-stub.js +19 -0
  233. package/lib/export/document-pdf.sf-stub.js.map +1 -0
  234. package/lib/export/preview-export-options.d.ts +17 -0
  235. package/lib/export/preview-export-options.d.ts.map +1 -0
  236. package/lib/export/preview-export-options.js +28 -0
  237. package/lib/export/preview-export-options.js.map +1 -0
  238. package/lib/export/preview-html-document.d.ts +10 -0
  239. package/lib/export/preview-html-document.d.ts.map +1 -0
  240. package/lib/export/preview-html-document.js +29 -0
  241. package/lib/export/preview-html-document.js.map +1 -0
  242. package/lib/export/preview-html-styles.d.ts +10 -0
  243. package/lib/export/preview-html-styles.d.ts.map +1 -0
  244. package/lib/export/preview-html-styles.js +527 -0
  245. package/lib/export/preview-html-styles.js.map +1 -0
  246. package/lib/export/preview-html-styles.test.d.ts +2 -0
  247. package/lib/export/preview-html-styles.test.d.ts.map +1 -0
  248. package/lib/export/preview-html-styles.test.js +56 -0
  249. package/lib/export/preview-html-styles.test.js.map +1 -0
  250. package/lib/export/preview-pdf-mount.d.ts +14 -0
  251. package/lib/export/preview-pdf-mount.d.ts.map +1 -0
  252. package/lib/export/preview-pdf-mount.js +41 -0
  253. package/lib/export/preview-pdf-mount.js.map +1 -0
  254. package/lib/export/preview-pdf-parity.test.d.ts +2 -0
  255. package/lib/export/preview-pdf-parity.test.d.ts.map +1 -0
  256. package/lib/export/preview-pdf-parity.test.js +217 -0
  257. package/lib/export/preview-pdf-parity.test.js.map +1 -0
  258. package/lib/fields/barcode-encode.d.ts +33 -0
  259. package/lib/fields/barcode-encode.d.ts.map +1 -0
  260. package/lib/fields/barcode-encode.js +118 -0
  261. package/lib/fields/barcode-encode.js.map +1 -0
  262. package/lib/fields/barcode-encode.test.d.ts +2 -0
  263. package/lib/fields/barcode-encode.test.d.ts.map +1 -0
  264. package/lib/fields/barcode-encode.test.js +38 -0
  265. package/lib/fields/barcode-encode.test.js.map +1 -0
  266. package/lib/fields/collect-field-values.test.d.ts +2 -0
  267. package/lib/fields/collect-field-values.test.d.ts.map +1 -0
  268. package/lib/fields/collect-field-values.test.js +71 -0
  269. package/lib/fields/collect-field-values.test.js.map +1 -0
  270. package/lib/fields/columns-serialize.test.d.ts +2 -0
  271. package/lib/fields/columns-serialize.test.d.ts.map +1 -0
  272. package/lib/fields/columns-serialize.test.js +68 -0
  273. package/lib/fields/columns-serialize.test.js.map +1 -0
  274. package/lib/fields/cross-section-reposition.d.ts +19 -0
  275. package/lib/fields/cross-section-reposition.d.ts.map +1 -0
  276. package/lib/fields/cross-section-reposition.js +185 -0
  277. package/lib/fields/cross-section-reposition.js.map +1 -0
  278. package/lib/fields/cross-section-reposition.test.d.ts +2 -0
  279. package/lib/fields/cross-section-reposition.test.d.ts.map +1 -0
  280. package/lib/fields/cross-section-reposition.test.js +190 -0
  281. package/lib/fields/cross-section-reposition.test.js.map +1 -0
  282. package/lib/fields/document-preview.d.ts +10 -0
  283. package/lib/fields/document-preview.d.ts.map +1 -0
  284. package/lib/fields/document-preview.js +781 -0
  285. package/lib/fields/document-preview.js.map +1 -0
  286. package/lib/fields/document-preview.test.d.ts +2 -0
  287. package/lib/fields/document-preview.test.d.ts.map +1 -0
  288. package/lib/fields/document-preview.test.js +1433 -0
  289. package/lib/fields/document-preview.test.js.map +1 -0
  290. package/lib/fields/field-clipboard.d.ts +32 -0
  291. package/lib/fields/field-clipboard.d.ts.map +1 -0
  292. package/lib/fields/field-clipboard.js +642 -0
  293. package/lib/fields/field-clipboard.js.map +1 -0
  294. package/lib/fields/field-clipboard.test.d.ts +2 -0
  295. package/lib/fields/field-clipboard.test.d.ts.map +1 -0
  296. package/lib/fields/field-clipboard.test.js +281 -0
  297. package/lib/fields/field-clipboard.test.js.map +1 -0
  298. package/lib/fields/field-display-style.d.ts +76 -0
  299. package/lib/fields/field-display-style.d.ts.map +1 -0
  300. package/lib/fields/field-display-style.js +429 -0
  301. package/lib/fields/field-display-style.js.map +1 -0
  302. package/lib/fields/field-display-style.test.d.ts +2 -0
  303. package/lib/fields/field-display-style.test.d.ts.map +1 -0
  304. package/lib/fields/field-display-style.test.js +299 -0
  305. package/lib/fields/field-display-style.test.js.map +1 -0
  306. package/lib/fields/field-keyboard.d.ts +9 -0
  307. package/lib/fields/field-keyboard.d.ts.map +1 -0
  308. package/lib/fields/field-keyboard.js +1118 -0
  309. package/lib/fields/field-keyboard.js.map +1 -0
  310. package/lib/fields/field-keyboard.test.d.ts +2 -0
  311. package/lib/fields/field-keyboard.test.d.ts.map +1 -0
  312. package/lib/fields/field-keyboard.test.js +390 -0
  313. package/lib/fields/field-keyboard.test.js.map +1 -0
  314. package/lib/fields/field-selection.d.ts +12 -0
  315. package/lib/fields/field-selection.d.ts.map +1 -0
  316. package/lib/fields/field-selection.js +123 -0
  317. package/lib/fields/field-selection.js.map +1 -0
  318. package/lib/fields/field-selection.test.d.ts +2 -0
  319. package/lib/fields/field-selection.test.d.ts.map +1 -0
  320. package/lib/fields/field-selection.test.js +67 -0
  321. package/lib/fields/field-selection.test.js.map +1 -0
  322. package/lib/fields/field-token-drag.test.d.ts +2 -0
  323. package/lib/fields/field-token-drag.test.d.ts.map +1 -0
  324. package/lib/fields/field-token-drag.test.js +55 -0
  325. package/lib/fields/field-token-drag.test.js.map +1 -0
  326. package/lib/fields/fill-defaults.test.d.ts +2 -0
  327. package/lib/fields/fill-defaults.test.d.ts.map +1 -0
  328. package/lib/fields/fill-defaults.test.js +70 -0
  329. package/lib/fields/fill-defaults.test.js.map +1 -0
  330. package/lib/fields/fill-field-focus.d.ts +51 -0
  331. package/lib/fields/fill-field-focus.d.ts.map +1 -0
  332. package/lib/fields/fill-field-focus.js +230 -0
  333. package/lib/fields/fill-field-focus.js.map +1 -0
  334. package/lib/fields/fill-field-focus.test.d.ts +2 -0
  335. package/lib/fields/fill-field-focus.test.d.ts.map +1 -0
  336. package/lib/fields/fill-field-focus.test.js +201 -0
  337. package/lib/fields/fill-field-focus.test.js.map +1 -0
  338. package/lib/fields/handlers/builtins.d.ts +3 -0
  339. package/lib/fields/handlers/builtins.d.ts.map +1 -0
  340. package/lib/fields/handlers/builtins.js +869 -0
  341. package/lib/fields/handlers/builtins.js.map +1 -0
  342. package/lib/fields/handlers/index.d.ts +4 -0
  343. package/lib/fields/handlers/index.d.ts.map +1 -0
  344. package/lib/fields/handlers/index.js +5 -0
  345. package/lib/fields/handlers/index.js.map +1 -0
  346. package/lib/fields/handlers/registry.d.ts +27 -0
  347. package/lib/fields/handlers/registry.d.ts.map +1 -0
  348. package/lib/fields/handlers/registry.js +69 -0
  349. package/lib/fields/handlers/registry.js.map +1 -0
  350. package/lib/fields/handlers/registry.test.d.ts +2 -0
  351. package/lib/fields/handlers/registry.test.d.ts.map +1 -0
  352. package/lib/fields/handlers/registry.test.js +203 -0
  353. package/lib/fields/handlers/registry.test.js.map +1 -0
  354. package/lib/fields/handlers/schema-form-dom.d.ts +36 -0
  355. package/lib/fields/handlers/schema-form-dom.d.ts.map +1 -0
  356. package/lib/fields/handlers/schema-form-dom.js +114 -0
  357. package/lib/fields/handlers/schema-form-dom.js.map +1 -0
  358. package/lib/fields/heading-line-breaks.test.d.ts +2 -0
  359. package/lib/fields/heading-line-breaks.test.d.ts.map +1 -0
  360. package/lib/fields/heading-line-breaks.test.js +755 -0
  361. package/lib/fields/heading-line-breaks.test.js.map +1 -0
  362. package/lib/fields/inline-field-from-selection.test.d.ts +2 -0
  363. package/lib/fields/inline-field-from-selection.test.d.ts.map +1 -0
  364. package/lib/fields/inline-field-from-selection.test.js +185 -0
  365. package/lib/fields/inline-field-from-selection.test.js.map +1 -0
  366. package/lib/fields/inline-fields.d.ts +150 -0
  367. package/lib/fields/inline-fields.d.ts.map +1 -0
  368. package/lib/fields/inline-fields.js +3408 -0
  369. package/lib/fields/inline-fields.js.map +1 -0
  370. package/lib/fields/logical-display.d.ts +8 -0
  371. package/lib/fields/logical-display.d.ts.map +1 -0
  372. package/lib/fields/logical-display.js +29 -0
  373. package/lib/fields/logical-display.js.map +1 -0
  374. package/lib/fields/logical-display.test.d.ts +2 -0
  375. package/lib/fields/logical-display.test.d.ts.map +1 -0
  376. package/lib/fields/logical-display.test.js +31 -0
  377. package/lib/fields/logical-display.test.js.map +1 -0
  378. package/lib/fields/manual-field-values.d.ts +87 -0
  379. package/lib/fields/manual-field-values.d.ts.map +1 -0
  380. package/lib/fields/manual-field-values.js +189 -0
  381. package/lib/fields/manual-field-values.js.map +1 -0
  382. package/lib/fields/manual-field-values.test.d.ts +2 -0
  383. package/lib/fields/manual-field-values.test.d.ts.map +1 -0
  384. package/lib/fields/manual-field-values.test.js +84 -0
  385. package/lib/fields/manual-field-values.test.js.map +1 -0
  386. package/lib/fields/pivot-table-field.d.ts +25 -0
  387. package/lib/fields/pivot-table-field.d.ts.map +1 -0
  388. package/lib/fields/pivot-table-field.js +408 -0
  389. package/lib/fields/pivot-table-field.js.map +1 -0
  390. package/lib/fields/plain-text-newlines.test.d.ts +2 -0
  391. package/lib/fields/plain-text-newlines.test.d.ts.map +1 -0
  392. package/lib/fields/plain-text-newlines.test.js +40 -0
  393. package/lib/fields/plain-text-newlines.test.js.map +1 -0
  394. package/lib/fields/repeater-field.d.ts +10 -0
  395. package/lib/fields/repeater-field.d.ts.map +1 -0
  396. package/lib/fields/repeater-field.js +48 -0
  397. package/lib/fields/repeater-field.js.map +1 -0
  398. package/lib/fields/rich-text.d.ts +27 -0
  399. package/lib/fields/rich-text.d.ts.map +1 -0
  400. package/lib/fields/rich-text.js +984 -0
  401. package/lib/fields/rich-text.js.map +1 -0
  402. package/lib/fields/table-field.d.ts +57 -0
  403. package/lib/fields/table-field.d.ts.map +1 -0
  404. package/lib/fields/table-field.js +836 -0
  405. package/lib/fields/table-field.js.map +1 -0
  406. package/lib/fields/table-field.test.d.ts +2 -0
  407. package/lib/fields/table-field.test.d.ts.map +1 -0
  408. package/lib/fields/table-field.test.js +456 -0
  409. package/lib/fields/table-field.test.js.map +1 -0
  410. package/lib/fields/tree-paths.d.ts +5 -0
  411. package/lib/fields/tree-paths.d.ts.map +1 -0
  412. package/lib/fields/tree-paths.js +7 -0
  413. package/lib/fields/tree-paths.js.map +1 -0
  414. package/lib/fields/tree-selection.d.ts +9 -0
  415. package/lib/fields/tree-selection.d.ts.map +1 -0
  416. package/lib/fields/tree-selection.js +39 -0
  417. package/lib/fields/tree-selection.js.map +1 -0
  418. package/lib/fields/tree.d.ts +7 -0
  419. package/lib/fields/tree.d.ts.map +1 -0
  420. package/lib/fields/tree.js +7 -0
  421. package/lib/fields/tree.js.map +1 -0
  422. package/lib/fields/wire-columns-resize.d.ts +6 -0
  423. package/lib/fields/wire-columns-resize.d.ts.map +1 -0
  424. package/lib/fields/wire-columns-resize.js +130 -0
  425. package/lib/fields/wire-columns-resize.js.map +1 -0
  426. package/lib/fields/wire-columns-resize.test.d.ts +2 -0
  427. package/lib/fields/wire-columns-resize.test.d.ts.map +1 -0
  428. package/lib/fields/wire-columns-resize.test.js +38 -0
  429. package/lib/fields/wire-columns-resize.test.js.map +1 -0
  430. package/lib/fields/wire-editorjs-native-drop-guard.d.ts +34 -0
  431. package/lib/fields/wire-editorjs-native-drop-guard.d.ts.map +1 -0
  432. package/lib/fields/wire-editorjs-native-drop-guard.js +453 -0
  433. package/lib/fields/wire-editorjs-native-drop-guard.js.map +1 -0
  434. package/lib/fields/wire-editorjs-native-drop-guard.test.d.ts +2 -0
  435. package/lib/fields/wire-editorjs-native-drop-guard.test.d.ts.map +1 -0
  436. package/lib/fields/wire-editorjs-native-drop-guard.test.js +230 -0
  437. package/lib/fields/wire-editorjs-native-drop-guard.test.js.map +1 -0
  438. package/lib/fields/wire-table-column-reorder.d.ts +23 -0
  439. package/lib/fields/wire-table-column-reorder.d.ts.map +1 -0
  440. package/lib/fields/wire-table-column-reorder.js +207 -0
  441. package/lib/fields/wire-table-column-reorder.js.map +1 -0
  442. package/lib/fields/wire-table-column-reorder.test.d.ts +2 -0
  443. package/lib/fields/wire-table-column-reorder.test.d.ts.map +1 -0
  444. package/lib/fields/wire-table-column-reorder.test.js +133 -0
  445. package/lib/fields/wire-table-column-reorder.test.js.map +1 -0
  446. package/lib/fields/wire-table-column-resize.d.ts +118 -0
  447. package/lib/fields/wire-table-column-resize.d.ts.map +1 -0
  448. package/lib/fields/wire-table-column-resize.js +406 -0
  449. package/lib/fields/wire-table-column-resize.js.map +1 -0
  450. package/lib/fields/wire-table-column-resize.test.d.ts +2 -0
  451. package/lib/fields/wire-table-column-resize.test.d.ts.map +1 -0
  452. package/lib/fields/wire-table-column-resize.test.js +407 -0
  453. package/lib/fields/wire-table-column-resize.test.js.map +1 -0
  454. package/lib/index.d.ts +39 -0
  455. package/lib/index.d.ts.map +1 -0
  456. package/lib/index.js +37 -0
  457. package/lib/index.js.map +1 -0
  458. package/lib/node.d.ts +20 -0
  459. package/lib/node.d.ts.map +1 -0
  460. package/lib/node.js +20 -0
  461. package/lib/node.js.map +1 -0
  462. package/lib/registry/registry-context.d.ts +6 -0
  463. package/lib/registry/registry-context.d.ts.map +1 -0
  464. package/lib/registry/registry-context.js +39 -0
  465. package/lib/registry/registry-context.js.map +1 -0
  466. package/lib/registry/schema-registry.d.ts +18 -0
  467. package/lib/registry/schema-registry.d.ts.map +1 -0
  468. package/lib/registry/schema-registry.js +67 -0
  469. package/lib/registry/schema-registry.js.map +1 -0
  470. package/lib/services/image-upload.d.ts +27 -0
  471. package/lib/services/image-upload.d.ts.map +1 -0
  472. package/lib/services/image-upload.js +159 -0
  473. package/lib/services/image-upload.js.map +1 -0
  474. package/lib/services/image-upload.test.d.ts +2 -0
  475. package/lib/services/image-upload.test.d.ts.map +1 -0
  476. package/lib/services/image-upload.test.js +141 -0
  477. package/lib/services/image-upload.test.js.map +1 -0
  478. package/lib/sf-entry.d.ts +5 -0
  479. package/lib/sf-entry.d.ts.map +1 -0
  480. package/lib/sf-entry.js +15 -0
  481. package/lib/sf-entry.js.map +1 -0
  482. package/lib/sf-pdf-viewer/main.d.ts +2 -0
  483. package/lib/sf-pdf-viewer/main.d.ts.map +1 -0
  484. package/lib/sf-pdf-viewer/main.js +57 -0
  485. package/lib/sf-pdf-viewer/main.js.map +1 -0
  486. package/lib/tools/document-section.d.ts +54 -0
  487. package/lib/tools/document-section.d.ts.map +1 -0
  488. package/lib/tools/document-section.js +591 -0
  489. package/lib/tools/document-section.js.map +1 -0
  490. package/lib/tools/template-block.d.ts +18 -0
  491. package/lib/tools/template-block.d.ts.map +1 -0
  492. package/lib/tools/template-block.js +243 -0
  493. package/lib/tools/template-block.js.map +1 -0
  494. package/lib/ui/action-icons.d.ts +10 -0
  495. package/lib/ui/action-icons.d.ts.map +1 -0
  496. package/lib/ui/action-icons.js +11 -0
  497. package/lib/ui/action-icons.js.map +1 -0
  498. package/lib/ui/document-actions.d.ts +12 -0
  499. package/lib/ui/document-actions.d.ts.map +1 -0
  500. package/lib/ui/document-actions.js +37 -0
  501. package/lib/ui/document-actions.js.map +1 -0
  502. package/lib/ui/drag-handle.d.ts +11 -0
  503. package/lib/ui/drag-handle.d.ts.map +1 -0
  504. package/lib/ui/drag-handle.js +38 -0
  505. package/lib/ui/drag-handle.js.map +1 -0
  506. package/lib/ui/existing-image-modal.d.ts +10 -0
  507. package/lib/ui/existing-image-modal.d.ts.map +1 -0
  508. package/lib/ui/existing-image-modal.js +153 -0
  509. package/lib/ui/existing-image-modal.js.map +1 -0
  510. package/lib/ui/field-form-modal.d.ts +33 -0
  511. package/lib/ui/field-form-modal.d.ts.map +1 -0
  512. package/lib/ui/field-form-modal.js +103 -0
  513. package/lib/ui/field-form-modal.js.map +1 -0
  514. package/lib/ui/field-form-modal.test.d.ts +2 -0
  515. package/lib/ui/field-form-modal.test.d.ts.map +1 -0
  516. package/lib/ui/field-form-modal.test.js +81 -0
  517. package/lib/ui/field-form-modal.test.js.map +1 -0
  518. package/lib/ui/field-mapping-badges.d.ts +9 -0
  519. package/lib/ui/field-mapping-badges.d.ts.map +1 -0
  520. package/lib/ui/field-mapping-badges.js +208 -0
  521. package/lib/ui/field-mapping-badges.js.map +1 -0
  522. package/lib/ui/field-mapping-badges.test.d.ts +2 -0
  523. package/lib/ui/field-mapping-badges.test.d.ts.map +1 -0
  524. package/lib/ui/field-mapping-badges.test.js +81 -0
  525. package/lib/ui/field-mapping-badges.test.js.map +1 -0
  526. package/lib/ui/field-mapping-modal-open.test.d.ts +2 -0
  527. package/lib/ui/field-mapping-modal-open.test.d.ts.map +1 -0
  528. package/lib/ui/field-mapping-modal-open.test.js +58 -0
  529. package/lib/ui/field-mapping-modal-open.test.js.map +1 -0
  530. package/lib/ui/field-mapping-modal.d.ts +4 -0
  531. package/lib/ui/field-mapping-modal.d.ts.map +1 -0
  532. package/lib/ui/field-mapping-modal.js +992 -0
  533. package/lib/ui/field-mapping-modal.js.map +1 -0
  534. package/lib/ui/filename-prompt.d.ts +6 -0
  535. package/lib/ui/filename-prompt.d.ts.map +1 -0
  536. package/lib/ui/filename-prompt.js +85 -0
  537. package/lib/ui/filename-prompt.js.map +1 -0
  538. package/lib/ui/format-icons.d.ts +23 -0
  539. package/lib/ui/format-icons.d.ts.map +1 -0
  540. package/lib/ui/format-icons.js +23 -0
  541. package/lib/ui/format-icons.js.map +1 -0
  542. package/lib/ui/html-text-modal.d.ts +6 -0
  543. package/lib/ui/html-text-modal.d.ts.map +1 -0
  544. package/lib/ui/html-text-modal.js +195 -0
  545. package/lib/ui/html-text-modal.js.map +1 -0
  546. package/lib/ui/image-modal.d.ts +6 -0
  547. package/lib/ui/image-modal.d.ts.map +1 -0
  548. package/lib/ui/image-modal.js +237 -0
  549. package/lib/ui/image-modal.js.map +1 -0
  550. package/lib/ui/integer-modal.d.ts +12 -0
  551. package/lib/ui/integer-modal.d.ts.map +1 -0
  552. package/lib/ui/integer-modal.js +71 -0
  553. package/lib/ui/integer-modal.js.map +1 -0
  554. package/lib/ui/list-modal.d.ts +6 -0
  555. package/lib/ui/list-modal.d.ts.map +1 -0
  556. package/lib/ui/list-modal.js +627 -0
  557. package/lib/ui/list-modal.js.map +1 -0
  558. package/lib/ui/list-modal.test.d.ts +2 -0
  559. package/lib/ui/list-modal.test.d.ts.map +1 -0
  560. package/lib/ui/list-modal.test.js +185 -0
  561. package/lib/ui/list-modal.test.js.map +1 -0
  562. package/lib/ui/logical-modal.d.ts +11 -0
  563. package/lib/ui/logical-modal.d.ts.map +1 -0
  564. package/lib/ui/logical-modal.js +104 -0
  565. package/lib/ui/logical-modal.js.map +1 -0
  566. package/lib/ui/mapping-drag-drop.d.ts +44 -0
  567. package/lib/ui/mapping-drag-drop.d.ts.map +1 -0
  568. package/lib/ui/mapping-drag-drop.js +339 -0
  569. package/lib/ui/mapping-drag-drop.js.map +1 -0
  570. package/lib/ui/mapping-drag-drop.test.d.ts +2 -0
  571. package/lib/ui/mapping-drag-drop.test.d.ts.map +1 -0
  572. package/lib/ui/mapping-drag-drop.test.js +47 -0
  573. package/lib/ui/mapping-drag-drop.test.js.map +1 -0
  574. package/lib/ui/mapping-result-helper.d.ts +130 -0
  575. package/lib/ui/mapping-result-helper.d.ts.map +1 -0
  576. package/lib/ui/mapping-result-helper.js +659 -0
  577. package/lib/ui/mapping-result-helper.js.map +1 -0
  578. package/lib/ui/mapping-result-helper.test.d.ts +2 -0
  579. package/lib/ui/mapping-result-helper.test.d.ts.map +1 -0
  580. package/lib/ui/mapping-result-helper.test.js +185 -0
  581. package/lib/ui/mapping-result-helper.test.js.map +1 -0
  582. package/lib/ui/modal-picker-keyboard.d.ts +12 -0
  583. package/lib/ui/modal-picker-keyboard.d.ts.map +1 -0
  584. package/lib/ui/modal-picker-keyboard.js +72 -0
  585. package/lib/ui/modal-picker-keyboard.js.map +1 -0
  586. package/lib/ui/modal-picker-keyboard.test.d.ts +2 -0
  587. package/lib/ui/modal-picker-keyboard.test.d.ts.map +1 -0
  588. package/lib/ui/modal-picker-keyboard.test.js +53 -0
  589. package/lib/ui/modal-picker-keyboard.test.js.map +1 -0
  590. package/lib/ui/modal-picker-pills.d.ts +2 -0
  591. package/lib/ui/modal-picker-pills.d.ts.map +1 -0
  592. package/lib/ui/modal-picker-pills.js +26 -0
  593. package/lib/ui/modal-picker-pills.js.map +1 -0
  594. package/lib/ui/notification.d.ts +2 -0
  595. package/lib/ui/notification.d.ts.map +1 -0
  596. package/lib/ui/notification.js +47 -0
  597. package/lib/ui/notification.js.map +1 -0
  598. package/lib/ui/palette-icons.d.ts +5 -0
  599. package/lib/ui/palette-icons.d.ts.map +1 -0
  600. package/lib/ui/palette-icons.js +28 -0
  601. package/lib/ui/palette-icons.js.map +1 -0
  602. package/lib/ui/pdf-canvas-preview.d.ts +11 -0
  603. package/lib/ui/pdf-canvas-preview.d.ts.map +1 -0
  604. package/lib/ui/pdf-canvas-preview.js +88 -0
  605. package/lib/ui/pdf-canvas-preview.js.map +1 -0
  606. package/lib/ui/preview-modal.d.ts +24 -0
  607. package/lib/ui/preview-modal.d.ts.map +1 -0
  608. package/lib/ui/preview-modal.js +536 -0
  609. package/lib/ui/preview-modal.js.map +1 -0
  610. package/lib/ui/recent-fill-colors.d.ts +21 -0
  611. package/lib/ui/recent-fill-colors.d.ts.map +1 -0
  612. package/lib/ui/recent-fill-colors.js +95 -0
  613. package/lib/ui/recent-fill-colors.js.map +1 -0
  614. package/lib/ui/recent-fill-colors.test.d.ts +2 -0
  615. package/lib/ui/recent-fill-colors.test.d.ts.map +1 -0
  616. package/lib/ui/recent-fill-colors.test.js +56 -0
  617. package/lib/ui/recent-fill-colors.test.js.map +1 -0
  618. package/lib/ui/repeater-editor-modal.d.ts +10 -0
  619. package/lib/ui/repeater-editor-modal.d.ts.map +1 -0
  620. package/lib/ui/repeater-editor-modal.js +124 -0
  621. package/lib/ui/repeater-editor-modal.js.map +1 -0
  622. package/lib/ui/rich-text-toolbar.d.ts +13 -0
  623. package/lib/ui/rich-text-toolbar.d.ts.map +1 -0
  624. package/lib/ui/rich-text-toolbar.js +670 -0
  625. package/lib/ui/rich-text-toolbar.js.map +1 -0
  626. package/lib/ui/rich-text-toolbar.test.d.ts +2 -0
  627. package/lib/ui/rich-text-toolbar.test.d.ts.map +1 -0
  628. package/lib/ui/rich-text-toolbar.test.js +167 -0
  629. package/lib/ui/rich-text-toolbar.test.js.map +1 -0
  630. package/lib/ui/signature-modal.d.ts +13 -0
  631. package/lib/ui/signature-modal.d.ts.map +1 -0
  632. package/lib/ui/signature-modal.js +219 -0
  633. package/lib/ui/signature-modal.js.map +1 -0
  634. package/lib/ui/source-path-canvas-drop.d.ts +121 -0
  635. package/lib/ui/source-path-canvas-drop.d.ts.map +1 -0
  636. package/lib/ui/source-path-canvas-drop.js +300 -0
  637. package/lib/ui/source-path-canvas-drop.js.map +1 -0
  638. package/lib/ui/source-path-canvas-drop.test.d.ts +2 -0
  639. package/lib/ui/source-path-canvas-drop.test.d.ts.map +1 -0
  640. package/lib/ui/source-path-canvas-drop.test.js +216 -0
  641. package/lib/ui/source-path-canvas-drop.test.js.map +1 -0
  642. package/lib/ui/source-schema-tree.d.ts +33 -0
  643. package/lib/ui/source-schema-tree.d.ts.map +1 -0
  644. package/lib/ui/source-schema-tree.js +326 -0
  645. package/lib/ui/source-schema-tree.js.map +1 -0
  646. package/lib/ui/text-modal.d.ts +13 -0
  647. package/lib/ui/text-modal.d.ts.map +1 -0
  648. package/lib/ui/text-modal.js +31 -0
  649. package/lib/ui/text-modal.js.map +1 -0
  650. package/lib/ui/tree-modal.d.ts +8 -0
  651. package/lib/ui/tree-modal.d.ts.map +1 -0
  652. package/lib/ui/tree-modal.js +586 -0
  653. package/lib/ui/tree-modal.js.map +1 -0
  654. package/lib/ui/tree-modal.test.d.ts +2 -0
  655. package/lib/ui/tree-modal.test.d.ts.map +1 -0
  656. package/lib/ui/tree-modal.test.js +390 -0
  657. package/lib/ui/tree-modal.test.js.map +1 -0
  658. package/lib/ui/wire-modal-escape.d.ts +13 -0
  659. package/lib/ui/wire-modal-escape.d.ts.map +1 -0
  660. package/lib/ui/wire-modal-escape.js +26 -0
  661. package/lib/ui/wire-modal-escape.js.map +1 -0
  662. package/lib/ui/wire-modal-escape.test.d.ts +2 -0
  663. package/lib/ui/wire-modal-escape.test.d.ts.map +1 -0
  664. package/lib/ui/wire-modal-escape.test.js +57 -0
  665. package/lib/ui/wire-modal-escape.test.js.map +1 -0
  666. package/lib/ui/wire-modal-focus-trap.test.d.ts +2 -0
  667. package/lib/ui/wire-modal-focus-trap.test.d.ts.map +1 -0
  668. package/lib/ui/wire-modal-focus-trap.test.js +264 -0
  669. package/lib/ui/wire-modal-focus-trap.test.js.map +1 -0
  670. package/lib/ui/wire-modal-move.d.ts +23 -0
  671. package/lib/ui/wire-modal-move.d.ts.map +1 -0
  672. package/lib/ui/wire-modal-move.js +179 -0
  673. package/lib/ui/wire-modal-move.js.map +1 -0
  674. package/lib/ui/wire-modal-move.test.d.ts +2 -0
  675. package/lib/ui/wire-modal-move.test.d.ts.map +1 -0
  676. package/lib/ui/wire-modal-move.test.js +84 -0
  677. package/lib/ui/wire-modal-move.test.js.map +1 -0
  678. package/lib/ui/wire-modal-palette.d.ts +56 -0
  679. package/lib/ui/wire-modal-palette.d.ts.map +1 -0
  680. package/lib/ui/wire-modal-palette.js +501 -0
  681. package/lib/ui/wire-modal-palette.js.map +1 -0
  682. package/lib/ui/wire-modal-resize.d.ts +27 -0
  683. package/lib/ui/wire-modal-resize.d.ts.map +1 -0
  684. package/lib/ui/wire-modal-resize.js +146 -0
  685. package/lib/ui/wire-modal-resize.js.map +1 -0
  686. package/lib/ui/wire-modal-resize.test.d.ts +2 -0
  687. package/lib/ui/wire-modal-resize.test.d.ts.map +1 -0
  688. package/lib/ui/wire-modal-resize.test.js +61 -0
  689. package/lib/ui/wire-modal-resize.test.js.map +1 -0
  690. package/lib/ui/wire-panel-splitter.d.ts +67 -0
  691. package/lib/ui/wire-panel-splitter.d.ts.map +1 -0
  692. package/lib/ui/wire-panel-splitter.js +361 -0
  693. package/lib/ui/wire-panel-splitter.js.map +1 -0
  694. package/lib/ui/wire-panel-splitter.test.d.ts +2 -0
  695. package/lib/ui/wire-panel-splitter.test.d.ts.map +1 -0
  696. package/lib/ui/wire-panel-splitter.test.js +152 -0
  697. package/lib/ui/wire-panel-splitter.test.js.map +1 -0
  698. package/lib/utils/export-filename.d.ts +24 -0
  699. package/lib/utils/export-filename.d.ts.map +1 -0
  700. package/lib/utils/export-filename.js +42 -0
  701. package/lib/utils/export-filename.js.map +1 -0
  702. package/lib/utils/export-filename.test.d.ts +2 -0
  703. package/lib/utils/export-filename.test.d.ts.map +1 -0
  704. package/lib/utils/export-filename.test.js +42 -0
  705. package/lib/utils/export-filename.test.js.map +1 -0
  706. package/lib/utils/print-document.d.ts +17 -0
  707. package/lib/utils/print-document.d.ts.map +1 -0
  708. package/lib/utils/print-document.js +132 -0
  709. package/lib/utils/print-document.js.map +1 -0
  710. package/lib/utils/save-blob.d.ts +9 -0
  711. package/lib/utils/save-blob.d.ts.map +1 -0
  712. package/lib/utils/save-blob.js +41 -0
  713. package/lib/utils/save-blob.js.map +1 -0
  714. package/lib/web-component.d.ts +6 -0
  715. package/lib/web-component.d.ts.map +1 -0
  716. package/lib/web-component.js +59 -0
  717. package/lib/web-component.js.map +1 -0
  718. package/package.json +61 -6
  719. package/src/catalog/catalog-provider.ts +91 -0
  720. package/src/core/computed-formula.test.ts +258 -0
  721. package/src/core/computed-formula.ts +18 -0
  722. package/src/core/document-display-defaults.ts +13 -0
  723. package/src/core/document-history.test.ts +54 -0
  724. package/src/core/document-history.ts +102 -0
  725. package/src/core/document-io.test.ts +739 -0
  726. package/src/core/document-io.ts +27 -0
  727. package/src/core/document-section-defaults.test.ts +56 -0
  728. package/src/core/document-section-defaults.ts +67 -0
  729. package/src/core/field-id.test.ts +299 -0
  730. package/src/core/field-id.ts +23 -0
  731. package/src/core/field-io/sectioned-document-io.test.ts +568 -0
  732. package/src/core/field-io/sectioned-document-io.ts +15 -0
  733. package/src/core/field-io/table-field-io.test.ts +242 -0
  734. package/src/core/field-io/table-field-io.ts +13 -0
  735. package/src/core/field-schemas.test.ts +472 -0
  736. package/src/core/field-schemas.ts +46 -0
  737. package/src/core/formula-field-index.test.ts +140 -0
  738. package/src/core/formula-field-index.ts +16 -0
  739. package/src/core/page-setup-styles.test.ts +274 -0
  740. package/src/core/page-setup-styles.ts +213 -0
  741. package/src/core/repeater-io.test.ts +899 -0
  742. package/src/core/repeater-io.ts +37 -0
  743. package/src/core/segment-tree.test.ts +41 -0
  744. package/src/core/segment-tree.ts +6 -0
  745. package/src/create-editor.ts +3848 -0
  746. package/src/design/collection-tree-picker.test.ts +105 -0
  747. package/src/design/collection-tree-picker.ts +340 -0
  748. package/src/design/design-mode.ts +7 -0
  749. package/src/design/design-shell.ts +76 -0
  750. package/src/design/display-style-form.test.ts +174 -0
  751. package/src/design/display-style-form.ts +217 -0
  752. package/src/design/field-highlight-form.test.ts +64 -0
  753. package/src/design/field-highlight-form.ts +169 -0
  754. package/src/design/field-palette.test.ts +97 -0
  755. package/src/design/field-palette.ts +250 -0
  756. package/src/design/formula-field-picker.test.ts +158 -0
  757. package/src/design/formula-field-picker.ts +189 -0
  758. package/src/design/palette-block-drop.ts +66 -0
  759. package/src/design/properties-panel.ts +900 -0
  760. package/src/design/schema-editor-controller.test.ts +296 -0
  761. package/src/design/schema-editor-controller.ts +1122 -0
  762. package/src/design/schema-editor-modal.ts +83 -0
  763. package/src/design/schema-items-designer-modal.ts +209 -0
  764. package/src/design/schema-items-designer.test.ts +148 -0
  765. package/src/design/schema-items-designer.ts +442 -0
  766. package/src/design/style-toolbar-shared.ts +218 -0
  767. package/src/dom-pragmatic.d.ts +83 -0
  768. package/src/domain/ophthalmology/catalogs.ts +72 -0
  769. package/src/domain/ophthalmology/life-anamnesis-tree.ts +43 -0
  770. package/src/domain/ophthalmology/norm-options.ts +24 -0
  771. package/src/domain/ophthalmology/ophthalmology-complaints-tree.ts +47 -0
  772. package/src/domain/ophthalmology/ophthalmology-diagnoses.ts +12 -0
  773. package/src/domain/ophthalmology/vision-values.ts +58 -0
  774. package/src/editorjs-shim.d.ts +2 -0
  775. package/src/export/document-pdf.sf-stub.ts +23 -0
  776. package/src/export/document-pdf.ts +44 -0
  777. package/src/export/preview-export-options.ts +29 -0
  778. package/src/export/preview-html-document.ts +34 -0
  779. package/src/export/preview-html-styles.test.ts +60 -0
  780. package/src/export/preview-html-styles.ts +551 -0
  781. package/src/export/preview-pdf-mount.ts +48 -0
  782. package/src/export/preview-pdf-parity.test.ts +237 -0
  783. package/src/fields/barcode-encode.test.ts +43 -0
  784. package/src/fields/barcode-encode.ts +147 -0
  785. package/src/fields/collect-field-values.test.ts +95 -0
  786. package/src/fields/columns-serialize.test.ts +75 -0
  787. package/src/fields/cross-section-reposition.test.ts +206 -0
  788. package/src/fields/cross-section-reposition.ts +214 -0
  789. package/src/fields/document-preview.test.ts +1621 -0
  790. package/src/fields/document-preview.ts +910 -0
  791. package/src/fields/field-clipboard.test.ts +312 -0
  792. package/src/fields/field-clipboard.ts +705 -0
  793. package/src/fields/field-display-style.test.ts +403 -0
  794. package/src/fields/field-display-style.ts +435 -0
  795. package/src/fields/field-keyboard.test.ts +446 -0
  796. package/src/fields/field-keyboard.ts +1281 -0
  797. package/src/fields/field-selection.test.ts +85 -0
  798. package/src/fields/field-selection.ts +137 -0
  799. package/src/fields/field-token-drag.test.ts +65 -0
  800. package/src/fields/fill-defaults.test.ts +89 -0
  801. package/src/fields/fill-field-focus.test.ts +239 -0
  802. package/src/fields/fill-field-focus.ts +249 -0
  803. package/src/fields/handlers/builtins.ts +879 -0
  804. package/src/fields/handlers/index.ts +16 -0
  805. package/src/fields/handlers/registry.test.ts +266 -0
  806. package/src/fields/handlers/registry.ts +88 -0
  807. package/src/fields/handlers/schema-form-dom.ts +135 -0
  808. package/src/fields/heading-line-breaks.test.ts +931 -0
  809. package/src/fields/inline-field-from-selection.test.ts +202 -0
  810. package/src/fields/inline-fields.ts +3760 -0
  811. package/src/fields/logical-display.test.ts +37 -0
  812. package/src/fields/logical-display.ts +29 -0
  813. package/src/fields/manual-field-values.test.ts +152 -0
  814. package/src/fields/manual-field-values.ts +207 -0
  815. package/src/fields/pivot-table-field.ts +458 -0
  816. package/src/fields/plain-text-newlines.test.ts +48 -0
  817. package/src/fields/repeater-field.ts +61 -0
  818. package/src/fields/rich-text.ts +1018 -0
  819. package/src/fields/table-field.test.ts +504 -0
  820. package/src/fields/table-field.ts +1026 -0
  821. package/src/fields/tree-paths.ts +6 -0
  822. package/src/fields/tree-selection.ts +50 -0
  823. package/src/fields/tree.ts +11 -0
  824. package/src/fields/wire-columns-resize.test.ts +40 -0
  825. package/src/fields/wire-columns-resize.ts +138 -0
  826. package/src/fields/wire-editorjs-native-drop-guard.test.ts +273 -0
  827. package/src/fields/wire-editorjs-native-drop-guard.ts +491 -0
  828. package/src/fields/wire-table-column-reorder.test.ts +163 -0
  829. package/src/fields/wire-table-column-reorder.ts +223 -0
  830. package/src/fields/wire-table-column-resize.test.ts +459 -0
  831. package/src/fields/wire-table-column-resize.ts +433 -0
  832. package/src/index.ts +290 -0
  833. package/src/node.ts +114 -0
  834. package/src/registry/registry-context.ts +36 -0
  835. package/src/registry/schema-registry.ts +80 -0
  836. package/src/services/image-upload.test.ts +180 -0
  837. package/src/services/image-upload.ts +185 -0
  838. package/src/sf-entry.ts +19 -0
  839. package/src/sf-pdf-viewer/main.ts +57 -0
  840. package/src/sf-pdf-viewer/viewer.html +40 -0
  841. package/src/styles/editor.css +5472 -0
  842. package/src/themes/bridge.css +2071 -0
  843. package/src/themes/prime.css +207 -0
  844. package/src/themes/slds.css +123 -0
  845. package/src/tools/document-section.ts +692 -0
  846. package/src/tools/template-block.ts +289 -0
  847. package/src/types.d.ts +1782 -0
  848. package/src/ui/action-icons.ts +13 -0
  849. package/src/ui/document-actions.ts +41 -0
  850. package/src/ui/drag-handle.ts +52 -0
  851. package/src/ui/existing-image-modal.ts +164 -0
  852. package/src/ui/field-form-modal.test.ts +92 -0
  853. package/src/ui/field-form-modal.ts +168 -0
  854. package/src/ui/field-mapping-badges.test.ts +93 -0
  855. package/src/ui/field-mapping-badges.ts +243 -0
  856. package/src/ui/field-mapping-modal-open.test.ts +72 -0
  857. package/src/ui/field-mapping-modal.ts +1277 -0
  858. package/src/ui/filename-prompt.ts +96 -0
  859. package/src/ui/format-icons.ts +42 -0
  860. package/src/ui/html-text-modal.ts +224 -0
  861. package/src/ui/image-modal.ts +264 -0
  862. package/src/ui/integer-modal.ts +76 -0
  863. package/src/ui/list-modal.test.ts +220 -0
  864. package/src/ui/list-modal.ts +701 -0
  865. package/src/ui/mapping-drag-drop.test.ts +61 -0
  866. package/src/ui/mapping-drag-drop.ts +382 -0
  867. package/src/ui/mapping-result-helper.test.ts +231 -0
  868. package/src/ui/mapping-result-helper.ts +725 -0
  869. package/src/ui/modal-picker-keyboard.test.ts +65 -0
  870. package/src/ui/modal-picker-keyboard.ts +87 -0
  871. package/src/ui/modal-picker-pills.ts +31 -0
  872. package/src/ui/notification.ts +54 -0
  873. package/src/ui/palette-icons.ts +64 -0
  874. package/src/ui/pdf-canvas-preview.ts +93 -0
  875. package/src/ui/preview-modal.ts +580 -0
  876. package/src/ui/recent-fill-colors.test.ts +66 -0
  877. package/src/ui/recent-fill-colors.ts +91 -0
  878. package/src/ui/repeater-editor-modal.ts +137 -0
  879. package/src/ui/rich-text-toolbar.test.ts +180 -0
  880. package/src/ui/rich-text-toolbar.ts +740 -0
  881. package/src/ui/signature-modal.ts +240 -0
  882. package/src/ui/source-path-canvas-drop.test.ts +256 -0
  883. package/src/ui/source-path-canvas-drop.ts +367 -0
  884. package/src/ui/source-schema-tree.ts +384 -0
  885. package/src/ui/text-modal.ts +37 -0
  886. package/src/ui/tree-modal.test.ts +484 -0
  887. package/src/ui/tree-modal.ts +682 -0
  888. package/src/ui/wire-modal-escape.test.ts +66 -0
  889. package/src/ui/wire-modal-escape.ts +23 -0
  890. package/src/ui/wire-modal-focus-trap.test.ts +307 -0
  891. package/src/ui/wire-modal-move.test.ts +107 -0
  892. package/src/ui/wire-modal-move.ts +201 -0
  893. package/src/ui/wire-modal-palette.ts +533 -0
  894. package/src/ui/wire-modal-resize.test.ts +76 -0
  895. package/src/ui/wire-modal-resize.ts +176 -0
  896. package/src/ui/wire-panel-splitter.test.ts +178 -0
  897. package/src/ui/wire-panel-splitter.ts +381 -0
  898. package/src/utils/export-filename.test.ts +54 -0
  899. package/src/utils/export-filename.ts +58 -0
  900. package/src/utils/print-document.ts +136 -0
  901. package/src/utils/save-blob.ts +40 -0
  902. package/src/web-component.ts +68 -0
@@ -0,0 +1,3848 @@
1
+ import { wireEditorJsNativeDropGuard } from './fields/wire-editorjs-native-drop-guard.js';
2
+ import EditorJS from '@editorjs/editorjs';
3
+ // EditorJS CJS typings conflict with verbatimModuleSyntax; treat as any constructable.
4
+ const EditorJSCtor: any = EditorJS;
5
+
6
+ import DocumentSection from './tools/document-section.js';
7
+ import TemplateBlock from './tools/template-block.js';
8
+
9
+ import { createTreeModal } from './ui/tree-modal.js';
10
+ import { createListModal } from './ui/list-modal.js';
11
+ import { createTextModal } from './ui/text-modal.js';
12
+ import { createHtmlTextModal } from './ui/html-text-modal.js';
13
+ import { createIntegerModal } from './ui/integer-modal.js';
14
+ import { createSignatureModal } from './ui/signature-modal.js';
15
+ import { createImageModal } from './ui/image-modal.js';
16
+ import { resolveFieldModalParent, resolvePreviewModalParent } from './ui/wire-modal-palette.js';
17
+ import { createSchemaEditorModal } from './design/schema-editor-modal.js';
18
+ import { configureSchemaItemsDesignerModal } from './design/schema-items-designer-modal.js';
19
+ import { createFieldPalette } from './design/field-palette.js';
20
+ import { createDesignShell } from './design/design-shell.js';
21
+ import { createPropertiesPanel } from './design/properties-panel.js';
22
+ import { wirePaletteBlockDrop } from './design/palette-block-drop.js';
23
+ import { createRichTextToolbar } from './ui/rich-text-toolbar.js';
24
+ import { createPreviewModal } from './ui/preview-modal.js';
25
+ import { createFieldMappingModal } from './ui/field-mapping-modal.js';
26
+ import { createRepeaterEditorModal } from './ui/repeater-editor-modal.js';
27
+ import {
28
+ extractRepeaterValueFromDocument,
29
+ getRepeaterFieldSchemas,
30
+ ensureRepeaterChildSchemas,
31
+ ensureRepeaterSchemasFromBlockValues,
32
+ sanitizeRepeaterChildSchemas,
33
+ normalizeRepeaterValue,
34
+ normalizeRepeaterSchema,
35
+ parseRepeaterTemplateImport,
36
+ applyRepeaterTemplateImport,
37
+ syncRepeaterTemplateFromFillDocument,
38
+ extractRepeaterFieldValueFromBlocks,
39
+ stripForeignKeysFromRepeaterValue,
40
+ buildRepeaterFillDocument,
41
+ repeaterHasTemplate,
42
+ } from './core/repeater-io.js';
43
+ import { createDocumentActions } from './ui/document-actions.js';
44
+ import { DEFAULT_FIELD_VALUE_STYLE_OPTIONS, DOCUMENT_TABLE_TEXT_STYLE } from './core/document-display-defaults.js';
45
+ import { cloneHistorySnapshot, createDocumentHistory } from './core/document-history.js';
46
+ import {
47
+ applyDocumentBodyTextStyle,
48
+ applyDocumentTextStyleCssVars,
49
+ refreshDocumentFieldTokenStyles,
50
+ resolvePageSetupFieldValueStyle,
51
+ resolvePageSetupTextStyle,
52
+ resolvePageSetupFieldHighlightStyle,
53
+ applyFieldHighlightCssVars,
54
+ applyPageFormatCssVars,
55
+ FILL_MODE_PAGE_SCALE,
56
+ migratePageSetup,
57
+ } from './core/page-setup-styles.js';
58
+ import { generateDocumentPdfBlob, isClientPdfAvailable } from './export/document-pdf.js';
59
+ import { buildPreviewHtmlBlob, buildPreviewHtmlDocument } from './export/preview-html-document.js';
60
+ import { resolvePreviewExportOptions } from './export/preview-export-options.js';
61
+ import { saveBlobToDisk } from './utils/save-blob.js';
62
+ import { buildExportFilename } from './utils/export-filename.js';
63
+ import { applyDesignMode } from './design/design-mode.js';
64
+ import { showNotification } from './ui/notification.js';
65
+ import {
66
+ applyFieldMapping as runFieldMapping,
67
+ previewFieldMapping as runFieldMappingPreview,
68
+ normalizeFieldMappingSpec,
69
+ syncFieldMappingSpecToSchema,
70
+ evaluateSectionVisibility,
71
+ registerFormulaFunction,
72
+ omitMappedFields,
73
+ createMappingRulesFromDrop,
74
+ } from '@docengine/engine';
75
+ import { applyMappingBadges } from './ui/field-mapping-badges.js';
76
+ import {
77
+ classifySourcePathDrop,
78
+ buildTableMappingRulesFromSourceDrop,
79
+ mergeMappingRulesIntoSpec,
80
+ } from './ui/source-path-canvas-drop.js';
81
+
82
+ import {
83
+ buildTemplateExport,
84
+ buildFieldsExport,
85
+ buildDocExport,
86
+ applyDocumentValues,
87
+ normalizeImportedDoc,
88
+ normalizeDocumentValues,
89
+ validateRequiredFields,
90
+ collectAllValues,
91
+ isFieldsExport,
92
+ materializeRepeatableSectionInstances,
93
+ } from './core/document-io.js';
94
+ import { resolveRepeatablePagePlan } from './core/field-io/sectioned-document-io.js';
95
+ import {
96
+ createDefaultSchema,
97
+ createDefaultBlockData,
98
+ ensureCellSchemas,
99
+ syncBlocksAfterSchemaChange,
100
+ applyFieldIdChange,
101
+ listColumnCellFieldIds,
102
+ parseCellFieldId,
103
+ syncColumnListSourceSettings,
104
+ syncTableColumnKeyChanges,
105
+ ensureSchemaForFieldProperties,
106
+ resolveSchemaDefaultValue,
107
+ } from './core/field-schemas.js';
108
+ import {
109
+ findFieldPlacement,
110
+ migrateFieldIds,
111
+ rebuildFieldIdsForSection,
112
+ resolveSectionName,
113
+ allocateUniqueSectionName,
114
+ collectUsedSectionNames,
115
+ DEFAULT_SECTION_NAME,
116
+ } from './core/field-id.js';
117
+ import { renameSectionInFormulas } from './core/formula-field-index.js';
118
+ import { SchemaRegistry } from './registry/schema-registry.js';
119
+ import { createCatalogProvider } from './catalog/catalog-provider.js';
120
+ import { attachRegistryToHolder, detachRegistryFromHolder } from './registry/registry-context.js';
121
+ import {
122
+ insertInlineField,
123
+ focusCaretAtEnd,
124
+ focusCaretAfter,
125
+ refreshFieldSchemaInDom,
126
+ refreshTableCellTokens,
127
+ pruneTableCellCaretAnchors,
128
+ insertTableAtCaret,
129
+ insertColumnsAtCaret,
130
+ insertColumnsAtPoint,
131
+ insertPaletteFieldAtPoint,
132
+ insertPaletteTableAtPoint,
133
+ wireTableRegions,
134
+ applyColumnWidthsToElement,
135
+ updateFieldToken,
136
+ findLiveFieldToken,
137
+ collectAllFieldValuesFromHolder,
138
+ resolveSelectedTextForFieldConversion,
139
+ syncFillComputedFields,
140
+ recoverImageValuesFromDom,
141
+ } from './fields/inline-fields.js';
142
+ import { saveSelection } from './fields/rich-text.js';
143
+ import { readTableRowsFromDom, refreshTableHeadersInDom, applyTableColumnWidthsToElement, addTableColumnToWrapper } from './fields/table-field.js';
144
+ import {
145
+ setFieldSelectionChangeCallback,
146
+ clearAllDesignTokenSelection,
147
+ } from './fields/field-selection.js';
148
+ import {
149
+ isEmptyFieldDisplayStyle,
150
+ normalizeFieldDisplayStyle,
151
+ refreshTableColumnStylesForFieldIds,
152
+ resolveFieldDisplayStyle,
153
+ resolveTableCellDisplayStyle,
154
+ } from './fields/field-display-style.js';
155
+ import { configureImageUpload } from './services/image-upload.js';
156
+ import { getFieldHandler, isInlineFieldType } from './fields/handlers/index.js';
157
+ import {
158
+ createEmptyDocumentSectionBlock,
159
+ ensureAtLeastOneDocumentSection,
160
+ } from './core/document-section-defaults.js';
161
+
162
+ const DEFAULT_EMPTY_DOCUMENT = {
163
+ time: Date.now(),
164
+ fieldSchemas: {},
165
+ blocks: [createEmptyDocumentSectionBlock()],
166
+ };
167
+
168
+ /** Types that change document structure and require an Editor.js remount. */
169
+ function isStructuralFieldType(type: any) {
170
+ return type === 'table' || type === 'child';
171
+ }
172
+
173
+ /**
174
+ * Inline↔inline type switches (text/choice/image/…) can refresh tokens in place.
175
+ * Table/child transitions still remount.
176
+ */
177
+ function canRefreshFieldTypeInDom(previousType: any, newType: any) {
178
+ if (!previousType || !newType || previousType === newType) return false;
179
+ if (isStructuralFieldType(previousType) || isStructuralFieldType(newType)) return false;
180
+ return isInlineFieldType(previousType) && isInlineFieldType(newType);
181
+ }
182
+
183
+ function migrateFieldSchemas(schemas: any) {
184
+ const next: any = { ...schemas };
185
+ for (const [id, schema] of Object.entries(next) as [string, any][]) {
186
+ if (schema?.type === 'group') delete next[id];
187
+ const migrated = schema?.type === 'repeater' ? { ...schema, type: 'child' } : schema;
188
+ if (migrated?.type === 'child') {
189
+ next[id] = normalizeRepeaterSchema(migrated);
190
+ }
191
+ }
192
+ return next;
193
+ }
194
+
195
+ function migrateBlocks(blocks: any,options: any = {}) {
196
+ const { visionTableFieldId = 'visionTable' } = options;
197
+
198
+ return blocks
199
+ .filter((block: any) => {
200
+ if (block.type === 'image') return false;
201
+ if (block.type === 'templateBlock' && block.data?.fieldType === 'group') return false;
202
+ return true;
203
+ })
204
+ .map((block: any) => {
205
+ if (block.type === 'templateBlock' && block.data?.fieldType === 'repeater') {
206
+ block = { ...block, data: { ...block.data, fieldType: 'child' } };
207
+ }
208
+ if (block.type === 'documentSection' && Array.isArray(block.data?.segments)) {
209
+ const segments = block.data.segments.map((seg: any) =>
210
+ seg?.type === 'repeater' ? { ...seg, type: 'child' } : seg,
211
+ );
212
+ block = { ...block, data: { ...block.data, segments } };
213
+ }
214
+ if (block.type !== 'visionTable') return block;
215
+
216
+ const fieldId = block.data?.fieldId ?? visionTableFieldId;
217
+ const cells: any = {};
218
+ for (const [key, val] of Object.entries(block.data?.cells ?? {})) {
219
+ if (key.startsWith(`${visionTableFieldId}_`) || key.startsWith(`${fieldId}_`)) {
220
+ cells[key] = val;
221
+ } else if (/^(od|os)_/.test(key)) {
222
+ cells[`${fieldId}_${key}`] = val;
223
+ } else {
224
+ cells[key] = val;
225
+ }
226
+ }
227
+
228
+ const tableSchema = options.defaultDocument?.fieldSchemas?.[fieldId]
229
+ ?? options.fieldSchemas?.[fieldId];
230
+ const schemaRows = Array.isArray(tableSchema?.rows)
231
+ ? tableSchema.rows.map((row: any) => ({
232
+ key: String(row.key),
233
+ label: String(row.label ?? ''),
234
+ }))
235
+ : [
236
+ { key: 'row1', label: '' },
237
+ { key: 'row2', label: '' },
238
+ ];
239
+
240
+ return {
241
+ type: 'documentSection',
242
+ data: {
243
+ name: tableSchema?.name ?? 'Visual acuity',
244
+ label: tableSchema?.label ?? tableSchema?.name ?? 'Visual acuity',
245
+ segments: [
246
+ {
247
+ type: 'table',
248
+ id: fieldId,
249
+ rows: schemaRows,
250
+ },
251
+ ],
252
+ fieldValues: cells,
253
+ },
254
+ };
255
+ });
256
+ }
257
+
258
+ function normalizeRepeaterValuesInBlocks(blocks: any,fieldSchemas: any) {
259
+ return (blocks ?? []).map((block: any) => {
260
+ if (block.type !== 'documentSection' || !block.data?.fieldValues) return block;
261
+
262
+ const fieldValues = { ...block.data.fieldValues };
263
+ for (const [fieldId, value] of Object.entries(fieldValues)) {
264
+ const schema = fieldSchemas?.[fieldId];
265
+ if (schema?.type === 'child') {
266
+ fieldValues[fieldId] = normalizeRepeaterValue(value, schema);
267
+ }
268
+ }
269
+
270
+ return {
271
+ ...block,
272
+ data: {
273
+ ...block.data,
274
+ fieldValues,
275
+ },
276
+ };
277
+ });
278
+ }
279
+
280
+ function normalizeDocument(data: any,options: any = {}) {
281
+ const fallback = options.defaultDocument ?? DEFAULT_EMPTY_DOCUMENT;
282
+
283
+ let result: any;
284
+ if (data?.blocks) {
285
+ result = {
286
+ time: data.time ?? Date.now(),
287
+ fieldSchemas: migrateFieldSchemas(data.fieldSchemas ?? { ...fallback.fieldSchemas }),
288
+ blocks: migrateBlocks(data.blocks, {
289
+ ...options,
290
+ fieldSchemas: migrateFieldSchemas(data.fieldSchemas ?? { ...fallback.fieldSchemas }),
291
+ }),
292
+ };
293
+ } else {
294
+ result = {
295
+ time: fallback.time ?? Date.now(),
296
+ fieldSchemas: { ...fallback.fieldSchemas },
297
+ blocks: migrateBlocks(fallback.blocks ?? [], options),
298
+ };
299
+ }
300
+
301
+ const migrated = migrateFieldIds(result.blocks, result.fieldSchemas);
302
+ let fieldSchemas = { ...migrated.fieldSchemas };
303
+ for (const [fieldId, schema] of Object.entries(fieldSchemas)) {
304
+ if (schema?.type === 'child') {
305
+ fieldSchemas[fieldId] = sanitizeRepeaterChildSchemas(schema, fieldSchemas, migrated.blocks);
306
+ }
307
+ }
308
+ fieldSchemas = ensureRepeaterSchemasFromBlockValues(fieldSchemas, migrated.blocks);
309
+ const resultDoc = {
310
+ ...result,
311
+ fieldSchemas,
312
+ blocks: ensureAtLeastOneDocumentSection(
313
+ normalizeRepeaterValuesInBlocks(migrated.blocks, fieldSchemas),
314
+ ),
315
+ };
316
+ if (data?.pageSetup && typeof data.pageSetup === 'object') {
317
+ resultDoc.pageSetup = JSON.parse(JSON.stringify(data.pageSetup));
318
+ }
319
+ if (data?.fieldMapping && typeof data.fieldMapping === 'object') {
320
+ resultDoc.fieldMapping = JSON.parse(JSON.stringify(data.fieldMapping));
321
+ }
322
+ return resultDoc;
323
+ }
324
+
325
+ function resolveHolder(holder: any) {
326
+ if (!holder) throw new Error('createEditor: holder is required');
327
+ if (typeof holder === 'string') {
328
+ const el = document.querySelector(holder);
329
+ if (!el) throw new Error(`createEditor: holder not found: ${holder}`);
330
+ return el;
331
+ }
332
+ return holder;
333
+ }
334
+
335
+ function resolveElement(target: any) {
336
+ if (!target) return null;
337
+ if (typeof target === 'string') return document.querySelector(target);
338
+ return target;
339
+ }
340
+
341
+ /**
342
+ * Mount a UI element relative to the editor holder.
343
+ * - paletteAfter / toolbarBefore: insert immediately after/before a sibling anchor
344
+ * - paletteParent with holder inside parent: insertBefore(holder)
345
+ * - paletteParent without holder as child: insert after parent (e.g. after page header)
346
+ * - default: insert before holder in holder.parentElement
347
+ */
348
+ function mountAdjacentUi(element: any,holder: any,parentOption: any,anchorOption: any,mode: any = 'before-holder') {
349
+ const anchor = resolveElement(anchorOption);
350
+
351
+ if (anchor) {
352
+ if (mode === 'before-holder') {
353
+ anchor.after(element);
354
+ } else {
355
+ anchor.before(element);
356
+ }
357
+ return;
358
+ }
359
+
360
+ const parent = resolveElement(parentOption) ?? holder.parentElement;
361
+ if (parent?.contains(holder)) {
362
+ parent.insertBefore(element, holder);
363
+ return;
364
+ }
365
+
366
+ if (parent) {
367
+ parent.after(element);
368
+ return;
369
+ }
370
+
371
+ holder.parentElement?.insertBefore(element, holder);
372
+ }
373
+
374
+ function mountInContainer(element: any,containerOption: any) {
375
+ const container = resolveElement(containerOption);
376
+ if (container) {
377
+ container.appendChild(element);
378
+ return true;
379
+ }
380
+ return false;
381
+ }
382
+
383
+ /**
384
+ * Mount palette + format toolbar wrapper relative to holder or host chrome container.
385
+ */
386
+ function mountTopChrome(topChrome: any,holder: any,ui: any) {
387
+ const chromeParent = resolveElement(ui.chromeParent ?? ui.paletteParent);
388
+ if (chromeParent) {
389
+ chromeParent.appendChild(topChrome);
390
+ return;
391
+ }
392
+
393
+ const anchorAfter = resolveElement(ui.paletteAfter);
394
+ if (anchorAfter) {
395
+ anchorAfter.after(topChrome);
396
+ return;
397
+ }
398
+
399
+ const anchorBefore = resolveElement(ui.toolbarBefore);
400
+ if (anchorBefore) {
401
+ anchorBefore.before(topChrome);
402
+ return;
403
+ }
404
+
405
+ const toolbarParent = resolveElement(ui.toolbarParent);
406
+ if (toolbarParent?.contains(holder)) {
407
+ toolbarParent.insertBefore(topChrome, holder);
408
+ return;
409
+ }
410
+
411
+ holder.parentElement?.insertBefore(topChrome, holder);
412
+ }
413
+
414
+ /**
415
+ * @param {object} options
416
+ * @returns {import('./types.js').DocEditorInstance}
417
+ */
418
+ export function createEditor(options: any = {}) {
419
+ const holder = resolveHolder(options.holder);
420
+ if (!holder.id) {
421
+ holder.id = `doc-editor-${Date.now().toString(36)}`;
422
+ }
423
+
424
+ let designMode = !!options.designMode;
425
+ let showFieldsInFillMode = options.ui?.showFieldsInFillMode !== false;
426
+ let editor: any = null;
427
+ /** Serializes setDesignMode so concurrent reinits don't call EditorJS.destroy() twice. */
428
+ let setDesignModeInFlight: Promise<void> | null = null;
429
+ let destroyed = false;
430
+ let lastFocusedEditable: any = null;
431
+ let historyTimer: ReturnType<typeof setTimeout> | null = null;
432
+ let historyBusy = false;
433
+ const documentHistory = createDocumentHistory({ maxDepth: 50 });
434
+ const fieldValueStyle = {
435
+ ...DEFAULT_FIELD_VALUE_STYLE_OPTIONS,
436
+ ...options.fieldValueStyle,
437
+ default: {
438
+ ...DEFAULT_FIELD_VALUE_STYLE_OPTIONS.default,
439
+ ...options.fieldValueStyle?.default,
440
+ },
441
+ };
442
+
443
+ function getFillModeHighlightContext() {
444
+ return {
445
+ fillModeFieldHighlight: !designMode && showFieldsInFillMode && !options.mappingMode,
446
+ mappingMode: !!options.mappingMode,
447
+ };
448
+ }
449
+
450
+ function syncStylesFromPageSetup() {
451
+ const resolved = resolvePageSetupFieldValueStyle(documentPageSetup, options.fieldValueStyle);
452
+ Object.assign(fieldValueStyle.default, resolved.default);
453
+
454
+ const textStyle = resolvePageSetupTextStyle(documentPageSetup);
455
+ // Scope Default text style to the template canvas only — never Interface chrome.
456
+ applyDocumentTextStyleCssVars(holder, textStyle);
457
+ for (const body of holder.querySelectorAll('.document-section__body')) {
458
+ applyDocumentBodyTextStyle(body, textStyle);
459
+ }
460
+
461
+ syncFieldHighlightStyles();
462
+ syncPageFormatLayout();
463
+ const highlightContext = getFillModeHighlightContext();
464
+ refreshDocumentFieldTokenStyles(holder, fieldValueStyle, highlightContext);
465
+ refreshTableCellTokens(holder, {
466
+ getRegistry: () => registry,
467
+ fieldValueStyle,
468
+ ...highlightContext,
469
+ });
470
+ refreshTableHeadersInDom(holder, {
471
+ getRegistry: () => registry,
472
+ fieldValueStyle,
473
+ getDocumentTextStyle: () => resolvePageSetupTextStyle(documentPageSetup),
474
+ });
475
+ }
476
+
477
+ /** Editor window sized from Page Setup format/orientation (+10%), fill and design. */
478
+ function syncPageFormatLayout() {
479
+ const chromeHosts = collectFillPageChromeHosts();
480
+
481
+ applyPageFormatCssVars(holder, documentPageSetup, {
482
+ scale: FILL_MODE_PAGE_SCALE,
483
+ fillPage: true,
484
+ });
485
+ for (const host of chromeHosts) {
486
+ applyPageFormatCssVars(host, documentPageSetup, {
487
+ scale: FILL_MODE_PAGE_SCALE,
488
+ fillPage: false,
489
+ });
490
+ if (host.classList.contains('doc-shell')) {
491
+ host.classList.add('doc-shell--fill-page');
492
+ }
493
+ if (host.classList.contains('page')) {
494
+ host.classList.add('page--fill-page');
495
+ }
496
+ if (host.classList.contains('design-panel__editor-scroll')) {
497
+ host.classList.add('design-panel__editor-scroll--fill-page');
498
+ }
499
+ }
500
+ }
501
+
502
+ function collectFillPageChromeHosts() {
503
+ /** @type {HTMLElement[]} */
504
+ const hosts: HTMLElement[] = [];
505
+ const seen = new Set<HTMLElement>();
506
+
507
+ const add = (el: Element | null | undefined) => {
508
+ if (!(el instanceof HTMLElement) || el === holder || seen.has(el)) return;
509
+ seen.add(el);
510
+ hosts.push(el);
511
+ };
512
+
513
+ add(holder.closest?.('.doc-shell'));
514
+ add(holder.closest?.('.page'));
515
+ add(designEditorScroll);
516
+ add(holder.closest?.('.design-panel__editor-scroll'));
517
+
518
+ const modalParent = resolveFieldModalParent(holder);
519
+ if (modalParent && modalParent !== document.body) {
520
+ add(modalParent);
521
+ }
522
+
523
+ return hosts;
524
+ }
525
+
526
+ function resolveFieldHighlightStyle() {
527
+ return resolvePageSetupFieldHighlightStyle(documentPageSetup, options.ui?.fieldHighlight);
528
+ }
529
+
530
+ function syncFieldHighlightStyles() {
531
+ const style = resolveFieldHighlightStyle();
532
+ applyFieldHighlightCssVars(holder, style);
533
+ // Field dialogs mount on .doc-shell (sibling of holder) — mirror vars so
534
+ // dialog chrome can use --me-field-fill-color (empty-field style).
535
+ const modalParent = resolveFieldModalParent(holder);
536
+ if (modalParent && modalParent !== holder) {
537
+ applyFieldHighlightCssVars(modalParent, style);
538
+ }
539
+ }
540
+ const ui = options.ui ?? {};
541
+ const useDesignPanels = ui.designLayout === 'panels';
542
+
543
+ let designShell: any = null;
544
+ let propertiesPanel: any = null;
545
+ let selectedSectionBlockIndex = -1;
546
+ let selectedColumnsEl: any = null;
547
+ let selectedTableEl: any = null;
548
+ let designToolbarWrap: any = null;
549
+ let designEditorScroll: any = null;
550
+ /** @type {import('./types.d.ts').TemplatePageSetup} */
551
+ let documentPageSetup: any = {};
552
+ /** @type {import('./types.d.ts').FieldMappingSpec | null} */
553
+ let documentFieldMapping: any = null;
554
+ /** Set once the field palette is created (vertical Source / Database tab). */
555
+ let refreshDatabaseSourceTree: (() => void) | null = null;
556
+ const getFormTextStyle = () => resolvePageSetupTextStyle(documentPageSetup);
557
+ /** @type {Record<string, import('./types.d.ts').DocumentSectionValues> | null} */
558
+ let loadedDocumentSections: any = null;
559
+
560
+ const catalogProvider = createCatalogProvider(options.catalogs ?? {});
561
+ const registry = new SchemaRegistry(catalogProvider);
562
+ attachRegistryToHolder(holder, registry);
563
+
564
+ if (useDesignPanels) {
565
+ designShell = createDesignShell(holder);
566
+ if (designMode) designShell.show();
567
+ else designShell.hide();
568
+ }
569
+
570
+ function syncShowFieldsHighlight() {
571
+ holder.classList.toggle(
572
+ 'editor-holder--show-fields',
573
+ !designMode && showFieldsInFillMode,
574
+ );
575
+ syncFieldHighlightStyles();
576
+ if (!designMode && showFieldsInFillMode) {
577
+ const highlightContext = getFillModeHighlightContext();
578
+ refreshDocumentFieldTokenStyles(holder, fieldValueStyle, highlightContext);
579
+ refreshTableCellTokens(holder, {
580
+ getRegistry: () => registry,
581
+ fieldValueStyle,
582
+ ...highlightContext,
583
+ });
584
+ }
585
+ }
586
+
587
+ function scheduleEditorStylesSync() {
588
+ const current = editor;
589
+ if (!current) return;
590
+ void current.isReady.then(() => {
591
+ if (destroyed || editor !== current) return;
592
+ syncPageFormatLayout();
593
+ syncShowFieldsHighlight();
594
+ });
595
+ }
596
+
597
+ function syncDesignChromeVisibility() {
598
+ if (useDesignPanels) {
599
+ if (designMode) {
600
+ designShell?.show();
601
+ } else {
602
+ designShell?.hide();
603
+ propertiesPanel?.showEmpty();
604
+ selectedSectionBlockIndex = -1;
605
+ clearStructureSelection();
606
+ updateSectionSelectionHighlight();
607
+ }
608
+ if (designToolbarWrap) designToolbarWrap.hidden = !designMode;
609
+ }
610
+ // Format toolbar is design-only; Preview lives in document actions / host chrome.
611
+ if (richTextToolbar?.element) richTextToolbar.element.hidden = !designMode;
612
+ syncShowFieldsHighlight();
613
+ }
614
+
615
+ if (options.imageUpload) {
616
+ configureImageUpload(options.imageUpload);
617
+ }
618
+
619
+ if (Array.isArray(options.formulaFunctions)) {
620
+ for (const def of options.formulaFunctions) {
621
+ if (def) registerFormulaFunction(def);
622
+ }
623
+ }
624
+
625
+ const fieldModalParent = resolveFieldModalParent(holder);
626
+ const previewModalParent = resolvePreviewModalParent(holder);
627
+ const treeModal = createTreeModal({ parent: fieldModalParent });
628
+ const listModal = createListModal({ parent: fieldModalParent });
629
+ const textModal = createTextModal({ parent: fieldModalParent });
630
+ const htmlTextModal = createHtmlTextModal({ parent: fieldModalParent });
631
+ const integerModal = createIntegerModal({ parent: fieldModalParent });
632
+ const signatureModal = createSignatureModal({ parent: fieldModalParent });
633
+ const imageModal = createImageModal({ parent: fieldModalParent });
634
+ const repeaterEditorModal = createRepeaterEditorModal({
635
+ getEditorOptions: () => options,
636
+ });
637
+ const schemaEditor = createSchemaEditorModal({
638
+ getRegistry: () => registry,
639
+ onRepeaterTemplateChange: (fieldId: any,schema: any) => applyRepeaterSchemaUpdate(fieldId, schema),
640
+ getRemoteListCollections: options.remoteListCollections ?? null,
641
+ getRemoteListLabelFields: options.remoteListLabelFields ?? null,
642
+ });
643
+
644
+ configureSchemaItemsDesignerModal();
645
+
646
+ const previewModal = createPreviewModal({
647
+ getFieldValueStyle: () => fieldValueStyle,
648
+ defaultPdfFilename: ui.pdfFilename ?? 'document.pdf',
649
+ pdfTitle: ui.pdfTitle,
650
+ getPageSetup: () => documentPageSetup,
651
+ getTextStyle: getFormTextStyle,
652
+ generatePdfBlob: options.generatePdfBlob ?? null,
653
+ pdfAvailable: options.pdfAvailable,
654
+ embedPdfInIframe: ui.embedPdfInIframe !== false,
655
+ parent: previewModalParent,
656
+ onOpenChange: (open: boolean) => {
657
+ options.onPreviewStateChange?.(!!open);
658
+ },
659
+ onShareDocument:
660
+ typeof options.onShareDocument === 'function' ? options.onShareDocument : null,
661
+ });
662
+ const fieldMappingModal = options.mappingMode
663
+ ? null
664
+ : createFieldMappingModal({
665
+ getTemplate: () => ({
666
+ blocks: registry.getBlocks(),
667
+ fieldSchemas: registry.getFieldSchemas(),
668
+ }),
669
+ onSave: (spec: any) => {
670
+ documentFieldMapping = spec;
671
+ refreshDatabaseSourceTree?.();
672
+ refreshDesignMappingBadges();
673
+ },
674
+ });
675
+ const richTextToolbar = createRichTextToolbar();
676
+
677
+ /** Depth of open nested field dialogs — keeps host Escape blockers accurate when stacked. */
678
+ let nestedModalDepth = 0;
679
+ function notifyNestedModal(open: boolean) {
680
+ if (open) nestedModalDepth += 1;
681
+ else nestedModalDepth = Math.max(0, nestedModalDepth - 1);
682
+ options.onNestedModalStateChange?.(nestedModalDepth > 0);
683
+ }
684
+ function guardNestedModal<T>(promise: Promise<T>): Promise<T> {
685
+ notifyNestedModal(true);
686
+ return Promise.resolve(promise).then(
687
+ (result) => {
688
+ // Resolved (OK / Clear) — not Close/Escape/cancel.
689
+ options.onFieldPickerApplied?.();
690
+ return result;
691
+ },
692
+ (err) => {
693
+ throw err;
694
+ },
695
+ ).finally(() => {
696
+ notifyNestedModal(false);
697
+ });
698
+ }
699
+
700
+ const openTree =
701
+ options.pickers?.openTreePicker ??
702
+ ((opts: any) => treeModal.open({ ...opts, textStyle: getFormTextStyle() }));
703
+ const openList =
704
+ options.pickers?.openListPicker ??
705
+ ((opts: any) => listModal.open({ ...opts, textStyle: getFormTextStyle() }));
706
+ const openText =
707
+ options.pickers?.openTextPicker ??
708
+ ((opts: any) => textModal.open({ ...opts, textStyle: getFormTextStyle() }));
709
+ const openHtmlText =
710
+ options.pickers?.openHtmlTextPicker ??
711
+ ((opts: any) => htmlTextModal.open({ ...opts, textStyle: getFormTextStyle() }));
712
+ const openInteger =
713
+ options.pickers?.openIntegerPicker ?? ((opts: any) => integerModal.open(opts));
714
+ const openSignature =
715
+ options.pickers?.openSignaturePicker ?? ((opts: any) => signatureModal.open(opts));
716
+ const openImage =
717
+ options.pickers?.openImagePicker ?? ((opts: any) => imageModal.open(opts));
718
+ const openDate = options.pickers?.openDatePicker;
719
+
720
+ const pickerCallbacks = {
721
+ ...(options.pickers ?? {}),
722
+ openTreePicker: (opts: any) => guardNestedModal(Promise.resolve(openTree(opts))),
723
+ openListPicker: (opts: any) => guardNestedModal(Promise.resolve(openList(opts))),
724
+ openTextPicker: (opts: any) => guardNestedModal(Promise.resolve(openText(opts))),
725
+ openHtmlTextPicker: (opts: any) => guardNestedModal(Promise.resolve(openHtmlText(opts))),
726
+ openIntegerPicker: (opts: any) => guardNestedModal(Promise.resolve(openInteger(opts))),
727
+ openSignaturePicker: (opts: any) => guardNestedModal(Promise.resolve(openSignature(opts))),
728
+ openImagePicker: (opts: any) => guardNestedModal(Promise.resolve(openImage(opts))),
729
+ openDatePicker: openDate
730
+ ? (opts: any) =>
731
+ guardNestedModal(Promise.resolve(openDate({ ...opts, parent: fieldModalParent })))
732
+ : undefined,
733
+ };
734
+
735
+ function getAllDocumentEditables() {
736
+ return [...holder.querySelectorAll('.document-section__body')];
737
+ }
738
+
739
+ function resolveTargetEditable() {
740
+ if (lastFocusedEditable?.isConnected) return lastFocusedEditable;
741
+
742
+ if (editor) {
743
+ const currentIndex = editor.blocks.getCurrentBlockIndex();
744
+ if (currentIndex >= 0) {
745
+ const blocks = holder.querySelectorAll('.ce-block');
746
+ const editable = blocks[currentIndex]?.querySelector('.document-section__body');
747
+ if (editable) return editable;
748
+ }
749
+ }
750
+
751
+ const all = getAllDocumentEditables();
752
+ return all[all.length - 1] ?? null;
753
+ }
754
+
755
+ async function ensureDocumentSectionAtEnd() {
756
+ await editor.isReady;
757
+ let editable = resolveTargetEditable();
758
+ if (!editable) {
759
+ const count = editor.blocks.getBlocksCount();
760
+ await editor.blocks.insert('documentSection', createUniqueSectionData(), {}, count);
761
+ await editor.isReady;
762
+ editable = getAllDocumentEditables().at(-1) ?? null;
763
+ }
764
+
765
+ if (editable) {
766
+ lastFocusedEditable = editable;
767
+ focusCaretAtEnd(editable);
768
+ }
769
+
770
+ return editable;
771
+ }
772
+
773
+ function applyLiveTableColumnWidths(tableId: any, columns: any) {
774
+ if (!tableId || !Array.isArray(columns)) return;
775
+ const schema = registry.getFieldSchemas()?.[tableId];
776
+ if (!schema || schema.type !== 'table') return;
777
+ registry.updateFieldSchema(tableId, { ...schema, columns });
778
+ applyTableColumnWidthsToElement(findLiveTableEl(tableId), columns);
779
+ options.onSchemaChange?.(registry.getFieldSchemas());
780
+ }
781
+
782
+ function syncTableWidthsToProperties(tableId: any, columns: any) {
783
+ if (!propertiesPanel || !tableId) return;
784
+ propertiesPanel.cancelPersist?.();
785
+ propertiesPanel.syncTableColumnWidths?.(tableId, columns);
786
+ }
787
+
788
+ function handleTableColumnWidthsChange(tableId: any, columns: any) {
789
+ // Same path as typing in Properties — splitter updates schema already, but
790
+ // must re-apply col + header widths or the canvas can stay equal-width.
791
+ applyTableColumnWidthsToElement(findLiveTableEl(tableId), columns);
792
+ options.onSchemaChange?.(registry.getFieldSchemas());
793
+ syncTableWidthsToProperties(tableId, columns);
794
+ }
795
+
796
+ function handleTableColumnWidthsPreview(tableId: any, columns: any) {
797
+ syncTableWidthsToProperties(tableId, columns);
798
+ }
799
+
800
+ function handleTableColumnResizeStart(tableId: any) {
801
+ const columns = propertiesPanel?.commitLiveTableColumnWidths?.(tableId);
802
+ if (columns) applyLiveTableColumnWidths(tableId, columns);
803
+ propertiesPanel?.cancelPersist?.();
804
+ }
805
+
806
+ function isTableWidthOnlyChange(prev: any, next: any) {
807
+ if (!prev || prev.type !== 'table' || next?.type !== 'table') return false;
808
+ if (!!prev.hideHeader !== !!next.hideHeader) return false;
809
+ if (!!prev.hideBorders !== !!next.hideBorders) return false;
810
+ if (!!prev.allowAddRows !== !!next.allowAddRows) return false;
811
+ if (String(prev.name ?? prev.label ?? '') !== String(next.name ?? next.label ?? '')) return false;
812
+ if (String(prev.label ?? '') !== String(next.label ?? '')) return false;
813
+ const prevCols = prev.columns ?? [];
814
+ const nextCols = next.columns ?? [];
815
+ if (prevCols.length !== nextCols.length) return false;
816
+ return prevCols.every((col: any, index: any) => (
817
+ col.key === nextCols[index].key &&
818
+ col.label === nextCols[index].label &&
819
+ (col.name ?? col.label) === (nextCols[index].name ?? nextCols[index].label)
820
+ ));
821
+ }
822
+
823
+ function refreshDesignMappingBadges() {
824
+ if (!holder || options.mappingMode) return;
825
+ applyMappingBadges(holder, documentFieldMapping?.rules ?? [], {
826
+ getRegistry: () => registry,
827
+ fieldValueStyle,
828
+ });
829
+ }
830
+
831
+ /**
832
+ * Keep fieldMapping.rules section/field/child names (and fieldIds) aligned with
833
+ * the live template after renames.
834
+ */
835
+ function syncDocumentFieldMappingNames(
836
+ blocks: any = registry.getBlocks() ?? [],
837
+ fieldSchemas: any = registry.getFieldSchemas(),
838
+ fieldIdRenames: Record<string, string> | null = null,
839
+ ) {
840
+ if (!documentFieldMapping?.rules?.length) return;
841
+ documentFieldMapping = syncFieldMappingSpecToSchema(
842
+ documentFieldMapping,
843
+ blocks,
844
+ fieldSchemas,
845
+ fieldIdRenames ? { fieldIdRenames } : undefined,
846
+ );
847
+ refreshDesignMappingBadges();
848
+ }
849
+
850
+ function commitMappingRules(rules: any[]) {
851
+ if (!rules?.length) return;
852
+ documentFieldMapping = normalizeFieldMappingSpec(
853
+ mergeMappingRulesIntoSpec(documentFieldMapping, rules),
854
+ );
855
+ refreshDesignMappingBadges();
856
+ scheduleHistoryRecord();
857
+ }
858
+
859
+ function getInlineFieldOptions() {
860
+ return {
861
+ getRegistry: () => registry,
862
+ fieldValueStyle,
863
+ designMode,
864
+ designPropertiesPanel: useDesignPanels && designMode,
865
+ openEditor: !(useDesignPanels && designMode),
866
+ onEditSchema: handleEditSchema,
867
+ onDeleteField: (fieldId: any,token: any) => {
868
+ token?.remove();
869
+ handleDeleteSchema(fieldId);
870
+ },
871
+ onPaletteDrop: handlePaletteDrop,
872
+ onSourcePathCanvasDrop: handleSourcePathCanvasDrop,
873
+ onSchemaChange: (schemas: any) => options.onSchemaChange?.(schemas),
874
+ onTableColumnWidthsChange: handleTableColumnWidthsChange,
875
+ onTableColumnWidthsPreview: handleTableColumnWidthsPreview,
876
+ onTableColumnResizeStart: handleTableColumnResizeStart,
877
+ onTableColumnsChange: (tableId: any, columns: any) => {
878
+ propertiesPanel?.cancelPersist?.();
879
+ propertiesPanel?.syncTableColumns?.(tableId, columns);
880
+ options.onSchemaChange?.(registry.getFieldSchemas());
881
+ scheduleHistoryRecord();
882
+ },
883
+ onColumnsWidthsChange: (columnsEl: any) => {
884
+ // Keep the columns block selected in the properties panel after a splitter drag.
885
+ if (columnsEl?.isConnected) {
886
+ selectColumnsEl(columnsEl);
887
+ }
888
+ },
889
+ };
890
+ }
891
+
892
+ function syncSectionDataToRegistry(sectionData: any, sectionEl: any = null) {
893
+ if (!sectionData) return;
894
+ const blocks = [...(registry.getBlocks() ?? [])];
895
+ let index = -1;
896
+
897
+ // Prefer DOM block index so duplicate section names (legacy Untitled…) do not
898
+ // overwrite the wrong registry entry.
899
+ if (sectionEl?.closest) {
900
+ const ceBlock = sectionEl.closest('.ce-block');
901
+ if (ceBlock) {
902
+ const allBlocks = [...holder.querySelectorAll('.ce-block')];
903
+ index = allBlocks.indexOf(ceBlock);
904
+ }
905
+ }
906
+
907
+ if (index < 0 || blocks[index]?.type !== 'documentSection') {
908
+ const sectionName = resolveSectionName(sectionData);
909
+ index = blocks.findIndex(
910
+ (block: any) =>
911
+ block.type === 'documentSection' && resolveSectionName(block.data ?? {}) === sectionName,
912
+ );
913
+ }
914
+
915
+ if (index < 0 || blocks[index]?.type !== 'documentSection') return;
916
+ blocks[index] = {
917
+ ...blocks[index],
918
+ data: {
919
+ ...blocks[index].data,
920
+ ...sectionData,
921
+ },
922
+ };
923
+ registry.setBlocks(blocks);
924
+ scheduleHistoryRecord();
925
+ }
926
+
927
+ function collectLiveSectionNames() {
928
+ const used = collectUsedSectionNames(registry.getBlocks() ?? []);
929
+ holder.querySelectorAll?.('.document-section[data-section-name]')?.forEach((el: Element) => {
930
+ const name = el.getAttribute('data-section-name');
931
+ if (name) used.add(name);
932
+ });
933
+ return used;
934
+ }
935
+
936
+ /** Names allocated for in-flight inserts before registry/DOM catch up. */
937
+ const pendingSectionNames = new Set<string>();
938
+
939
+ function allocateSectionName() {
940
+ const used = collectLiveSectionNames();
941
+ for (const name of pendingSectionNames) used.add(name);
942
+ const next = allocateUniqueSectionName(used, DEFAULT_SECTION_NAME);
943
+ pendingSectionNames.add(next);
944
+ queueMicrotask(() => {
945
+ const live = collectLiveSectionNames();
946
+ for (const name of [...pendingSectionNames]) {
947
+ if (live.has(name)) pendingSectionNames.delete(name);
948
+ }
949
+ });
950
+ return next;
951
+ }
952
+
953
+ function createUniqueSectionData(extra: Record<string, unknown> = {}) {
954
+ const name = allocateSectionName();
955
+ return {
956
+ name,
957
+ label: '',
958
+ segments: [],
959
+ fieldValues: {},
960
+ ...extra,
961
+ };
962
+ }
963
+
964
+ function getHistorySnapshot() {
965
+ const snap: any = {
966
+ fieldSchemas: registry.getFieldSchemas() ?? {},
967
+ blocks: registry.getBlocks() ?? [],
968
+ };
969
+ if (Object.keys(documentPageSetup).length > 0) {
970
+ snap.pageSetup = documentPageSetup;
971
+ }
972
+ if (documentFieldMapping) {
973
+ snap.fieldMapping = documentFieldMapping;
974
+ }
975
+ return cloneHistorySnapshot(snap);
976
+ }
977
+
978
+ function scheduleHistoryRecord(immediate = false) {
979
+ if (destroyed || historyBusy || documentHistory.isSuspended()) return;
980
+
981
+ const run = () => {
982
+ historyTimer = null;
983
+ if (destroyed || historyBusy || documentHistory.isSuspended()) return;
984
+ documentHistory.record(getHistorySnapshot());
985
+ };
986
+
987
+ if (immediate) {
988
+ if (historyTimer) {
989
+ clearTimeout(historyTimer);
990
+ historyTimer = null;
991
+ }
992
+ run();
993
+ return;
994
+ }
995
+
996
+ if (historyTimer) clearTimeout(historyTimer);
997
+ historyTimer = setTimeout(run, 400);
998
+ }
999
+
1000
+ function flushHistoryRecord() {
1001
+ if (historyTimer) {
1002
+ clearTimeout(historyTimer);
1003
+ historyTimer = null;
1004
+ if (!destroyed && !historyBusy && !documentHistory.isSuspended()) {
1005
+ documentHistory.record(getHistorySnapshot());
1006
+ }
1007
+ }
1008
+ }
1009
+
1010
+ function canSoftRestoreHistory(snapshot: any) {
1011
+ if (!editor || !snapshot || destroyed) return false;
1012
+ const snapBlocks = snapshot.blocks ?? [];
1013
+ const liveBlocks = listEditorBlocks();
1014
+ if (liveBlocks.length !== snapBlocks.length) return false;
1015
+
1016
+ for (let i = 0; i < snapBlocks.length; i += 1) {
1017
+ const snapBlock = snapBlocks[i];
1018
+ if (!snapBlock || snapBlock.type !== 'documentSection') return false;
1019
+ const section = liveBlocks[i]?.querySelector?.('.document-section') as any;
1020
+ if (!section?.__documentSectionTool?.applyHistoryData) return false;
1021
+ }
1022
+ return true;
1023
+ }
1024
+
1025
+ function softRestoreHistory(snapshot: any) {
1026
+ const normalized = normalizeDocument(snapshot, {
1027
+ defaultDocument: options.defaultDocument,
1028
+ visionTableFieldId: options.visionTableFieldId,
1029
+ });
1030
+ registry.setFieldSchemas({ ...normalized.fieldSchemas });
1031
+ registry.setBlocks(normalized.blocks ?? []);
1032
+ options.onSchemaChange?.(registry.getFieldSchemas());
1033
+
1034
+ documentPageSetup = snapshot.pageSetup
1035
+ ? migratePageSetup(JSON.parse(JSON.stringify(snapshot.pageSetup)))
1036
+ : {};
1037
+ documentFieldMapping = snapshot.fieldMapping
1038
+ ? normalizeFieldMappingSpec(snapshot.fieldMapping)
1039
+ : null;
1040
+ refreshDatabaseSourceTree?.();
1041
+ refreshDesignMappingBadges();
1042
+ syncStylesFromPageSetup();
1043
+
1044
+ const liveBlocks = listEditorBlocks();
1045
+ const snapBlocks = normalized.blocks ?? [];
1046
+ for (let i = 0; i < snapBlocks.length; i += 1) {
1047
+ const block = snapBlocks[i];
1048
+ if (block?.type !== 'documentSection') continue;
1049
+ const section = liveBlocks[i]?.querySelector?.('.document-section') as any;
1050
+ section?.__documentSectionTool?.applyHistoryData?.(block.data ?? {});
1051
+ }
1052
+
1053
+ refreshSectionVisibility();
1054
+ }
1055
+
1056
+ async function restoreHistorySnapshot(snapshot: any, focusHint: any = null) {
1057
+ if (!snapshot || historyBusy || destroyed) return false;
1058
+ historyBusy = true;
1059
+ const resume = documentHistory.suspend();
1060
+ try {
1061
+ if (historyTimer) {
1062
+ clearTimeout(historyTimer);
1063
+ historyTimer = null;
1064
+ }
1065
+ if (canSoftRestoreHistory(snapshot)) {
1066
+ softRestoreHistory(snapshot);
1067
+ } else {
1068
+ initEditor(snapshot);
1069
+ if (editor) await editor.isReady;
1070
+ }
1071
+ if (useDesignPanels && designMode && propertiesPanel) {
1072
+ syncPropertiesPanel();
1073
+ }
1074
+ options.onChange?.(await getDocument());
1075
+ restoreEditorFocusAfterHistory(focusHint);
1076
+ return true;
1077
+ } catch {
1078
+ return false;
1079
+ } finally {
1080
+ resume();
1081
+ historyBusy = false;
1082
+ }
1083
+ }
1084
+
1085
+ function captureHistoryFocusHint() {
1086
+ const active = document.activeElement;
1087
+ const editable =
1088
+ (active?.closest?.('.document-section__body') as HTMLElement | null) ??
1089
+ (lastFocusedEditable?.isConnected ? lastFocusedEditable : null) ??
1090
+ null;
1091
+ if (!editable || !holder.contains(editable)) {
1092
+ return { sectionIndex: 0 };
1093
+ }
1094
+ const sections = [...holder.querySelectorAll('.document-section__body')];
1095
+ const sectionIndex = Math.max(0, sections.indexOf(editable));
1096
+ const sectionName =
1097
+ editable.closest?.('.document-section')?.getAttribute?.('data-section-name') ?? null;
1098
+ return { sectionIndex, sectionName };
1099
+ }
1100
+
1101
+ function resolveHistoryFocusEditable(focusHint: any = null) {
1102
+ const editables = [...holder.querySelectorAll('.document-section__body')];
1103
+ if (!editables.length) return null;
1104
+ if (focusHint?.sectionName) {
1105
+ const byName = editables.find(
1106
+ (el) =>
1107
+ el.closest?.('.document-section')?.getAttribute?.('data-section-name') ===
1108
+ focusHint.sectionName,
1109
+ );
1110
+ if (byName) return byName;
1111
+ }
1112
+ const index = Number(focusHint?.sectionIndex);
1113
+ if (Number.isFinite(index) && index >= 0 && index < editables.length) {
1114
+ return editables[index];
1115
+ }
1116
+ return editables[0];
1117
+ }
1118
+
1119
+ function restoreEditorFocusAfterHistory(focusHint: any = null) {
1120
+ if (destroyed) return;
1121
+ const editable = resolveHistoryFocusEditable(focusHint);
1122
+ if (!editable || typeof editable.focus !== 'function') return;
1123
+
1124
+ lastFocusedEditable = editable;
1125
+ const focusEditable = () => {
1126
+ if (!editable.isConnected || destroyed) return;
1127
+ editable.focus({ preventScroll: true });
1128
+ try {
1129
+ const sel = window.getSelection();
1130
+ const range = document.createRange();
1131
+ range.selectNodeContents(editable);
1132
+ range.collapse(false);
1133
+ sel?.removeAllRanges();
1134
+ sel?.addRange(range);
1135
+ } catch {
1136
+ // linkedom / restricted selections
1137
+ }
1138
+ if (!options.mappingMode) {
1139
+ richTextToolbar?.show?.(editable);
1140
+ }
1141
+ };
1142
+
1143
+ // Remount finishes asynchronously; focus after the new editable is interactive.
1144
+ requestAnimationFrame(() => {
1145
+ requestAnimationFrame(focusEditable);
1146
+ });
1147
+ }
1148
+
1149
+ async function undoDocument() {
1150
+ flushHistoryRecord();
1151
+ const focusHint = captureHistoryFocusHint();
1152
+ const snapshot = documentHistory.undo();
1153
+ if (!snapshot) return false;
1154
+ return restoreHistorySnapshot(snapshot, focusHint);
1155
+ }
1156
+
1157
+ async function redoDocument() {
1158
+ flushHistoryRecord();
1159
+ const focusHint = captureHistoryFocusHint();
1160
+ const snapshot = documentHistory.redo();
1161
+ if (!snapshot) return false;
1162
+ return restoreHistorySnapshot(snapshot, focusHint);
1163
+ }
1164
+
1165
+ function shouldHandleHistoryShortcut(e: KeyboardEvent) {
1166
+ const raw = e.target as any;
1167
+ const el = raw?.nodeType === Node.ELEMENT_NODE ? raw : raw?.parentElement;
1168
+ if (!el) return false;
1169
+ if (el.closest?.('.modal-overlay:not([hidden])')) return false;
1170
+ if (el.closest?.('input, textarea, select')) {
1171
+ // Let native undo work in property forms / prompts outside the canvas.
1172
+ if (!el.closest?.('.document-section__body, .document-columns__col')) return false;
1173
+ }
1174
+ return true;
1175
+ }
1176
+
1177
+ function refreshSectionVisibility() {
1178
+ if (designMode || options.mappingMode) return;
1179
+ const blocks = registry.getBlocks() ?? [];
1180
+ const values = collectAllFieldValuesFromHolder(holder);
1181
+ const schemas = registry.getFieldSchemas();
1182
+ const blockEls = [...holder.querySelectorAll('.ce-block')];
1183
+
1184
+ for (let index = 0; index < blockEls.length; index += 1) {
1185
+ const blockEl = blockEls[index] as HTMLElement;
1186
+ const block = blocks[index];
1187
+ if (block?.type !== 'documentSection') {
1188
+ blockEl.hidden = false;
1189
+ continue;
1190
+ }
1191
+ blockEl.hidden = !evaluateSectionVisibility(block.data?.visibility, values, schemas);
1192
+ }
1193
+ }
1194
+
1195
+ async function getBlocksForProperties() {
1196
+ await editor.isReady;
1197
+ let blocks = registry.getBlocks() ?? [];
1198
+ if (!blocks.length) {
1199
+ const saved = await editor.save();
1200
+ blocks = saved.blocks ?? [];
1201
+ registry.setBlocks(blocks);
1202
+ }
1203
+ return blocks;
1204
+ }
1205
+
1206
+ /**
1207
+ * When a table cell token is selected but its schema was never materialised
1208
+ * (or was pruned), recreate cell schemas so the properties panel can open.
1209
+ */
1210
+ function ensureFieldSchemaForProperties(fieldId: any,token: any = null) {
1211
+ const schemas = registry.getFieldSchemas();
1212
+ if (schemas[fieldId]) return schemas[fieldId];
1213
+
1214
+ const tableId = token?.dataset?.tableId;
1215
+ const wrapper = tableId
1216
+ ? (token?.closest?.('.document-table') ??
1217
+ holder.querySelector(`.document-table[data-table-id="${CSS.escape(tableId)}"]`))
1218
+ : null;
1219
+
1220
+ const { fieldSchemas: next, schema } = ensureSchemaForFieldProperties(fieldId, schemas, {
1221
+ tableId,
1222
+ rowKey: token?.dataset?.rowKey,
1223
+ colKey: token?.dataset?.colKey,
1224
+ rows: wrapper ? readTableRowsFromDom(wrapper) : undefined,
1225
+ });
1226
+
1227
+ if (!schema) return null;
1228
+ if (next !== schemas) registry.setFieldSchemas(next);
1229
+ return schema;
1230
+ }
1231
+
1232
+ async function loadFieldProperties(fieldId: any,token: any = null) {
1233
+ if (!propertiesPanel || !editor) return;
1234
+
1235
+ const schema =
1236
+ registry.getFieldSchemas()[fieldId] ??
1237
+ ensureFieldSchemaForProperties(fieldId, token ?? findLiveFieldToken(fieldId, holder));
1238
+ if (!schema) return;
1239
+
1240
+ try {
1241
+ const blocks = await getBlocksForProperties();
1242
+ const schemas = registry.getFieldSchemas();
1243
+ const liveSchema = schemas[fieldId] ?? schema;
1244
+ const placement = findFieldPlacement(fieldId, blocks);
1245
+ selectedSectionBlockIndex = -1;
1246
+ updateSectionSelectionHighlight();
1247
+ clearColumnsSelection();
1248
+
1249
+ if (liveSchema.type === 'table' || liveSchema.type === 'pivotTable') {
1250
+ const tableEl = findLiveTableEl(fieldId);
1251
+ if (tableEl) {
1252
+ clearTableSelection();
1253
+ selectedTableEl = tableEl;
1254
+ tableEl.classList.add('document-table--selected');
1255
+ } else {
1256
+ clearTableSelection();
1257
+ }
1258
+ } else {
1259
+ clearTableSelection();
1260
+ }
1261
+
1262
+ propertiesPanel.showField(fieldId, liveSchema, {
1263
+ sectionName: placement.sectionName,
1264
+ sectionLabel: placement.sectionName,
1265
+ blocks,
1266
+ fieldSchemas: schemas,
1267
+ });
1268
+ } catch {
1269
+ // editor not ready
1270
+ }
1271
+ }
1272
+
1273
+ async function applySchemaSaveResult(result: any,previousType: any,previousSchema: any) {
1274
+ const { fieldId: newFieldId, previousFieldId, schema: updated } = result;
1275
+ const idChanged = newFieldId !== previousFieldId;
1276
+ const typeChanged = previousType !== updated.type;
1277
+
1278
+ // Compatible inline type change — update schema + tokens without remounting Editor.js.
1279
+ if (!idChanged && typeChanged && canRefreshFieldTypeInDom(previousType, updated.type)) {
1280
+ const defaultValue = resolveSchemaDefaultValue(updated, { forTemplate: true });
1281
+ let nextSchemas = syncColumnListSourceSettings(previousFieldId, updated, {
1282
+ ...registry.getFieldSchemas(),
1283
+ [previousFieldId]: updated,
1284
+ });
1285
+ registry.setFieldSchemas(nextSchemas);
1286
+
1287
+ const registryBlocks = registry.getBlocks() ?? [];
1288
+ if (registryBlocks.length) {
1289
+ registry.setBlocks(syncBlocksAfterSchemaChange(registryBlocks, previousFieldId, updated));
1290
+ }
1291
+
1292
+ const tokenSelector = `.field-token[data-field-id="${CSS.escape(previousFieldId)}"]`;
1293
+ for (const section of holder.querySelectorAll('.document-section')) {
1294
+ const tool = (section as any).__documentSectionTool;
1295
+ if (!tool?.data) continue;
1296
+ if (!section.querySelector(tokenSelector)) continue;
1297
+ if (!tool.data.fieldValues || typeof tool.data.fieldValues !== 'object') {
1298
+ tool.data.fieldValues = {};
1299
+ }
1300
+ tool.data.fieldValues[previousFieldId] = defaultValue;
1301
+ }
1302
+
1303
+ const ctx = { getRegistry: () => registry, fieldValueStyle };
1304
+ for (const token of holder.querySelectorAll(tokenSelector)) {
1305
+ updateFieldToken(token, defaultValue, updated.label ?? token.dataset.placeholder, ctx);
1306
+ }
1307
+
1308
+ for (const wrapper of holder.querySelectorAll('.template-block')) {
1309
+ if (!wrapper.querySelector(tokenSelector)) continue;
1310
+ for (const cls of [...wrapper.classList]) {
1311
+ if (cls.startsWith('template-block--')) wrapper.classList.remove(cls);
1312
+ }
1313
+ wrapper.classList.add(`template-block--${updated.type}`);
1314
+ }
1315
+
1316
+ refreshFieldSchemaInDom(previousFieldId, ctx, holder);
1317
+ const cellRef = parseCellFieldId(previousFieldId, registry.getFieldSchemas());
1318
+ if (cellRef) {
1319
+ refreshTableColumnStylesForFieldIds(
1320
+ [previousFieldId],
1321
+ registry.getFieldSchemas(),
1322
+ holder,
1323
+ fieldValueStyle,
1324
+ );
1325
+ }
1326
+
1327
+ options.onSchemaChange?.(registry.getFieldSchemas());
1328
+ syncDocumentFieldMappingNames();
1329
+ scheduleHistoryRecord(true);
1330
+ return true;
1331
+ }
1332
+
1333
+ if (idChanged || typeChanged) {
1334
+ const saved = await editor.save();
1335
+ let nextSchemas = registry.getFieldSchemas();
1336
+ let nextBlocks = saved.blocks;
1337
+
1338
+ if (idChanged) {
1339
+ try {
1340
+ const changeResult = applyFieldIdChange(
1341
+ previousFieldId,
1342
+ newFieldId,
1343
+ updated,
1344
+ nextSchemas,
1345
+ nextBlocks,
1346
+ );
1347
+ nextSchemas = changeResult.fieldSchemas;
1348
+ nextBlocks = changeResult.blocks;
1349
+ } catch (err: any) {
1350
+ showNotification(err.message ?? 'Could not rename field ID.');
1351
+ return false;
1352
+ }
1353
+ } else {
1354
+ registry.updateFieldSchema(previousFieldId, updated);
1355
+ nextSchemas = registry.getFieldSchemas();
1356
+ nextBlocks = syncBlocksAfterSchemaChange(nextBlocks, previousFieldId, updated);
1357
+ }
1358
+
1359
+ if (updated.type === 'table') {
1360
+ const migrated = syncTableColumnKeyChanges(
1361
+ newFieldId,
1362
+ previousSchema.columns,
1363
+ updated.columns,
1364
+ nextSchemas,
1365
+ nextBlocks,
1366
+ );
1367
+ nextSchemas = migrated.fieldSchemas;
1368
+ nextBlocks = migrated.blocks;
1369
+ nextSchemas = ensureCellSchemas(updated, newFieldId, nextSchemas, undefined);
1370
+ }
1371
+
1372
+ if (updated.type === 'child') {
1373
+ nextBlocks = normalizeRepeaterFieldInBlocks(nextBlocks, newFieldId, updated);
1374
+ }
1375
+
1376
+ registry.setFieldSchemas(nextSchemas);
1377
+ options.onSchemaChange?.(registry.getFieldSchemas());
1378
+ syncDocumentFieldMappingNames(
1379
+ nextBlocks,
1380
+ nextSchemas,
1381
+ idChanged ? { [previousFieldId]: newFieldId } : null,
1382
+ );
1383
+
1384
+ initEditor({
1385
+ time: saved.time,
1386
+ fieldSchemas: registry.getFieldSchemas(),
1387
+ blocks: nextBlocks,
1388
+ });
1389
+ return true;
1390
+ }
1391
+
1392
+ if (updated.type === 'table') {
1393
+ if (!idChanged && isTableWidthOnlyChange(previousSchema, updated)) {
1394
+ registry.updateFieldSchema(previousFieldId, {
1395
+ ...previousSchema,
1396
+ ...updated,
1397
+ columns: updated.columns,
1398
+ });
1399
+ applyTableColumnWidthsToElement(findLiveTableEl(previousFieldId), updated.columns);
1400
+ options.onSchemaChange?.(registry.getFieldSchemas());
1401
+ return true;
1402
+ }
1403
+
1404
+ const saved = await editor.save();
1405
+ let nextSchemas = registry.getFieldSchemas();
1406
+ let nextBlocks = saved.blocks;
1407
+
1408
+ if (previousSchema.type === 'table') {
1409
+ const migrated = syncTableColumnKeyChanges(
1410
+ previousFieldId,
1411
+ previousSchema.columns,
1412
+ updated.columns,
1413
+ nextSchemas,
1414
+ nextBlocks,
1415
+ );
1416
+ nextSchemas = migrated.fieldSchemas;
1417
+ nextBlocks = migrated.blocks;
1418
+ }
1419
+
1420
+ registry.updateFieldSchema(previousFieldId, updated);
1421
+ nextSchemas = ensureCellSchemas(updated, previousFieldId, {
1422
+ ...nextSchemas,
1423
+ [previousFieldId]: updated,
1424
+ }, undefined);
1425
+ registry.setFieldSchemas(nextSchemas);
1426
+ options.onSchemaChange?.(registry.getFieldSchemas());
1427
+ syncDocumentFieldMappingNames(nextBlocks, nextSchemas);
1428
+
1429
+ initEditor({
1430
+ time: saved.time,
1431
+ fieldSchemas: registry.getFieldSchemas(),
1432
+ blocks: nextBlocks,
1433
+ });
1434
+ return true;
1435
+ }
1436
+
1437
+ if (updated.type === 'child') {
1438
+ const saved = await editor.save();
1439
+ let nextBlocks = saved.blocks;
1440
+
1441
+ registry.updateFieldSchema(previousFieldId, updated);
1442
+ nextBlocks = normalizeRepeaterFieldInBlocks(nextBlocks, previousFieldId, updated);
1443
+ registry.setFieldSchemas(registry.getFieldSchemas());
1444
+ options.onSchemaChange?.(registry.getFieldSchemas());
1445
+ syncDocumentFieldMappingNames(nextBlocks, registry.getFieldSchemas());
1446
+
1447
+ initEditor({
1448
+ time: saved.time,
1449
+ fieldSchemas: registry.getFieldSchemas(),
1450
+ blocks: nextBlocks,
1451
+ });
1452
+ return true;
1453
+ }
1454
+
1455
+ const nextSchemas = syncColumnListSourceSettings(previousFieldId, updated, {
1456
+ ...registry.getFieldSchemas(),
1457
+ [previousFieldId]: updated,
1458
+ });
1459
+ registry.setFieldSchemas(nextSchemas);
1460
+ options.onSchemaChange?.(registry.getFieldSchemas());
1461
+ refreshFieldSchemaInDom(previousFieldId, { getRegistry: () => registry, fieldValueStyle }, holder);
1462
+ const cellRef = parseCellFieldId(previousFieldId, registry.getFieldSchemas());
1463
+ if (cellRef) {
1464
+ refreshTableColumnStylesForFieldIds(
1465
+ [previousFieldId],
1466
+ registry.getFieldSchemas(),
1467
+ holder,
1468
+ fieldValueStyle,
1469
+ );
1470
+ }
1471
+ syncDocumentFieldMappingNames();
1472
+ return true;
1473
+ }
1474
+
1475
+ async function handlePaletteDrop(item: any,container: any,clientX: any,clientY: any) {
1476
+ const opts = getInlineFieldOptions();
1477
+
1478
+ if (item.kind === 'layout' && item.type === 'columns') {
1479
+ insertColumnsAtPoint(container, clientX, clientY, opts);
1480
+ return;
1481
+ }
1482
+
1483
+ if (item.kind !== 'field') return;
1484
+
1485
+ if (getFieldHandler(item.type)?.insertion === 'table' || item.type === 'table') {
1486
+ const { fieldId } = await insertPaletteTableAtPoint(container, clientX, clientY, {
1487
+ ...opts,
1488
+ fieldType: item.type === 'pivotTable' ? 'pivotTable' : 'table',
1489
+ });
1490
+ options.onSchemaChange?.(registry.getFieldSchemas());
1491
+ await handleEditSchema(fieldId);
1492
+ return;
1493
+ }
1494
+
1495
+ if (item.type === 'child') {
1496
+ const { fieldId } = await insertPaletteFieldAtPoint(container, 'child', clientX, clientY, opts);
1497
+ options.onSchemaChange?.(registry.getFieldSchemas());
1498
+ await handleEditSchema(fieldId);
1499
+ return;
1500
+ }
1501
+
1502
+ if (isInlineFieldType(item.type)) {
1503
+ const { fieldId } = await insertPaletteFieldAtPoint(container, item.type, clientX, clientY, opts);
1504
+ options.onSchemaChange?.(registry.getFieldSchemas());
1505
+ await handleEditSchema(fieldId);
1506
+ }
1507
+ }
1508
+
1509
+ async function handleSourcePathCanvasDrop(
1510
+ meta: { path: string; type?: string; label?: string },
1511
+ container: any,
1512
+ clientX: any,
1513
+ clientY: any,
1514
+ dropTarget: any,
1515
+ ) {
1516
+ const sourcePath = String(meta?.path ?? '').trim();
1517
+ if (!sourcePath) return;
1518
+
1519
+ const sample = documentFieldMapping?.sourceSample;
1520
+ const plan = classifySourcePathDrop({
1521
+ path: sourcePath,
1522
+ type: meta?.type,
1523
+ label: meta?.label,
1524
+ sample,
1525
+ });
1526
+
1527
+ // Prefer mapping onto an existing field/cell/pivot when dropped on one
1528
+ // (except array-member drops onto a table, which add a column instead).
1529
+ const pivot = dropTarget?.closest?.('.document-table--pivot[data-pivot-field-id]');
1530
+ const token = dropTarget?.closest?.('.field-token');
1531
+ const tableWrapper =
1532
+ dropTarget?.closest?.('.document-table[data-table-id]:not(.document-table--pivot)') ?? null;
1533
+ const mapTargetId = pivot?.dataset?.pivotFieldId || pivot?.dataset?.tableId || token?.dataset?.fieldId;
1534
+
1535
+ const droppingArrayColumnOntoTable =
1536
+ plan.kind === 'table-column' && tableWrapper && !pivot;
1537
+
1538
+ if (mapTargetId && !token?.classList?.contains?.('field-token--computed') && !droppingArrayColumnOntoTable) {
1539
+ let blocks = registry.getBlocks() ?? [];
1540
+ if (editor) {
1541
+ const saved = await editor.save();
1542
+ blocks = saved.blocks ?? blocks;
1543
+ registry.setBlocks(blocks);
1544
+ }
1545
+ const rules = createMappingRulesFromDrop(
1546
+ mapTargetId,
1547
+ sourcePath,
1548
+ blocks,
1549
+ registry.getFieldSchemas(),
1550
+ {
1551
+ childFieldIds: [],
1552
+ bulkChild: !!token?.classList?.contains?.('field-token--repeater'),
1553
+ },
1554
+ );
1555
+ commitMappingRules(rules);
1556
+ return;
1557
+ }
1558
+
1559
+ const opts = {
1560
+ ...getInlineFieldOptions(),
1561
+ openEditor: false,
1562
+ };
1563
+
1564
+ async function syncBlocks() {
1565
+ let blocks = registry.getBlocks() ?? [];
1566
+ if (editor) {
1567
+ const saved = await editor.save();
1568
+ blocks = saved.blocks ?? blocks;
1569
+ registry.setBlocks(blocks);
1570
+ }
1571
+ return blocks;
1572
+ }
1573
+
1574
+ // 1) Scalar → simple typed field (with visible "Label: " before the token)
1575
+ if (plan.kind === 'field') {
1576
+ const { fieldId } = await insertPaletteFieldAtPoint(
1577
+ container,
1578
+ plan.fieldType,
1579
+ clientX,
1580
+ clientY,
1581
+ { ...opts, label: plan.label, insertVisibleLabel: true, readonly: true },
1582
+ );
1583
+ options.onSchemaChange?.(registry.getFieldSchemas());
1584
+ const blocks = await syncBlocks();
1585
+ const rules = createMappingRulesFromDrop(
1586
+ fieldId,
1587
+ plan.sourcePath,
1588
+ blocks,
1589
+ registry.getFieldSchemas(),
1590
+ );
1591
+ commitMappingRules(rules);
1592
+ return;
1593
+ }
1594
+
1595
+ // 2) Array member → add column only when dropped on a table; otherwise new 1-col table
1596
+ if (plan.kind === 'table-column') {
1597
+ if (tableWrapper) {
1598
+ const added = addTableColumnToWrapper(tableWrapper, plan.column, {
1599
+ ...opts,
1600
+ getRegistry: () => registry,
1601
+ onSchemaChange: (schemas: any) => options.onSchemaChange?.(schemas),
1602
+ });
1603
+ if (added) {
1604
+ const sectionBody = tableWrapper.closest?.('.document-section__body') ?? container;
1605
+ sectionBody?.dispatchEvent?.(new InputEvent('input', { bubbles: true }));
1606
+ const blocks = await syncBlocks();
1607
+ const rules = buildTableMappingRulesFromSourceDrop({
1608
+ tableFieldId: added.tableId,
1609
+ blocks,
1610
+ fieldSchemas: registry.getFieldSchemas(),
1611
+ columnSourcePaths: [{ columnKey: added.columnKey, sourcePath: plan.sourcePath }],
1612
+ });
1613
+ commitMappingRules(rules);
1614
+ return;
1615
+ }
1616
+ }
1617
+
1618
+ const { fieldId } = await insertPaletteTableAtPoint(container, clientX, clientY, {
1619
+ ...opts,
1620
+ fieldType: 'table',
1621
+ label: plan.label,
1622
+ columns: [plan.column],
1623
+ readonly: true,
1624
+ });
1625
+ options.onSchemaChange?.(registry.getFieldSchemas());
1626
+ const blocks = await syncBlocks();
1627
+ const rules = buildTableMappingRulesFromSourceDrop({
1628
+ tableFieldId: fieldId,
1629
+ blocks,
1630
+ fieldSchemas: registry.getFieldSchemas(),
1631
+ columnSourcePaths: [{ columnKey: plan.column.key, sourcePath: plan.sourcePath }],
1632
+ });
1633
+ commitMappingRules(rules);
1634
+ return;
1635
+ }
1636
+
1637
+ // 3) Whole array → multi-column table
1638
+ const { fieldId } = await insertPaletteTableAtPoint(container, clientX, clientY, {
1639
+ ...opts,
1640
+ fieldType: 'table',
1641
+ label: plan.label,
1642
+ columns: plan.columns,
1643
+ readonly: true,
1644
+ });
1645
+ options.onSchemaChange?.(registry.getFieldSchemas());
1646
+ const blocks = await syncBlocks();
1647
+ const rules = buildTableMappingRulesFromSourceDrop({
1648
+ tableFieldId: fieldId,
1649
+ blocks,
1650
+ fieldSchemas: registry.getFieldSchemas(),
1651
+ columnSourcePaths: plan.columnSourcePaths,
1652
+ });
1653
+ commitMappingRules(rules);
1654
+ }
1655
+
1656
+ async function insertDocumentSection(atIndex: any) {
1657
+ if (!editor) return;
1658
+ await editor.isReady;
1659
+ const count = editor.blocks.getBlocksCount();
1660
+ const index = atIndex ?? count;
1661
+ const sectionData = createUniqueSectionData();
1662
+ await editor.blocks.insert('documentSection', sectionData, {}, index);
1663
+ selectedSectionBlockIndex = index;
1664
+ if (propertiesPanel) {
1665
+ propertiesPanel.showSection(index, {
1666
+ name: sectionData.name,
1667
+ label: sectionData.label,
1668
+ });
1669
+ updateSectionSelectionHighlight();
1670
+ }
1671
+ }
1672
+
1673
+ async function insertColumnsIntoTargetSection() {
1674
+ await editor.isReady;
1675
+ let editable = resolveTargetEditable();
1676
+ if (!editable) {
1677
+ editable = await ensureDocumentSectionAtEnd();
1678
+ } else {
1679
+ editable.focus();
1680
+ }
1681
+ if (!editable) return;
1682
+
1683
+ insertColumnsAtCaret(editable, getInlineFieldOptions());
1684
+ editable.dispatchEvent(new InputEvent('input', { bubbles: true }));
1685
+ lastFocusedEditable = editable;
1686
+ }
1687
+
1688
+ async function handleSaveSection({
1689
+ blockIndex,
1690
+ name,
1691
+ label,
1692
+ repeatable,
1693
+ hideTitleInPreview,
1694
+ borderTop,
1695
+ borderBottom,
1696
+ eachRowOnNewPage,
1697
+ keepOnOnePage,
1698
+ visibility,
1699
+ sectionEl,
1700
+ }: any) {
1701
+ if (!editor) return;
1702
+ const saved = await editor.save();
1703
+ const blocks = [...saved.blocks];
1704
+ const block = blocks[blockIndex];
1705
+ if (!block || block.type !== 'documentSection') return;
1706
+
1707
+ const oldSectionName = resolveSectionName(block.data);
1708
+ const clearedRepeatableIndexes: number[] = [];
1709
+
1710
+ if (repeatable) {
1711
+ for (let i = 0; i < blocks.length; i += 1) {
1712
+ if (i === blockIndex) continue;
1713
+ const other = blocks[i];
1714
+ if (other.type === 'documentSection' && other.data?.repeatable) {
1715
+ other.data = { ...other.data, repeatable: false };
1716
+ blocks[i] = other;
1717
+ clearedRepeatableIndexes.push(i);
1718
+ }
1719
+ }
1720
+ }
1721
+
1722
+ block.data = {
1723
+ ...block.data,
1724
+ name,
1725
+ label,
1726
+ repeatable: !!repeatable,
1727
+ hideTitleInPreview: !!hideTitleInPreview,
1728
+ borderTop: !!borderTop,
1729
+ borderBottom: !!borderBottom,
1730
+ eachRowOnNewPage: !!eachRowOnNewPage,
1731
+ keepOnOnePage: !!keepOnOnePage,
1732
+ visibility: visibility ?? null,
1733
+ };
1734
+ blocks[blockIndex] = block;
1735
+
1736
+ const newSectionName = resolveSectionName(block.data);
1737
+ const nameChanged = oldSectionName !== newSectionName;
1738
+
1739
+ if (!nameChanged) {
1740
+ registry.setBlocks(blocks);
1741
+
1742
+ const section =
1743
+ sectionEl ??
1744
+ listEditorBlocks()[blockIndex]?.querySelector('.document-section') ??
1745
+ null;
1746
+ const tool = section?.__documentSectionTool;
1747
+ if (tool?.applyPropertiesPatch) {
1748
+ tool.applyPropertiesPatch({
1749
+ name,
1750
+ label,
1751
+ repeatable: !!repeatable,
1752
+ hideTitleInPreview: !!hideTitleInPreview,
1753
+ borderTop: !!borderTop,
1754
+ borderBottom: !!borderBottom,
1755
+ eachRowOnNewPage: !!eachRowOnNewPage,
1756
+ keepOnOnePage: !!keepOnOnePage,
1757
+ visibility: visibility ?? null,
1758
+ });
1759
+ }
1760
+
1761
+ for (const index of clearedRepeatableIndexes) {
1762
+ const otherSection = listEditorBlocks()[index]?.querySelector('.document-section');
1763
+ const otherTool = otherSection?.__documentSectionTool;
1764
+ otherTool?.applyPropertiesPatch?.({ repeatable: false });
1765
+ }
1766
+
1767
+ selectedSectionBlockIndex = blockIndex;
1768
+ updateSectionSelectionHighlight();
1769
+ scheduleHistoryRecord(true);
1770
+ options.onChange?.(await getDocument());
1771
+ return;
1772
+ }
1773
+
1774
+ let nextSchemas = registry.getFieldSchemas();
1775
+ nextSchemas = renameSectionInFormulas(nextSchemas, oldSectionName, newSectionName);
1776
+ const result = rebuildFieldIdsForSection(block, nextSchemas, blocks);
1777
+ nextSchemas = result.fieldSchemas;
1778
+ const nextBlocks = result.blocks;
1779
+
1780
+ registry.setFieldSchemas(nextSchemas);
1781
+ options.onSchemaChange?.(registry.getFieldSchemas());
1782
+ selectedSectionBlockIndex = blockIndex;
1783
+ syncDocumentFieldMappingNames(nextBlocks, nextSchemas, result.idRenames);
1784
+
1785
+ initEditor({
1786
+ time: saved.time,
1787
+ fieldSchemas: nextSchemas,
1788
+ blocks: nextBlocks,
1789
+ pageSetup: documentPageSetup,
1790
+ });
1791
+
1792
+ if (!designMode || !useDesignPanels) return;
1793
+
1794
+ try {
1795
+ await editor.isReady;
1796
+ await loadSelectedSectionProperties();
1797
+ } catch {
1798
+ // editor not ready
1799
+ }
1800
+ }
1801
+
1802
+ function openPageSetupPanel() {
1803
+ selectedSectionBlockIndex = -1;
1804
+ clearStructureSelection();
1805
+ clearAllDesignTokenSelection(holder);
1806
+ updateSectionSelectionHighlight();
1807
+ propertiesPanel?.showDocument(documentPageSetup);
1808
+ }
1809
+
1810
+ async function handleSaveDocument(pageSetup: any) {
1811
+ documentPageSetup = pageSetup ? JSON.parse(JSON.stringify(pageSetup)) : {};
1812
+ syncStylesFromPageSetup();
1813
+ scheduleHistoryRecord(true);
1814
+ options.onChange?.(await getDocument());
1815
+ }
1816
+
1817
+ function clearColumnsSelection(columnsEl: any = null) {
1818
+ const selector = columnsEl
1819
+ ? null
1820
+ : '.document-columns--selected';
1821
+ if (columnsEl) {
1822
+ columnsEl.classList.remove('document-columns--selected');
1823
+ } else {
1824
+ holder.querySelectorAll(selector).forEach((el: any) => {
1825
+ el.classList.remove('document-columns--selected');
1826
+ });
1827
+ }
1828
+ if (!columnsEl || selectedColumnsEl === columnsEl) {
1829
+ selectedColumnsEl = null;
1830
+ }
1831
+ }
1832
+
1833
+ function clearTableSelection(tableEl: any = null) {
1834
+ const selector = tableEl ? null : '.document-table--selected';
1835
+ if (tableEl) {
1836
+ tableEl.classList.remove('document-table--selected');
1837
+ } else {
1838
+ holder.querySelectorAll(selector).forEach((el: any) => {
1839
+ el.classList.remove('document-table--selected');
1840
+ });
1841
+ }
1842
+ if (!tableEl || selectedTableEl === tableEl) {
1843
+ selectedTableEl = null;
1844
+ }
1845
+ }
1846
+
1847
+ function clearStructureSelection() {
1848
+ clearColumnsSelection();
1849
+ clearTableSelection();
1850
+ }
1851
+
1852
+ /** Section / table / columns chrome — not free prose the user is typing into. */
1853
+ function isDesignStructureTarget(target: Element | null) {
1854
+ if (!target?.closest) return false;
1855
+ if (
1856
+ target.closest(
1857
+ '.document-section__header, .document-table__toolbar, .document-columns__toolbar, .editor-drag-handle, .vision-table__col-resizer, .document-columns__col-resizer',
1858
+ )
1859
+ ) {
1860
+ return true;
1861
+ }
1862
+ if (target.closest('.document-table')) return true;
1863
+ // Columns wrapper chrome, but not the editable column body.
1864
+ if (target.closest('.document-columns') && !target.closest('.document-columns__col')) {
1865
+ return true;
1866
+ }
1867
+ return false;
1868
+ }
1869
+
1870
+ function shouldClearObjectSelectionForTextTarget(target: Element | null) {
1871
+ if (!target || !designMode || !useDesignPanels) return false;
1872
+ if (target.closest?.('.field-token')) return false;
1873
+ if (isDesignStructureTarget(target)) return false;
1874
+ const prose = target.closest?.('.document-section__body, .document-columns__col');
1875
+ return !!(prose && holder.contains(prose));
1876
+ }
1877
+
1878
+ /** Drop Section/Table/Columns/Setup selection when the caret moves into plain text. */
1879
+ function clearObjectSelectionForTextEdit() {
1880
+ if (!useDesignPanels || !designMode || !propertiesPanel) return;
1881
+ const mode = propertiesPanel.getMode?.();
1882
+ const hadObjectSelection =
1883
+ selectedSectionBlockIndex >= 0 ||
1884
+ !!selectedTableEl?.isConnected ||
1885
+ !!selectedColumnsEl?.isConnected ||
1886
+ mode === 'section' ||
1887
+ mode === 'columns' ||
1888
+ mode === 'document';
1889
+ if (!hadObjectSelection) return;
1890
+
1891
+ selectedSectionBlockIndex = -1;
1892
+ clearStructureSelection();
1893
+ updateSectionSelectionHighlight();
1894
+ if (!getSelectedDesignFieldTokens().length) {
1895
+ propertiesPanel.showEmpty();
1896
+ }
1897
+ }
1898
+
1899
+ function findLiveTableEl(tableId: any) {
1900
+ if (!tableId) return null;
1901
+ try {
1902
+ return holder.querySelector(`.document-table[data-table-id="${CSS.escape(tableId)}"]`);
1903
+ } catch {
1904
+ return null;
1905
+ }
1906
+ }
1907
+
1908
+ function removeTableSchemas(tableId: any) {
1909
+ if (!tableId) return;
1910
+ const next = { ...registry.getFieldSchemas() };
1911
+ delete next[tableId];
1912
+ const prefix = `${tableId}_`;
1913
+ for (const key of Object.keys(next)) {
1914
+ if (key.startsWith(prefix)) delete next[key];
1915
+ }
1916
+ registry.setFieldSchemas(next);
1917
+ options.onSchemaChange?.(next);
1918
+ }
1919
+
1920
+ function removeOwnedSchemasFromSubtree(root: any) {
1921
+ if (!root?.querySelectorAll) return;
1922
+ const tableIds = new Set();
1923
+ root.querySelectorAll('.document-table[data-table-id]').forEach((el: any) => {
1924
+ if (el.dataset.tableId) tableIds.add(el.dataset.tableId);
1925
+ });
1926
+ for (const tableId of tableIds) {
1927
+ removeTableSchemas(tableId);
1928
+ }
1929
+
1930
+ root.querySelectorAll('.field-token[data-field-id]:not(.field-token--cell)').forEach((token: any) => {
1931
+ const fieldId = token.dataset.fieldId;
1932
+ if (!fieldId || tableIds.has(fieldId)) return;
1933
+ handleDeleteSchema(fieldId);
1934
+ });
1935
+ }
1936
+
1937
+ function selectColumnsEl(columnsEl: any) {
1938
+ if (!columnsEl?.isConnected) return;
1939
+ clearAllDesignTokenSelection(holder);
1940
+ selectedSectionBlockIndex = -1;
1941
+ updateSectionSelectionHighlight();
1942
+ clearStructureSelection();
1943
+ selectedColumnsEl = columnsEl;
1944
+ columnsEl.classList.add('document-columns--selected');
1945
+ focusStructureTarget(columnsEl);
1946
+ loadSelectedColumnsProperties(columnsEl);
1947
+ }
1948
+
1949
+ function selectTableEl(tableEl: any) {
1950
+ if (!tableEl?.isConnected) return;
1951
+ const tableId = tableEl.dataset.tableId;
1952
+ const alreadyShowing = selectedTableEl === tableEl
1953
+ && propertiesPanel?.getCurrentFieldId?.() === tableId;
1954
+ if (alreadyShowing) {
1955
+ tableEl.classList.add('document-table--selected');
1956
+ focusStructureTarget(tableEl);
1957
+ return;
1958
+ }
1959
+ clearAllDesignTokenSelection(holder);
1960
+ selectedSectionBlockIndex = -1;
1961
+ updateSectionSelectionHighlight();
1962
+ clearStructureSelection();
1963
+ selectedTableEl = tableEl;
1964
+ tableEl.classList.add('document-table--selected');
1965
+ focusStructureTarget(tableEl);
1966
+ if (tableId) void loadFieldProperties(tableId, null);
1967
+ }
1968
+
1969
+ function loadSelectedColumnsProperties(columnsEl: any = selectedColumnsEl) {
1970
+ if (!columnsEl?.isConnected || !propertiesPanel) return;
1971
+ const widths = [
1972
+ columnsEl.dataset.columnWidth0 ?? '',
1973
+ columnsEl.dataset.columnWidth1 ?? '',
1974
+ ];
1975
+ propertiesPanel.showColumns(columnsEl, { widths });
1976
+ }
1977
+
1978
+ function notifyStructureRemoved(sectionBody: any) {
1979
+ sectionBody?.dispatchEvent?.(new InputEvent('input', { bubbles: true }));
1980
+ scheduleHistoryRecord(true);
1981
+ if (propertiesPanel && designMode && useDesignPanels) {
1982
+ propertiesPanel.showEmpty();
1983
+ }
1984
+ }
1985
+
1986
+ function deleteSelectedColumnsBlock() {
1987
+ const columnsEl = selectedColumnsEl;
1988
+ if (!columnsEl?.isConnected) return false;
1989
+ const sectionBody = columnsEl.closest('.document-section__body');
1990
+ removeOwnedSchemasFromSubtree(columnsEl);
1991
+ clearColumnsSelection(columnsEl);
1992
+ columnsEl.remove();
1993
+ notifyStructureRemoved(sectionBody);
1994
+ return true;
1995
+ }
1996
+
1997
+ function deleteSelectedTableBlock() {
1998
+ const tableEl = selectedTableEl;
1999
+ if (!tableEl?.isConnected) return false;
2000
+ const sectionBody = tableEl.closest('.document-section__body');
2001
+ const tableId = tableEl.dataset.tableId;
2002
+ clearTableSelection(tableEl);
2003
+ tableEl.remove();
2004
+ removeTableSchemas(tableId);
2005
+ notifyStructureRemoved(sectionBody);
2006
+ return true;
2007
+ }
2008
+
2009
+ async function deleteSelectedSectionBlock() {
2010
+ if (!editor || selectedSectionBlockIndex < 0) return false;
2011
+ const index = selectedSectionBlockIndex;
2012
+ const before = countLiveDocumentSections();
2013
+ if (before <= 1) {
2014
+ showNotification('At least one section is required.', { type: 'status' });
2015
+ return false;
2016
+ }
2017
+
2018
+ const sectionEl =
2019
+ listEditorBlocks()[index]?.querySelector('.document-section') ?? null;
2020
+ if (sectionEl) removeOwnedSchemasFromSubtree(sectionEl);
2021
+
2022
+ editor.blocks.delete(index);
2023
+ // Guard may no-op when only one section remains.
2024
+ if (countLiveDocumentSections() >= before) return false;
2025
+
2026
+ selectedSectionBlockIndex = -1;
2027
+ clearStructureSelection();
2028
+ clearAllDesignTokenSelection(holder);
2029
+ updateSectionSelectionHighlight();
2030
+ propertiesPanel?.showEmpty();
2031
+ scheduleHistoryRecord(true);
2032
+ return true;
2033
+ }
2034
+
2035
+ function focusStructureTarget(el: any) {
2036
+ if (!el?.isConnected) return;
2037
+ if (!el.hasAttribute('tabindex')) el.setAttribute('tabindex', '-1');
2038
+ try {
2039
+ el.focus({ preventScroll: true });
2040
+ } catch {
2041
+ // ignore focus failures (hidden / detached)
2042
+ }
2043
+ }
2044
+
2045
+ function shouldIgnoreStructureDeleteKey(e: KeyboardEvent) {
2046
+ const candidates = [];
2047
+ if (typeof e.composedPath === 'function') {
2048
+ for (const node of e.composedPath()) {
2049
+ if (node instanceof Element) {
2050
+ candidates.push(node);
2051
+ break;
2052
+ }
2053
+ }
2054
+ }
2055
+ const target = e.target;
2056
+ if (target instanceof Element) candidates.push(target);
2057
+ else if (target && (target as Node).parentElement) candidates.push((target as Node).parentElement);
2058
+ if (document.activeElement instanceof Element) candidates.push(document.activeElement);
2059
+
2060
+ for (const el of candidates) {
2061
+ if (!el) continue;
2062
+ if (el.closest?.('.modal-overlay:not([hidden])')) return true;
2063
+ // Allow Delete to remove a selected section/table even when caret is in a
2064
+ // section body; only skip real form controls (e.g. Properties inputs).
2065
+ if (el.closest?.('input, textarea, select, .schema-editor, .document-section__label-input, .document-section__name-input')) {
2066
+ return true;
2067
+ }
2068
+ }
2069
+
2070
+ // Prefer field-token Delete handling when fields are selected.
2071
+ if (getSelectedDesignFieldTokens().length) return true;
2072
+ return false;
2073
+ }
2074
+
2075
+ async function handleSaveColumns({ columnsEl, widths }: any) {
2076
+ if (!columnsEl?.isConnected) return;
2077
+ applyColumnWidthsToElement(columnsEl, widths);
2078
+ const sectionBody = columnsEl.closest('.document-section__body');
2079
+ sectionBody?.dispatchEvent(new InputEvent('input', { bubbles: true }));
2080
+ selectedColumnsEl = columnsEl;
2081
+ scheduleHistoryRecord(true);
2082
+ }
2083
+
2084
+ function syncPropertiesPanel() {
2085
+ if (!useDesignPanels || !designMode || !propertiesPanel) return;
2086
+
2087
+ const tokens = getSelectedDesignFieldTokens();
2088
+ if (tokens.length >= 1) {
2089
+ const token = tokens[0];
2090
+ const fieldId = token.dataset.fieldId;
2091
+ if (fieldId) {
2092
+ const schema =
2093
+ registry.getFieldSchemas()[fieldId] ??
2094
+ ensureFieldSchemaForProperties(fieldId, token);
2095
+ if (schema) {
2096
+ selectedSectionBlockIndex = -1;
2097
+ clearStructureSelection();
2098
+ updateSectionSelectionHighlight();
2099
+ void loadFieldProperties(fieldId, token);
2100
+ return;
2101
+ }
2102
+ }
2103
+ // Keep selection highlighted; do not wipe the panel to empty while a
2104
+ // field token is still selected (e.g. schema briefly unavailable).
2105
+ return;
2106
+ }
2107
+
2108
+ if (selectedSectionBlockIndex >= 0) {
2109
+ clearStructureSelection();
2110
+ void loadSelectedSectionProperties();
2111
+ return;
2112
+ }
2113
+
2114
+ if (selectedColumnsEl?.isConnected) {
2115
+ updateSectionSelectionHighlight();
2116
+ clearTableSelection();
2117
+ loadSelectedColumnsProperties();
2118
+ return;
2119
+ }
2120
+
2121
+ if (selectedTableEl?.isConnected) {
2122
+ updateSectionSelectionHighlight();
2123
+ clearColumnsSelection();
2124
+ return;
2125
+ }
2126
+
2127
+ updateSectionSelectionHighlight();
2128
+ clearStructureSelection();
2129
+ propertiesPanel.showEmpty();
2130
+ }
2131
+
2132
+ async function insertPaletteFieldInline(fieldType: any) {
2133
+ await editor.isReady;
2134
+ let editable = resolveTargetEditable();
2135
+ // Capture before focus() collapses the selection in some browsers.
2136
+ const savedRange = editable ? saveSelection(editable) : null;
2137
+ const preferredLabel = editable
2138
+ ? resolveSelectedTextForFieldConversion(editable, savedRange)
2139
+ : '';
2140
+ if (!editable) {
2141
+ editable = await ensureDocumentSectionAtEnd();
2142
+ } else {
2143
+ editable.focus();
2144
+ }
2145
+ if (!editable) return;
2146
+
2147
+ const { fieldId, token } = await insertInlineField(editable, fieldType, {
2148
+ ...getInlineFieldOptions(),
2149
+ ...(preferredLabel ? { preferredLabel, savedRange } : {}),
2150
+ });
2151
+ if (useDesignPanels && designMode && fieldId) {
2152
+ await handleEditSchema(fieldId);
2153
+ }
2154
+ if (token.isConnected) {
2155
+ focusCaretAfter(token);
2156
+ } else {
2157
+ focusCaretAtEnd(editable);
2158
+ }
2159
+ lastFocusedEditable = editable;
2160
+ }
2161
+
2162
+ async function insertPaletteTableInline(fieldType = 'table') {
2163
+ await editor.isReady;
2164
+ let editable = resolveTargetEditable();
2165
+ if (!editable) {
2166
+ editable = await ensureDocumentSectionAtEnd();
2167
+ } else {
2168
+ editable.focus();
2169
+ }
2170
+ if (!editable) return;
2171
+
2172
+ const { fieldId } = insertTableAtCaret(editable, {
2173
+ ...getInlineFieldOptions(),
2174
+ fieldType: fieldType === 'pivotTable' ? 'pivotTable' : 'table',
2175
+ });
2176
+ options.onSchemaChange?.(registry.getFieldSchemas());
2177
+ wireTableRegions(editable, {
2178
+ ...getInlineFieldOptions(),
2179
+ onStructureChange: () => {
2180
+ editable.dispatchEvent(new InputEvent('input', { bubbles: true }));
2181
+ },
2182
+ });
2183
+ editable.dispatchEvent(new InputEvent('input', { bubbles: true }));
2184
+ await handleEditSchema(fieldId);
2185
+ lastFocusedEditable = editable;
2186
+ }
2187
+
2188
+ async function insertPaletteRepeaterInline() {
2189
+ await insertPaletteFieldInline('child');
2190
+ }
2191
+ void insertPaletteRepeaterInline;
2192
+
2193
+ function normalizeRepeaterFieldInBlocks(blocks: any,fieldId: any,repeaterSchema: any) {
2194
+ const updated = normalizeRepeaterSchema(repeaterSchema);
2195
+ return blocks.map((block: any) => {
2196
+ if (block.type === 'documentSection' && block.data?.fieldValues?.[fieldId] !== undefined) {
2197
+ return {
2198
+ ...block,
2199
+ data: {
2200
+ ...block.data,
2201
+ fieldValues: {
2202
+ ...block.data.fieldValues,
2203
+ [fieldId]: normalizeRepeaterValue(block.data.fieldValues[fieldId], updated),
2204
+ },
2205
+ },
2206
+ };
2207
+ }
2208
+ if (
2209
+ block.type === 'templateBlock' &&
2210
+ block.data?.fieldId === fieldId &&
2211
+ block.data?.fieldType === 'child'
2212
+ ) {
2213
+ return {
2214
+ ...block,
2215
+ data: {
2216
+ ...block.data,
2217
+ value: normalizeRepeaterValue(block.data.value, updated),
2218
+ },
2219
+ };
2220
+ }
2221
+ return block;
2222
+ });
2223
+ }
2224
+
2225
+ async function handleSectionNameChange() {
2226
+ if (!editor) return;
2227
+ const saved = await editor.save();
2228
+ let nextSchemas = registry.getFieldSchemas();
2229
+ let nextBlocks = saved.blocks;
2230
+ /** @type {Record<string, string>} */
2231
+ const idRenames: Record<string, string> = {};
2232
+
2233
+ for (const block of nextBlocks) {
2234
+ if (block.type !== 'documentSection') continue;
2235
+ const result = rebuildFieldIdsForSection(block, nextSchemas, nextBlocks);
2236
+ nextSchemas = result.fieldSchemas;
2237
+ nextBlocks = result.blocks;
2238
+ Object.assign(idRenames, result.idRenames);
2239
+ }
2240
+
2241
+ registry.setFieldSchemas(nextSchemas);
2242
+ options.onSchemaChange?.(registry.getFieldSchemas());
2243
+ syncDocumentFieldMappingNames(nextBlocks, nextSchemas, idRenames);
2244
+ initEditor({
2245
+ time: saved.time,
2246
+ fieldSchemas: nextSchemas,
2247
+ blocks: nextBlocks,
2248
+ });
2249
+ }
2250
+
2251
+ async function applyRepeaterSchemaUpdate(fieldId: any,schema: any,{ reinit = true }: any = {}) {
2252
+ let blocks = registry.getBlocks() ?? [];
2253
+ let savedTime = Date.now();
2254
+ if (editor && reinit) {
2255
+ const saved = await editor.save();
2256
+ blocks = saved.blocks ?? blocks;
2257
+ savedTime = saved.time;
2258
+ }
2259
+
2260
+ const sanitized = sanitizeRepeaterChildSchemas(
2261
+ normalizeRepeaterSchema(schema),
2262
+ registry.getFieldSchemas(),
2263
+ blocks,
2264
+ );
2265
+
2266
+ registry.updateFieldSchema(fieldId, sanitized);
2267
+ options.onSchemaChange?.(registry.getFieldSchemas());
2268
+
2269
+ if (editor && reinit) {
2270
+ const nextBlocks = normalizeRepeaterFieldInBlocks(blocks, fieldId, sanitized);
2271
+ syncDocumentFieldMappingNames(nextBlocks, registry.getFieldSchemas());
2272
+ initEditor({
2273
+ time: savedTime,
2274
+ fieldSchemas: registry.getFieldSchemas(),
2275
+ blocks: nextBlocks,
2276
+ });
2277
+ } else {
2278
+ syncDocumentFieldMappingNames(blocks, registry.getFieldSchemas());
2279
+ }
2280
+
2281
+ return sanitized;
2282
+ }
2283
+
2284
+ /**
2285
+ * Persist repeater schema without destroying the live editor DOM.
2286
+ * Used while a fill-mode Child modal is open so the click handler's token
2287
+ * (and section callbacks) stay connected.
2288
+ */
2289
+ async function applyRepeaterSchemaUpdateSoft(fieldId: any,schema: any) {
2290
+ return applyRepeaterSchemaUpdate(fieldId, schema, { reinit: false });
2291
+ }
2292
+
2293
+ /**
2294
+ * Prefer the repeater value that carries more child keys (token vs last save).
2295
+ * An empty `{}` stored value must not eclipse a populated token value.
2296
+ */
2297
+ function pickRicherRepeaterValue(storedValue: any,tokenValue: any) {
2298
+ const storedObj =
2299
+ storedValue && typeof storedValue === 'object' && !Array.isArray(storedValue)
2300
+ ? storedValue
2301
+ : null;
2302
+ const tokenObj =
2303
+ tokenValue && typeof tokenValue === 'object' && !Array.isArray(tokenValue)
2304
+ ? tokenValue
2305
+ : null;
2306
+ if (!storedObj && tokenObj) return tokenValue;
2307
+ if (storedObj && !tokenObj) return storedValue;
2308
+ if (!storedObj && !tokenObj) {
2309
+ return storedValue !== undefined ? storedValue : tokenValue;
2310
+ }
2311
+ const storedKeys = Object.keys(storedObj).filter((key: any) => key !== 'instances').length;
2312
+ const tokenKeys = Object.keys(tokenObj).filter((key: any) => key !== 'instances').length;
2313
+ if (tokenKeys > storedKeys) return tokenValue;
2314
+ if (storedKeys > 0) return storedValue;
2315
+ return tokenValue !== undefined ? tokenValue : storedValue;
2316
+ }
2317
+
2318
+ function promptRepeaterTemplateUpload(fieldId: any) {
2319
+ return new Promise((resolve: any) => {
2320
+ const input = document.createElement('input');
2321
+ input.type = 'file';
2322
+ input.accept = '.json,application/json';
2323
+ input.hidden = true;
2324
+ document.body.appendChild(input);
2325
+
2326
+ const finish = (result: any) => {
2327
+ input.remove();
2328
+ resolve(result);
2329
+ };
2330
+
2331
+ input.addEventListener('change', async () => {
2332
+ const file = input.files?.[0];
2333
+ if (!file) {
2334
+ finish(null);
2335
+ return;
2336
+ }
2337
+ try {
2338
+ const text = await file.text();
2339
+ finish(parseRepeaterTemplateImport(JSON.parse(text), fieldId));
2340
+ } catch (err: any) {
2341
+ showNotification(err?.message ?? 'Could not read repeater template file.', { type: 'error' });
2342
+ finish(null);
2343
+ }
2344
+ });
2345
+
2346
+ input.addEventListener('cancel', () => finish(null));
2347
+ input.click();
2348
+ });
2349
+ }
2350
+
2351
+ async function handleOpenRepeaterEditor({ fieldId, value }: any) {
2352
+ const parentSchemas = registry.getFieldSchemas();
2353
+ let blocks: any[] = [];
2354
+ if (editor) {
2355
+ const saved = await editor.save();
2356
+ blocks = saved.blocks ?? [];
2357
+ }
2358
+ let schema = parentSchemas[fieldId];
2359
+ if (!schema || schema.type !== 'child') {
2360
+ return extractRepeaterFieldValueFromBlocks(fieldId, blocks) ?? value;
2361
+ }
2362
+
2363
+ const storedValue = extractRepeaterFieldValueFromBlocks(fieldId, blocks);
2364
+ // Prefer the richer of DOM token value vs last saved section value.
2365
+ const resolvedValue = stripForeignKeysFromRepeaterValue(
2366
+ pickRicherRepeaterValue(storedValue, value),
2367
+ parentSchemas,
2368
+ schema,
2369
+ );
2370
+
2371
+ // Soft schema updates only — never reinitEditor here. A full reinit would
2372
+ // detach the token/callback that opened this modal, so Save couldn't update
2373
+ // the live Child cell in the main form.
2374
+ const persistSchema = (next: any) => applyRepeaterSchemaUpdateSoft(fieldId, next);
2375
+
2376
+ if (!schema.template?.blocks?.length) {
2377
+ const previousChildKeys = Object.keys(getRepeaterFieldSchemas(schema)).sort();
2378
+ schema = sanitizeRepeaterChildSchemas(schema, parentSchemas, blocks);
2379
+ const cleanedChildKeys = Object.keys(getRepeaterFieldSchemas(schema)).sort();
2380
+ if (cleanedChildKeys.join(',') !== previousChildKeys.join(',')) {
2381
+ schema = (await persistSchema(schema)) ?? schema;
2382
+ }
2383
+ }
2384
+
2385
+ schema = ensureRepeaterChildSchemas(schema, resolvedValue, parentSchemas, blocks);
2386
+
2387
+ const currentChildKeys = Object.keys(
2388
+ getRepeaterFieldSchemas(registry.getFieldSchemas()[fieldId] ?? {}),
2389
+ ).sort();
2390
+ const ensuredChildKeys = Object.keys(getRepeaterFieldSchemas(schema)).sort();
2391
+ if (ensuredChildKeys.join(',') !== currentChildKeys.join(',')) {
2392
+ schema = (await persistSchema(schema)) ?? schema;
2393
+ }
2394
+
2395
+ if (!repeaterHasTemplate(schema)) {
2396
+ const imported = await promptRepeaterTemplateUpload(fieldId);
2397
+ if (imported) {
2398
+ schema = applyRepeaterTemplateImport(schema, imported);
2399
+ schema = (await persistSchema(schema)) ?? schema;
2400
+ }
2401
+ }
2402
+
2403
+ if (!repeaterHasTemplate(schema)) {
2404
+ showNotification(
2405
+ 'Repeater has no template. Upload a template JSON (kind: "template") when prompted, or upload one in design mode field properties.',
2406
+ { type: 'warning', key: `repeater-no-template:${fieldId}` },
2407
+ );
2408
+ return resolvedValue;
2409
+ }
2410
+
2411
+ // Migrate legacy short storage keys (e.g. colliding "name"/"id") from the template.
2412
+ const migrated = normalizeRepeaterSchema(schema);
2413
+ if (
2414
+ migrated &&
2415
+ Object.keys(getRepeaterFieldSchemas(migrated)).join(',') !==
2416
+ Object.keys(getRepeaterFieldSchemas(schema)).join(',')
2417
+ ) {
2418
+ schema = (await persistSchema(migrated)) ?? migrated;
2419
+ }
2420
+
2421
+ const normalized = normalizeRepeaterValue(resolvedValue, schema);
2422
+ const doc = buildRepeaterFillDocument(schema, normalized);
2423
+ const result = await repeaterEditorModal.open({
2424
+ title: schema.label ?? fieldId,
2425
+ data: doc,
2426
+ designMode: false,
2427
+ });
2428
+
2429
+ // Use modal live fieldSchemas so newly added nested table rows are mapped.
2430
+ const extractSchema = {
2431
+ ...schema,
2432
+ template: {
2433
+ ...(schema.template ?? {}),
2434
+ fieldSchemas: {
2435
+ ...(schema.template?.fieldSchemas ?? {}),
2436
+ ...((result as any)?.fieldSchemas ?? {}),
2437
+ },
2438
+ },
2439
+ };
2440
+ const extracted = extractRepeaterValueFromDocument(result, extractSchema);
2441
+ const synced = syncRepeaterTemplateFromFillDocument(schema, result);
2442
+ if (synced) {
2443
+ await persistSchema(synced);
2444
+ }
2445
+
2446
+ // Update the live main-form token immediately so Save is visible even if
2447
+ // the click-handler token reference is stale or structure-change races.
2448
+ const liveToken = findLiveFieldToken(fieldId, holder);
2449
+ if (liveToken) {
2450
+ updateFieldToken(liveToken, extracted, liveToken.dataset.placeholder, {
2451
+ getRegistry: () => registry,
2452
+ isTableCell: liveToken.classList.contains('field-token--cell'),
2453
+ });
2454
+ }
2455
+
2456
+ return extracted;
2457
+ }
2458
+
2459
+ function buildToolConfig() {
2460
+ return {
2461
+ ...pickerCallbacks,
2462
+ openRepeaterEditor: (opts: any) => handleOpenRepeaterEditor(opts),
2463
+ editorHolder: holder,
2464
+ getRegistry: () => registry,
2465
+ resolveListItems: options.resolveListItems,
2466
+ fieldValueStyle,
2467
+ getDocumentTextStyle: () => resolvePageSetupTextStyle(documentPageSetup),
2468
+ getProtectFieldsInFillMode: () => documentPageSetup.protectFieldsInFillMode !== false,
2469
+ getAutoAdvanceFillFields: () => documentPageSetup.autoAdvanceFillFields !== false,
2470
+ designMode,
2471
+ fillModeFieldHighlight: !designMode && showFieldsInFillMode && !options.mappingMode,
2472
+ mappingMode: !!options.mappingMode,
2473
+ onMappingRuleChange: options.onMappingRuleChange,
2474
+ getMappingRules: options.getMappingRules,
2475
+ designPropertiesPanel: useDesignPanels && designMode,
2476
+ openEditor: !(useDesignPanels && designMode),
2477
+ onEditSchema: handleEditSchema,
2478
+ onDeleteSchema: handleDeleteSchema,
2479
+ onSectionNameChange: handleSectionNameChange,
2480
+ onPaletteDrop: handlePaletteDrop,
2481
+ onSourcePathCanvasDrop: handleSourcePathCanvasDrop,
2482
+ allocateSectionName,
2483
+ onSectionDataChange: syncSectionDataToRegistry,
2484
+ onFieldValueChange: refreshSectionVisibility,
2485
+ onSchemaChange: (schemas: any) => options.onSchemaChange?.(schemas),
2486
+ onTableColumnWidthsChange: handleTableColumnWidthsChange,
2487
+ onTableColumnWidthsPreview: handleTableColumnWidthsPreview,
2488
+ onTableColumnResizeStart: handleTableColumnResizeStart,
2489
+ onTableColumnsChange: (tableId: any, columns: any) => {
2490
+ propertiesPanel?.cancelPersist?.();
2491
+ propertiesPanel?.syncTableColumns?.(tableId, columns);
2492
+ options.onSchemaChange?.(registry.getFieldSchemas());
2493
+ scheduleHistoryRecord();
2494
+ },
2495
+ onColumnsWidthsChange: (columnsEl: any) => {
2496
+ if (columnsEl?.isConnected) {
2497
+ selectColumnsEl(columnsEl);
2498
+ }
2499
+ },
2500
+ };
2501
+ }
2502
+
2503
+ async function handleEditSchema(fieldId: any) {
2504
+ const token = findLiveFieldToken(fieldId, holder);
2505
+ const schema =
2506
+ registry.getFieldSchemas()[fieldId] ??
2507
+ ensureFieldSchemaForProperties(fieldId, token);
2508
+ if (!schema) return;
2509
+
2510
+ if (useDesignPanels && designMode && propertiesPanel) {
2511
+ await loadFieldProperties(fieldId, token);
2512
+ return;
2513
+ }
2514
+
2515
+ const schemas = registry.getFieldSchemas();
2516
+
2517
+ const previousType = schema.type;
2518
+
2519
+ try {
2520
+ const saved = await editor.save();
2521
+ const placement = findFieldPlacement(fieldId, saved.blocks);
2522
+ const result = await schemaEditor.open(fieldId, schema, {
2523
+ sectionName: placement.sectionName,
2524
+ sectionLabel: placement.sectionName,
2525
+ blocks: saved.blocks,
2526
+ fieldSchemas: schemas,
2527
+ });
2528
+ await applySchemaSaveResult(result, previousType, schema);
2529
+ } catch {
2530
+ // cancelled
2531
+ }
2532
+ }
2533
+
2534
+ function handleDeleteSchema(fieldId: any) {
2535
+ registry.removeFieldSchema(fieldId);
2536
+ options.onSchemaChange?.(registry.getFieldSchemas());
2537
+ }
2538
+
2539
+ function buildToolsMap(config: any) {
2540
+ const enabled = options.tools ?? ['documentSection', 'templateBlock'];
2541
+ const tools: any = {};
2542
+
2543
+ if (enabled.includes('documentSection')) {
2544
+ tools.documentSection = { class: DocumentSection, config };
2545
+ }
2546
+ if (enabled.includes('templateBlock')) {
2547
+ tools.templateBlock = { class: TemplateBlock, config };
2548
+ }
2549
+ if (enabled.includes('visionTable') && options.visionTableTool) {
2550
+ tools.visionTable = { class: options.visionTableTool, config };
2551
+ }
2552
+
2553
+ return tools;
2554
+ }
2555
+
2556
+ function countLiveDocumentSections() {
2557
+ if (!editor) return 0;
2558
+ const count = editor.blocks.getBlocksCount();
2559
+ let sections = 0;
2560
+ for (let i = 0; i < count; i += 1) {
2561
+ if (editor.blocks.getBlockByIndex(i)?.name === 'documentSection') {
2562
+ sections += 1;
2563
+ }
2564
+ }
2565
+ return sections;
2566
+ }
2567
+
2568
+ let restoringRequiredSection = false;
2569
+
2570
+ async function ensureLiveDocumentSection() {
2571
+ if (!editor || destroyed || restoringRequiredSection) return;
2572
+ if (countLiveDocumentSections() > 0) return;
2573
+
2574
+ restoringRequiredSection = true;
2575
+ try {
2576
+ await editor.isReady;
2577
+ if (destroyed || !editor || countLiveDocumentSections() > 0) return;
2578
+ await editor.blocks.insert(
2579
+ 'documentSection',
2580
+ createUniqueSectionData(),
2581
+ {},
2582
+ 0,
2583
+ true,
2584
+ );
2585
+ showNotification('At least one section is required.', { type: 'status' });
2586
+ } finally {
2587
+ restoringRequiredSection = false;
2588
+ }
2589
+ }
2590
+
2591
+ function guardDocumentSectionDeletion() {
2592
+ if (!editor) return;
2593
+ const blocksApi = editor.blocks;
2594
+ const originalDelete = blocksApi.delete.bind(blocksApi);
2595
+ const originalClear = blocksApi.clear.bind(blocksApi);
2596
+
2597
+ blocksApi.delete = (index: any) => {
2598
+ const blockIndex = index ?? blocksApi.getCurrentBlockIndex();
2599
+ const block = blocksApi.getBlockByIndex(blockIndex);
2600
+ if (block?.name === 'documentSection' && countLiveDocumentSections() <= 1) {
2601
+ showNotification('At least one section is required.', { type: 'status' });
2602
+ return;
2603
+ }
2604
+ return originalDelete(index);
2605
+ };
2606
+
2607
+ blocksApi.clear = async () => {
2608
+ await originalClear();
2609
+ await ensureLiveDocumentSection();
2610
+ };
2611
+ }
2612
+
2613
+ function initEditor(docData: any) {
2614
+ const normalized = normalizeDocument(docData, {
2615
+ defaultDocument: options.defaultDocument,
2616
+ visionTableFieldId: options.visionTableFieldId,
2617
+ });
2618
+ registry.setFieldSchemas({ ...normalized.fieldSchemas });
2619
+ registry.setBlocks(normalized.blocks ?? []);
2620
+ options.onSchemaChange?.(registry.getFieldSchemas());
2621
+
2622
+ if (docData && Object.prototype.hasOwnProperty.call(docData, 'pageSetup')) {
2623
+ documentPageSetup = docData.pageSetup
2624
+ ? migratePageSetup(JSON.parse(JSON.stringify(docData.pageSetup)))
2625
+ : {};
2626
+ } else if (normalized.pageSetup) {
2627
+ documentPageSetup = migratePageSetup(JSON.parse(JSON.stringify(normalized.pageSetup)));
2628
+ }
2629
+ if (docData && Object.prototype.hasOwnProperty.call(docData, 'fieldMapping')) {
2630
+ documentFieldMapping = docData.fieldMapping
2631
+ ? normalizeFieldMappingSpec(docData.fieldMapping)
2632
+ : null;
2633
+ } else if (normalized.fieldMapping) {
2634
+ documentFieldMapping = normalizeFieldMappingSpec(normalized.fieldMapping);
2635
+ }
2636
+ // Heal stale section/field names left over from renames before re-init.
2637
+ if (documentFieldMapping?.rules?.length) {
2638
+ documentFieldMapping = syncFieldMappingSpecToSchema(
2639
+ documentFieldMapping,
2640
+ registry.getBlocks() ?? [],
2641
+ registry.getFieldSchemas(),
2642
+ );
2643
+ }
2644
+ // Palette may already exist on re-init; keep Database tab + badges in sync.
2645
+ refreshDatabaseSourceTree?.();
2646
+ refreshDesignMappingBadges();
2647
+ syncStylesFromPageSetup();
2648
+
2649
+ // EditorJS.destroy() deletes its own methods; never call destroy twice on the same instance.
2650
+ if (editor) {
2651
+ const prev = editor;
2652
+ editor = null;
2653
+ if (typeof prev.destroy === 'function') {
2654
+ try {
2655
+ prev.destroy();
2656
+ } catch {
2657
+ // already torn down or mid-destroy from a concurrent reinit
2658
+ }
2659
+ }
2660
+ }
2661
+
2662
+ const config = buildToolConfig();
2663
+
2664
+ // Must run before EditorJS so our capture listener beats DragNDrop.processDrop
2665
+ // (which deletes the selection then crashes in processHTML on text DnD).
2666
+ wireEditorJsNativeDropGuard(holder);
2667
+
2668
+ editor = new EditorJSCtor({
2669
+ // Pass the element — string IDs fail under LWC shadow DOM (getElementById).
2670
+ holder,
2671
+ autofocus: false,
2672
+ minHeight: 0,
2673
+ defaultBlock: 'documentSection',
2674
+ data: { blocks: normalized.blocks },
2675
+ tools: buildToolsMap(config),
2676
+ onChange: async () => {
2677
+ if (destroyed) return;
2678
+ try {
2679
+ await ensureLiveDocumentSection();
2680
+ scheduleHistoryRecord();
2681
+ options.onChange?.(await getDocument());
2682
+ } catch {
2683
+ // editor not ready
2684
+ }
2685
+ },
2686
+ onReady: () => {
2687
+ if (destroyed || !editor) return;
2688
+ guardDocumentSectionDeletion();
2689
+ refreshSectionVisibility();
2690
+ if (!documentHistory.hasPresent()) {
2691
+ documentHistory.reset(getHistorySnapshot());
2692
+ } else if (!historyBusy && !documentHistory.isSuspended()) {
2693
+ scheduleHistoryRecord(true);
2694
+ }
2695
+ },
2696
+ });
2697
+
2698
+ applyDesignMode(designMode);
2699
+ syncFieldStyleToolbar();
2700
+ syncStylesFromPageSetup();
2701
+ scheduleEditorStylesSync();
2702
+ return editor;
2703
+ }
2704
+
2705
+ async function getDocument() {
2706
+ if (!editor) {
2707
+ const doc = normalizeDocument(options.data ?? options.defaultDocument, {
2708
+ defaultDocument: options.defaultDocument,
2709
+ visionTableFieldId: options.visionTableFieldId,
2710
+ });
2711
+ if (Object.keys(documentPageSetup).length > 0) {
2712
+ doc.pageSetup = JSON.parse(JSON.stringify(documentPageSetup));
2713
+ }
2714
+ if (documentFieldMapping) {
2715
+ doc.fieldMapping = JSON.parse(JSON.stringify(documentFieldMapping));
2716
+ }
2717
+ attachRepeatableInstances(doc);
2718
+ return doc;
2719
+ }
2720
+ // Ensure preview/export always sees the latest live token state (including
2721
+ // table-cell values) even before EditorJS serialization runs.
2722
+ refreshTableCellTokens(holder, {
2723
+ getRegistry: () => registry,
2724
+ fieldValueStyle,
2725
+ fillModeFieldHighlight: !designMode && showFieldsInFillMode && !options.mappingMode,
2726
+ });
2727
+ syncFillComputedFields(holder, {}, {
2728
+ getRegistry: () => registry,
2729
+ editorHolder: holder,
2730
+ fieldValueStyle,
2731
+ fillModeFieldHighlight: !designMode && showFieldsInFillMode && !options.mappingMode,
2732
+ });
2733
+ const saved = await editor.save();
2734
+ registry.setBlocks(saved.blocks ?? []);
2735
+ // Re-attach image data URLs from live thumbs (dataset only keeps a compact stub under LWS).
2736
+ for (const block of saved.blocks ?? []) {
2737
+ if (block?.type !== 'documentSection' || !block.data) continue;
2738
+ block.data.fieldValues = recoverImageValuesFromDom(holder, block.data.fieldValues ?? {});
2739
+ }
2740
+ const doc: any = {
2741
+ time: saved.time,
2742
+ fieldSchemas: registry.getFieldSchemas(),
2743
+ blocks: saved.blocks,
2744
+ };
2745
+ if (Object.keys(documentPageSetup).length > 0) {
2746
+ doc.pageSetup = JSON.parse(JSON.stringify(documentPageSetup));
2747
+ }
2748
+ if (documentFieldMapping) {
2749
+ doc.fieldMapping = JSON.parse(JSON.stringify(documentFieldMapping));
2750
+ }
2751
+ attachRepeatableInstances(doc);
2752
+ return doc;
2753
+ }
2754
+
2755
+ function attachRepeatableInstances(doc: any) {
2756
+ // Clone from loaded instance arrays and/or explicit `repeatable` — never from `_source` alone.
2757
+ const plan = resolveRepeatablePagePlan(
2758
+ doc.blocks ?? [],
2759
+ doc.fieldSchemas ?? {},
2760
+ collectAllValues(doc.blocks ?? []),
2761
+ loadedDocumentSections,
2762
+ );
2763
+ if (plan && plan.instances.length > 1) {
2764
+ doc.repeatablePagePlan = plan;
2765
+ doc.repeatableSectionInstances = { [plan.sectionName]: plan.instances };
2766
+ return;
2767
+ }
2768
+ delete doc.repeatablePagePlan;
2769
+ delete doc.repeatableSectionInstances;
2770
+ }
2771
+
2772
+ async function addBlock(fieldType: any) {
2773
+ if (!editor) return;
2774
+
2775
+ if (isInlineFieldType(fieldType)) {
2776
+ await insertPaletteFieldInline(fieldType);
2777
+ return;
2778
+ }
2779
+
2780
+ const handler = getFieldHandler(fieldType);
2781
+ if (handler?.insertion === 'table' || fieldType === 'table') {
2782
+ await insertPaletteTableInline(fieldType === 'pivotTable' ? 'pivotTable' : 'table');
2783
+ return;
2784
+ }
2785
+
2786
+ const blockData = createDefaultBlockData(fieldType);
2787
+ const schema = createDefaultSchema(fieldType, blockData.label);
2788
+ registry.updateFieldSchema(blockData.fieldId, schema);
2789
+
2790
+ if (fieldType === 'table') {
2791
+ const merged = ensureCellSchemas(schema, blockData.fieldId, registry.getFieldSchemas(), undefined);
2792
+ registry.setFieldSchemas(merged);
2793
+ }
2794
+
2795
+ options.onSchemaChange?.(registry.getFieldSchemas());
2796
+
2797
+ await editor.isReady;
2798
+ const count = editor.blocks.getBlocksCount();
2799
+ await editor.blocks.insert('templateBlock', blockData, {}, count);
2800
+ }
2801
+
2802
+ async function addPaletteItem(item: any) {
2803
+ if (!editor) return;
2804
+
2805
+ if (item.kind === 'block' && item.type === 'documentSection') {
2806
+ await insertDocumentSection(undefined);
2807
+ return;
2808
+ }
2809
+
2810
+ if (item.kind === 'layout' && item.type === 'columns') {
2811
+ await insertColumnsIntoTargetSection();
2812
+ return;
2813
+ }
2814
+
2815
+ if (item.kind === 'field') {
2816
+ await addBlock(item.type);
2817
+ }
2818
+ }
2819
+
2820
+ const palette = createFieldPalette((item: any) => addPaletteItem(item), {
2821
+ layout: useDesignPanels ? 'vertical' : 'horizontal',
2822
+ excludeTypes: ui.embedded ? ['child'] : [],
2823
+ getSourceSample: () => documentFieldMapping?.sourceSample ?? null,
2824
+ onSourceSampleChange: (sample: unknown) => {
2825
+ documentFieldMapping = normalizeFieldMappingSpec({
2826
+ ...(documentFieldMapping ?? {}),
2827
+ sourceSample: sample,
2828
+ rules: documentFieldMapping?.rules ?? [],
2829
+ });
2830
+ scheduleHistoryRecord();
2831
+ },
2832
+ });
2833
+ refreshDatabaseSourceTree = () => palette.refreshDatabase();
2834
+
2835
+ // Declared later on the public instance; Preview chrome must use the same
2836
+ // mapping-aware path (nested $values rows), not a bare getDocument() open.
2837
+ let runPreview: (options?: any) => Promise<void> = async () => {};
2838
+
2839
+ const documentActions = createDocumentActions({
2840
+ onPreview: ui.showPreview === false ? null : () => {
2841
+ void runPreview().catch((err: any) => {
2842
+ showNotification(err?.message ?? 'Preview failed.', { type: 'error' });
2843
+ });
2844
+ },
2845
+ });
2846
+
2847
+ let topChrome: any = null;
2848
+ const showPalette = ui.palette !== false && !useDesignPanels;
2849
+ const showToolbar = ui.richTextToolbar !== false;
2850
+
2851
+ if (useDesignPanels && designShell) {
2852
+ designShell.leftPanel.appendChild(palette.element);
2853
+
2854
+ propertiesPanel = createPropertiesPanel({
2855
+ getRegistry: () => registry,
2856
+ onRepeaterTemplateChange: (fieldId: any,schema: any) => applyRepeaterSchemaUpdate(fieldId, schema),
2857
+ getRemoteListCollections: options.remoteListCollections ?? null,
2858
+ getRemoteListLabelFields: options.remoteListLabelFields ?? null,
2859
+ onSaveField: async (result: any) => {
2860
+ const previousSchema = registry.getFieldSchemas()[result.previousFieldId];
2861
+ const previousType = previousSchema?.type;
2862
+ if (!previousSchema || !previousType) return;
2863
+ const widthOnly = isTableWidthOnlyChange(previousSchema, result.schema);
2864
+ const ok = await applySchemaSaveResult(result, previousType, previousSchema);
2865
+ if (ok && !widthOnly) await loadFieldProperties(result.fieldId);
2866
+ },
2867
+ onLiveTableColumnWidths: applyLiveTableColumnWidths,
2868
+ onSaveSection: handleSaveSection,
2869
+ onSaveColumns: handleSaveColumns,
2870
+ onSaveDocument: handleSaveDocument,
2871
+ onOpenPageSetup: openPageSetupPanel,
2872
+ });
2873
+ designShell.rightPanel.appendChild(propertiesPanel.element);
2874
+
2875
+ if (showToolbar) {
2876
+ designToolbarWrap = document.createElement('div');
2877
+ designToolbarWrap.className = 'design-panel__toolbar';
2878
+ designToolbarWrap.appendChild(richTextToolbar.element);
2879
+ designShell.centerPanel.insertBefore(designToolbarWrap, holder);
2880
+ }
2881
+
2882
+ designEditorScroll = document.createElement('div');
2883
+ designEditorScroll.className = 'design-panel__editor-scroll';
2884
+ designShell.centerPanel.insertBefore(designEditorScroll, holder);
2885
+ designEditorScroll.appendChild(holder);
2886
+
2887
+ wirePaletteBlockDrop(holder, {
2888
+ onInsertSection: (index: any) => insertDocumentSection(index),
2889
+ });
2890
+
2891
+ palette.refreshDatabase();
2892
+ refreshDesignMappingBadges();
2893
+ }
2894
+
2895
+ if (showPalette || (showToolbar && !useDesignPanels)) {
2896
+ topChrome = document.createElement('div');
2897
+ topChrome.className = 'editor-top-chrome';
2898
+ if (showPalette) topChrome.appendChild(palette.element);
2899
+ if (showToolbar) topChrome.appendChild(richTextToolbar.element);
2900
+ if (ui.stickyChrome !== false && !ui.chromeParent) {
2901
+ topChrome.classList.add('editor-top-chrome--sticky');
2902
+ }
2903
+ mountTopChrome(topChrome, holder, ui);
2904
+ }
2905
+
2906
+ // Always sync after mount — chrome fill mode (SF modal / no design panels) also
2907
+ // mounts the toolbar, and must hide it when designMode is false.
2908
+ syncDesignChromeVisibility();
2909
+
2910
+ if (ui.documentActions !== false) {
2911
+ if (!mountInContainer(documentActions.element, ui.documentActionsContainer)) {
2912
+ mountAdjacentUi(
2913
+ documentActions.element,
2914
+ holder,
2915
+ ui.documentActionsParent,
2916
+ ui.documentActionsAfter,
2917
+ 'before-holder',
2918
+ );
2919
+ }
2920
+ }
2921
+
2922
+ function getSelectedDesignFieldTokens() {
2923
+ return [...holder.querySelectorAll('.field-token--selected.field-token--design')];
2924
+ }
2925
+
2926
+ function listEditorBlocks() {
2927
+ return [...holder.querySelectorAll('.ce-block')];
2928
+ }
2929
+
2930
+ function resolveSectionBlockIndex(sectionEl: any) {
2931
+ const block = sectionEl?.closest('.ce-block');
2932
+ if (!block || !holder.contains(block)) return -1;
2933
+ return listEditorBlocks().indexOf(block);
2934
+ }
2935
+
2936
+ async function loadSelectedSectionProperties(sectionEl: any = null) {
2937
+ if (selectedSectionBlockIndex < 0 || !propertiesPanel || !editor) return;
2938
+
2939
+ try {
2940
+ await editor.isReady;
2941
+ const saved = await editor.save();
2942
+ const block = saved.blocks?.[selectedSectionBlockIndex];
2943
+ if (block?.type !== 'documentSection') return;
2944
+
2945
+ const section =
2946
+ sectionEl ??
2947
+ listEditorBlocks()[selectedSectionBlockIndex]?.querySelector('.document-section') ??
2948
+ null;
2949
+
2950
+ propertiesPanel.showSection(
2951
+ selectedSectionBlockIndex,
2952
+ {
2953
+ name: block.data?.name ?? '',
2954
+ label: block.data?.label ?? '',
2955
+ repeatable: !!block.data?.repeatable,
2956
+ hideTitleInPreview: !!block.data?.hideTitleInPreview,
2957
+ borderTop: !!block.data?.borderTop,
2958
+ borderBottom: !!block.data?.borderBottom,
2959
+ eachRowOnNewPage: !!block.data?.eachRowOnNewPage,
2960
+ keepOnOnePage: !!block.data?.keepOnOnePage,
2961
+ visibility: block.data?.visibility ?? null,
2962
+ },
2963
+ section,
2964
+ );
2965
+ updateSectionSelectionHighlight();
2966
+ } catch {
2967
+ // editor not ready
2968
+ }
2969
+ }
2970
+
2971
+ function updateSectionSelectionHighlight() {
2972
+ holder.querySelectorAll('.document-section--selected').forEach((el: any) => {
2973
+ el.classList.remove('document-section--selected');
2974
+ });
2975
+ if (selectedSectionBlockIndex < 0) return;
2976
+ listEditorBlocks()[selectedSectionBlockIndex]
2977
+ ?.querySelector('.document-section')
2978
+ ?.classList.add('document-section--selected');
2979
+ }
2980
+
2981
+ function onDesignHolderClick(e: any) {
2982
+ if (!designMode || !useDesignPanels || !propertiesPanel) return;
2983
+ // Ignore leftover clicks from a table or columns resize / reorder drag.
2984
+ if (document.body.classList.contains('vision-table-col-resize-active')) return;
2985
+ if (document.body.classList.contains('vision-table-col-reorder-active')) return;
2986
+ if (document.body.classList.contains('document-columns-col-resize-active')) return;
2987
+ if (e.target?.closest?.('.vision-table__col-resizer')) return;
2988
+ if (e.target?.closest?.('.document-columns__col-resizer')) return;
2989
+
2990
+ if (
2991
+ e.target === holder ||
2992
+ e.target === designEditorScroll ||
2993
+ e.target.classList?.contains('codex-editor') ||
2994
+ e.target.classList?.contains('codex-editor__redactor') ||
2995
+ e.target.classList?.contains('ce-block') ||
2996
+ e.target.classList?.contains('ce-block__content')
2997
+ ) {
2998
+ selectedSectionBlockIndex = -1;
2999
+ clearStructureSelection();
3000
+ clearAllDesignTokenSelection(holder);
3001
+ updateSectionSelectionHighlight();
3002
+ propertiesPanel.showDocument(documentPageSetup);
3003
+ return;
3004
+ }
3005
+
3006
+ const columnsToolbar = e.target.closest('.document-columns__toolbar');
3007
+ if (columnsToolbar && holder.contains(columnsToolbar)) {
3008
+ if (e.target.closest('[data-action="delete-columns"]')) {
3009
+ return;
3010
+ }
3011
+ const columnsEl = columnsToolbar.closest('.document-columns');
3012
+ if (!columnsEl) return;
3013
+
3014
+ e.preventDefault();
3015
+ e.stopPropagation();
3016
+ selectColumnsEl(columnsEl);
3017
+ return;
3018
+ }
3019
+
3020
+ const tableToolbar = e.target.closest('.document-table__toolbar');
3021
+ if (tableToolbar && holder.contains(tableToolbar)) {
3022
+ if (e.target.closest('[data-action="delete-table"]')) {
3023
+ return;
3024
+ }
3025
+ const tableEl = tableToolbar.closest('.document-table');
3026
+ if (!tableEl) return;
3027
+
3028
+ e.preventDefault();
3029
+ e.stopPropagation();
3030
+ selectTableEl(tableEl);
3031
+ return;
3032
+ }
3033
+
3034
+ // Pivot has no cell tokens — clicking the grid should still select the block.
3035
+ const pivotEl = e.target.closest('.document-table--pivot');
3036
+ if (pivotEl && holder.contains(pivotEl)) {
3037
+ if (e.target.closest('[data-action="delete-table"], .pivot-table__row-label-resizer, .vision-table__col-resizer')) {
3038
+ return;
3039
+ }
3040
+ e.preventDefault();
3041
+ e.stopPropagation();
3042
+ selectTableEl(pivotEl);
3043
+ return;
3044
+ }
3045
+
3046
+ // Clicking into prose clears Section/Table selection so Properties don't stick.
3047
+ if (shouldClearObjectSelectionForTextTarget(e.target)) {
3048
+ clearObjectSelectionForTextEdit();
3049
+ return;
3050
+ }
3051
+
3052
+ const header = e.target.closest('.document-section__header');
3053
+ if (!header || !holder.contains(header)) return;
3054
+ if (e.target.closest('.document-section__body, .field-token')) {
3055
+ return;
3056
+ }
3057
+
3058
+ const section = header.closest('.document-section');
3059
+ const blockIndex = resolveSectionBlockIndex(section);
3060
+ if (blockIndex < 0) return;
3061
+
3062
+ e.preventDefault();
3063
+ e.stopPropagation();
3064
+
3065
+ selectedSectionBlockIndex = blockIndex;
3066
+ clearStructureSelection();
3067
+ clearAllDesignTokenSelection(holder);
3068
+ updateSectionSelectionHighlight();
3069
+ focusStructureTarget(section);
3070
+ void loadSelectedSectionProperties(section);
3071
+ }
3072
+
3073
+ holder.addEventListener('click', onDesignHolderClick);
3074
+
3075
+ function getStyleTargetFieldIds() {
3076
+ const schemas = registry.getFieldSchemas();
3077
+ const ids = new Set();
3078
+
3079
+ for (const token of getSelectedDesignFieldTokens()) {
3080
+ if (token.classList.contains('field-token--cell')) {
3081
+ const tableId = token.dataset.tableId;
3082
+ const colKey = token.dataset.colKey;
3083
+ if (tableId && colKey) {
3084
+ for (const id of listColumnCellFieldIds(tableId, colKey, schemas)) {
3085
+ ids.add(id);
3086
+ }
3087
+ } else if (token.dataset.fieldId) {
3088
+ ids.add(token.dataset.fieldId);
3089
+ }
3090
+ continue;
3091
+ }
3092
+
3093
+ if (token.dataset.fieldId) ids.add(token.dataset.fieldId);
3094
+ }
3095
+
3096
+ return [...ids];
3097
+ }
3098
+
3099
+ function getPrimaryStyleFieldId() {
3100
+ const tokens = getSelectedDesignFieldTokens();
3101
+ if (!tokens.length) return null;
3102
+
3103
+ const anchor =
3104
+ tokens.find((token: any) => token.classList.contains('field-token--column-anchor')) ?? tokens[0];
3105
+ return anchor?.dataset.fieldId ?? null;
3106
+ }
3107
+
3108
+ function isTableColumnSelection() {
3109
+ const tokens = getSelectedDesignFieldTokens();
3110
+ return tokens.length > 0 && tokens.every((token: any) => token.classList.contains('field-token--cell'));
3111
+ }
3112
+
3113
+ function getTableColumnSelectionHint() {
3114
+ const tokens = getSelectedDesignFieldTokens();
3115
+ const token =
3116
+ tokens.find((t: any) => t.classList.contains('field-token--column-anchor')) ?? tokens[0];
3117
+ const colKey = String(token?.dataset?.colKey ?? '').trim();
3118
+ const label = colKey ? `“${colKey}”` : 'Table column';
3119
+ return `${label} column selected — formatting applies to the whole column.`;
3120
+ }
3121
+
3122
+ function applyDisplayStyleToFieldIds(fieldIds: any,normalized: any) {
3123
+ const schemas = registry.getFieldSchemas();
3124
+
3125
+ for (const fieldId of fieldIds) {
3126
+ const schema = schemas[fieldId];
3127
+ if (!schema) continue;
3128
+ const updated = { ...schema };
3129
+ if (isEmptyFieldDisplayStyle(normalized)) {
3130
+ delete updated.displayStyle;
3131
+ } else {
3132
+ updated.displayStyle = normalized;
3133
+ }
3134
+ registry.updateFieldSchema(fieldId, updated);
3135
+ refreshFieldSchemaInDom(fieldId, { getRegistry: () => registry, fieldValueStyle }, holder);
3136
+ }
3137
+
3138
+ refreshTableColumnStylesForFieldIds(fieldIds, registry.getFieldSchemas(), holder, fieldValueStyle);
3139
+
3140
+ options.onSchemaChange?.(registry.getFieldSchemas());
3141
+ syncFieldStyleToolbar();
3142
+ }
3143
+
3144
+ function applyDisplayStyleToSelectedFields(override: any) {
3145
+ applyDisplayStyleToFieldIds(getStyleTargetFieldIds(), normalizeFieldDisplayStyle(override));
3146
+ }
3147
+
3148
+ function syncFieldStyleToolbar() {
3149
+ if (!designMode || !showToolbar) {
3150
+ if (richTextToolbar.isFieldModeActive()) {
3151
+ richTextToolbar.clearFieldMode();
3152
+ if (lastFocusedEditable?.isConnected) {
3153
+ richTextToolbar.show(lastFocusedEditable);
3154
+ } else {
3155
+ richTextToolbar.clearActive();
3156
+ }
3157
+ }
3158
+ return;
3159
+ }
3160
+
3161
+ const tokens = getSelectedDesignFieldTokens();
3162
+ if (!tokens.length) {
3163
+ richTextToolbar.clearFieldMode();
3164
+ if (lastFocusedEditable?.isConnected) {
3165
+ richTextToolbar.show(lastFocusedEditable);
3166
+ } else {
3167
+ richTextToolbar.clearActive();
3168
+ }
3169
+ return;
3170
+ }
3171
+
3172
+ richTextToolbar.showForField({
3173
+ getResolvedStyle: () => {
3174
+ const fieldId = getPrimaryStyleFieldId();
3175
+ const schemas = registry.getFieldSchemas();
3176
+ const schema = schemas[fieldId];
3177
+ const cellRef = fieldId ? parseCellFieldId(fieldId, schemas) : null;
3178
+ if (cellRef) {
3179
+ return resolveTableCellDisplayStyle(
3180
+ cellRef.tableFieldId,
3181
+ cellRef.colKey,
3182
+ schema,
3183
+ schemas,
3184
+ fieldValueStyle,
3185
+ );
3186
+ }
3187
+ return resolveFieldDisplayStyle(schema, fieldValueStyle?.default);
3188
+ },
3189
+ getOverrideStyle: () => {
3190
+ const fieldId = getPrimaryStyleFieldId();
3191
+ return normalizeFieldDisplayStyle(registry.getFieldSchemas()[fieldId]?.displayStyle);
3192
+ },
3193
+ getGlobalDefault: () => isTableColumnSelection()
3194
+ ? { ...DOCUMENT_TABLE_TEXT_STYLE, ...(fieldValueStyle?.default ?? {}) }
3195
+ : (fieldValueStyle?.default ?? {}),
3196
+ hint: isTableColumnSelection() ? getTableColumnSelectionHint() : undefined,
3197
+ onStyleChange: (override: any) => {
3198
+ applyDisplayStyleToSelectedFields(override);
3199
+ },
3200
+ onClearStyle: () => {
3201
+ applyDisplayStyleToFieldIds(getStyleTargetFieldIds(), {});
3202
+ },
3203
+ });
3204
+ }
3205
+
3206
+ function eventFocusTarget(e: Event): Element | null {
3207
+ // Prefer composedPath; under LWS document listeners may still retarget — prefer shell listeners.
3208
+ const path = typeof e.composedPath === 'function' ? e.composedPath() : [];
3209
+ for (const node of path) {
3210
+ if (node instanceof Element) return node;
3211
+ }
3212
+ return e.target instanceof Element ? e.target : null;
3213
+ }
3214
+
3215
+ function activateToolbarForTarget(target: Element | null) {
3216
+ if (!target) return false;
3217
+
3218
+ if (designMode && target.closest?.('.field-token--design')) {
3219
+ syncFieldStyleToolbar();
3220
+ return true;
3221
+ }
3222
+
3223
+ if (shouldClearObjectSelectionForTextTarget(target)) {
3224
+ clearObjectSelectionForTextEdit();
3225
+ }
3226
+
3227
+ const columnEditable = target.closest?.('.document-columns__col');
3228
+ if (columnEditable && holder.contains(columnEditable)) {
3229
+ lastFocusedEditable = columnEditable;
3230
+ if (designMode && getSelectedDesignFieldTokens().length) {
3231
+ syncFieldStyleToolbar();
3232
+ return true;
3233
+ }
3234
+ richTextToolbar.show(columnEditable);
3235
+ return true;
3236
+ }
3237
+
3238
+ const editable = target.closest?.('.document-section__body');
3239
+ if (editable && holder.contains(editable)) {
3240
+ // Focusing a selected table/columns block lives inside the section body —
3241
+ // don't treat that as prose editing.
3242
+ if (isDesignStructureTarget(target)) {
3243
+ return false;
3244
+ }
3245
+ lastFocusedEditable = editable;
3246
+ if (designMode && getSelectedDesignFieldTokens().length) {
3247
+ syncFieldStyleToolbar();
3248
+ return true;
3249
+ }
3250
+ richTextToolbar.show(editable);
3251
+ return true;
3252
+ }
3253
+
3254
+ if (target.closest('.rich-text-toolbar')) {
3255
+ return true;
3256
+ }
3257
+
3258
+ if (designMode && getSelectedDesignFieldTokens().length) {
3259
+ syncFieldStyleToolbar();
3260
+ return true;
3261
+ }
3262
+
3263
+ return false;
3264
+ }
3265
+
3266
+ function onFocusIn(e: any) {
3267
+ const target = eventFocusTarget(e);
3268
+ if (!activateToolbarForTarget(target)) {
3269
+ richTextToolbar.clearActive();
3270
+ }
3271
+ }
3272
+
3273
+ /** Click/mouseup backup — LWS can swallow document focusin into the shadow tree. */
3274
+ function onEditorPointerActivate(e: any) {
3275
+ const target = eventFocusTarget(e);
3276
+ activateToolbarForTarget(target);
3277
+ }
3278
+
3279
+ /** Block Salesforce page shortcuts (e.g. "e" → Edit). Class cke_editable is the reliable SF bypass. */
3280
+ function onEditorKeyDown(e: KeyboardEvent) {
3281
+ e.stopPropagation();
3282
+ if (e.defaultPrevented) return;
3283
+
3284
+ const mod = e.ctrlKey || e.metaKey;
3285
+ if (!mod || e.altKey) return;
3286
+ if (!shouldHandleHistoryShortcut(e)) return;
3287
+
3288
+ const key = e.key.toLowerCase();
3289
+ if (key === 'z' && !e.shiftKey) {
3290
+ e.preventDefault();
3291
+ void undoDocument();
3292
+ return;
3293
+ }
3294
+ if (key === 'y' || (key === 'z' && e.shiftKey)) {
3295
+ e.preventDefault();
3296
+ void redoDocument();
3297
+ }
3298
+ }
3299
+
3300
+ function onDesignStructureDeleteKeyDown(e: KeyboardEvent) {
3301
+ if (!designMode) return;
3302
+ if (e.key !== 'Delete' && e.key !== 'Backspace') return;
3303
+ if (e.ctrlKey || e.metaKey || e.altKey) return;
3304
+ if (e.defaultPrevented) return;
3305
+ if (shouldIgnoreStructureDeleteKey(e)) return;
3306
+
3307
+ if (selectedColumnsEl?.isConnected) {
3308
+ e.preventDefault();
3309
+ e.stopPropagation();
3310
+ deleteSelectedColumnsBlock();
3311
+ return;
3312
+ }
3313
+
3314
+ if (selectedTableEl?.isConnected) {
3315
+ e.preventDefault();
3316
+ e.stopPropagation();
3317
+ deleteSelectedTableBlock();
3318
+ return;
3319
+ }
3320
+
3321
+ if (selectedSectionBlockIndex >= 0) {
3322
+ e.preventDefault();
3323
+ e.stopPropagation();
3324
+ void deleteSelectedSectionBlock();
3325
+ }
3326
+ }
3327
+
3328
+ setFieldSelectionChangeCallback(() => {
3329
+ syncFieldStyleToolbar();
3330
+ syncPropertiesPanel();
3331
+ });
3332
+
3333
+ // Listen on the shell/holder (same tree as contenteditable) — not document alone (LWS retargets).
3334
+ // Also listen on document so Delete still works after selecting a non-focusable header
3335
+ // (focus often moves to <body> and never reaches the shell).
3336
+ const focusRoot = designShell?.element ?? holder;
3337
+ focusRoot.addEventListener('focusin', onFocusIn);
3338
+ focusRoot.addEventListener('mouseup', onEditorPointerActivate);
3339
+ focusRoot.addEventListener('keydown', onEditorKeyDown);
3340
+ focusRoot.addEventListener('keydown', onDesignStructureDeleteKeyDown, true);
3341
+ holder.addEventListener('keydown', onEditorKeyDown);
3342
+ holder.addEventListener('keydown', onDesignStructureDeleteKeyDown, true);
3343
+ document.addEventListener('keydown', onDesignStructureDeleteKeyDown, true);
3344
+
3345
+ syncShowFieldsHighlight();
3346
+ initEditor(options.data ?? options.defaultDocument ?? DEFAULT_EMPTY_DOCUMENT);
3347
+
3348
+ async function applyFieldMappingToEditor(payload: any, specOverride: any = null) {
3349
+ const doc = await getDocument();
3350
+ const spec = specOverride
3351
+ ? normalizeFieldMappingSpec(specOverride)
3352
+ : documentFieldMapping;
3353
+ if (specOverride) {
3354
+ documentFieldMapping = spec;
3355
+ }
3356
+ if (!spec?.rules?.length && !spec?.expression?.trim()) {
3357
+ throw new Error('No field mapping configured.');
3358
+ }
3359
+ const result = runFieldMapping(payload, spec, {
3360
+ blocks: doc.blocks,
3361
+ fieldSchemas: doc.fieldSchemas,
3362
+ });
3363
+ loadedDocumentSections = result.fieldsExport.sections
3364
+ ? JSON.parse(JSON.stringify(result.fieldsExport.sections))
3365
+ : null;
3366
+ const mappedMaterialized = materializeRepeatableSectionInstances(
3367
+ result.blocks,
3368
+ result.fieldSchemas,
3369
+ loadedDocumentSections,
3370
+ );
3371
+ initEditor({
3372
+ time: Date.now(),
3373
+ fieldSchemas: mappedMaterialized.fieldSchemas,
3374
+ blocks: mappedMaterialized.blocks,
3375
+ pageSetup: documentPageSetup,
3376
+ fieldMapping: documentFieldMapping,
3377
+ });
3378
+ // Wait for sections to mount, then recompute like preview (sum of mapped table columns).
3379
+ if (editor) await editor.isReady;
3380
+ syncFillComputedFields(holder, {}, {
3381
+ getRegistry: () => registry,
3382
+ editorHolder: holder,
3383
+ fieldValueStyle,
3384
+ fillModeFieldHighlight: !designMode && showFieldsInFillMode && !options.mappingMode,
3385
+ });
3386
+ return result;
3387
+ }
3388
+
3389
+ runPreview = async (previewOptions: any = {}) => {
3390
+ if (editor) await editor.save();
3391
+ documentActions.setBusy(true);
3392
+ try {
3393
+ // Re-apply mapping in memory (do not remount the editor). Remounting lets
3394
+ // EditorJS mutate the shared blocks reference back to a single seed row
3395
+ // before Preview clones them — dropping nested $values detail rows.
3396
+ const sample = documentFieldMapping?.sourceSample;
3397
+ const hasRules =
3398
+ Array.isArray(documentFieldMapping?.rules) && documentFieldMapping.rules.length > 0;
3399
+ let previewDoc: any = null;
3400
+ if (sample != null && hasRules) {
3401
+ try {
3402
+ const doc = await getDocument();
3403
+ const result = runFieldMapping(sample, documentFieldMapping, {
3404
+ blocks: doc.blocks,
3405
+ fieldSchemas: doc.fieldSchemas,
3406
+ });
3407
+ const sections = result.fieldsExport?.sections
3408
+ ? JSON.parse(JSON.stringify(result.fieldsExport.sections))
3409
+ : null;
3410
+ loadedDocumentSections = sections;
3411
+ previewDoc = {
3412
+ time: Date.now(),
3413
+ blocks: JSON.parse(JSON.stringify(result.blocks)),
3414
+ fieldSchemas: JSON.parse(JSON.stringify(result.fieldSchemas)),
3415
+ loadedDocumentSections: sections,
3416
+ };
3417
+ if (Object.keys(documentPageSetup).length > 0) {
3418
+ previewDoc.pageSetup = JSON.parse(JSON.stringify(documentPageSetup));
3419
+ }
3420
+ if (documentFieldMapping) {
3421
+ previewDoc.fieldMapping = JSON.parse(JSON.stringify(documentFieldMapping));
3422
+ }
3423
+ attachRepeatableInstances(previewDoc);
3424
+ } catch (err: any) {
3425
+ console.warn('[docengine] preview mapping apply failed', err);
3426
+ showNotification(err?.message ?? 'Preview mapping failed.', { type: 'error' });
3427
+ previewDoc = null;
3428
+ }
3429
+ }
3430
+ await previewModal.open(previewDoc ?? (await getDocument()), {
3431
+ hideEmptyValues: previewOptions.hideEmptyValues === true,
3432
+ });
3433
+ } finally {
3434
+ documentActions.setBusy(false);
3435
+ refreshTableCellTokens(holder, { getRegistry: () => registry, fieldValueStyle });
3436
+ pruneTableCellCaretAnchors(holder);
3437
+ }
3438
+ };
3439
+
3440
+ /**
3441
+ * Build an HTML or PDF blob for the host to email / Slack / attach.
3442
+ * Use `format: 'current'` to follow the open preview view mode (defaults to html).
3443
+ */
3444
+ async function getPreviewArtifact(callOptions: any = {}) {
3445
+ if (editor) await editor.save();
3446
+ const doc = await getDocument();
3447
+
3448
+ const {
3449
+ format: formatOption,
3450
+ filename: filenameOption,
3451
+ generatePdfBlob: generateOverride,
3452
+ hideEmptyValues: hideEmptyOption,
3453
+ title: titleOption,
3454
+ ...restExport
3455
+ } = callOptions;
3456
+
3457
+ const format: 'html' | 'pdf' =
3458
+ formatOption === 'pdf' || formatOption === 'html'
3459
+ ? formatOption
3460
+ : previewModal.isOpen()
3461
+ ? previewModal.getViewMode()
3462
+ : 'html';
3463
+
3464
+ const hideEmptyValues =
3465
+ typeof hideEmptyOption === 'boolean'
3466
+ ? hideEmptyOption
3467
+ : previewModal.isOpen()
3468
+ ? previewModal.getHideEmptyValues()
3469
+ : false;
3470
+
3471
+ const exportOptions = resolvePreviewExportOptions(doc, {
3472
+ ...restExport,
3473
+ hideEmptyValues,
3474
+ fieldValueStyle,
3475
+ title: titleOption ?? (documentPageSetup as any).title ?? ui.pdfTitle,
3476
+ });
3477
+
3478
+ const title =
3479
+ titleOption ??
3480
+ exportOptions.title ??
3481
+ (documentPageSetup as any).title ??
3482
+ ui.pdfTitle ??
3483
+ 'document';
3484
+
3485
+ if (format === 'pdf') {
3486
+ const pdfOk =
3487
+ options.pdfAvailable !== undefined
3488
+ ? !!(await Promise.resolve(
3489
+ typeof options.pdfAvailable === 'function'
3490
+ ? options.pdfAvailable()
3491
+ : options.pdfAvailable,
3492
+ ))
3493
+ : typeof options.generatePdfBlob === 'function' ||
3494
+ typeof generateOverride === 'function' ||
3495
+ isClientPdfAvailable;
3496
+ if (!pdfOk) {
3497
+ throw new Error('PDF generation is not available.');
3498
+ }
3499
+ const generate =
3500
+ typeof generateOverride === 'function'
3501
+ ? generateOverride
3502
+ : typeof options.generatePdfBlob === 'function'
3503
+ ? options.generatePdfBlob
3504
+ : null;
3505
+ const blob = generate
3506
+ ? await generate(doc, exportOptions)
3507
+ : await generateDocumentPdfBlob(doc, exportOptions);
3508
+ const filename =
3509
+ filenameOption ??
3510
+ buildExportFilename({ title, baseName: ui.pdfFilename, format: 'pdf' });
3511
+ return { blob, filename, mimeType: 'application/pdf', format: 'pdf' as const };
3512
+ }
3513
+
3514
+ const blob = buildPreviewHtmlBlob(doc, exportOptions);
3515
+ const filename =
3516
+ filenameOption ??
3517
+ buildExportFilename({ title, baseName: ui.pdfFilename, format: 'html' });
3518
+ return { blob, filename, mimeType: 'text/html;charset=utf-8', format: 'html' as const };
3519
+ }
3520
+
3521
+ const instance = {
3522
+ holder,
3523
+ registry,
3524
+ palette,
3525
+ richTextToolbar,
3526
+ documentActions,
3527
+
3528
+ get ready() {
3529
+ return editor?.isReady ?? Promise.resolve();
3530
+ },
3531
+
3532
+ getDocument,
3533
+ exportDoc: async () => buildDocExport(await getDocument()),
3534
+ exportFields: async (exportOptions: any = {}) => {
3535
+ const doc = await getDocument();
3536
+ let exported = buildFieldsExport(doc, exportOptions);
3537
+ if (exportOptions?.omitMappedFields === true) {
3538
+ exported = omitMappedFields(exported, documentFieldMapping ?? doc.fieldMapping);
3539
+ }
3540
+ return exported;
3541
+ },
3542
+ exportTemplate: async () => buildTemplateExport(await getDocument()),
3543
+ /** @deprecated Use exportFields() */
3544
+ exportDocument: async (exportOptions: any = {}) => {
3545
+ const doc = await getDocument();
3546
+ let exported = buildFieldsExport(doc, exportOptions);
3547
+ if (exportOptions?.omitMappedFields === true) {
3548
+ exported = omitMappedFields(exported, documentFieldMapping ?? doc.fieldMapping);
3549
+ }
3550
+ return exported;
3551
+ },
3552
+
3553
+ async load(data: any, loadOptions: any = {}) {
3554
+ if (editor) await editor.save();
3555
+
3556
+ if (isFieldsExport(data)) {
3557
+ const doc = await getDocument();
3558
+ let fieldsPayload = data;
3559
+ if (loadOptions?.omitMappedFields === true) {
3560
+ fieldsPayload = omitMappedFields(
3561
+ data,
3562
+ documentFieldMapping ?? doc.fieldMapping,
3563
+ );
3564
+ }
3565
+ loadedDocumentSections = fieldsPayload.sections
3566
+ ? JSON.parse(JSON.stringify(fieldsPayload.sections))
3567
+ : null;
3568
+ const values = normalizeDocumentValues(fieldsPayload, doc.blocks, doc.fieldSchemas);
3569
+ const applied = applyDocumentValues(
3570
+ doc.blocks,
3571
+ values,
3572
+ doc.fieldSchemas,
3573
+ );
3574
+ // Expand `_source` section arrays into concrete fill blocks (one per
3575
+ // instance, including nested table rows). Preview/PDF already clones via
3576
+ // repeatableSectionInstances; without this the editor only shows [0].
3577
+ const materialized = materializeRepeatableSectionInstances(
3578
+ applied.blocks,
3579
+ applied.fieldSchemas,
3580
+ loadedDocumentSections,
3581
+ );
3582
+ const resume = documentHistory.suspend();
3583
+ try {
3584
+ initEditor({
3585
+ time: fieldsPayload.time ?? Date.now(),
3586
+ fieldSchemas: materialized.fieldSchemas,
3587
+ blocks: materialized.blocks,
3588
+ pageSetup: documentPageSetup,
3589
+ });
3590
+ if (editor) await editor.isReady;
3591
+ documentHistory.reset(getHistorySnapshot());
3592
+ } finally {
3593
+ resume();
3594
+ }
3595
+ } else {
3596
+ loadedDocumentSections = null;
3597
+ const resume = documentHistory.suspend();
3598
+ try {
3599
+ initEditor(normalizeImportedDoc(data));
3600
+ if (editor) await editor.isReady;
3601
+ documentHistory.reset(getHistorySnapshot());
3602
+ } finally {
3603
+ resume();
3604
+ }
3605
+ }
3606
+
3607
+ // Keep parity with mapping apply: after import/load remounts EditorJS and
3608
+ // tokens are seeded, recompute all computed values from loaded fields so
3609
+ // table totals/subtotals are immediately correct before manual edits.
3610
+ syncFillComputedFields(holder, {}, {
3611
+ getRegistry: () => registry,
3612
+ editorHolder: holder,
3613
+ fieldValueStyle,
3614
+ fillModeFieldHighlight: !designMode && showFieldsInFillMode && !options.mappingMode,
3615
+ });
3616
+
3617
+ // Version switch / import remounts EditorJS; drop stale section selection
3618
+ // and show Page Setup so the properties panel matches the new document.
3619
+ if (useDesignPanels && designMode) {
3620
+ openPageSetupPanel();
3621
+ }
3622
+ },
3623
+
3624
+ undo: () => undoDocument(),
3625
+ redo: () => redoDocument(),
3626
+ canUndo: () => {
3627
+ flushHistoryRecord();
3628
+ return documentHistory.canUndo();
3629
+ },
3630
+ canRedo: () => {
3631
+ flushHistoryRecord();
3632
+ return documentHistory.canRedo();
3633
+ },
3634
+
3635
+ async setDesignMode(enabled: any) {
3636
+ if (setDesignModeInFlight) {
3637
+ await setDesignModeInFlight;
3638
+ }
3639
+ const run = (async () => {
3640
+ if (typeof propertiesPanel?.flush === 'function') {
3641
+ try {
3642
+ await propertiesPanel.flush();
3643
+ } catch {
3644
+ // keep switching mode even if properties save fails
3645
+ }
3646
+ }
3647
+ if (editor) {
3648
+ try {
3649
+ await editor.isReady;
3650
+ await editor.save();
3651
+ } catch {
3652
+ // editor not ready
3653
+ }
3654
+ }
3655
+ designMode = !!enabled;
3656
+ applyDesignMode(designMode);
3657
+ syncDesignChromeVisibility();
3658
+ const doc = await getDocument();
3659
+ initEditor(doc);
3660
+ if (editor) {
3661
+ try {
3662
+ await editor.isReady;
3663
+ } catch {
3664
+ // ignore
3665
+ }
3666
+ }
3667
+ })();
3668
+ setDesignModeInFlight = run.finally(() => {
3669
+ if (setDesignModeInFlight === run) setDesignModeInFlight = null;
3670
+ });
3671
+ await setDesignModeInFlight;
3672
+ },
3673
+
3674
+ getDesignMode: () => designMode,
3675
+
3676
+ setShowFieldsInFillMode(enabled: any) {
3677
+ showFieldsInFillMode = !!enabled;
3678
+ syncShowFieldsHighlight();
3679
+ },
3680
+
3681
+ getShowFieldsInFillMode: () => showFieldsInFillMode,
3682
+
3683
+ async preview(options: any = {}) {
3684
+ return runPreview(options);
3685
+ },
3686
+
3687
+ isPreviewOpen: () => previewModal.isOpen(),
3688
+
3689
+ closePreview: () => {
3690
+ previewModal.close();
3691
+ },
3692
+
3693
+ /**
3694
+ * Render Simple preview HTML (optionally hiding empty fields) for export/attach.
3695
+ * @returns {Promise<string>}
3696
+ */
3697
+ async exportPreviewHtml(callOptions: any = {}) {
3698
+ if (editor) await editor.save();
3699
+ const doc = await getDocument();
3700
+ const exportOptions = resolvePreviewExportOptions(doc, {
3701
+ hideEmptyValues: callOptions.hideEmptyValues === true,
3702
+ fieldValueStyle,
3703
+ title: callOptions.title,
3704
+ });
3705
+ return buildPreviewHtmlDocument(doc, exportOptions);
3706
+ },
3707
+
3708
+ getPreviewArtifact,
3709
+
3710
+ async exportPdf(callOptions: any) {
3711
+ try {
3712
+ const artifact = await getPreviewArtifact({
3713
+ ...callOptions,
3714
+ format: 'pdf',
3715
+ filename:
3716
+ callOptions?.filename ??
3717
+ (ui.pdfFilename
3718
+ ? buildExportFilename({
3719
+ baseName: ui.pdfFilename,
3720
+ format: 'pdf',
3721
+ unique: false,
3722
+ })
3723
+ : undefined),
3724
+ });
3725
+ await saveBlobToDisk(artifact.blob, artifact.filename, 'application/pdf');
3726
+ } catch (err: any) {
3727
+ showNotification(err?.message ?? 'PDF export failed.');
3728
+ }
3729
+ },
3730
+
3731
+ validate: async () => validateRequiredFields(await getDocument()),
3732
+
3733
+ getFieldMapping() {
3734
+ return documentFieldMapping ? JSON.parse(JSON.stringify(documentFieldMapping)) : null;
3735
+ },
3736
+
3737
+ setFieldMapping(spec: any) {
3738
+ documentFieldMapping = spec ? normalizeFieldMappingSpec(spec) : null;
3739
+ if (documentFieldMapping?.rules?.length) {
3740
+ syncDocumentFieldMappingNames();
3741
+ } else {
3742
+ refreshDesignMappingBadges();
3743
+ }
3744
+ refreshDatabaseSourceTree?.();
3745
+ },
3746
+
3747
+ async previewFieldMapping(payload: any) {
3748
+ const doc = await getDocument();
3749
+ const spec = documentFieldMapping ?? normalizeFieldMappingSpec(null);
3750
+ return runFieldMappingPreview(payload, spec, {
3751
+ blocks: doc.blocks,
3752
+ fieldSchemas: doc.fieldSchemas,
3753
+ });
3754
+ },
3755
+
3756
+ async applyFieldMapping(payload: any) {
3757
+ return applyFieldMappingToEditor(payload);
3758
+ },
3759
+
3760
+ async openFieldMapping(options: any = {}) {
3761
+ if (!fieldMappingModal) {
3762
+ throw new Error('Field mapping editor is not available in this editor.');
3763
+ }
3764
+ // Persist live canvas tokens into registry blocks before the modal reads
3765
+ // getTemplate(). Palette drops update fieldSchemas immediately but blocks
3766
+ // stay stale until EditorJS save — without this, new fields (e.g. _root_text)
3767
+ // are pruned from buildTemplateExport and missing from Template fields.
3768
+ if (editor) {
3769
+ try {
3770
+ await editor.isReady;
3771
+ const live = await editor.save();
3772
+ registry.setBlocks(live.blocks ?? []);
3773
+ } catch {
3774
+ // editor not ready — fall through with current registry state
3775
+ }
3776
+ }
3777
+ const spec = options.spec ?? documentFieldMapping ?? normalizeFieldMappingSpec(null);
3778
+ // Keep Database tab Source payload in sync with the sample Mapping will show.
3779
+ if (spec?.sourceSample != null) {
3780
+ documentFieldMapping = normalizeFieldMappingSpec({
3781
+ ...(documentFieldMapping ?? spec),
3782
+ sourceSample: spec.sourceSample,
3783
+ rules: documentFieldMapping?.rules ?? spec.rules ?? [],
3784
+ expression: documentFieldMapping?.expression ?? spec.expression ?? '',
3785
+ });
3786
+ } else if (!documentFieldMapping && spec) {
3787
+ documentFieldMapping = normalizeFieldMappingSpec(spec);
3788
+ }
3789
+ // Align rule section/field names with current template before editing.
3790
+ syncDocumentFieldMappingNames();
3791
+ refreshDatabaseSourceTree?.();
3792
+ const saved = await fieldMappingModal.open({
3793
+ spec: documentFieldMapping ?? spec,
3794
+ onApply: (payload: any, mappingSpec: any) =>
3795
+ applyFieldMappingToEditor(payload, mappingSpec ?? null),
3796
+ onExpandSourcePath: options.onExpandSourcePath,
3797
+ });
3798
+ documentFieldMapping = saved;
3799
+ refreshDatabaseSourceTree?.();
3800
+ refreshDesignMappingBadges();
3801
+ options.onChange?.(await getDocument());
3802
+ return saved;
3803
+ },
3804
+
3805
+ async save() {
3806
+ if (editor) await editor.save();
3807
+ return getDocument();
3808
+ },
3809
+
3810
+ destroy() {
3811
+ destroyed = true;
3812
+ if (historyTimer) {
3813
+ clearTimeout(historyTimer);
3814
+ historyTimer = null;
3815
+ }
3816
+ focusRoot.removeEventListener('focusin', onFocusIn);
3817
+ focusRoot.removeEventListener('mouseup', onEditorPointerActivate);
3818
+ focusRoot.removeEventListener('keydown', onEditorKeyDown);
3819
+ focusRoot.removeEventListener('keydown', onDesignStructureDeleteKeyDown, true);
3820
+ holder.removeEventListener('keydown', onEditorKeyDown);
3821
+ holder.removeEventListener('keydown', onDesignStructureDeleteKeyDown, true);
3822
+ document.removeEventListener('keydown', onDesignStructureDeleteKeyDown, true);
3823
+ holder.removeEventListener('click', onDesignHolderClick);
3824
+ if (editor) {
3825
+ const prev = editor;
3826
+ editor = null;
3827
+ if (typeof prev.destroy === 'function') {
3828
+ try {
3829
+ prev.destroy();
3830
+ } catch {
3831
+ // ignore
3832
+ }
3833
+ }
3834
+ }
3835
+ topChrome?.remove();
3836
+ designToolbarWrap?.remove();
3837
+ if (designEditorScroll?.contains(holder) && designShell?.centerPanel) {
3838
+ designShell.centerPanel.insertBefore(holder, designEditorScroll);
3839
+ }
3840
+ designEditorScroll?.remove();
3841
+ designShell?.destroy();
3842
+ documentActions.element.remove();
3843
+ detachRegistryFromHolder(holder);
3844
+ },
3845
+ };
3846
+
3847
+ return instance;
3848
+ }