@donotdev/crud 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (373) hide show
  1. package/dist/CrudService.bulk.d.ts +17 -16
  2. package/dist/CrudService.bulk.d.ts.map +1 -1
  3. package/dist/CrudService.bulk.js +1 -1
  4. package/dist/CrudService.bulkAcross.d.ts +15 -8
  5. package/dist/CrudService.bulkAcross.d.ts.map +1 -1
  6. package/dist/CrudService.bulkAcross.js +1 -1
  7. package/dist/CrudService.bulkReconciliation.d.ts +4 -0
  8. package/dist/CrudService.bulkReconciliation.d.ts.map +1 -0
  9. package/dist/CrudService.bulkReconciliation.js +1 -0
  10. package/dist/CrudService.cache.d.ts +22 -3
  11. package/dist/CrudService.cache.d.ts.map +1 -1
  12. package/dist/CrudService.cache.js +1 -1
  13. package/dist/CrudService.d.ts +42 -11
  14. package/dist/CrudService.d.ts.map +1 -1
  15. package/dist/CrudService.internal.d.ts +3 -2
  16. package/dist/CrudService.internal.d.ts.map +1 -1
  17. package/dist/CrudService.internal.js +2 -2
  18. package/dist/CrudService.js +1 -1
  19. package/dist/CrudService.mutations.d.ts +3 -3
  20. package/dist/CrudService.mutations.d.ts.map +1 -1
  21. package/dist/CrudService.mutations.js +1 -1
  22. package/dist/CrudService.optimistic.d.ts +2 -2
  23. package/dist/CrudService.optimistic.d.ts.map +1 -1
  24. package/dist/CrudService.optimistic.js +1 -1
  25. package/dist/CrudService.queries.d.ts.map +1 -1
  26. package/dist/CrudService.queries.js +1 -1
  27. package/dist/CrudService.subscriptions.d.ts.map +1 -1
  28. package/dist/CrudService.subscriptions.js +1 -1
  29. package/dist/CrudService.writeRules.d.ts +57 -0
  30. package/dist/CrudService.writeRules.d.ts.map +1 -0
  31. package/dist/CrudService.writeRules.js +1 -0
  32. package/dist/CrudService.writeSchema.d.ts +64 -0
  33. package/dist/CrudService.writeSchema.d.ts.map +1 -0
  34. package/dist/CrudService.writeSchema.js +1 -0
  35. package/dist/CrudStore.d.ts +10 -1
  36. package/dist/CrudStore.d.ts.map +1 -1
  37. package/dist/CrudStore.js +1 -1
  38. package/dist/FieldRegistry.d.ts +1 -1
  39. package/dist/FieldRegistry.d.ts.map +1 -1
  40. package/dist/adapters/FunctionsAdapter.d.ts +3 -3
  41. package/dist/adapters/FunctionsAdapter.d.ts.map +1 -1
  42. package/dist/adapters/FunctionsAdapter.js +1 -1
  43. package/dist/components/CrudButton.d.ts +3 -2
  44. package/dist/components/CrudButton.d.ts.map +1 -1
  45. package/dist/components/CrudButton.js +1 -1
  46. package/dist/components/CrudCard.d.ts +2 -2
  47. package/dist/components/CrudCard.d.ts.map +1 -1
  48. package/dist/components/CrudCard.js +1 -1
  49. package/dist/components/DateFilter.js +1 -1
  50. package/dist/components/DisplayFieldRenderer.d.ts +5 -2
  51. package/dist/components/DisplayFieldRenderer.d.ts.map +1 -1
  52. package/dist/components/DisplayFieldRenderer.js +1 -1
  53. package/dist/components/DisplayThumbnail.d.ts.map +1 -1
  54. package/dist/components/DisplayThumbnail.js +1 -1
  55. package/dist/components/EntityFilters.d.ts +26 -4
  56. package/dist/components/EntityFilters.d.ts.map +1 -1
  57. package/dist/components/EntityFilters.js +1 -1
  58. package/dist/components/FormFieldRenderer.d.ts +21 -12
  59. package/dist/components/FormFieldRenderer.d.ts.map +1 -1
  60. package/dist/components/FormFieldRenderer.js +1 -1
  61. package/dist/components/FormLayout.d.ts.map +1 -1
  62. package/dist/components/FormLayout.js +1 -1
  63. package/dist/components/SortableCardList.d.ts +47 -0
  64. package/dist/components/SortableCardList.d.ts.map +1 -0
  65. package/dist/components/SortableCardList.js +1 -0
  66. package/dist/components/YearFilter.js +1 -1
  67. package/dist/components/controlled/complex/ControlledAddressField.d.ts.map +1 -1
  68. package/dist/components/controlled/complex/ControlledAddressField.js +1 -1
  69. package/dist/components/controlled/complex/ControlledDateField.d.ts.map +1 -1
  70. package/dist/components/controlled/complex/ControlledDateField.js +1 -1
  71. package/dist/components/controlled/complex/ControlledFieldArrayField.d.ts +9 -0
  72. package/dist/components/controlled/complex/ControlledFieldArrayField.d.ts.map +1 -1
  73. package/dist/components/controlled/complex/ControlledFieldArrayField.js +1 -1
  74. package/dist/components/controlled/complex/ControlledGeoPointField.d.ts.map +1 -1
  75. package/dist/components/controlled/complex/ControlledMapField.d.ts.map +1 -1
  76. package/dist/components/controlled/complex/ControlledMultiInputField.d.ts.map +1 -1
  77. package/dist/components/controlled/complex/ControlledMultiInputField.js +1 -1
  78. package/dist/components/controlled/complex/ControlledRichTextField.d.ts.map +1 -1
  79. package/dist/components/controlled/complex/ControlledTimestampField.d.ts.map +1 -1
  80. package/dist/components/controlled/complex/ControlledTimestampField.js +1 -1
  81. package/dist/components/controlled/fieldOptions.d.ts +48 -0
  82. package/dist/components/controlled/fieldOptions.d.ts.map +1 -0
  83. package/dist/components/controlled/fieldOptions.js +1 -0
  84. package/dist/components/controlled/file/ControlledDocumentField.js +1 -1
  85. package/dist/components/controlled/file/ControlledFileField.js +1 -1
  86. package/dist/components/controlled/file/ControlledImageField.d.ts.map +1 -1
  87. package/dist/components/controlled/file/ControlledImageField.js +1 -1
  88. package/dist/components/controlled/file/ControlledMultiDocumentField.d.ts.map +1 -1
  89. package/dist/components/controlled/file/ControlledMultiDocumentField.js +1 -1
  90. package/dist/components/controlled/file/ControlledMultiFileField.d.ts.map +1 -1
  91. package/dist/components/controlled/file/ControlledMultiFileField.js +1 -1
  92. package/dist/components/controlled/file/ControlledMultiImageField.d.ts.map +1 -1
  93. package/dist/components/controlled/file/ControlledMultiImageField.js +1 -1
  94. package/dist/components/controlled/input/ControlledCheckboxField.d.ts.map +1 -1
  95. package/dist/components/controlled/input/ControlledCurrencyField.d.ts.map +1 -1
  96. package/dist/components/controlled/input/ControlledCurrencyField.js +1 -1
  97. package/dist/components/controlled/input/ControlledDurationField.d.ts.map +1 -1
  98. package/dist/components/controlled/input/ControlledDurationField.js +1 -1
  99. package/dist/components/controlled/input/ControlledGdprConsentField.d.ts.map +1 -1
  100. package/dist/components/controlled/input/ControlledGdprConsentField.js +1 -1
  101. package/dist/components/controlled/input/ControlledNumberField.d.ts.map +1 -1
  102. package/dist/components/controlled/input/ControlledNumberField.js +1 -1
  103. package/dist/components/controlled/input/ControlledPasswordField.d.ts.map +1 -1
  104. package/dist/components/controlled/input/ControlledPasswordField.js +1 -1
  105. package/dist/components/controlled/input/ControlledPhoneField.d.ts.map +1 -1
  106. package/dist/components/controlled/input/ControlledPhoneField.js +1 -1
  107. package/dist/components/controlled/input/ControlledPriceField.d.ts.map +1 -1
  108. package/dist/components/controlled/input/ControlledPriceField.js +1 -1
  109. package/dist/components/controlled/input/ControlledRangeField.d.ts.map +1 -1
  110. package/dist/components/controlled/input/ControlledRangeField.js +1 -1
  111. package/dist/components/controlled/input/ControlledRatingField.d.ts.map +1 -1
  112. package/dist/components/controlled/input/ControlledRatingField.js +1 -1
  113. package/dist/components/controlled/input/ControlledSwitchField.d.ts.map +1 -1
  114. package/dist/components/controlled/input/ControlledSwitchField.js +1 -1
  115. package/dist/components/controlled/input/ControlledTextField.d.ts.map +1 -1
  116. package/dist/components/controlled/input/ControlledTextField.js +1 -1
  117. package/dist/components/controlled/input/ControlledTextareaField.d.ts.map +1 -1
  118. package/dist/components/controlled/input/ControlledTextareaField.js +1 -1
  119. package/dist/components/controlled/select/ControlledComboboxField.d.ts.map +1 -1
  120. package/dist/components/controlled/select/ControlledComboboxField.js +1 -1
  121. package/dist/components/controlled/select/ControlledDropdownField.d.ts.map +1 -1
  122. package/dist/components/controlled/select/ControlledDropdownField.js +1 -1
  123. package/dist/components/controlled/select/ControlledMultiDropdownField.d.ts.map +1 -1
  124. package/dist/components/controlled/select/ControlledMultiDropdownField.js +1 -1
  125. package/dist/components/controlled/select/ControlledRadioField.d.ts.map +1 -1
  126. package/dist/components/controlled/select/ControlledReferenceField.d.ts.map +1 -1
  127. package/dist/components/controlled/select/ControlledReferenceField.js +1 -1
  128. package/dist/components/controlled/select/ControlledYearField.d.ts.map +1 -1
  129. package/dist/components/controlled/select/ControlledYearField.js +1 -1
  130. package/dist/components/controlled/types.d.ts.map +1 -1
  131. package/dist/components/fields/display/AvatarFieldDisplay.d.ts.map +1 -1
  132. package/dist/components/fields/display/AvatarFieldDisplay.js +1 -1
  133. package/dist/components/fields/display/BadgeFieldDisplay.d.ts.map +1 -1
  134. package/dist/components/fields/display/ButtonFieldDisplay.d.ts.map +1 -1
  135. package/dist/components/fields/display/CheckboxFieldDisplay.d.ts.map +1 -1
  136. package/dist/components/fields/display/CheckboxFieldDisplay.js +1 -1
  137. package/dist/components/fields/display/DateFieldDisplay.d.ts.map +1 -1
  138. package/dist/components/fields/display/DateFieldDisplay.js +1 -1
  139. package/dist/components/fields/display/DropdownDisplay.d.ts.map +1 -1
  140. package/dist/components/fields/display/FileFieldDisplay.d.ts.map +1 -1
  141. package/dist/components/fields/display/FileFieldDisplay.js +1 -1
  142. package/dist/components/fields/display/GeoPointFieldDisplay.d.ts.map +1 -1
  143. package/dist/components/fields/display/HiddenFieldDisplay.d.ts.map +1 -1
  144. package/dist/components/fields/display/ImageFieldDisplay.d.ts.map +1 -1
  145. package/dist/components/fields/display/LinkFieldDisplay.d.ts.map +1 -1
  146. package/dist/components/fields/display/LinkFieldDisplay.js +1 -1
  147. package/dist/components/fields/display/MapFieldDisplay.d.ts.map +1 -1
  148. package/dist/components/fields/display/MultiDropdownDisplay.d.ts.map +1 -1
  149. package/dist/components/fields/display/MultiInputTextFieldDisplay.d.ts.map +1 -1
  150. package/dist/components/fields/display/NumberFieldDisplay.d.ts.map +1 -1
  151. package/dist/components/fields/display/NumberFieldDisplay.js +1 -1
  152. package/dist/components/fields/display/PasswordFieldDisplay.d.ts.map +1 -1
  153. package/dist/components/fields/display/PasswordFieldDisplay.js +1 -1
  154. package/dist/components/fields/display/PhoneNumberDisplay.d.ts.map +1 -1
  155. package/dist/components/fields/display/RadioFieldDisplay.d.ts.map +1 -1
  156. package/dist/components/fields/display/RangeFieldDisplay.d.ts.map +1 -1
  157. package/dist/components/fields/display/ReferenceFieldDisplay.d.ts.map +1 -1
  158. package/dist/components/fields/display/ReferenceFieldDisplay.js +1 -1
  159. package/dist/components/fields/display/RichTextDisplay.d.ts.map +1 -1
  160. package/dist/components/fields/display/TextAreaDisplay.d.ts.map +1 -1
  161. package/dist/components/fields/display/TextAreaDisplay.js +1 -1
  162. package/dist/components/fields/display/TextFieldDisplay.d.ts.map +1 -1
  163. package/dist/components/fields/display/TextFieldDisplay.js +1 -1
  164. package/dist/components/fields/display/TimestampFieldDisplay.d.ts.map +1 -1
  165. package/dist/components/form/fields/AddressFieldComponent.d.ts +3 -1
  166. package/dist/components/form/fields/AddressFieldComponent.d.ts.map +1 -1
  167. package/dist/components/form/fields/AddressFieldComponent.js +1 -1
  168. package/dist/components/form/fields/AvatarFieldComponent.d.ts.map +1 -1
  169. package/dist/components/form/fields/AvatarFieldComponent.js +1 -1
  170. package/dist/components/form/fields/BadgeFieldComponent.d.ts.map +1 -1
  171. package/dist/components/form/fields/BadgeFieldComponent.js +1 -1
  172. package/dist/components/form/fields/ButtonFieldComponent.js +1 -1
  173. package/dist/components/form/fields/CheckboxFieldComponent.d.ts.map +1 -1
  174. package/dist/components/form/fields/CheckboxFieldComponent.js +1 -1
  175. package/dist/components/form/fields/ComboboxComponent.d.ts +2 -0
  176. package/dist/components/form/fields/ComboboxComponent.d.ts.map +1 -1
  177. package/dist/components/form/fields/ComboboxComponent.js +1 -1
  178. package/dist/components/form/fields/CurrencyFieldComponent.d.ts +2 -0
  179. package/dist/components/form/fields/CurrencyFieldComponent.d.ts.map +1 -1
  180. package/dist/components/form/fields/CurrencyFieldComponent.js +1 -1
  181. package/dist/components/form/fields/DateFieldComponent.d.ts +2 -0
  182. package/dist/components/form/fields/DateFieldComponent.d.ts.map +1 -1
  183. package/dist/components/form/fields/DateFieldComponent.js +1 -1
  184. package/dist/components/form/fields/DocumentFieldComponent.js +1 -1
  185. package/dist/components/form/fields/DropdownComponent.d.ts +2 -0
  186. package/dist/components/form/fields/DropdownComponent.d.ts.map +1 -1
  187. package/dist/components/form/fields/DropdownComponent.js +1 -1
  188. package/dist/components/form/fields/DurationFieldComponent.d.ts.map +1 -1
  189. package/dist/components/form/fields/DurationFieldComponent.js +1 -1
  190. package/dist/components/form/fields/FileFieldComponent.js +1 -1
  191. package/dist/components/form/fields/GdprConsentFieldComponent.d.ts.map +1 -1
  192. package/dist/components/form/fields/GdprConsentFieldComponent.js +1 -1
  193. package/dist/components/form/fields/GeoPointFieldComponent.js +1 -1
  194. package/dist/components/form/fields/ImageFieldComponent.d.ts.map +1 -1
  195. package/dist/components/form/fields/ImageFieldComponent.js +1 -1
  196. package/dist/components/form/fields/MapFieldComponent.d.ts.map +1 -1
  197. package/dist/components/form/fields/MultiDropdownComponent.d.ts +2 -0
  198. package/dist/components/form/fields/MultiDropdownComponent.d.ts.map +1 -1
  199. package/dist/components/form/fields/MultiDropdownComponent.js +1 -1
  200. package/dist/components/form/fields/MultiInputTextFieldComponent.d.ts +2 -0
  201. package/dist/components/form/fields/MultiInputTextFieldComponent.d.ts.map +1 -1
  202. package/dist/components/form/fields/MultiInputTextFieldComponent.js +1 -1
  203. package/dist/components/form/fields/NumberFieldComponent.d.ts +2 -0
  204. package/dist/components/form/fields/NumberFieldComponent.d.ts.map +1 -1
  205. package/dist/components/form/fields/NumberFieldComponent.js +1 -1
  206. package/dist/components/form/fields/PasswordFieldComponent.d.ts +2 -0
  207. package/dist/components/form/fields/PasswordFieldComponent.d.ts.map +1 -1
  208. package/dist/components/form/fields/PasswordFieldComponent.js +1 -1
  209. package/dist/components/form/fields/PhoneNumberComponent.d.ts +11 -1
  210. package/dist/components/form/fields/PhoneNumberComponent.d.ts.map +1 -1
  211. package/dist/components/form/fields/PhoneNumberComponent.js +1 -1
  212. package/dist/components/form/fields/PriceFieldComponent.d.ts +2 -0
  213. package/dist/components/form/fields/PriceFieldComponent.d.ts.map +1 -1
  214. package/dist/components/form/fields/PriceFieldComponent.js +1 -1
  215. package/dist/components/form/fields/RangeFieldComponent.js +1 -1
  216. package/dist/components/form/fields/RatingFieldComponent.js +1 -1
  217. package/dist/components/form/fields/ReferenceFieldComponent.d.ts +3 -1
  218. package/dist/components/form/fields/ReferenceFieldComponent.d.ts.map +1 -1
  219. package/dist/components/form/fields/ReferenceFieldComponent.js +1 -1
  220. package/dist/components/form/fields/RichTextComponent.js +1 -1
  221. package/dist/components/form/fields/SwitchFieldComponent.d.ts.map +1 -1
  222. package/dist/components/form/fields/SwitchFieldComponent.js +1 -1
  223. package/dist/components/form/fields/TextAreaComponent.d.ts +2 -0
  224. package/dist/components/form/fields/TextAreaComponent.d.ts.map +1 -1
  225. package/dist/components/form/fields/TextAreaComponent.js +1 -1
  226. package/dist/components/form/fields/TextFieldComponent.d.ts +3 -1
  227. package/dist/components/form/fields/TextFieldComponent.d.ts.map +1 -1
  228. package/dist/components/form/fields/TextFieldComponent.js +1 -1
  229. package/dist/components/form/fields/TimestampFieldComponent.d.ts +2 -0
  230. package/dist/components/form/fields/TimestampFieldComponent.d.ts.map +1 -1
  231. package/dist/components/form/fields/TimestampFieldComponent.js +1 -1
  232. package/dist/components/form/fields/internal/InlineFieldRow.d.ts +24 -0
  233. package/dist/components/form/fields/internal/InlineFieldRow.d.ts.map +1 -0
  234. package/dist/components/form/fields/internal/InlineFieldRow.js +1 -0
  235. package/dist/components/form/fields/internal/TiptapEditor.d.ts.map +1 -1
  236. package/dist/components/form/fields/internal/TiptapEditor.js +2 -2
  237. package/dist/components/form/internal/ImageViewerDialog.js +1 -1
  238. package/dist/components/index.d.ts +2 -0
  239. package/dist/components/index.d.ts.map +1 -1
  240. package/dist/components/index.js +1 -1
  241. package/dist/fieldTypeRegistry.d.ts +2 -2
  242. package/dist/fieldTypeRegistry.d.ts.map +1 -1
  243. package/dist/fieldTypeRegistry.js +1 -1
  244. package/dist/fieldTypeRegistry.store.d.ts +0 -2
  245. package/dist/fieldTypeRegistry.store.d.ts.map +1 -1
  246. package/dist/fieldTypeRegistry.store.js +1 -1
  247. package/dist/fieldTypeRegistry.types.d.ts +8 -9
  248. package/dist/fieldTypeRegistry.types.d.ts.map +1 -1
  249. package/dist/forms/FormNavigation.d.ts +24 -0
  250. package/dist/forms/FormNavigation.d.ts.map +1 -0
  251. package/dist/forms/FormNavigation.js +1 -0
  252. package/dist/forms/childRows.d.ts +184 -0
  253. package/dist/forms/childRows.d.ts.map +1 -0
  254. package/dist/forms/childRows.js +1 -0
  255. package/dist/forms/extend.d.ts +88 -0
  256. package/dist/forms/extend.d.ts.map +1 -0
  257. package/dist/forms/extend.js +1 -0
  258. package/dist/forms/hooks/useController.js +1 -1
  259. package/dist/forms/hooks/useEntityField.d.ts +11 -5
  260. package/dist/forms/hooks/useEntityField.d.ts.map +1 -1
  261. package/dist/forms/hooks/useEntityField.js +1 -1
  262. package/dist/forms/hooks/useEntityForm.d.ts +50 -5
  263. package/dist/forms/hooks/useEntityForm.d.ts.map +1 -1
  264. package/dist/forms/hooks/useEntityForm.js +1 -1
  265. package/dist/forms/hooks/useFormDraftState.d.ts +53 -0
  266. package/dist/forms/hooks/useFormDraftState.d.ts.map +1 -0
  267. package/dist/forms/hooks/useFormDraftState.js +1 -0
  268. package/dist/forms/index.d.ts +6 -2
  269. package/dist/forms/index.d.ts.map +1 -1
  270. package/dist/forms/index.js +1 -1
  271. package/dist/forms/types.d.ts +171 -25
  272. package/dist/forms/types.d.ts.map +1 -1
  273. package/dist/forms/utils/buildInitialValues.d.ts +32 -17
  274. package/dist/forms/utils/buildInitialValues.d.ts.map +1 -1
  275. package/dist/forms/utils/buildInitialValues.js +1 -1
  276. package/dist/forms/utils/conditionAwareResolver.d.ts +35 -0
  277. package/dist/forms/utils/conditionAwareResolver.d.ts.map +1 -0
  278. package/dist/forms/utils/conditionAwareResolver.js +1 -0
  279. package/dist/forms/utils/emptyValue.d.ts +34 -0
  280. package/dist/forms/utils/emptyValue.d.ts.map +1 -0
  281. package/dist/forms/utils/emptyValue.js +1 -0
  282. package/dist/forms/utils/getFieldsForOperation.d.ts +30 -19
  283. package/dist/forms/utils/getFieldsForOperation.d.ts.map +1 -1
  284. package/dist/forms/utils/getFieldsForOperation.js +1 -1
  285. package/dist/forms/utils/index.d.ts +1 -0
  286. package/dist/forms/utils/index.d.ts.map +1 -1
  287. package/dist/forms/utils/index.js +1 -1
  288. package/dist/forms/utils/isFieldEditable.d.ts +21 -22
  289. package/dist/forms/utils/isFieldEditable.d.ts.map +1 -1
  290. package/dist/forms/utils/isFieldEditable.js +1 -1
  291. package/dist/forms/utils/translateFieldLabel.d.ts +1 -9
  292. package/dist/forms/utils/translateFieldLabel.d.ts.map +1 -1
  293. package/dist/forms/utils/translateFieldLabel.js +1 -1
  294. package/dist/forms/utils/validateEntity.js +1 -1
  295. package/dist/forms/utils/writableFields.d.ts +19 -0
  296. package/dist/forms/utils/writableFields.d.ts.map +1 -0
  297. package/dist/forms/utils/writableFields.js +1 -0
  298. package/dist/hooks/index.d.ts +2 -0
  299. package/dist/hooks/index.d.ts.map +1 -1
  300. package/dist/hooks/index.js +1 -1
  301. package/dist/hooks/useChildRows.d.ts +161 -0
  302. package/dist/hooks/useChildRows.d.ts.map +1 -0
  303. package/dist/hooks/useChildRows.js +1 -0
  304. package/dist/hooks/useCrudFilters.d.ts +21 -1
  305. package/dist/hooks/useCrudFilters.d.ts.map +1 -1
  306. package/dist/hooks/useCrudFilters.js +1 -1
  307. package/dist/hooks/useCrudPageSize.js +1 -1
  308. package/dist/hooks/useEntityFavorites.js +1 -1
  309. package/dist/hooks/useExtensionRows.d.ts +24 -0
  310. package/dist/hooks/useExtensionRows.d.ts.map +1 -0
  311. package/dist/hooks/useExtensionRows.js +1 -0
  312. package/dist/hooks/useFieldConditions.d.ts +2 -2
  313. package/dist/hooks/useFieldConditions.d.ts.map +1 -1
  314. package/dist/hooks/useFieldConditions.js +1 -1
  315. package/dist/hooks/useFileUpload.js +1 -1
  316. package/dist/hooks/useReferenceResolver.d.ts +4 -1
  317. package/dist/hooks/useReferenceResolver.d.ts.map +1 -1
  318. package/dist/hooks/useReferenceResolver.js +1 -1
  319. package/dist/hooks/useRelatedItems.js +1 -1
  320. package/dist/index.d.ts +6 -5
  321. package/dist/index.d.ts.map +1 -1
  322. package/dist/index.js +1 -1
  323. package/dist/registerBuiltinFieldTypes.d.ts +4 -2
  324. package/dist/registerBuiltinFieldTypes.d.ts.map +1 -1
  325. package/dist/registerBuiltinFieldTypes.js +1 -1
  326. package/dist/stores/FormStore.d.ts +116 -5
  327. package/dist/stores/FormStore.d.ts.map +1 -1
  328. package/dist/stores/FormStore.js +1 -1
  329. package/dist/stores/UploadStore.js +1 -1
  330. package/dist/stores/index.d.ts +1 -1
  331. package/dist/stores/index.d.ts.map +1 -1
  332. package/dist/stores/index.js +1 -1
  333. package/dist/symbol-index.json +1 -1
  334. package/dist/tsconfig.tsbuildinfo +1 -1
  335. package/dist/types.d.ts +40 -7
  336. package/dist/types.d.ts.map +1 -1
  337. package/dist/useBaseCrudList.d.ts.map +1 -1
  338. package/dist/useBaseCrudList.js +1 -1
  339. package/dist/useCrud.d.ts +20 -9
  340. package/dist/useCrud.d.ts.map +1 -1
  341. package/dist/useCrud.js +1 -1
  342. package/dist/useCrudCardList.js +1 -1
  343. package/dist/useCrudDoc.d.ts.map +1 -1
  344. package/dist/useCrudDoc.js +1 -1
  345. package/dist/useCrudList.js +1 -1
  346. package/dist/utils/clientListProcessing.d.ts +9 -12
  347. package/dist/utils/clientListProcessing.d.ts.map +1 -1
  348. package/dist/utils/clientListProcessing.js +1 -1
  349. package/dist/utils/collections.d.ts.map +1 -1
  350. package/dist/utils/collections.js +1 -1
  351. package/dist/utils/filterUrl.d.ts +45 -0
  352. package/dist/utils/filterUrl.d.ts.map +1 -0
  353. package/dist/utils/filterUrl.js +1 -0
  354. package/dist/utils/imageProcessing.js +1 -1
  355. package/dist/utils/matchesFilter.d.ts +27 -3
  356. package/dist/utils/matchesFilter.d.ts.map +1 -1
  357. package/dist/utils/matchesFilter.js +1 -1
  358. package/dist/utils/referenceEntity.d.ts +11 -0
  359. package/dist/utils/referenceEntity.d.ts.map +1 -0
  360. package/dist/utils/referenceEntity.js +1 -0
  361. package/dist/utils/uploadValidation.js +1 -1
  362. package/dist/utils/useRowTranslator.d.ts +21 -0
  363. package/dist/utils/useRowTranslator.d.ts.map +1 -0
  364. package/dist/utils/useRowTranslator.js +1 -0
  365. package/dist/workflows/defineWorkflow.js +1 -1
  366. package/dist/workflows/useEntityWorkflow.js +1 -1
  367. package/guidelines/COMPONENTS.md +87 -10
  368. package/guidelines/CRUD.md +336 -17
  369. package/guidelines/GOTCHAS.md +19 -1
  370. package/package.json +8 -8
  371. package/dist/builtinFieldTypes.d.ts +0 -23
  372. package/dist/builtinFieldTypes.d.ts.map +0 -1
  373. package/dist/builtinFieldTypes.js +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FormNavigation.d.ts","sourceRoot":"","sources":["../../src/forms/FormNavigation.ts"],"names":[],"mappings":"AAgBA,yEAAyE;AACzE,MAAM,WAAW,cAAc;IAC7B,+BAA+B;IAC/B,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACjC,2CAA2C;IAC3C,WAAW,EAAE,MAAM,MAAM,CAAC;IAC1B,0FAA0F;IAC1F,UAAU,EAAE,MAAM,MAAM,CAAC;CAC1B;AAQD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,sBAAsB,iDAAiC,CAAC;AAErE,mEAAmE;AACnE,wBAAgB,iBAAiB,IAAI,cAAc,GAAG,IAAI,CAEzD"}
@@ -0,0 +1 @@
1
+ import{createContext as r,useContext as t}from"react";const o=r(null),e=o.Provider;function n(){return t(o)}export{e as FormNavigationProvider,n as useFormNavigation};
@@ -0,0 +1,184 @@
1
+ import { createSchemas } from '@donotdev/core';
2
+ import type { AnyEntity, BulkAcrossBatch } from '@donotdev/core';
3
+ import type { ChildRowEdits } from '../stores/FormStore';
4
+ import type { ResolvedExtension } from './extend';
5
+ import { writableFields } from './utils/writableFields';
6
+ export { writableFields };
7
+ /** No edits. Shared constant: compare by reference to skip store writes. */
8
+ export declare const EMPTY_CHILD_EDITS: ChildRowEdits;
9
+ /** A row as the child list sees it. */
10
+ export type ChildRow = Record<string, unknown> & {
11
+ id: string;
12
+ };
13
+ /** Why a field of a row is invalid: empty while required, or a value the rules reject. */
14
+ export type ChildRowErrorKind = 'required' | 'invalid';
15
+ /** Invalid fields by row id: `errors[rowId][field]` (extension fields prefixed). */
16
+ export type ChildRowErrorKinds = Record<string, Record<string, ChildRowErrorKind>>;
17
+ /**
18
+ * The entity's `createSchemas`, built once per entity (validation runs on every
19
+ * change; repeated writes carry the same schemas).
20
+ *
21
+ * @param entity - The entity
22
+ */
23
+ export declare function schemasOf(entity: AnyEntity): ReturnType<typeof createSchemas>;
24
+ /**
25
+ * Collection of the parent record: the child field's referenced collection
26
+ * (descriptor `value.kind === 'ref'`: any field type with `validation.reference`,
27
+ * custom ones included). Throws when `field` is not a reference field of `entity`
28
+ * (a wrong parent would silently list nothing).
29
+ *
30
+ * @param entity - The child entity
31
+ * @param field - The child's field pointing at the parent
32
+ * @returns The parent collection
33
+ */
34
+ export declare function parentCollectionOf(entity: AnyEntity, field: string): string;
35
+ /**
36
+ * The child entity of a joined list, from its collection (entities register on
37
+ * `defineEntity`). Throws when no entity defines it.
38
+ *
39
+ * @param collection - The child collection
40
+ * @returns The child entity
41
+ */
42
+ export declare function childEntityOf(collection: string): AnyEntity;
43
+ /** What the viewer may do on the child entity (`entity.access`). */
44
+ export interface ChildRowsAccess {
45
+ /** Add rows (`access.create`) */
46
+ create: boolean;
47
+ /** Edit saved rows (`access.update`) */
48
+ update: boolean;
49
+ /** Remove saved rows (`access.delete`) */
50
+ delete: boolean;
51
+ }
52
+ /**
53
+ * What the viewer may do on the entity, from its `access` roles.
54
+ *
55
+ * @param entity - The child entity
56
+ * @param viewerRole - The viewer's role
57
+ */
58
+ export declare function childRowsAccess(entity: AnyEntity, viewerRole: string): ChildRowsAccess;
59
+ /** Whether the edits hold anything a Save would write. */
60
+ export declare function hasChildEdits(edits: ChildRowEdits): boolean;
61
+ /** Pending count: edited cells + added rows + removed rows. */
62
+ export declare function countChildEdits(edits: ChildRowEdits): number;
63
+ /**
64
+ * Rows as shown: saved rows minus removed ones, then added rows. `base` holds
65
+ * them without cell changes (a DataTable's data under its pending changes),
66
+ * `items` with them applied.
67
+ *
68
+ * @param saved - The saved rows
69
+ * @param edits - The unsaved edits
70
+ */
71
+ export declare function applyChildEdits<T extends ChildRow>(saved: readonly T[], edits: ChildRowEdits): {
72
+ base: T[];
73
+ items: T[];
74
+ };
75
+ /**
76
+ * Set field values of one row: a value equal to the row's base value drops the
77
+ * pending change (as a table cell set back to its saved value).
78
+ *
79
+ * @param edits - Current edits
80
+ * @param base - The row without changes (saved or added)
81
+ * @param patch - Field values to set
82
+ */
83
+ export declare function setChildValues(edits: ChildRowEdits, base: ChildRow, patch: Record<string, unknown>): ChildRowEdits;
84
+ /**
85
+ * Remove rows: an added row is dropped, a saved row is marked for deletion.
86
+ * Their cell changes are dropped either way.
87
+ *
88
+ * @param edits - Current edits
89
+ * @param ids - Rows to remove
90
+ */
91
+ export declare function removeChildRows(edits: ChildRowEdits, ids: readonly string[]): ChildRowEdits;
92
+ /**
93
+ * Settle edits against the saved rows (after a load, a refetch, a partly
94
+ * failed write): an added row now saved was written (its remaining changes
95
+ * apply to the saved row), a removed row no longer saved was deleted, a change
96
+ * equal to the saved value was written, a change of a row that exists nowhere
97
+ * is dropped. Returns `edits` itself when nothing changed.
98
+ *
99
+ * @param edits - Current edits
100
+ * @param saved - The saved rows (loaded)
101
+ */
102
+ export declare function reconcileChildEdits(edits: ChildRowEdits, saved: readonly ChildRow[]): ChildRowEdits;
103
+ /**
104
+ * Edits made while a write was in flight, minus what that write submitted
105
+ * (written on success): submitted added rows and removals leave, changes equal
106
+ * to the submitted ones leave.
107
+ *
108
+ * @param current - Edits now
109
+ * @param submitted - Edits the write carried
110
+ */
111
+ export declare function rebaseChildEdits(current: ChildRowEdits, submitted: ChildRowEdits): ChildRowEdits;
112
+ /** Only the given keys of a record. */
113
+ export declare function pickFields(values: Record<string, unknown>, keys: ReadonlySet<string>): Record<string, unknown>;
114
+ /** What a child list knows to validate and write its rows. */
115
+ export interface ChildRowsContext {
116
+ /** The child entity */
117
+ entity: AnyEntity;
118
+ /** The child's parent field and the parent record id (none: every record) */
119
+ parent?: {
120
+ field: string;
121
+ value: string;
122
+ };
123
+ /** 1:1 extensions of the rows, resolved for the viewer */
124
+ extensions?: readonly ResolvedExtension[];
125
+ /** Existing extension row ids: `extensionIds[rowId][key]` (absent: inserted on Save) */
126
+ extensionIds?: Record<string, Record<string, string>>;
127
+ /** Stored rows by id (as loaded, extensions merged under their key): edits are checked merged with them */
128
+ savedRows?: ReadonlyMap<string, ChildRow>;
129
+ /**
130
+ * Id of the extension row inserted for a record (`key` from `extensionMintKey`):
131
+ * the same on every call until written. Default: a new id per call.
132
+ */
133
+ mintId?: (key: string) => string;
134
+ }
135
+ /**
136
+ * Edits read back from a form draft (browser storage: untrusted, possibly from
137
+ * an older page version), kept only as far as the entity's rules allow: fields
138
+ * the viewer may write (extension fields `key.field` included), values of the
139
+ * right type, ids of record shape; added rows belong to the parent. Throws when
140
+ * the shape is not an edits object.
141
+ *
142
+ * @param context - The child entity, parent and extensions
143
+ * @param raw - The stored value
144
+ * @param viewerRole - The viewer's role
145
+ */
146
+ export declare function parseChildEdits(context: ChildRowsContext, raw: unknown, viewerRole: string): ChildRowEdits;
147
+ /**
148
+ * Fields a Save would reject, by row, checked on every change. A grid is a
149
+ * shortcut onto the same records, so it follows the record form's rules: the CRUD
150
+ * rules (core/schemas crud/), as every writer and the server apply them:
151
+ * - added row (and a missing extension row, inserted on Save: its defaults and
152
+ * edits): `prepareCreate`;
153
+ * - edited stored row: `prepareUpdate` with the changed fields on the stored row (a
154
+ * draft may leave required fields empty; leaving draft checks the whole record).
155
+ * Extension rows the same way. Only fields the viewer can see are checked (a row
156
+ * read for the viewer carries only those). Only rows with edits are checked.
157
+ * Extension fields are reported prefixed.
158
+ *
159
+ * @param context - The child entity, parent, extensions and stored rows
160
+ * @param edits - The edits
161
+ * @param viewerRole - The viewer's role
162
+ * @returns `errors[rowId][field]` = kind (empty when all are valid)
163
+ */
164
+ export declare function childEditsErrors(context: ChildRowsContext, edits: ChildRowEdits, viewerRole?: string): ChildRowErrorKinds;
165
+ /**
166
+ * The `bulkAcross` batches writing the edits: the child collection (inserts =
167
+ * added rows with their changes and the parent id, pre-minted ids kept;
168
+ * updates; deletes) and one per extension (updates of existing extension rows,
169
+ * inserts of missing ones; an extension of an added row depends on its insert).
170
+ * Each batch carries its entity's schemas.
171
+ *
172
+ * @param context - The child entity, parent, extensions and extension ids
173
+ * @param edits - The edits to write
174
+ * @param viewerRole - The viewer's role (extension defaults)
175
+ */
176
+ export declare function childEditsBatches(context: ChildRowsContext, edits: ChildRowEdits, viewerRole?: string): BulkAcrossBatch[];
177
+ /**
178
+ * Batches of the same collection merged into one (`bulkAcross` takes one batch
179
+ * per collection), e.g. two child lists of one entity under different parents.
180
+ *
181
+ * @param batches - Batches to merge
182
+ */
183
+ export declare function mergeBatches(batches: BulkAcrossBatch[]): BulkAcrossBatch[];
184
+ //# sourceMappingURL=childRows.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"childRows.d.ts","sourceRoot":"","sources":["../../src/forms/childRows.ts"],"names":[],"mappings":"AAkBA,OAAO,EACL,aAAa,EAQd,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAGjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AASzD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAElD,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAExD,OAAO,EAAE,cAAc,EAAE,CAAC;AAE1B,4EAA4E;AAC5E,eAAO,MAAM,iBAAiB,EAAE,aAI/B,CAAC;AAiBF,uCAAuC;AACvC,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC;AAEhE,0FAA0F;AAC1F,MAAM,MAAM,iBAAiB,GAAG,UAAU,GAAG,SAAS,CAAC;AAEvD,oFAAoF;AACpF,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC;AAInF;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,SAAS,GAAG,UAAU,CAAC,OAAO,aAAa,CAAC,CAO7E;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAQ3E;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,CAQ3D;AAED,oEAAoE;AACpE,MAAM,WAAW,eAAe;IAC9B,iCAAiC;IACjC,MAAM,EAAE,OAAO,CAAC;IAChB,wCAAwC;IACxC,MAAM,EAAE,OAAO,CAAC;IAChB,0CAA0C;IAC1C,MAAM,EAAE,OAAO,CAAC;CACjB;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,SAAS,EACjB,UAAU,EAAE,MAAM,GACjB,eAAe,CAMjB;AAWD,0DAA0D;AAC1D,wBAAgB,aAAa,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAM3D;AAED,+DAA+D;AAC/D,wBAAgB,eAAe,CAAC,KAAK,EAAE,aAAa,GAAG,MAAM,CAS5D;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,QAAQ,EAChD,KAAK,EAAE,SAAS,CAAC,EAAE,EACnB,KAAK,EAAE,aAAa,GACnB;IAAE,IAAI,EAAE,CAAC,EAAE,CAAC;IAAC,KAAK,EAAE,CAAC,EAAE,CAAA;CAAE,CAY3B;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC5B,KAAK,EAAE,aAAa,EACpB,IAAI,EAAE,QAAQ,EACd,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC7B,aAAa,CAUf;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,aAAa,EACpB,GAAG,EAAE,SAAS,MAAM,EAAE,GACrB,aAAa,CAef;AAED;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,aAAa,EACpB,KAAK,EAAE,SAAS,QAAQ,EAAE,GACzB,aAAa,CAsBf;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,aAAa,EACtB,SAAS,EAAE,aAAa,GACvB,aAAa,CAoBf;AAmBD,uCAAuC;AACvC,wBAAgB,UAAU,CACxB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,IAAI,EAAE,WAAW,CAAC,MAAM,CAAC,GACxB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAIzB;AAED,8DAA8D;AAC9D,MAAM,WAAW,gBAAgB;IAC/B,uBAAuB;IACvB,MAAM,EAAE,SAAS,CAAC;IAClB,6EAA6E;IAC7E,MAAM,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1C,0DAA0D;IAC1D,UAAU,CAAC,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC1C,wFAAwF;IACxF,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACtD,2GAA2G;IAC3G,SAAS,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAC1C;;;OAGG;IACH,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,CAAC;CAClC;AAiBD;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAC7B,OAAO,EAAE,gBAAgB,EACzB,GAAG,EAAE,OAAO,EACZ,UAAU,EAAE,MAAM,GACjB,aAAa,CAuDf;AA4BD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,gBAAgB,EACzB,KAAK,EAAE,aAAa,EACpB,UAAU,SAAU,GACnB,kBAAkB,CAuEpB;AAmBD;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,gBAAgB,EACzB,KAAK,EAAE,aAAa,EACpB,UAAU,SAAU,GACnB,eAAe,EAAE,CAqFnB;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,eAAe,EAAE,GAAG,eAAe,EAAE,CAuB1E"}
@@ -0,0 +1 @@
1
+ import*as p from"valibot";import{createSchemas as q,describeEntity as z,generateUUID as H,getEntityByCollection as Y,hasRoleAccess as K,isFieldVisible as Z,prepareCreate as G,prepareUpdate as Q}from"@donotdev/core";import{extensionMintKey as X}from"../stores/FormStore";import{injectScope as J}from"../utils/scopeUtils";import{extensionFieldName as B,extensionWritable as $,splitExtensionField as A,splitPatch as x,withoutLinkField as P}from"./extend";import{buildSchemaDefaults as ee}from"./utils/buildInitialValues";import{writableFields as D}from"./utils/writableFields";const M={changes:{},added:[],removed:[]},I=/^[A-Za-z0-9_-]{1,128}$/,te=p.object({changes:p.record(p.pipe(p.string(),p.regex(I)),p.record(p.string(),p.unknown())),added:p.array(p.looseObject({id:p.pipe(p.string(),p.regex(I))})),removed:p.array(p.pipe(p.string(),p.regex(I)))}),U=new WeakMap;function C(e){let t=U.get(e);return t||(t=q(e),U.set(e,t)),t}function ne(e,t){const n=z(e).fields[t]?.value;if(n?.kind!=="ref"||n.ref===void 0)throw new Error(`useChildRows: parent field "${t}" is not a reference field of entity "${e.name}".`);return n.ref}function se(e){const t=Y(e);if(!t)throw new Error(`useEntityForm: no entity defines collection "${e}" (joined child rows). Define it with defineEntity().`);return t}function W(e,t){return{create:K(t,e.access.create),update:K(t,e.access.update),delete:K(t,e.access.delete)}}function N(e,t){const n=e??null,s=t??null;return n===s?!0:typeof n!="object"||typeof s!="object"?!1:JSON.stringify(n)===JSON.stringify(s)}function E(e){return Object.keys(e.changes).length>0||e.added.length>0||e.removed.length>0}function ie(e){return Object.values(e.changes).reduce((t,n)=>t+Object.keys(n).length,0)+e.added.length+e.removed.length}function oe(e,t){if(!E(t))return{base:[...e],items:[...e]};const n=new Set(t.removed),s=[...e.filter(r=>!n.has(r.id)),...t.added],o=s.map(r=>t.changes[r.id]?{...r,...t.changes[r.id]}:r);return{base:s,items:o}}function re(e,t,n){const s={...e.changes[t.id]};for(const[r,c]of Object.entries(n))N(c,t[r])?delete s[r]:s[r]=c;const o={...e.changes};return Object.keys(s).length===0?delete o[t.id]:o[t.id]=s,{...e,changes:o}}function ce(e,t){const n=new Set(t),s=new Set(e.added.map(o=>o.id));return{changes:Object.fromEntries(Object.entries(e.changes).filter(([o])=>!n.has(o))),added:e.added.filter(o=>!n.has(o.id)),removed:[...new Set([...e.removed,...t.filter(o=>!s.has(o))])]}}function de(e,t){if(!E(e))return e;const n=new Map(t.map(a=>[a.id,a])),s=e.added.filter(a=>!n.has(a.id)),o=new Set(s.map(a=>a.id)),r=e.removed.filter(a=>n.has(a)),c={};for(const[a,b]of Object.entries(e.changes)){const j=n.get(a);if(!j){o.has(a)&&(c[a]=b);continue}const d=Object.fromEntries(Object.entries(b).filter(([u,g])=>!N(g,j[u])));Object.keys(d).length>0&&(c[a]=d)}const w={changes:c,added:s,removed:r};return JSON.stringify(w)===JSON.stringify(e)?e:w}function ae(e,t){if(e===t)return M;const n=new Set(t.added.map(c=>c.id)),s=new Set(t.removed),o={};for(const[c,w]of Object.entries(e.changes)){const a=t.changes[c]??{},b=Object.fromEntries(Object.entries(w).filter(([j,d])=>!(j in a&&N(d,a[j]))));Object.keys(b).length>0&&(o[c]=b)}const r={changes:o,added:e.added.filter(c=>!n.has(c.id)),removed:e.removed.filter(c=>!s.has(c))};return E(r)?r:M}function _(e,t,n){const s=p.safeParse(C(e).update,{...n,id:t}),o=new Set(Object.keys(n));if(!s.success)for(const r of s.issues){const c=r.path?.[0]?.key;typeof c=="string"&&o.delete(c)}return o}function F(e,t){return Object.fromEntries(Object.entries(e).filter(([n])=>t.has(n)))}const le=e=>new Set([...e].map(t=>A(t)?.[1]??t));function L(e,t){return ee(e.entity,le($(e,t,"create")))}function fe(e,t,n){const{entity:s,parent:o,extensions:r=[]}=e,c=p.parse(te,t),w=W(s,n),a=r.flatMap(i=>[...$(i,n,"create")]),b=[...a,...r.flatMap(i=>[...$(i,n,"edit")])],j=new Set([...D(s,n,"edit"),...b]),d=new Set([...D(s,n,"create"),...a]);o&&d.delete(o.field);const u=(i,m)=>{const{own:h,byKey:l}=x(m,r),k=_(s,i,h);for(const S of r){const R=l[S.key];if(R)for(const V of _(S.entity,i,R))k.add(B(S.key,V))}return F(m,k)},g=(w.create?c.added:[]).map(i=>({...u(i.id,F(i,d)),id:i.id,...o&&{[o.field]:o.value}})),y=new Set(g.map(i=>i.id)),f={};for(const[i,m]of Object.entries(c.changes)){const h=y.has(i)?d:new Set([...j].filter(k=>A(k)!==null||w.update)),l=u(i,F(m,h));Object.keys(l).length>0&&(f[i]=l)}const O=w.delete?[...new Set(c.removed.filter(i=>!y.has(i)))]:[],v={changes:f,added:g,removed:O};return E(v)?v:M}const T=new WeakMap;function he(e,t){let n=T.get(e);n||(n=new Map,T.set(e,n));let s=n.get(t);return s||(s={...e,fields:Object.fromEntries(Object.entries(e.fields).filter(([,o])=>Z(o.visibility??"guest",t)))},n.set(t,s)),s}function ue(e,t,n="guest"){const{entity:s,extensions:o=[],savedRows:r}=e;if(!E(t))return{};const c=new Set(t.added.map(d=>d.id)),w=new Set(t.removed),a={},b=(d,u,g,y,f,O)=>{const v=C(he(d,n)),i=f===void 0?G(v,g):Q(v,{id:String(f.id??u),patch:O??{},stored:f});if(!i.ok)for(const m of i.issues){const h=m.path?.[0]?.key;if(typeof h!="string")continue;const l=m.path?.[0]?.value,k=l==null||l===""?"required":"invalid",S=y?B(y,h):h;a[u]={...a[u],[S]:a[u]?.[S]??k}}},j=(d,u,g,y)=>{for(const f of o){const O=g[f.key],v=y?void 0:u?.[f.key];ge(v)?O&&b(P(f),d,{...v,...O},f.key,v,O):(y&&f.create||O)&&b(P(f),d,{...L(f,n),...O},f.key)}};for(const d of t.added){const{id:u,...g}={...d,...t.changes[d.id]},{own:y,byKey:f}=x(g,o);b(s,u,y,""),j(u,void 0,f,!0)}for(const[d,u]of Object.entries(t.changes)){if(c.has(d)||w.has(d))continue;const g=r?.get(d);if(!g)continue;const{own:y,byKey:f}=x(u,o);Object.keys(y).length>0&&b(s,d,pe(g,y),"",g,y),j(d,g,f,!1)}return a}function pe(e,t){const n={};for(const[s,o]of Object.entries(e))A(s)||(n[s]=o);return{...n,...t}}function ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ye(e,t,n="guest"){const{entity:s,parent:o,extensions:r=[],extensionIds:c={},mintId:w=()=>H()}=e,a=C(s),b=new Set(t.added.map(i=>i.id)),j=new Set(t.removed),d={},u={},g=new Set,y=(i,m,h)=>{for(const l of r){const k=m[l.key],S=h?void 0:c[i]?.[l.key];if(S){if(!k)continue;if(!l.update)throw new Error(`extend.${l.key}: the viewer may not edit it.`);(u[l.key]??=[]).push({id:S,patch:k})}else if(h&&l.create||k){if(!l.create)throw new Error(`extend.${l.key}: the viewer may not create it.`);(d[l.key]??=[]).push(J({...L(l,n),...k,id:w(X(l.entity.collection,i)),[l.field]:i},l.entity.scope)),h&&g.add(l.key)}}},f=t.added.map(i=>{const{own:m,byKey:h}=x({...i,...t.changes[i.id]},r);return y(i.id,h,!0),J({...m,id:i.id,...o&&{[o.field]:o.value}},s.scope)}),O=Object.entries(t.changes).filter(([i])=>!b.has(i)&&!j.has(i)).flatMap(([i,m])=>{const{own:h,byKey:l}=x(m,r);return y(i,l,!1),Object.keys(h).length>0?[{id:i,patch:h}]:[]}),v=[];(f.length>0||O.length>0||t.removed.length>0)&&v.push({collection:s.collection,...f.length>0&&{inserts:f},...O.length>0&&{updates:O},...t.removed.length>0&&{deletes:[...t.removed]},schemas:a});for(const i of r){const m=d[i.key]??[],h=u[i.key]??[];if(m.length===0&&h.length===0)continue;const l=C(i.entity);v.push({collection:i.entity.collection,...m.length>0&&{inserts:m},...h.length>0&&{updates:h},schemas:l,...g.has(i.key)&&{dependsOn:[s.collection]}})}return v}function me(e){const t=new Map;for(const n of e){const s=t.get(n.collection);if(!s){t.set(n.collection,n);continue}const o=[...s.inserts??[],...n.inserts??[]],r=[...s.updates??[],...n.updates??[]],c=[...s.deletes??[],...n.deletes??[]],w=[...new Set([...s.dependsOn??[],...n.dependsOn??[]])];t.set(n.collection,{...s,...o.length>0&&{inserts:o},...r.length>0&&{updates:r},...c.length>0&&{deletes:c},...w.length>0&&{dependsOn:w}})}return[...t.values()]}export{M as EMPTY_CHILD_EDITS,oe as applyChildEdits,ye as childEditsBatches,ue as childEditsErrors,se as childEntityOf,W as childRowsAccess,ie as countChildEdits,E as hasChildEdits,me as mergeBatches,ne as parentCollectionOf,fe as parseChildEdits,F as pickFields,ae as rebaseChildEdits,de as reconcileChildEdits,ce as removeChildRows,C as schemasOf,re as setChildValues,D as writableFields};
@@ -0,0 +1,88 @@
1
+ import type { AnyEntity, EntityExtensions } from '@donotdev/core';
2
+ import type { RenderableField } from './utils/getFieldsForOperation';
3
+ /**
4
+ * Largest `in` list sent in one extension query: Firestore's `in` limit, the
5
+ * strictest of the supported adapters. Longer id lists are read in chunks.
6
+ */
7
+ export declare const EXTENSION_IN_CHUNK = 30;
8
+ /** An extension resolved for a viewer. */
9
+ export interface ResolvedExtension {
10
+ /** Name its fields are addressed under (`offer`) */
11
+ key: string;
12
+ /** The extension entity */
13
+ entity: AnyEntity;
14
+ /** Its reference field pointing at the extended record */
15
+ field: string;
16
+ /** The viewer may read it (`access.read`); otherwise it does not exist for them */
17
+ readable: boolean;
18
+ /** The viewer may insert / update it (`access.create` / `access.update`) */
19
+ create: boolean;
20
+ update: boolean;
21
+ }
22
+ /**
23
+ * Validate and resolve `extend` for a viewer. Throws on a key with `.`, a key
24
+ * equal to a field of the extended entity, or a `field` that is not a reference
25
+ * to the extended entity's collection.
26
+ *
27
+ * @param entity - The extended entity
28
+ * @param extend - The extensions (`undefined`: none)
29
+ * @param viewerRole - The viewer's role
30
+ */
31
+ export declare function resolveExtensions(entity: AnyEntity, extend: EntityExtensions | undefined, viewerRole: string): ResolvedExtension[];
32
+ /** Stable signature of `extend` (memo key: callers pass object literals). */
33
+ export declare function extensionsSignature(extend: EntityExtensions | undefined): string;
34
+ /** `key.field` */
35
+ export declare const extensionFieldName: (key: string, field: string) => string;
36
+ /**
37
+ * `[key, field]` of a prefixed extension field name, or `null` for a field of
38
+ * the extended entity itself.
39
+ */
40
+ export declare function splitExtensionField(name: string): [key: string, field: string] | null;
41
+ /**
42
+ * The extension entity without its link field: the extended record sets it, the
43
+ * viewer never edits it (validation of extension values ignores it).
44
+ */
45
+ export declare function withoutLinkField(ext: ResolvedExtension): AnyEntity;
46
+ /**
47
+ * Renderable fields of an extension for a viewer, prefixed `key.` (form fields,
48
+ * list columns): visible to the viewer, without its id, link field, status and
49
+ * backend-generated fields. Labels are bound to the extension's namespace;
50
+ * `scope` is the key (conditions read the extension's values). Editable and
51
+ * written (derived fields) only when the viewer may write the extension
52
+ * (`create` / `update` access).
53
+ *
54
+ * @param ext - The resolved extension
55
+ * @param viewerRole - The viewer's role
56
+ * @param operation - `'create'` when the extension row does not exist yet
57
+ */
58
+ export declare function extensionFields(ext: ResolvedExtension, viewerRole: string, operation: 'create' | 'edit'): RenderableField[];
59
+ /**
60
+ * Extension field names (prefixed) the viewer may write for an operation: inputs
61
+ * editable for the viewer and derived (`editable: 'computed'`) fields, with their
62
+ * i18n companions (`<name>I18n`).
63
+ *
64
+ * @param ext - The resolved extension
65
+ * @param viewerRole - The viewer's role
66
+ * @param operation - `'create'` (insert of the extension) or `'edit'` (update)
67
+ */
68
+ export declare function extensionWritable(ext: ResolvedExtension, viewerRole: string, operation: 'create' | 'edit'): Set<string>;
69
+ /**
70
+ * Split a flat patch into the extended record's own values and each
71
+ * extension's values (unprefixed). Throws on a prefixed field of an unknown key.
72
+ *
73
+ * @param patch - Flat values (`price`, `offer.priceExclVat`)
74
+ * @param extensions - The resolved extensions
75
+ */
76
+ export declare function splitPatch(patch: Record<string, unknown>, extensions: readonly ResolvedExtension[]): {
77
+ own: Record<string, unknown>;
78
+ byKey: Record<string, Record<string, unknown>>;
79
+ };
80
+ /**
81
+ * Set a value at a dotted path (`offer.image`) in a copy of `values`.
82
+ *
83
+ * @param values - The values
84
+ * @param path - Field name, dotted for an extension field
85
+ * @param value - The value
86
+ */
87
+ export declare function setAtPath(values: Record<string, unknown>, path: string, value: unknown): Record<string, unknown>;
88
+ //# sourceMappingURL=extend.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extend.d.ts","sourceRoot":"","sources":["../../src/forms/extend.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAGlE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAErE;;;GAGG;AACH,eAAO,MAAM,kBAAkB,KAAK,CAAC;AAErC,0CAA0C;AAC1C,MAAM,WAAW,iBAAiB;IAChC,oDAAoD;IACpD,GAAG,EAAE,MAAM,CAAC;IACZ,2BAA2B;IAC3B,MAAM,EAAE,SAAS,CAAC;IAClB,0DAA0D;IAC1D,KAAK,EAAE,MAAM,CAAC;IACd,mFAAmF;IACnF,QAAQ,EAAE,OAAO,CAAC;IAClB,4EAA4E;IAC5E,MAAM,EAAE,OAAO,CAAC;IAChB,MAAM,EAAE,OAAO,CAAC;CACjB;AAaD;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,SAAS,EACjB,MAAM,EAAE,gBAAgB,GAAG,SAAS,EACpC,UAAU,EAAE,MAAM,GACjB,iBAAiB,EAAE,CA2BrB;AAED,6EAA6E;AAC7E,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,gBAAgB,GAAG,SAAS,GACnC,MAAM,CAKR;AAED,kBAAkB;AAClB,eAAO,MAAM,kBAAkB,GAAI,KAAK,MAAM,EAAE,OAAO,MAAM,KAAG,MAC7C,CAAC;AAEpB;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,MAAM,GACX,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,GAAG,IAAI,CAGrC;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,iBAAiB,GAAG,SAAS,CAalE;AAKD;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAC7B,GAAG,EAAE,iBAAiB,EACtB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,QAAQ,GAAG,MAAM,GAC3B,eAAe,EAAE,CAkBnB;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAC/B,GAAG,EAAE,iBAAiB,EACtB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,QAAQ,GAAG,MAAM,GAC3B,GAAG,CAAC,MAAM,CAAC,CAUb;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CACxB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9B,UAAU,EAAE,SAAS,iBAAiB,EAAE,GACvC;IAAE,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAA;CAAE,CAgBlF;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CACvB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,OAAO,GACb,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAUzB"}
@@ -0,0 +1 @@
1
+ import{BACKEND_GENERATED_FIELD_NAMES as b,describeEntity as w,hasRoleAccess as f}from"@donotdev/core";import{getFieldsForOperation as $}from"./utils/getFieldsForOperation";const E=30;function x(e,n){return n===e.field||n==="status"||b.includes(n)}function g(e,n,i){return n?Object.entries(n).map(([o,t])=>{if(o.includes(".")||o in e.fields)throw new Error(`extend: key "${o}" must not contain "." nor be a field of entity "${e.name}".`);const s=t.entity.fields[t.field];if(s?.type!=="reference"||s.validation?.reference!==e.collection)throw new Error(`extend.${o}: "${t.field}" is not a reference of entity "${t.entity.name}" to "${e.collection}".`);const r=f(i,t.entity.access.read);return{key:o,entity:t.entity,field:t.field,readable:r,create:r&&f(i,t.entity.access.create),update:r&&f(i,t.entity.access.update)}}):[]}function k(e){return e?Object.entries(e).map(([n,i])=>`${n}:${i.entity.collection}:${i.field}`).join("|"):""}const c=(e,n)=>`${e}.${n}`;function l(e){const n=e.indexOf(".");return n===-1?null:[e.slice(0,n),e.slice(n+1)]}function N(e){let n=d.get(e.entity);n||(n=new Map,d.set(e.entity,n));let i=n.get(e.field);if(!i){const{[e.field]:o,...t}=e.entity.fields;i={...e.entity,fields:t},n.set(e.field,i)}return i}const d=new WeakMap;function u(e,n,i){if(!e.readable)return[];const o=i==="create"?e.create:e.update;return $(e.entity,{operation:i,viewerRole:n}).filter(t=>!x(e,t.name)).map(t=>({name:c(e.key,t.name),config:{...t.config,name:c(e.key,t.name),label:(t.config.label||t.name).includes(":")?t.config.label||t.name:`${e.entity.namespace}:${t.config.label||t.name}`},editable:t.editable&&o,written:t.written&&o,scope:e.key}))}function h(e,n,i){const{fields:o}=w(e.entity);return new Set(u(e,n,i).filter(t=>t.written).flatMap(t=>{const s=o[l(t.name)?.[1]??t.name]?.companion;return s?[t.name,c(e.key,s)]:[t.name]}))}function A(e,n){const i={},o={};for(const[t,s]of Object.entries(e)){const r=l(t);if(!r){i[t]=s;continue}const[a,m]=r;if(!n.some(p=>p.key===a))throw new Error(`extend: no extension "${a}" for field "${t}".`);o[a]={...o[a],[m]:s}}return{own:i,byKey:o}}function y(e,n,i){const o=l(n);if(!o)return{...e,[n]:i};const[t,s]=o,r=e[t],a=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{};return{...e,[t]:y(a,s,i)}}export{E as EXTENSION_IN_CHUNK,c as extensionFieldName,u as extensionFields,h as extensionWritable,k as extensionsSignature,g as resolveExtensions,y as setAtPath,l as splitExtensionField,A as splitPatch,N as withoutLinkField};
@@ -1 +1 @@
1
- "use client";import{useController as o}from"react-hook-form";function r(e){return o(e)}export{r as useController};
1
+ "use client";import{useController as o}from"react-hook-form";function e(r){return o(r)}export{e as useController};
@@ -1,4 +1,5 @@
1
- import type { AnyEntity } from '@donotdev/core';
1
+ import type { FieldPath } from 'react-hook-form';
2
+ import type { AnyEntity, EntityExtensions, FieldOperation } from '@donotdev/core';
2
3
  import type { EntityFormReturn, InferEntityData, EntityFieldReturn } from '../types';
3
4
  /**
4
5
  * Granular hook for single field control within an entity form.
@@ -7,11 +8,16 @@ import type { EntityFormReturn, InferEntityData, EntityFieldReturn } from '../ty
7
8
  * such as custom components, conditional logic, or complex layouts.
8
9
  *
9
10
  * Returns `{ field, meta, config, isEditable, isVisible, display }`.
10
- * - `display(options?)` formats the current value using the registered field type formatter.
11
+ * - `isEditable` / `isVisible`: as `form.fields` (entity descriptor, viewer role, operation).
12
+ * - `display(options?)` formats the value using the registered field type formatter:
13
+ * the form value for fields the form writes, `form.record` for the others
14
+ * (technical, `editable: false`, role-denied: not in form state).
11
15
  *
12
16
  * @template E - Entity type from defineEntity()
13
17
  * @template K - Field key from entity
14
- * @param form - Form instance from useEntityForm
18
+ * @template Op - The form's operation (inferred from `form`)
19
+ * @template X - The form's 1:1 extensions (inferred from `form`)
20
+ * @param form - Form instance from useEntityForm (any operation, any extensions)
15
21
  * @param fieldName - Name of the field to control
16
22
  * @returns Field state, config, editability info, and display formatter
17
23
  *
@@ -50,9 +56,9 @@ import type { EntityFormReturn, InferEntityData, EntityFieldReturn } from '../ty
50
56
  * @see {@link useEntityForm} for creating the form instance
51
57
  * @see {@link EntityFieldReturn} for return type
52
58
  *
53
- * @version 0.1.0
59
+ * @version 0.2.0
54
60
  * @since 0.0.1
55
61
  * @author AMBROISE PARK Consulting
56
62
  */
57
- export declare function useEntityField<E extends AnyEntity, K extends keyof InferEntityData<E>>(form: EntityFormReturn<E>, fieldName: K): EntityFieldReturn<E, K>;
63
+ export declare function useEntityField<E extends AnyEntity, K extends string & keyof InferEntityData<E> & FieldPath<InferEntityData<E>>, Op extends FieldOperation = FieldOperation, X extends EntityExtensions = Record<never, never>>(form: EntityFormReturn<E, Op, X>, fieldName: K): EntityFieldReturn<E, K>;
58
64
  //# sourceMappingURL=useEntityField.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"useEntityField.d.ts","sourceRoot":"","sources":["../../../src/forms/hooks/useEntityField.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,SAAS,EAAe,MAAM,gBAAgB,CAAC;AAI7D,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EACf,iBAAiB,EAClB,MAAM,UAAU,CAAC;AAGlB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AACH,wBAAgB,cAAc,CAC5B,CAAC,SAAS,SAAS,EACnB,CAAC,SAAS,MAAM,eAAe,CAAC,CAAC,CAAC,EAClC,IAAI,EAAE,gBAAgB,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,GAAG,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,CAkFlE"}
1
+ {"version":3,"file":"useEntityField.d.ts","sourceRoot":"","sources":["../../../src/forms/hooks/useEntityField.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAW,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE1D,OAAO,KAAK,EACV,SAAS,EACT,gBAAgB,EAEhB,cAAc,EACf,MAAM,gBAAgB,CAAC;AAIxB,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EACf,iBAAiB,EAClB,MAAM,UAAU,CAAC;AAElB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AACH,wBAAgB,cAAc,CAC5B,CAAC,SAAS,SAAS,EACnB,CAAC,SAAS,MAAM,GAAG,MAAM,eAAe,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,EAC3E,EAAE,SAAS,cAAc,GAAG,cAAc,EAC1C,CAAC,SAAS,gBAAgB,GAAG,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,EACjD,IAAI,EAAE,gBAAgB,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,GAAG,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,CAmEzE"}
@@ -1 +1 @@
1
- "use client";import{useMemo as o,useCallback as p}from"react";import{useController as v}from"./useController";import{formatValue as h}from"../../components/DisplayFieldRenderer";import{isFieldEditable as g}from"../utils";function D(a,i){const{entity:b,operation:r,viewerRole:n,fields:u}=a,l=b.fields[i],e=o(()=>l?{...l,name:l.name||i,label:l.label||i}:{name:i,type:"text",label:i,visibility:"user"},[i,l]),s=o(()=>u.some(d=>d.name===i),[u,i]),c=o(()=>!s||r==="edit"&&e.visibility==="technical"&&e.editable===void 0?!1:g(e.editable,n,r),[s,r,e.visibility,e.editable,n]),{field:m,fieldState:t}=v({name:i,control:a.control}),f=o(()=>({error:t.error?.message,touched:t.isTouched,isDirty:t.isDirty}),[t.error?.message,t.isTouched,t.isDirty]),y=p(d=>h(m.value,e,a.t,d),[m.value,e,a.t]);return{field:m,meta:f,config:e,isEditable:c,isVisible:s,display:y}}export{D as useEntityField};
1
+ "use client";import{useMemo as l,useCallback as h}from"react";import{useController as p}from"./useController";import{formatValue as E}from"../../components/DisplayFieldRenderer";function D(r,e){const{entity:n,fields:d}=r,t=n.fields[e],o=l(()=>{if(!t)throw new Error(`useEntityField: entity "${n.name}" has no field "${e}".`);return{...t,name:t.name||e,label:t.label||e}},[e,t]),s=l(()=>d.find(a=>a.name===e),[d,e]),u=s!==void 0,c=s?.editable??!1,{field:m,fieldState:i}=p({name:e,control:r.control}),y=l(()=>({error:i.error?.message,touched:i.isTouched,isDirty:i.isDirty}),[i.error?.message,i.isTouched,i.isDirty]),f=s?.written?m.value:r.record?.[e],b=h(a=>E(f,o,r.t,a),[f,o,r.t]);return{field:m,meta:y,config:o,isEditable:c,isVisible:u,display:b}}export{D as useEntityField};
@@ -1,22 +1,67 @@
1
- import type { AnyEntity } from '@donotdev/core';
1
+ import type { AnyEntity, EntityExtensions, FieldOperation } from '@donotdev/core';
2
2
  import type { UseEntityFormOptions, EntityFormReturn } from '../types';
3
3
  /**
4
4
  * Creates a type-safe form instance from an entity definition.
5
5
  *
6
+ * Automatically binds translations to `[entity.namespace, 'crud']`, including
7
+ * language changes and the SSR request language. No `t` option is needed for
8
+ * normal framework usage; each entity form resolves its own namespace.
9
+ * Pass `options.t` only to override the default namespace resolution with your
10
+ * own translator. It replaces the default translator, rather than extending it.
11
+ * Pass the returned `form.t` to every FormFieldRenderer / DisplayFieldRenderer,
12
+ * including nested field-array fields. Do not duplicate entity labels in page locales.
13
+ * The viewer role is not inferred: pass the actual `viewerRole` (default: guest).
14
+ * Prefer EntityFormRenderer from @donotdev/ui when no custom layout is needed.
15
+ *
6
16
  * Simple, predictable behavior:
7
- * - Edit mode: defaultValues (DB object) is used as-is, auto-save to FormStore
8
- * - Create mode: starts empty, auto-save to FormStore
9
- * - Draft restored on mount with dismissible toast
17
+ * - Edit mode: defaultValues (DB object) is accepted as-is and becomes `form.record`;
18
+ * auto-save to FormStore
19
+ * - Create mode: schema/caller defaults, auto-save to FormStore
20
+ * - Draft restored on mount with dismissible toast (with the `form.record` it was
21
+ * saved with, so a concurrency token read from it stays the draft's base version)
22
+ *
23
+ * Form state, local draft and payload hold only the fields the form writes
24
+ * (entity descriptor, design 3.4): inputs editable for the viewer and operation,
25
+ * `editable: 'computed'` fields (shown read-only, written), their i18n companions,
26
+ * and `id` on edit. Generated, technical, `editable: false` and role-denied fields
27
+ * never enter them: read them from `form.record`. `handleSubmit(onValid)` passes
28
+ * `onValid` the resolver's output (`FormValues<E, Op, X>`; the extensions' values
29
+ * under their keys).
10
30
  *
11
31
  * When formId is provided:
12
32
  * - Tracks form status (uploading/validating/submitting)
13
33
  * - Orchestrates file uploads before validation
14
34
  * - Provides cleanup function for unmount
15
35
  *
36
+ * On a valid submit the page leaves for `successPath` (default: the previous
37
+ * breadcrumb) before the server answers, and returns on rejection. Pass
38
+ * `successPath: null` to stay.
39
+ *
40
+ * `handleSubmit()` without `onValid` uses the default writer: the record
41
+ * (update, or add on create) with the fields the form writes, plus the child
42
+ * rows joined to this form (`useChildRows` / a nested `EntityList`), in one
43
+ * `bulkAcross`. With `onValid`, write the joined rows from `form.pendingWrites()`
44
+ * (the submit fails explicitly when joined rows have edits and it was not read).
45
+ *
16
46
  * @template E - Entity type from defineEntity()
47
+ * @template Op - Form operation (`options.operation`; both when not given)
48
+ * @template X - 1:1 extensions (`options.extend`), none by default
17
49
  * @param entity - Entity definition from defineEntity()
18
50
  * @param options - Form configuration options
19
51
  * @returns Form instance with React Hook Form API plus entity-aware extensions
52
+ *
53
+ * @example
54
+ * ```tsx
55
+ * const viewerRole = useAuth('userRole');
56
+ * const form = useEntityForm(productEntity, {
57
+ * formId: 'product-create',
58
+ * operation: 'create',
59
+ * viewerRole,
60
+ * });
61
+ * // In the custom layout, for each editable field from form.fields:
62
+ * // <FormFieldRenderer name={field.name} config={field.config}
63
+ * // control={form.control} t={form.t} />
64
+ * ```
20
65
  */
21
- export declare function useEntityForm<E extends AnyEntity>(entity: E, options?: UseEntityFormOptions<E>): EntityFormReturn<E>;
66
+ export declare function useEntityForm<E extends AnyEntity, Op extends FieldOperation = FieldOperation, const X extends EntityExtensions = Record<never, never>>(entity: E, options?: UseEntityFormOptions<E, Op, X>): EntityFormReturn<E, Op, X>;
22
67
  //# sourceMappingURL=useEntityForm.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"useEntityForm.d.ts","sourceRoot":"","sources":["../../../src/forms/hooks/useEntityForm.ts"],"names":[],"mappings":"AA8BA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAKhD,OAAO,KAAK,EACV,oBAAoB,EACpB,gBAAgB,EAEjB,MAAM,UAAU,CAAC;AAuElB;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,SAAS,EAC/C,MAAM,EAAE,CAAC,EACT,OAAO,GAAE,oBAAoB,CAAC,CAAC,CAAM,GACpC,gBAAgB,CAAC,CAAC,CAAC,CAyoBrB"}
1
+ {"version":3,"file":"useEntityForm.d.ts","sourceRoot":"","sources":["../../../src/forms/hooks/useEntityForm.ts"],"names":[],"mappings":"AA0CA,OAAO,KAAK,EACV,SAAS,EAGT,gBAAgB,EAChB,cAAc,EAGf,MAAM,gBAAgB,CAAC;AAkCxB,OAAO,KAAK,EACV,oBAAoB,EAEpB,gBAAgB,EAGjB,MAAM,UAAU,CAAC;AA+GlB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8DG;AACH,wBAAgB,aAAa,CAC3B,CAAC,SAAS,SAAS,EACnB,EAAE,SAAS,cAAc,GAAG,cAAc,EAC1C,KAAK,CAAC,CAAC,SAAS,gBAAgB,GAAG,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,EAEvD,MAAM,EAAE,CAAC,EACT,OAAO,GAAE,oBAAoB,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAM,GAC3C,gBAAgB,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAi0C5B"}
@@ -1 +1 @@
1
- "use client";import{valibotResolver as B}from"@hookform/resolvers/valibot";import{useMemo as C,useEffect as T,useRef as y,createElement as ce}from"react";import{useForm as fe}from"react-hook-form";import{toast as G,ToastAction as de}from"@donotdev/components";import{BACKEND_GENERATED_FIELD_NAMES as me,createSchemas as ge}from"@donotdev/core";import{useFormStore as d,useFormStatus as pe,useUploadProgress as be}from"../../stores";import{useUploadStore as w}from"../../stores/UploadStore";import{checkForBlobUrls as Se,isStorageUrl as ye}from"../../utils/uploadValidation";import{getFieldsForOperation as he}from"../utils";import{buildInitialFromRecord as ve,buildSchemaDefaults as Ee}from"../utils/buildInitialValues";const je=t=>t;function K(t,f){const e={...t};for(const b of Object.keys(f)){const u=t[b],h=f[b];h!==null&&typeof h=="object"&&!Array.isArray(h)&&u!==null&&typeof u=="object"&&!Array.isArray(u)?e[b]=K(u,h):e[b]=h}return e}function L(t){if(t==null)return t;if(typeof t=="string")return t.startsWith("blob:")?null:t;if(Array.isArray(t)){const f=t.map(L).filter(e=>e!==null);return f.length>0?f:null}if(typeof t=="object"){const f=t;if("fullUrl"in f&&typeof f.fullUrl=="string")return ye(f.fullUrl)?f:null;const e={};for(const[b,u]of Object.entries(f))e[b]=L(u);return e}return t}function De(t,f={}){const{formId:e,operation:b,defaultValues:u,viewerRole:h,mode:W="onBlur",t:Y,loading:F=!1}=f,S=Y??je,N=h??"guest",c=b??(u?"edit":"create"),H=pe(e??""),J=be(e??""),I=C(()=>ge(t),[t.name]),Q=C(()=>{const r=B(I.create),o=B(I.draft),n=B(I.update);return async(a,s,i)=>c==="edit"?n(a,s,i):(a?.status??u?.status??"draft")==="draft"?o(a,s,i):r(a,s,i)},[I,c,u?.status]),A=C(()=>Ee(t),[t]),U=u,m=C(()=>{if(!F)return c==="edit"?U?ve(t,U):void 0:U?{...A,...U}:A},[F,c,A,t,U]),l=fe({defaultValues:c==="create"?m:void 0,mode:W,resolver:Q,shouldUnregister:!1,shouldFocusError:!0}),E=y(l);T(()=>{E.current=l},[l]);const R=y(null);T(()=>{if(c==="edit"&&m){const r=m.id??null;r&&r!==R.current?(E.current.reset(m),R.current=r):!r&&R.current===null&&(E.current.reset(m),R.current="initialized")}},[c,m]);const k=u?.id,x=`${t.name.toLowerCase()}-form-draft`,v=c==="create"?x:k?`${x}-${k}`:`${x}-edit`,j=y(!1),_=y(F);_.current&&!F&&(j.current=!1),_.current=F,T(()=>{if(j.current)return;const r=d.getState().loadDraft(v),o=n=>{const a=()=>{d.getState().clearDraft(v),n&&E.current.reset(n)};G({toastType:"info",title:S("draft.restored",{defaultValue:"Draft restored"}),description:S("draft.restoredDescription",{defaultValue:"Your unsaved changes were recovered"}),action:ce(de,{altText:S("draft.discard",{defaultValue:"Discard"}),onClick:a},S("draft.discard",{defaultValue:"Discard"})),duration:8e3})};if(c==="create"&&!u){r&&(l.reset(r.data),o(A)),j.current=!0;return}if(c==="edit"&&m){if(r){const n=K(m,r.data);l.reset(n),o(m)}j.current=!0}},[c,u,v,l,m,S,A]);const P=y(!1),V=y(null);T(()=>{const r=l.watch(o=>{P.current||!j.current||(V.current&&clearTimeout(V.current),V.current=setTimeout(()=>{if(o&&Object.values(o).some(n=>n!=null&&n!=="")){const n=L(o);d.getState().saveDraft(v,n,t.name,k)}},3e3))});return()=>{r.unsubscribe(),V.current&&clearTimeout(V.current)}},[l,v,t.name,k]);const D=y(null),O=y(!1),X=async r=>{if(!e)return{};const o=w.getState(),n=d.getState();if(!o.hasPendingUploads(e))return{};const a=setInterval(()=>{const s=w.getState().getTotalProgress(e);d.getState().setUploading(e,s)},200);try{return n.setUploading(e,0),await o.uploadAll(e,r),r?.aborted?null:w.getState().getResults(e)}catch(s){const i=w.getState().uploads[e];i&&Object.entries(i).forEach(([g,$])=>{$.status==="error"&&$.error&&l.setError(g,{type:"upload",message:$.error})});const p=s instanceof Error?s.message:"File upload failed";return d.getState().setError(e,p),null}finally{clearInterval(a)}},Z=r=>c!=="create"?r:Object.fromEntries(Object.entries(r).filter(([o])=>!me.includes(o))),ee=(r,o)=>{const n={...o};for(const[a,s]of Object.entries(r.fields))if(s.type==="price"&&a in n){const i=n[a];(i==null||i.amount==null)&&(n[a]=null)}return n},te=r=>{if(typeof window>"u")return;const o=Object.keys(r).find(a=>a!=="root"&&r[a]);if(!o)return;const n=document.querySelector(`input[name="${o}"][aria-invalid="true"], textarea[name="${o}"][aria-invalid="true"], select[name="${o}"][aria-invalid="true"]`)??document.querySelector(`[name="${o}"]`);n&&(n.scrollIntoView({behavior:"smooth",block:"center"}),n.focus())},re=l.handleSubmit,ae=((r,o)=>async n=>{if(n?.preventDefault?.(),O.current)return;const a=e?d.getState():null;await re(async(s,i)=>{if(O.current)return;O.current=!0,D.current?.abort();const p=new AbortController;D.current=p,P.current=!0;try{e&&a&&a.startSubmit(e);const g=await X(p.signal);if(g===null||p.signal.aborted)return;e&&a&&a.setSubmitting(e);const $={...s,...g},le=Z($),M=ee(t,le),z=Se(M);if(z.length>0){const ue=`Cannot save: blob URLs detected at ${z.join(", ")}. Re-upload the files.`;e&&a&&a.setError(e,ue);return}if(p.signal.aborted)return;await r(M,i),d.getState().clearDraft(v),E.current.reset(E.current.getValues()),e&&a&&a.setSuccess(e)}catch(g){throw e&&a&&a.setError(e,g instanceof Error?g.message:"Submission failed"),g}finally{if(P.current=!1,O.current=!1,D.current===p&&(D.current=null),e){const g=d.getState().forms[e]?.status;(g==="uploading"||g==="validating"||g==="submitting")&&d.getState().reset(e)}}},s=>{const i=Object.keys(s).filter(p=>p!=="root"&&s[p]);G({toastType:"error",title:S("validation.failed",{defaultValue:"Validation failed"}),description:S("validation.fixErrorsCount",{count:i.length,fields:i.join(", "),defaultValue:`${i.length} field(s) need attention: ${i.join(", ")}`}),duration:8e3}),te(s),o?.(s)})(n)}),ne=()=>{d.getState().clearDraft(v),l.reset(m),j.current=!1},q=()=>{D.current?.abort(),e&&(d.getState().cleanup(e),w.getState().cleanup(e))};T(()=>q,[]);const oe=()=>{D.current?.abort(),e&&(w.getState().abortAll(e),d.getState().reset(e)),O.current=!1},se=he(t,{operation:c,viewerRole:N,availableFields:void 0}),ie=l.formState.isSubmitted||Object.keys(l.formState.touchedFields||{}).length>0;return{...l,handleSubmit:ae,fields:se,operation:c,entity:t,t:S,viewerRole:N,formId:e,formStatus:e?H:"idle",uploadProgress:e?J:0,cleanup:q,cancel:oe,isDirty:l.formState.isDirty,hasUserInteracted:ie,resetForm:ne,originalValues:m}}export{De as useEntityForm};
1
+ "use client";import{useMemo as H,useEffect as C,useId as Bt,useRef as w,useState as De,createElement as Kt}from"react";import{useForm as Ht}from"react-hook-form";import{toast as Re,ToastAction as Jt}from"@donotdev/components";import{createSchemas as Gt,statusOf as Qt,useTranslation as Xt}from"@donotdev/core";import{childRowsKey as Yt,extensionMintKey as nt,useFormStore as l,useFormStatus as Zt,useUploadProgress as _t}from"../../stores";import{useExtensionRows as er}from"../../hooks/useExtensionRows";import{getCrudServiceInstance as ie}from"../../useCrud";import{hasChildEdits as Z,mergeBatches as tr,pickFields as _,rebaseChildEdits as rr,schemasOf as nr,writableFields as or}from"../childRows";import{extensionFields as sr,extensionWritable as ot,extensionsSignature as ar,resolveExtensions as cr,setAtPath as ir,splitExtensionField as Ae,withoutLinkField as lr}from"../extend";import{useFormNavigation as ur}from"../FormNavigation";import{useUploadStore as J}from"../../stores/UploadStore";import{checkForBlobUrls as dr,isStorageUrl as fr}from"../../utils/uploadValidation";import{injectScope as Ie}from"../../utils/scopeUtils";import{getFieldsForOperation as mr,translateFieldLabel as gr}from"../utils";import{createConditionAwareResolver as st,getFormConditionStates as Ve}from"../utils/conditionAwareResolver";import{buildInitialFromRecord as at,buildSchemaDefaults as ct}from"../utils/buildInitialValues";const it="@childRows",xe="@record",pr=s=>new Set([...s].map(p=>Ae(p)?.[1]??p)),Ce=(s,p,a)=>pr(ot(s,p,a));function M(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function lt(s){return M(s)?s.updatedAt:void 0}function ut(s,p){const a={...s};for(const $ of Object.keys(p)){const E=s[$],T=p[$];T!==null&&typeof T=="object"&&!Array.isArray(T)&&E!==null&&typeof E=="object"&&!Array.isArray(E)?a[$]=ut(E,T):a[$]=T}return a}function le(s){if(s==null)return s;if(typeof s=="string")return s.startsWith("blob:")?null:s;if(Array.isArray(s)){const p=s.map(le).filter(a=>a!==null);return p.length>0?p:null}if(typeof s=="object"){const p=s;if("fullUrl"in p&&typeof p.fullUrl=="string")return fr(p.fullUrl)?p:null;const a={};for(const[$,E]of Object.entries(p))a[$]=le(E);return a}return s}function yr(s,p={}){const{formId:a,operation:$,defaultValues:E,viewerRole:T,mode:dt="onBlur",t:ft,loading:$e=!1,successPath:mt,extend:Ue}=p,G=ur(),h=T??"guest",gt=ar(Ue),g=H(()=>cr(s,Ue,h).filter(e=>e.readable),[s,gt,h]),{t:pt}=Xt([s.namespace,"crud",...g.map(e=>e.entity.namespace)]),b=ft??pt,u=$??(E?"edit":"create"),ee=E?.id,Me=er(g,u==="edit"&&ee?[ee]:[],!$e),ue=e=>ee?Me[e]?.byRecord.get(ee):void 0,P=e=>u==="edit"&&ue(e)?"edit":"create",te=g.map(e=>ue(e.key)),yt=g.map(e=>`${e.key}:${P(e.key)}`).join("|"),L=$e||Object.values(Me).some(e=>e.loading),ht=Zt(a??""),bt=_t(a??""),j=E,Te=Qt(j),I=H(()=>or(s,h,u),[s,h,u]),St=H(()=>{const e=st(s,u,I,j),r=(n,o,c)=>e(u==="edit"?n:Ie(n,s.scope),o,c);if(g.length===0)return r;const t=g.map(n=>({key:n.key,resolve:st(lr(n),P(n.key),Ce(n,h,P(n.key)))}));return async(n,o,c)=>{const i=await r(n,o,c),v={...i.errors},m={...i.values},y={criteriaMode:c.criteriaMode,fields:c.fields,shouldUseNativeValidation:c.shouldUseNativeValidation};for(const{key:N,resolve:O}of t){const B=n[N],S=await O(M(B)?B:{},o,y);Object.keys(S.errors).length>0?v[N]=S.errors:m[N]=S.values}return Object.keys(v).length>0?{values:{},errors:v}:{values:m,errors:{}}}},[s,u,I,j,g,yt,h]),re=H(()=>ct(s,I),[s,I]),k=H(()=>{if(L)return;const e=u==="edit"?j?at(s,j,{fields:I,keepId:!0}):void 0:j?_({...re,...j},I):re;if(!e||g.length===0)return e;const r={...e};return g.forEach((t,n)=>{const o=te[n],c=Ce(t,h,o?"edit":"create");r[t.key]=o?at(t.entity,o,{fields:c,keepId:!0}):ct(t.entity,c)}),r},[L,u,re,s,j,I,h,g,...te]),de=H(()=>{if(u!=="edit"||L||!j)return;const e={...j};return g.forEach((r,t)=>{const n=te[t];n&&(e[r.key]=n)}),e},[u,L,j,g,...te]),[wt,fe]=De(null),me=wt??de,ge=w(me);ge.current=me;const pe=e=>{const r=_(e,I);u==="edit"&&Object.hasOwn(e,"id")&&(r.id=e.id);for(const t of g){const n=e[t.key];if(!M(n))continue;const o=P(t.key),c=_(n,Ce(t,h,o));o==="edit"&&Object.hasOwn(n,"id")&&(c.id=n.id),r[t.key]=c}return r},d=Ht({defaultValues:u==="create"?k:void 0,mode:dt,resolver:St,shouldUnregister:!1,shouldFocusError:!1});C(()=>{let e=Ve(s,d.getValues()),r=!0,t=!1;const n=new Set,o=async()=>{if(!t){t=!0;try{for(;r&&n.size>0;){const i=[...n];if(n.clear(),await d.trigger(i),!r)return;for(const v of Ve(s,d.getValues()))v.visible||d.clearErrors(v.name)}}finally{t=!1}}},c=d.watch(()=>{const i=Ve(s,d.getValues()),v=i.filter((m,y)=>m.visible!==e[y]?.visible||m.required!==e[y]?.required);e=i;for(const m of v){const y=m.name;m.visible||d.clearErrors(y),n.add(y)}n.size>0&&o()});return()=>{r=!1,n.clear(),c.unsubscribe()}},[s,d]);const V=w(d);C(()=>{V.current=d},[d]);const ne=w(null);C(()=>{if(u==="edit"&&k){const e=k.id??null;e&&e!==ne.current?(V.current.reset(k),ne.current=e):!e&&ne.current===null&&(V.current.reset(k),ne.current="initialized")}},[u,k]);const D=E?.id,ye=`${s.name.toLowerCase()}-form-draft${a?`-${a}`:""}`,F=u==="create"?ye:D?`${ye}-${D}`:`${ye}-edit`,W=w(!1),x=Bt(),R=u==="edit"?D:void 0,Q=e=>R?Object.keys(e).flatMap(r=>{const[t,n,o,c]=r.split("\0");return t===x&&n===R&&o&&c?[[r,o,c]]:[]}):[],Pe=()=>{const{childEdits:e,childWriters:r}=l.getState();return Q(e).flatMap(([t,n,o])=>{const c=e[t];if(!Z(c))return[];const i=r[t];if(!i)throw new Error(`useEntityForm(${s.name}): joined rows ${n}.${o} have edits but no useChildRows registered how to write them.`);return[{key:t,collection:n,field:o,writer:i,edits:c}]})},Le=()=>{const{childEdits:e,childDrafts:r}=l.getState(),t={};for(const[n,o,c]of Q(r))t[o]={...t[o],[c]:r[n]};for(const[n,o,c]of Q(e)){const i=e[n];Z(i)&&(t[o]={...t[o],[c]:i})}return Object.keys(t).length>0?t:void 0},vt=e=>{if(!(e===void 0||!R)&&M(e)){for(const[r,t]of Object.entries(e))if(M(t))for(const[n,o]of Object.entries(t))l.getState().setChildDraft(Yt(x,R,r,n),o)}},U=w(new Map),oe=w(null),he=()=>{if(U.current.size===0)return;const e={};for(const[r,t]of U.current)e[r]=t.get();return e},We=(e=!0)=>{const r=he(),t=Le(),n=e&&u==="edit"?ge.current:void 0;return!t&&!n?r:{...r,...t&&{[it]:t},...n&&{[xe]:n}}},kt=e=>{e!==void 0&&(!M(e)||!R||e.id!==R||fe(e))},Et=()=>{const e=V.current;return Object.keys(e.getValues()).some(r=>e.getFieldState(r).isDirty)},Ne=()=>Et()||[...U.current.values()].some(e=>e.edited())||Le()!==void 0,Ft=e=>{if(oe.current=e??null,!!e){for(const[r,t]of U.current)r in e&&t.restore(e[r]);vt(e[it]),kt(e[xe])}},qe=()=>{oe.current=null,fe(null);for(const r of U.current.values())r.reset();const e=l.getState();for(const[r]of Q(e.childEdits))e.setChildEdits(r,null);for(const[r]of Q(e.childDrafts))e.setChildDraft(r,null)},se=w(()=>{}),[Ot]=De(()=>({register:(e,r)=>{U.current.set(e,r);const t=oe.current;return t&&e in t&&r.restore(t[e]),()=>{U.current.get(e)===r&&U.current.delete(e)}},changed:()=>se.current()})),ze=w(L);ze.current&&!L&&(W.current=!1),ze.current=L;const jt=e=>{l.getState().clearDraft(F),V.current.reset(e),qe()},[be,Be]=De(null);C(()=>{if(!be)return;Be(null);const{base:e,conflict:r}=be;if(!Ne()){l.getState().clearDraft(F),oe.current=null,fe(null);return}Re({toastType:r?"warning":"info",title:b(r?"crud:draft.conflict":"crud:draft.restored"),description:b(r?"crud:draft.conflictDescription":"crud:draft.restoredDescription"),action:Kt(Jt,{altText:b("crud:draft.discard"),onClick:()=>jt(e)},b("crud:draft.discard")),duration:r?1/0:8e3})},[be]),C(()=>{if(W.current)return;const e=l.getState().loadDraft(F),r=t=>{if(!e)return;const n=e.extras?.[xe];d.reset(t);const o=pe(ut(t,e.data));for(const[c,i]of Object.entries(o))d.setValue(c,i,{shouldDirty:!0});Ft(e.extras),Be({base:t,conflict:u==="edit"&&n!==void 0&&lt(n)!==lt(de)})};if(u==="create"&&k){e?r(k):d.reset(k),W.current=!0;return}u==="edit"&&k&&(r(k),W.current=!0)},[u,E,F,d,k,de,b,re]);const q=w(null),ae=()=>{q.current&&clearTimeout(q.current),q.current=null},Ke=()=>{if(!Ne()){l.getState().clearDraft(F);return}l.getState().saveDraft(F,le(pe(V.current.getValues())),s.name,D,We())},He=()=>{Ke()},Se=w(He);Se.current=He,se.current=()=>{W.current&&(ae(),q.current=setTimeout(()=>{q.current=null,Se.current()},3e3))},C(()=>{const e=d.watch(()=>se.current()),r=Se.current;return()=>{e.unsubscribe(),q.current&&(ae(),r())}},[d,F,s.name,D]);const Je=w(h);Je.current=h,C(()=>{if(R)return l.getState().openRecord({formKey:x,collection:s.collection,recordId:R,viewerRole:Je.current,submitting:!1,changed:()=>se.current()}),()=>l.getState().closeRecord(x)},[x,s.collection,R]),C(()=>{l.getState().updateOpenRecord(x,{viewerRole:h})},[x,h]);const z=w(null),X=w(!1),Dt=async e=>{if(!a)return{};const r=J.getState(),t=l.getState();if(!r.hasPendingUploads(a))return{};const n=setInterval(()=>{const o=J.getState().getTotalProgress(a);l.getState().setUploading(a,o)},200);try{return t.setUploading(a,0),await r.uploadAll(a,e),e?.aborted?null:J.getState().getResults(a)}catch(o){const c=J.getState().uploads[a];c&&Object.entries(c).forEach(([v,m])=>{m.status==="error"&&m.error&&d.setError(v,{type:"upload",message:m.error})});const i=o instanceof Error?o.message:b("crud:form.uploadFailed");return l.getState().setError(a,i),null}finally{clearInterval(n)}},Ge=(e,r)=>{let t={...e};for(const[n,o]of Object.entries(r)){const c=Ae(n);t=c&&g.some(i=>i.key===c[0])?ir(t,n,o):{...t,[n]:o}}return t},we=(e,r)=>{const t={...r};for(const[n,o]of Object.entries(e.fields))if(o.type==="price"&&n in t){const c=t[n];(c==null||c.amount==null)&&(t[n]=null)}return t},Rt=(e,r)=>{if(typeof HTMLFormElement>"u"||!(r instanceof HTMLFormElement))return;const t=Object.keys(e).filter(o=>o!=="root"),n=r.querySelectorAll("input, textarea, select, button, [tabindex]");for(const o of n){const c=o.getAttribute("name");if(!(!(o.getAttribute("aria-invalid")==="true"||c!==null&&t.some(i=>c===i||c.startsWith(`${i}.`)))||o.matches(':disabled, input[type="hidden"]')||o.closest('[hidden], [inert], [aria-hidden="true"]')||o.getClientRects().length===0)&&(o.focus(),o.ownerDocument.activeElement===o)){o.scrollIntoView({behavior:"smooth",block:"center"});return}}},ve=w(null),ke=w(null),Ee=w(!1),Fe=`record\0${F}`,Oe=()=>g.filter(e=>P(e.key)==="edit"?e.update:e.create),At=(e,r)=>Oe().map(t=>{const n=P(t.key),o=new Set([...ot(t,h,n)].map(y=>Ae(y)?.[1]??y)),c=e[t.key],i=we(t.entity,_(M(c)?c:{},o)),v=nr(t.entity),m=ue(t.key);if(m)return{collection:t.entity.collection,updates:[{id:m.id,patch:i,stored:m}],schemas:v};if(!r)throw new Error(`useEntityForm(${s.name}): inserting extension "${t.key}" on create needs the record id: pendingWrites({ recordId }) (pre-mint it).`);return{collection:t.entity.collection,inserts:[Ie({...i,id:l.getState().mintId(nt(t.entity.collection,r)),[t.field]:r},t.entity.scope)],schemas:v,...u==="create"&&{dependsOn:[s.collection]}}}),It=async()=>{const e=ie();if(!e)throw new Error(b("crud:form.saveFailed"));if(u!=="edit"||!D)throw new Error(`useEntityForm(${s.name}): remove() needs an edited record (defaultValues.id).`);await e.remove(s.collection,D),l.getState().clearDraft(F)},Qe=(e={})=>{Ee.current=!0;const r=ve.current??Pe(),t=ke.current??V.current.getValues();return tr([...At(t,R??e.recordId),...r.flatMap(({writer:n,edits:o})=>n.batches(o))])},Xe=e=>{let r=0;for(const{writer:n,edits:o}of e){const c=n.errors(o),i=Object.keys(c).length;i!==0&&(r+=i)}if(r===0)return!1;const t=b("crud:childRows.invalidRows",{count:r});return a?l.getState().setError(a,t):Re({toastType:"error",title:t,duration:8e3}),!0},Vt=()=>!I.has("status")&&Te!==null?{status:Te}:{},xt=async e=>{const r=ie();if(!r)throw new Error(b("crud:form.saveFailed"));const t=Gt(s),n=_(e,I);if(u==="edit"&&!D)throw new Error(`useEntityForm(${s.name}): the default writer needs defaultValues.id in edit mode.`);const o=u==="create"&&Oe().length>0?l.getState().mintId(Fe):void 0,c=u==="edit"&&D?{collection:s.collection,updates:[{id:D,patch:n,stored:ge.current}],schemas:t}:{collection:s.collection,inserts:[Ie({...n,...Vt(),...o&&{id:o}},s.scope)],schemas:t};return r.bulkAcross([c,...Qe({recordId:o})])},Ct=d.handleSubmit,$t=(e,r,t)=>async n=>{let o;n?.preventDefault?.();const c=n?.currentTarget;if(X.current)return;const i=a?l.getState():null,v=structuredClone(V.current.getValues()),m=Pe().filter(({edits:y})=>Z(y));return await Ct(async(y,N)=>{if(X.current||Xe(m))return;X.current=!0,z.current?.abort();const O=new AbortController;z.current=O;let B=null;try{a&&i&&i.startSubmit(a);const S=await Dt(O.signal);if(S===null||O.signal.aborted)return;a&&i&&i.setSubmitting(a);const Lt=Ge(y,S),K=we(s,Lt);for(const f of g){const A=K[f.key];M(A)&&(K[f.key]=we(f.entity,A))}if(dr(K).length>0){a&&i&&i.setError(a,b("crud:form.reuploadFiles"));return}if(O.signal.aborted)return;const Wt=Ge(v,structuredClone(S));W.current&&(ae(),Ke());const Nt=new Map(Object.entries(he()??{}).map(([f,A])=>[f,JSON.stringify(A)])),_e=t&&"successPath"in t?t.successPath:mt;if(G&&_e!==null){const f=G.currentPath(),A=_e??G.parentPath();A!==f&&(B=f,G.navigate(A))}if(ve.current=m,ke.current=K,Ee.current=!1,l.getState().updateOpenRecord(x,{submitting:!0}),o=e?await e(K,N):await xt(K),[...m.map(({collection:f})=>f),...Oe().map(f=>f.entity.collection)].length>0&&!Ee.current)throw new Error(b("crud:childRows.notSaved"));let et=!1;for(const{key:f,collection:A,edits:zt}of m){const rt=l.getState().childEdits[f],Y=rt?rr(rt,zt):null;et||=!!Y&&Z(Y),l.getState().setChildEdits(f,Y&&Z(Y)?Y:null),ie()?.invalidateCollection(A)}for(const f of g)ie()?.invalidateCollection(f.entity.collection);const qt=l.getState().mintedIds[Fe],tt=R??qt;l.getState().releaseMintedIds([Fe,...tt?g.map(f=>nt(f.entity.collection,tt)):[]]);const ce=V.current,je=ce.getValues();ce.reset(Wt,{keepValues:!0}),ce.reset(je,{keepDefaultValues:!0}),ae(),Object.keys(je).some(f=>ce.getFieldState(f).isDirty)||Object.entries(he()??{}).some(([f,A])=>Nt.get(f)!==JSON.stringify(A))||et?l.getState().saveDraft(F,le(pe(je)),s.name,D,We(!1)):l.getState().clearDraft(F),a&&i&&i.setSuccess(a)}catch(S){throw B!==null&&G?.navigate(B),a&&i&&i.setError(a,S instanceof Error?S.message:b("crud:form.saveFailed"),S),S}finally{if(X.current=!1,ve.current=null,ke.current=null,l.getState().updateOpenRecord(x,{submitting:!1}),z.current===O&&(z.current=null),a){const S=l.getState().forms[a]?.status;(S==="uploading"||S==="validating"||S==="submitting")&&l.getState().reset(a)}}},y=>{const N=Object.keys(y).filter(O=>O!=="root");Re({toastType:"error",title:b("crud:form.validationFailed"),description:b("crud:form.fixFields",{fields:N.map(O=>gr(O,s.fields[O],b)).join(", ")}),duration:8e3}),Xe(m),Rt(y,c),r?.(y)})(n),o},Ut=()=>{l.getState().clearDraft(F),qe(),d.reset(k),W.current=!1},Ye=()=>{z.current?.abort(),a&&(l.getState().cleanup(a),J.getState().cleanup(a))};C(()=>Ye,[]);const Mt=()=>{z.current?.abort(),a&&(J.getState().abortAll(a),l.getState().reset(a)),X.current=!1},Ze=mr(s,{operation:u,viewerRole:h,availableFields:void 0}),Tt=g.length===0?Ze:[...Ze,...g.flatMap(e=>sr(e,h,P(e.key)))],Pt=d.formState.isSubmitted||Object.keys(d.formState.touchedFields||{}).length>0;return{...d,handleSubmit:$t,fields:Tt,operation:u,record:me,entity:s,t:b,viewerRole:h,formId:a,formStatus:a?ht:"idle",uploadProgress:a?bt:0,cleanup:Ye,cancel:Mt,isDirty:d.formState.isDirty,hasUserInteracted:Pt,resetForm:Ut,originalValues:k,draftState:Ot,pendingWrites:Qe,remove:It}}export{yr as useEntityForm};
@@ -0,0 +1,53 @@
1
+ /** One page-state slot as the form sees it. */
2
+ export interface FormDraftSlot {
3
+ /** Current value, read when the draft is saved. */
4
+ get: () => unknown;
5
+ /** True when the current value differs from the initial one (the slot holds an edit). */
6
+ edited: () => boolean;
7
+ /** Apply a value restored from the draft. */
8
+ restore: (value: unknown) => void;
9
+ /** Back to the initial value (Discard, resetForm). */
10
+ reset: () => void;
11
+ }
12
+ /** Slot registry exposed by `useEntityForm` as `form.draftState`. */
13
+ export interface FormDraftStateRegistry {
14
+ /** Register a slot; returns its unregister function. */
15
+ register: (key: string, slot: FormDraftSlot) => () => void;
16
+ /** A slot changed: schedule the form's draft autosave. */
17
+ changed: () => void;
18
+ }
19
+ /** Options for {@link useFormDraftState}. */
20
+ export interface UseFormDraftStateOptions<T> {
21
+ /**
22
+ * Validate a value read back from the draft (browser storage: untrusted, may
23
+ * come from an older page version) and adjust it before it is applied, e.g.
24
+ * drop table edits that already equal the loaded record. Throw to reject it;
25
+ * the slot then keeps `initial`.
26
+ */
27
+ parse: (draft: unknown) => T;
28
+ }
29
+ /**
30
+ * Page state saved in the form's draft: autosaved with it, saved at submit,
31
+ * restored with it ("Draft restored" toast), reset by its Discard, cleared when
32
+ * the submit succeeds and kept when it fails. A value different from `initial`
33
+ * is an edit: it keeps the draft like a dirty field. Values must be JSON-serializable.
34
+ *
35
+ * @param form - The `useEntityForm` result that owns the page Save
36
+ * @param key - Slot name, unique within the form
37
+ * @param initial - Value when no draft exists (and after Discard)
38
+ * @param options - See {@link UseFormDraftStateOptions}
39
+ * @returns `[value, setValue]`, like `useState`
40
+ *
41
+ * @example
42
+ * ```tsx
43
+ * const form = useEntityForm(routineEntity, { formId: 'routine', operation: 'edit', defaultValues });
44
+ * const [productIds, setProductIds] = useFormDraftState(form, 'productIds', initialIds, {
45
+ * parse: (draft) => v.parse(v.array(v.string()), draft),
46
+ * });
47
+ * const save = form.handleSubmit((values) => saveRoutine(values, productIds));
48
+ * ```
49
+ */
50
+ export declare function useFormDraftState<T>(form: {
51
+ draftState: FormDraftStateRegistry;
52
+ }, key: string, initial: T, options: UseFormDraftStateOptions<T>): [T, (next: T | ((previous: T) => T)) => void];
53
+ //# sourceMappingURL=useFormDraftState.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useFormDraftState.d.ts","sourceRoot":"","sources":["../../../src/forms/hooks/useFormDraftState.ts"],"names":[],"mappings":"AAiBA,+CAA+C;AAC/C,MAAM,WAAW,aAAa;IAC5B,mDAAmD;IACnD,GAAG,EAAE,MAAM,OAAO,CAAC;IACnB,yFAAyF;IACzF,MAAM,EAAE,MAAM,OAAO,CAAC;IACtB,6CAA6C;IAC7C,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IAClC,sDAAsD;IACtD,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB;AAED,qEAAqE;AACrE,MAAM,WAAW,sBAAsB;IACrC,wDAAwD;IACxD,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,KAAK,MAAM,IAAI,CAAC;IAC3D,0DAA0D;IAC1D,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAED,6CAA6C;AAC7C,MAAM,WAAW,wBAAwB,CAAC,CAAC;IACzC;;;;;OAKG;IACH,KAAK,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,CAAC,CAAC;CAC9B;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,EACjC,IAAI,EAAE;IAAE,UAAU,EAAE,sBAAsB,CAAA;CAAE,EAC5C,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,CAAC,EACV,OAAO,EAAE,wBAAwB,CAAC,CAAC,CAAC,GACnC,CAAC,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,IAAI,CAAC,CAmD/C"}
@@ -0,0 +1 @@
1
+ "use client";import{useEffect as p,useRef as a,useState as y}from"react";function d(S,i,n,f){const[o,u]=y(n),r=a(o),c=a(n),g=a(f.parse);p(()=>{c.current=n,g.current=f.parse});const{draftState:s}=S;return p(()=>s.register(i,{get:()=>r.current,edited:()=>JSON.stringify(r.current)!==JSON.stringify(c.current),restore:t=>{let e;try{e=g.current(t)}catch{return}r.current=e,u(e)},reset:()=>{r.current=c.current,u(c.current)}}),[s,i]),[o,t=>{const e=typeof t=="function"?t(r.current):t;r.current=e,u(e),s.changed()}]}export{d as useFormDraftState};
@@ -30,10 +30,14 @@
30
30
  * @author AMBROISE PARK Consulting
31
31
  */
32
32
  export { useEntityForm } from './hooks/useEntityForm';
33
+ export { FormNavigationProvider, useFormNavigation } from './FormNavigation';
34
+ export { useFormDraftState } from './hooks/useFormDraftState';
35
+ export type { FormDraftSlot, FormDraftStateRegistry, UseFormDraftStateOptions, } from './hooks/useFormDraftState';
36
+ export type { FormNavigation } from './FormNavigation';
33
37
  export { useEntityField } from './hooks/useEntityField';
34
38
  export { useController } from './hooks/useController';
35
39
  export type { UseControllerProps, UseControllerReturn, ControllerRenderProps, ControllerFieldState, } from './hooks/useController';
36
- export { isFieldEditable, getFieldsForOperation, validateEntity, translateFieldLabel, translateLabel, } from './utils';
40
+ export { EMPTY_VALUE, fromInputValue, isFieldEditable, getFieldsForOperation, validateEntity, translateFieldLabel, translateLabel, } from './utils';
37
41
  export type { ViewerRole, RenderableField, GetFieldsForOperationOptions, EntityFieldsInput, SchemaOperation, ValidationIssue, ValidationResult, } from './utils';
38
- export type { InferEntityData, InferEntityCreate, InferEntityInput, InferEntityOutput, UseEntityFormOptions, EntityFormReturn, EntityFieldReturn, Entity, EntityField, FieldType, Visibility, Editable, ValidationRules, dndevSchema, } from './types';
42
+ export type { InferEntityData, InferEntityCreate, InferEntityInput, InferEntityOutput, UseEntityFormOptions, EntityFormReturn, EntityFormHandleSubmit, EntityFormState, EntityFormSubmitOptions, EntityFieldReturn, Entity, EntityField, FieldType, Visibility, Editable, ValidationRules, dndevSchema, } from './types';
39
43
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/forms/index.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,YAAY,EACV,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,eAAe,EACf,qBAAqB,EACrB,cAAc,EACd,mBAAmB,EACnB,cAAc,GACf,MAAM,SAAS,CAAC;AAGjB,YAAY,EAEV,UAAU,EACV,eAAe,EACf,4BAA4B,EAC5B,iBAAiB,EACjB,eAAe,EACf,eAAe,EACf,gBAAgB,GACjB,MAAM,SAAS,CAAC;AAEjB,YAAY,EAEV,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EAChB,iBAAiB,EACjB,oBAAoB,EACpB,gBAAgB,EAChB,iBAAiB,EAEjB,MAAM,EACN,WAAW,EACX,SAAS,EACT,UAAU,EACV,QAAQ,EACR,eAAe,EACf,WAAW,GACZ,MAAM,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/forms/index.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC7E,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,YAAY,EACV,aAAa,EACb,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AACnC,YAAY,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,YAAY,EACV,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,WAAW,EACX,cAAc,EACd,eAAe,EACf,qBAAqB,EACrB,cAAc,EACd,mBAAmB,EACnB,cAAc,GACf,MAAM,SAAS,CAAC;AAGjB,YAAY,EAEV,UAAU,EACV,eAAe,EACf,4BAA4B,EAC5B,iBAAiB,EACjB,eAAe,EACf,eAAe,EACf,gBAAgB,GACjB,MAAM,SAAS,CAAC;AAEjB,YAAY,EAEV,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EAChB,iBAAiB,EACjB,oBAAoB,EACpB,gBAAgB,EAChB,sBAAsB,EACtB,eAAe,EACf,uBAAuB,EACvB,iBAAiB,EAEjB,MAAM,EACN,WAAW,EACX,SAAS,EACT,UAAU,EACV,QAAQ,EACR,eAAe,EACf,WAAW,GACZ,MAAM,SAAS,CAAC"}
@@ -1 +1 @@
1
- import{useEntityForm as a}from"./hooks/useEntityForm";import{useEntityField as t}from"./hooks/useEntityField";import{useController as e}from"./hooks/useController";import{isFieldEditable as s,getFieldsForOperation as i,validateEntity as l,translateFieldLabel as r,translateLabel as o}from"./utils";export{i as getFieldsForOperation,s as isFieldEditable,r as translateFieldLabel,o as translateLabel,e as useController,t as useEntityField,a as useEntityForm,l as validateEntity};
1
+ import{useEntityForm as a}from"./hooks/useEntityForm";import{FormNavigationProvider as t,useFormNavigation as s}from"./FormNavigation";import{useFormDraftState as e}from"./hooks/useFormDraftState";import{useEntityField as r}from"./hooks/useEntityField";import{useController as i}from"./hooks/useController";import{EMPTY_VALUE as o,fromInputValue as l,isFieldEditable as m,getFieldsForOperation as n,validateEntity as F,translateFieldLabel as d,translateLabel as u}from"./utils";export{o as EMPTY_VALUE,t as FormNavigationProvider,l as fromInputValue,n as getFieldsForOperation,m as isFieldEditable,d as translateFieldLabel,u as translateLabel,i as useController,r as useEntityField,a as useEntityForm,e as useFormDraftState,s as useFormNavigation,F as validateEntity};