@donotdev/crud 0.2.3 → 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 (267) hide show
  1. package/dist/CrudService.bulk.d.ts +13 -14
  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 +12 -7
  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 +1 -1
  11. package/dist/CrudService.cache.d.ts.map +1 -1
  12. package/dist/CrudService.cache.js +1 -1
  13. package/dist/CrudService.d.ts +35 -6
  14. package/dist/CrudService.d.ts.map +1 -1
  15. package/dist/CrudService.js +1 -1
  16. package/dist/CrudService.mutations.d.ts +3 -3
  17. package/dist/CrudService.mutations.d.ts.map +1 -1
  18. package/dist/CrudService.mutations.js +1 -1
  19. package/dist/CrudService.optimistic.d.ts +2 -2
  20. package/dist/CrudService.optimistic.d.ts.map +1 -1
  21. package/dist/CrudService.optimistic.js +1 -1
  22. package/dist/CrudService.subscriptions.js +1 -1
  23. package/dist/CrudService.writeRules.d.ts +57 -0
  24. package/dist/CrudService.writeRules.d.ts.map +1 -0
  25. package/dist/CrudService.writeRules.js +1 -0
  26. package/dist/CrudService.writeSchema.d.ts +64 -0
  27. package/dist/CrudService.writeSchema.d.ts.map +1 -0
  28. package/dist/CrudService.writeSchema.js +1 -0
  29. package/dist/CrudStore.d.ts +10 -1
  30. package/dist/CrudStore.d.ts.map +1 -1
  31. package/dist/CrudStore.js +1 -1
  32. package/dist/FieldRegistry.d.ts +1 -1
  33. package/dist/FieldRegistry.d.ts.map +1 -1
  34. package/dist/adapters/FunctionsAdapter.d.ts +3 -3
  35. package/dist/adapters/FunctionsAdapter.d.ts.map +1 -1
  36. package/dist/adapters/FunctionsAdapter.js +1 -1
  37. package/dist/components/CrudButton.d.ts +3 -2
  38. package/dist/components/CrudButton.d.ts.map +1 -1
  39. package/dist/components/CrudCard.d.ts.map +1 -1
  40. package/dist/components/CrudCard.js +1 -1
  41. package/dist/components/DateFilter.js +1 -1
  42. package/dist/components/EntityFilters.d.ts +23 -4
  43. package/dist/components/EntityFilters.d.ts.map +1 -1
  44. package/dist/components/EntityFilters.js +1 -1
  45. package/dist/components/FormFieldRenderer.d.ts +21 -4
  46. package/dist/components/FormFieldRenderer.d.ts.map +1 -1
  47. package/dist/components/FormFieldRenderer.js +1 -1
  48. package/dist/components/FormLayout.d.ts.map +1 -1
  49. package/dist/components/FormLayout.js +1 -1
  50. package/dist/components/SortableCardList.d.ts +47 -0
  51. package/dist/components/SortableCardList.d.ts.map +1 -0
  52. package/dist/components/SortableCardList.js +1 -0
  53. package/dist/components/YearFilter.js +1 -1
  54. package/dist/components/controlled/complex/ControlledAddressField.d.ts.map +1 -1
  55. package/dist/components/controlled/complex/ControlledAddressField.js +1 -1
  56. package/dist/components/controlled/complex/ControlledDateField.d.ts.map +1 -1
  57. package/dist/components/controlled/complex/ControlledDateField.js +1 -1
  58. package/dist/components/controlled/complex/ControlledFieldArrayField.d.ts +9 -0
  59. package/dist/components/controlled/complex/ControlledFieldArrayField.d.ts.map +1 -1
  60. package/dist/components/controlled/complex/ControlledFieldArrayField.js +1 -1
  61. package/dist/components/controlled/complex/ControlledMultiInputField.d.ts.map +1 -1
  62. package/dist/components/controlled/complex/ControlledMultiInputField.js +1 -1
  63. package/dist/components/controlled/complex/ControlledTimestampField.d.ts.map +1 -1
  64. package/dist/components/controlled/complex/ControlledTimestampField.js +1 -1
  65. package/dist/components/controlled/fieldOptions.d.ts +9 -0
  66. package/dist/components/controlled/fieldOptions.d.ts.map +1 -1
  67. package/dist/components/controlled/fieldOptions.js +1 -1
  68. package/dist/components/controlled/file/ControlledImageField.js +1 -1
  69. package/dist/components/controlled/input/ControlledCurrencyField.d.ts.map +1 -1
  70. package/dist/components/controlled/input/ControlledCurrencyField.js +1 -1
  71. package/dist/components/controlled/input/ControlledDurationField.js +1 -1
  72. package/dist/components/controlled/input/ControlledNumberField.d.ts.map +1 -1
  73. package/dist/components/controlled/input/ControlledNumberField.js +1 -1
  74. package/dist/components/controlled/input/ControlledPasswordField.d.ts.map +1 -1
  75. package/dist/components/controlled/input/ControlledPasswordField.js +1 -1
  76. package/dist/components/controlled/input/ControlledPhoneField.d.ts.map +1 -1
  77. package/dist/components/controlled/input/ControlledPhoneField.js +1 -1
  78. package/dist/components/controlled/input/ControlledPriceField.d.ts.map +1 -1
  79. package/dist/components/controlled/input/ControlledPriceField.js +1 -1
  80. package/dist/components/controlled/input/ControlledRatingField.js +1 -1
  81. package/dist/components/controlled/input/ControlledTextField.d.ts.map +1 -1
  82. package/dist/components/controlled/input/ControlledTextField.js +1 -1
  83. package/dist/components/controlled/input/ControlledTextareaField.d.ts.map +1 -1
  84. package/dist/components/controlled/input/ControlledTextareaField.js +1 -1
  85. package/dist/components/controlled/select/ControlledComboboxField.d.ts.map +1 -1
  86. package/dist/components/controlled/select/ControlledComboboxField.js +1 -1
  87. package/dist/components/controlled/select/ControlledDropdownField.d.ts.map +1 -1
  88. package/dist/components/controlled/select/ControlledDropdownField.js +1 -1
  89. package/dist/components/controlled/select/ControlledMultiDropdownField.d.ts.map +1 -1
  90. package/dist/components/controlled/select/ControlledMultiDropdownField.js +1 -1
  91. package/dist/components/controlled/select/ControlledReferenceField.d.ts.map +1 -1
  92. package/dist/components/controlled/select/ControlledReferenceField.js +1 -1
  93. package/dist/components/controlled/select/ControlledYearField.d.ts.map +1 -1
  94. package/dist/components/controlled/select/ControlledYearField.js +1 -1
  95. package/dist/components/fields/display/BadgeFieldDisplay.js +1 -1
  96. package/dist/components/fields/display/CheckboxFieldDisplay.js +1 -1
  97. package/dist/components/fields/display/MapFieldDisplay.js +1 -1
  98. package/dist/components/fields/display/NumberFieldDisplay.js +1 -1
  99. package/dist/components/fields/display/PasswordFieldDisplay.js +1 -1
  100. package/dist/components/fields/display/TextFieldDisplay.js +1 -1
  101. package/dist/components/form/fields/AddressFieldComponent.d.ts +3 -1
  102. package/dist/components/form/fields/AddressFieldComponent.d.ts.map +1 -1
  103. package/dist/components/form/fields/AddressFieldComponent.js +1 -1
  104. package/dist/components/form/fields/ComboboxComponent.d.ts +2 -0
  105. package/dist/components/form/fields/ComboboxComponent.d.ts.map +1 -1
  106. package/dist/components/form/fields/ComboboxComponent.js +1 -1
  107. package/dist/components/form/fields/CurrencyFieldComponent.d.ts +2 -0
  108. package/dist/components/form/fields/CurrencyFieldComponent.d.ts.map +1 -1
  109. package/dist/components/form/fields/CurrencyFieldComponent.js +1 -1
  110. package/dist/components/form/fields/DateFieldComponent.d.ts +2 -0
  111. package/dist/components/form/fields/DateFieldComponent.d.ts.map +1 -1
  112. package/dist/components/form/fields/DateFieldComponent.js +1 -1
  113. package/dist/components/form/fields/DocumentFieldComponent.js +1 -1
  114. package/dist/components/form/fields/DropdownComponent.d.ts +2 -0
  115. package/dist/components/form/fields/DropdownComponent.d.ts.map +1 -1
  116. package/dist/components/form/fields/DropdownComponent.js +1 -1
  117. package/dist/components/form/fields/DurationFieldComponent.d.ts.map +1 -1
  118. package/dist/components/form/fields/DurationFieldComponent.js +1 -1
  119. package/dist/components/form/fields/FileFieldComponent.js +1 -1
  120. package/dist/components/form/fields/GdprConsentFieldComponent.d.ts.map +1 -1
  121. package/dist/components/form/fields/GdprConsentFieldComponent.js +1 -1
  122. package/dist/components/form/fields/GeoPointFieldComponent.js +1 -1
  123. package/dist/components/form/fields/ImageFieldComponent.d.ts.map +1 -1
  124. package/dist/components/form/fields/ImageFieldComponent.js +1 -1
  125. package/dist/components/form/fields/MultiDropdownComponent.d.ts +2 -0
  126. package/dist/components/form/fields/MultiDropdownComponent.d.ts.map +1 -1
  127. package/dist/components/form/fields/MultiDropdownComponent.js +1 -1
  128. package/dist/components/form/fields/MultiInputTextFieldComponent.d.ts +2 -0
  129. package/dist/components/form/fields/MultiInputTextFieldComponent.d.ts.map +1 -1
  130. package/dist/components/form/fields/MultiInputTextFieldComponent.js +1 -1
  131. package/dist/components/form/fields/NumberFieldComponent.d.ts +2 -0
  132. package/dist/components/form/fields/NumberFieldComponent.d.ts.map +1 -1
  133. package/dist/components/form/fields/NumberFieldComponent.js +1 -1
  134. package/dist/components/form/fields/PasswordFieldComponent.d.ts +2 -0
  135. package/dist/components/form/fields/PasswordFieldComponent.d.ts.map +1 -1
  136. package/dist/components/form/fields/PasswordFieldComponent.js +1 -1
  137. package/dist/components/form/fields/PhoneNumberComponent.d.ts +11 -1
  138. package/dist/components/form/fields/PhoneNumberComponent.d.ts.map +1 -1
  139. package/dist/components/form/fields/PhoneNumberComponent.js +1 -1
  140. package/dist/components/form/fields/PriceFieldComponent.d.ts +2 -0
  141. package/dist/components/form/fields/PriceFieldComponent.d.ts.map +1 -1
  142. package/dist/components/form/fields/PriceFieldComponent.js +1 -1
  143. package/dist/components/form/fields/RangeFieldComponent.js +1 -1
  144. package/dist/components/form/fields/ReferenceFieldComponent.d.ts +3 -1
  145. package/dist/components/form/fields/ReferenceFieldComponent.d.ts.map +1 -1
  146. package/dist/components/form/fields/ReferenceFieldComponent.js +1 -1
  147. package/dist/components/form/fields/RichTextComponent.js +1 -1
  148. package/dist/components/form/fields/TextAreaComponent.d.ts +2 -0
  149. package/dist/components/form/fields/TextAreaComponent.d.ts.map +1 -1
  150. package/dist/components/form/fields/TextAreaComponent.js +1 -1
  151. package/dist/components/form/fields/TextFieldComponent.d.ts +3 -1
  152. package/dist/components/form/fields/TextFieldComponent.d.ts.map +1 -1
  153. package/dist/components/form/fields/TextFieldComponent.js +1 -1
  154. package/dist/components/form/fields/TimestampFieldComponent.d.ts +2 -0
  155. package/dist/components/form/fields/TimestampFieldComponent.d.ts.map +1 -1
  156. package/dist/components/form/fields/TimestampFieldComponent.js +1 -1
  157. package/dist/components/index.d.ts +2 -0
  158. package/dist/components/index.d.ts.map +1 -1
  159. package/dist/components/index.js +1 -1
  160. package/dist/fieldTypeRegistry.d.ts +2 -2
  161. package/dist/fieldTypeRegistry.d.ts.map +1 -1
  162. package/dist/fieldTypeRegistry.js +1 -1
  163. package/dist/fieldTypeRegistry.store.d.ts +0 -2
  164. package/dist/fieldTypeRegistry.store.d.ts.map +1 -1
  165. package/dist/fieldTypeRegistry.store.js +1 -1
  166. package/dist/fieldTypeRegistry.types.d.ts +8 -9
  167. package/dist/fieldTypeRegistry.types.d.ts.map +1 -1
  168. package/dist/forms/FormNavigation.d.ts +24 -0
  169. package/dist/forms/FormNavigation.d.ts.map +1 -0
  170. package/dist/forms/FormNavigation.js +1 -0
  171. package/dist/forms/childRows.d.ts +184 -0
  172. package/dist/forms/childRows.d.ts.map +1 -0
  173. package/dist/forms/childRows.js +1 -0
  174. package/dist/forms/extend.d.ts +88 -0
  175. package/dist/forms/extend.d.ts.map +1 -0
  176. package/dist/forms/extend.js +1 -0
  177. package/dist/forms/hooks/useEntityField.d.ts +11 -5
  178. package/dist/forms/hooks/useEntityField.d.ts.map +1 -1
  179. package/dist/forms/hooks/useEntityField.js +1 -1
  180. package/dist/forms/hooks/useEntityForm.d.ts +50 -5
  181. package/dist/forms/hooks/useEntityForm.d.ts.map +1 -1
  182. package/dist/forms/hooks/useEntityForm.js +1 -1
  183. package/dist/forms/hooks/useFormDraftState.d.ts +53 -0
  184. package/dist/forms/hooks/useFormDraftState.d.ts.map +1 -0
  185. package/dist/forms/hooks/useFormDraftState.js +1 -0
  186. package/dist/forms/index.d.ts +6 -2
  187. package/dist/forms/index.d.ts.map +1 -1
  188. package/dist/forms/index.js +1 -1
  189. package/dist/forms/types.d.ts +171 -25
  190. package/dist/forms/types.d.ts.map +1 -1
  191. package/dist/forms/utils/buildInitialValues.d.ts +32 -17
  192. package/dist/forms/utils/buildInitialValues.d.ts.map +1 -1
  193. package/dist/forms/utils/buildInitialValues.js +1 -1
  194. package/dist/forms/utils/conditionAwareResolver.d.ts +35 -0
  195. package/dist/forms/utils/conditionAwareResolver.d.ts.map +1 -0
  196. package/dist/forms/utils/conditionAwareResolver.js +1 -0
  197. package/dist/forms/utils/emptyValue.d.ts +34 -0
  198. package/dist/forms/utils/emptyValue.d.ts.map +1 -0
  199. package/dist/forms/utils/emptyValue.js +1 -0
  200. package/dist/forms/utils/getFieldsForOperation.d.ts +30 -19
  201. package/dist/forms/utils/getFieldsForOperation.d.ts.map +1 -1
  202. package/dist/forms/utils/getFieldsForOperation.js +1 -1
  203. package/dist/forms/utils/index.d.ts +1 -0
  204. package/dist/forms/utils/index.d.ts.map +1 -1
  205. package/dist/forms/utils/index.js +1 -1
  206. package/dist/forms/utils/isFieldEditable.d.ts +21 -22
  207. package/dist/forms/utils/isFieldEditable.d.ts.map +1 -1
  208. package/dist/forms/utils/isFieldEditable.js +1 -1
  209. package/dist/forms/utils/writableFields.d.ts +19 -0
  210. package/dist/forms/utils/writableFields.d.ts.map +1 -0
  211. package/dist/forms/utils/writableFields.js +1 -0
  212. package/dist/hooks/index.d.ts +2 -0
  213. package/dist/hooks/index.d.ts.map +1 -1
  214. package/dist/hooks/index.js +1 -1
  215. package/dist/hooks/useChildRows.d.ts +161 -0
  216. package/dist/hooks/useChildRows.d.ts.map +1 -0
  217. package/dist/hooks/useChildRows.js +1 -0
  218. package/dist/hooks/useCrudFilters.d.ts +21 -1
  219. package/dist/hooks/useCrudFilters.d.ts.map +1 -1
  220. package/dist/hooks/useCrudFilters.js +1 -1
  221. package/dist/hooks/useExtensionRows.d.ts +24 -0
  222. package/dist/hooks/useExtensionRows.d.ts.map +1 -0
  223. package/dist/hooks/useExtensionRows.js +1 -0
  224. package/dist/hooks/useFieldConditions.d.ts +2 -2
  225. package/dist/hooks/useFieldConditions.d.ts.map +1 -1
  226. package/dist/hooks/useFieldConditions.js +1 -1
  227. package/dist/hooks/useReferenceResolver.d.ts +4 -1
  228. package/dist/hooks/useReferenceResolver.d.ts.map +1 -1
  229. package/dist/hooks/useReferenceResolver.js +1 -1
  230. package/dist/index.d.ts +6 -5
  231. package/dist/index.d.ts.map +1 -1
  232. package/dist/index.js +1 -1
  233. package/dist/registerBuiltinFieldTypes.d.ts +2 -0
  234. package/dist/registerBuiltinFieldTypes.d.ts.map +1 -1
  235. package/dist/registerBuiltinFieldTypes.js +1 -1
  236. package/dist/stores/FormStore.d.ts +116 -5
  237. package/dist/stores/FormStore.d.ts.map +1 -1
  238. package/dist/stores/FormStore.js +1 -1
  239. package/dist/stores/UploadStore.js +1 -1
  240. package/dist/stores/index.d.ts +1 -1
  241. package/dist/stores/index.d.ts.map +1 -1
  242. package/dist/stores/index.js +1 -1
  243. package/dist/symbol-index.json +1 -1
  244. package/dist/tsconfig.tsbuildinfo +1 -1
  245. package/dist/types.d.ts +38 -6
  246. package/dist/types.d.ts.map +1 -1
  247. package/dist/useCrud.d.ts +7 -5
  248. package/dist/useCrud.d.ts.map +1 -1
  249. package/dist/useCrud.js +1 -1
  250. package/dist/useCrudDoc.js +1 -1
  251. package/dist/utils/clientListProcessing.d.ts +9 -12
  252. package/dist/utils/clientListProcessing.d.ts.map +1 -1
  253. package/dist/utils/clientListProcessing.js +1 -1
  254. package/dist/utils/collections.d.ts.map +1 -1
  255. package/dist/utils/collections.js +1 -1
  256. package/dist/utils/filterUrl.d.ts +45 -0
  257. package/dist/utils/filterUrl.d.ts.map +1 -0
  258. package/dist/utils/filterUrl.js +1 -0
  259. package/dist/utils/matchesFilter.d.ts +27 -3
  260. package/dist/utils/matchesFilter.d.ts.map +1 -1
  261. package/dist/utils/matchesFilter.js +1 -1
  262. package/dist/utils/uploadValidation.js +1 -1
  263. package/dist/utils/useRowTranslator.js +1 -1
  264. package/guidelines/COMPONENTS.md +82 -11
  265. package/guidelines/CRUD.md +242 -7
  266. package/guidelines/GOTCHAS.md +17 -1
  267. package/package.json +3 -3
@@ -1,30 +1,45 @@
1
- /**
2
- * @fileoverview Initial values builders for CRUD forms
3
- * @description
4
- * - buildSchemaDefaults: compute create-mode defaults from entity definition only.
5
- * - buildInitialFromRecord: overlay schema defaults with an existing DB record
6
- * and apply type-specific normalizations (switch, price, etc.).
7
- *
8
- * These helpers provide a single, canonical "initialValues" snapshot that
9
- * React Hook Form can use as its dirty baseline.
10
- */
11
1
  import type { AnyEntity } from '@donotdev/core';
12
- import type { InferEntityData } from '../types';
2
+ /** What the form state holds: the fields the form writes (`writableFields`). */
3
+ export interface FormProjection {
4
+ /** Field names the form writes, i18n companions included (`writableFields`) */
5
+ fields: ReadonlySet<string>;
6
+ /** Keep the record's `id` (edit of the record itself, not of an extension row) */
7
+ keepId?: boolean;
8
+ }
13
9
  /**
14
- * Build initial values for an existing DB record.
10
+ * Build initial values for an existing DB record, projected onto the form values.
15
11
  *
16
- * - Starts from the raw record (already filtered/masked by the backend).
17
- * - For each field in the entity:
12
+ * - Keeps only the fields the form writes (`projection.fields`) and, with
13
+ * `keepId`, the record id: generated, technical, `editable: false` and
14
+ * role-denied values never enter form state, the local draft or the payload.
15
+ * - For each written field:
18
16
  * - If the record has a non-null, non-undefined value, keep it.
19
17
  * - Otherwise, apply the same type-specific defaults we use in forms.
18
+ *
19
+ * @param entity - Entity from `defineEntity()`
20
+ * @param record - Stored row (or create defaults), already filtered by the backend
21
+ * @param projection - Fields the form writes (`writableFields(entity, role, op)`)
22
+ * @returns The form values
23
+ *
24
+ * @version 0.2.0
25
+ * @since 0.0.1
26
+ * @author AMBROISE PARK Consulting
20
27
  */
21
- export declare function buildInitialFromRecord<E extends AnyEntity>(entity: E, record: Partial<InferEntityData<E>>): Partial<InferEntityData<E>>;
28
+ export declare function buildInitialFromRecord(entity: AnyEntity, record: Readonly<Record<string, unknown>>, projection: FormProjection): Record<string, unknown>;
22
29
  /**
23
30
  * Build schema defaults for create-mode forms.
24
31
  *
25
32
  * - Starts from an empty record and applies the same type-specific defaults as
26
- * buildInitialFromRecord.
33
+ * buildInitialFromRecord, for the fields the form writes.
27
34
  * - This represents "what a brand-new object would look like" before any user edits.
35
+ *
36
+ * @param entity - Entity from `defineEntity()`
37
+ * @param fields - Field names the form writes on create (`writableFields(entity, role, 'create')`)
38
+ * @returns The create defaults
39
+ *
40
+ * @version 0.2.0
41
+ * @since 0.0.1
42
+ * @author AMBROISE PARK Consulting
28
43
  */
29
- export declare function buildSchemaDefaults<E extends AnyEntity>(entity: E): Partial<InferEntityData<E>>;
44
+ export declare function buildSchemaDefaults(entity: AnyEntity, fields: ReadonlySet<string>): Record<string, unknown>;
30
45
  //# sourceMappingURL=buildInitialValues.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"buildInitialValues.d.ts","sourceRoot":"","sources":["../../../src/forms/utils/buildInitialValues.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEhD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AA2BhD;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,SAAS,EACxD,MAAM,EAAE,CAAC,EACT,MAAM,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,GAClC,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CA6D7B;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,SAAS,SAAS,EACrD,MAAM,EAAE,CAAC,GACR,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAG7B"}
1
+ {"version":3,"file":"buildInitialValues.d.ts","sourceRoot":"","sources":["../../../src/forms/utils/buildInitialValues.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAgBhD,gFAAgF;AAChF,MAAM,WAAW,cAAc;IAC7B,+EAA+E;IAC/E,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC5B,kFAAkF;IAClF,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,SAAS,EACjB,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,EACzC,UAAU,EAAE,cAAc,GACzB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAoDzB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,SAAS,EACjB,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,GAC1B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAGzB"}
@@ -1 +1 @@
1
- function s(i,n){if(n in i)return i[n];const p=n.replace(/_([a-z])/g,(o,e)=>e.toUpperCase());if(p!==n&&p in i)return i[p]}function u(i,n){if(n in i)return!0;const p=n.replace(/_([a-z])/g,(o,e)=>e.toUpperCase());return p!==n&&p in i}function a(i,n){const p=n??{},o={...p};return Object.entries(i.fields).forEach(([e,t])=>{const c=s(o,e);c!==void 0&&!(e in o)&&(o[e]=c);const r=!u(p,e)||c===null||c===void 0;if(e==="status"&&r)o[e]="draft";else if(t.type==="switch"){if(c==null){const l=t.options?.fieldSpecific;o[e]=l?.uncheckedValue??!1}}else r&&(t.type==="price"?o[e]=null:t.type==="checkbox"||t.type==="boolean"?o[e]=!1:t.type==="text"||t.type==="textarea"||t.type==="email"||t.type==="url"||t.type==="tel"||t.type==="iban"||t.type==="password"||t.type==="color"?o[e]="":(t.type==="number"||t.type==="range"||t.type==="rating")&&(o[e]=void 0))}),o}function f(i){return a(i,{})}export{a as buildInitialFromRecord,f as buildSchemaDefaults};
1
+ import{createStatus as p}from"@donotdev/core";import{EMPTY_VALUE as d}from"./emptyValue";const b=new Set(["text","textarea","email","url","tel","iban","password","color"]);function a(s,i,c){const{fields:l,keepId:f=!1}=c,t=Object.fromEntries(Object.entries(i).filter(([e])=>l.has(e)||f&&e==="id"));return Object.entries(s.fields).forEach(([e,r])=>{if(!l.has(e))return;const n=t[e],o=!(e in t)||n===null||n===void 0;if(e==="status"&&o)t[e]=p(void 0);else if(b.has(r.type))(o||n==="")&&(t[e]=d);else if(r.type==="switch"){if(n==null){const u=r.options?.fieldSpecific;t[e]=u?.uncheckedValue??!1}}else o&&(r.type==="price"?t[e]=null:r.type==="checkbox"||r.type==="boolean"?t[e]=!1:(r.type==="number"||r.type==="range"||r.type==="rating")&&(t[e]=void 0))}),t}function h(s,i){return a(s,{},{fields:i})}export{a as buildInitialFromRecord,h as buildSchemaDefaults};
@@ -0,0 +1,35 @@
1
+ import type { FieldValues, Resolver } from 'react-hook-form';
2
+ import type { AnyEntity } from '@donotdev/core';
3
+ /** Evaluate only validation-relevant conditions against the complete retained form. */
4
+ export declare function getFormConditionStates(entity: AnyEntity, values: Record<string, unknown>): {
5
+ name: string;
6
+ visible: boolean;
7
+ required: boolean | undefined;
8
+ }[];
9
+ /**
10
+ * Form-only validation projection. Persistence schemas remain strict; inactive
11
+ * values are retained for drafts and domain normalization in the submit callback.
12
+ * Only the fields the form writes (`written`: `writableFields`) are validated and
13
+ * output: a field the viewer cannot write (a status editable by admins only, an
14
+ * `editable: false` field) is the writer's, not the form's.
15
+ * Schema and scope: the CRUD rules (core/schemas crud/), as the writers apply them.
16
+ * Create: the whole form (`draft` or `create` schema, `createStatus`). Edit
17
+ * (`updateCheck` on the base row): a draft, or leaving draft for a visible status,
18
+ * checks the whole form; any other edit checks only the fields that differ from the
19
+ * base row (rule 2: an update validates what changes).
20
+ *
21
+ * @template T - Form state the resolver reads
22
+ * @template TOutput - Values it outputs (`onValid`'s), `T` by default
23
+ * @param entity - Entity from `defineEntity()`
24
+ * @param operation - Form operation
25
+ * @param written - Field names the form writes (companions included)
26
+ * @param base - The row the form starts from: the stored row on edit, the caller's
27
+ * defaults on create (its status is read when form state has none)
28
+ * @returns React Hook Form resolver
29
+ *
30
+ * @version 0.4.0
31
+ * @since 0.2.4
32
+ * @author AMBROISE PARK Consulting
33
+ */
34
+ export declare function createConditionAwareResolver<T extends FieldValues, TOutput = T>(entity: AnyEntity, operation: 'create' | 'edit', written: ReadonlySet<string>, base?: Readonly<Record<string, unknown>> | null): Resolver<T, unknown, TOutput>;
35
+ //# sourceMappingURL=conditionAwareResolver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conditionAwareResolver.d.ts","sourceRoot":"","sources":["../../../src/forms/utils/conditionAwareResolver.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAU7D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEhD,uFAAuF;AACvF,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;;;;IAWxF;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,4BAA4B,CAC1C,CAAC,SAAS,WAAW,EACrB,OAAO,GAAG,CAAC,EAEX,MAAM,EAAE,SAAS,EACjB,SAAS,EAAE,QAAQ,GAAG,MAAM,EAC5B,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,EAC5B,IAAI,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,IAAI,GAC9C,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAkF/B"}
@@ -0,0 +1 @@
1
+ import{valibotResolver as K}from"@hookform/resolvers/valibot";import{createSchemas as q,evaluateFieldConditions as R,i18nFieldName as w,createStatus as x,statusCan as A,updateCheck as I}from"@donotdev/core";function S(d,u){return Object.entries(d.fields).filter(([,n])=>n.conditions?.visible||n.conditions?.required).map(([n,a])=>{const i=R(a.conditions,u);return{name:n,visible:i.visible,required:a.conditions?.required?i.required:a.validation?.required}})}function B(d,u,n,a){const i={...d,fields:Object.fromEntries(Object.entries(d.fields).filter(([s])=>n.has(s)))},k=q(i);let v,j,h=[];return async(s,E,g)=>{const m=S(i,s),p={...s,status:s.status??a?.status};let o,c=null;if(u==="edit"){const e=I(p,a);o=e.schemaKey,e.schemaKey==="update"&&!e.whole&&(c=Object.keys(i.fields).filter(l=>[l,w(l)].some(r=>JSON.stringify(s[r])!==JSON.stringify(a?.[r]))))}else o=A(x(p),"saveIncomplete")?"draft":"create";const y=JSON.stringify([o,m,c]);if(y!==v){const e=k[o];if(!("entries"in e)||typeof e.entries!="object"||e.entries===null)throw new Error("Expected an object write schema");const l=new Set(Object.keys(e.entries));h=m.filter(t=>!t.visible&&l.has(t.name)).flatMap(({name:t})=>i.fields[t]?.i18n===!0?[t,w(t)].filter(f=>l.has(f)):[t]);const r={...i.fields};if(c)for(const t of Object.keys(r))c.includes(t)||delete r[t];for(const[t,f]of Object.entries(r)){const O=m.find(J=>J.name===t);O&&(O.visible?f.conditions?.required&&(r[t]={...f,validation:{...f.validation,required:O.required}}):delete r[t])}const F=q({...i,fields:r})[o];j=K(F),v=y}const C=Object.fromEntries(h.filter(e=>Object.hasOwn(s,e)).map(e=>[e,s[e]])),b=await j(s,E,g);if(Object.keys(b.errors).length>0)return b;const N=c?Object.fromEntries(Object.entries(s).filter(([e])=>n.has(e))):{};return{errors:{},values:{...N,...C,...b.values}}}}export{B as createConditionAwareResolver,S as getFormConditionStates};
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @fileoverview Empty value contract of entity forms
3
+ * @description One value means "not filled in" in form state, in validated data and in
4
+ * every adapter payload: `null`. It is native to Firestore, Postgres, REST and GraphQL,
5
+ * survives JSON (an `undefined` key is dropped, so a cleared field would never be
6
+ * written) and is what `v.nullish()` accepts for an optional field. `''` exists only
7
+ * inside the DOM input: fields display `value ?? ''` and report an emptied input
8
+ * through {@link fromInputValue}.
9
+ *
10
+ * @version 0.1.0
11
+ * @since 0.2.4
12
+ * @author AMBROISE PARK Consulting
13
+ */
14
+ /**
15
+ * The form-state value of a field that is not filled in.
16
+ *
17
+ * @since 0.2.4
18
+ */
19
+ export declare const EMPTY_VALUE: null;
20
+ /**
21
+ * Form-state value of a text input's DOM value: an emptied input is {@link EMPTY_VALUE}.
22
+ *
23
+ * @param value - The input's DOM value
24
+ * @returns The value to store in form state
25
+ *
26
+ * @example
27
+ * ```tsx
28
+ * <Input value={field.value ?? ''} onChange={(e) => field.onChange(fromInputValue(e.target.value))} />
29
+ * ```
30
+ *
31
+ * @since 0.2.4
32
+ */
33
+ export declare function fromInputValue(value: string): string | null;
34
+ //# sourceMappingURL=emptyValue.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emptyValue.d.ts","sourceRoot":"","sources":["../../../src/forms/utils/emptyValue.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;GAYG;AAEH;;;;GAIG;AACH,eAAO,MAAM,WAAW,MAAO,CAAC;AAEhC;;;;;;;;;;;;GAYG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAE3D"}
@@ -0,0 +1 @@
1
+ const n=null;function t(l){return l===""?null:l}export{n as EMPTY_VALUE,t as fromInputValue};
@@ -17,6 +17,20 @@ export interface RenderableField<T extends FieldType = FieldType> {
17
17
  config: EntityField<T>;
18
18
  /** Whether field is editable (input vs read-only) */
19
19
  editable: boolean;
20
+ /**
21
+ * Whether the form writes the field: an input (`editable`) or a derived
22
+ * (`editable: 'computed'`) field. Its value lives in form state; a field the form
23
+ * does not write (technical, `editable: false`, role-denied) is read from
24
+ * `form.record`.
25
+ * @since 0.2.5
26
+ */
27
+ written: boolean;
28
+ /**
29
+ * Values the field's `conditions` read: the key of a 1:1 extension (`offer`)
30
+ * for its prefixed fields (`offer.priceExclVat`); omitted for the entity's own.
31
+ * @since 0.2.5
32
+ */
33
+ scope?: string;
20
34
  }
21
35
  /** Options for field filtering */
22
36
  export interface GetFieldsForOperationOptions {
@@ -32,42 +46,39 @@ export interface GetFieldsForOperationOptions {
32
46
  availableFields?: string[];
33
47
  }
34
48
  /**
35
- * Filters entity fields based on operation type and viewer role.
49
+ * Filters entity fields based on operation type and viewer role, from the entity
50
+ * descriptor (`describeEntity`: write class, `editableFor`, visibility).
36
51
  *
37
52
  * Pure function, no React dependencies. Use for building custom form layouts.
38
53
  *
39
- * **Create operation:**
40
- * - Excludes `visibility: 'technical'` fields (auto-added by backend)
41
- * - Excludes `visibility: 'hidden'` fields (never shown)
54
+ * Per write class (design 3.4):
55
+ * - `never` (hidden, `editable: 'generated'`, backend names): not shown, except
56
+ * technical fields on edit, shown read-only (`id`, `createdAt`, ...)
57
+ * - `program` (`editable: false`): shown read-only
58
+ * - `derived` (`editable: 'computed'`): shown read-only, written by the form
59
+ * - `user`: an input when `editableFor(viewerRole, operation)`, else read-only
42
60
  *
43
- * **Edit operation:**
44
- * - Excludes `visibility: 'hidden'` fields (never shown)
45
- * - Technical fields are marked as `editable: false` (read-only)
46
- * - If `availableFields` provided, only returns fields in that list (backend-filtered)
61
+ * **Create operation:** excludes `visibility: 'technical'` fields.
62
+ * **Edit operation:** if `availableFields` is provided, only returns those fields.
63
+ * Fields the viewer cannot see (`visibility` above the role, `hidden`) are left out.
47
64
  *
48
- * @param entity - Entity definition from defineEntity()
65
+ * @param entity - Entity definition from defineEntity(), or a field map
49
66
  * @param options - Filtering options
50
67
  * @returns Array of renderable fields with computed editability
68
+ * @throws When a field has a custom type and no value shape (`describeEntity`)
51
69
  *
52
70
  * @example
53
71
  * ```typescript
54
72
  * import { getFieldsForOperation } from '@donotdev/crud/forms';
55
73
  * import { productEntity } from './entities/product';
56
74
  *
57
- * // Create form - excludes technical and hidden
58
- * const createFields = getFieldsForOperation(productEntity, {
59
- * operation: 'create',
60
- * viewerRole: 'user'
61
- * });
62
- *
63
- * // Edit form - uses backend-filtered fields
64
75
  * const editFields = getFieldsForOperation(productEntity, {
65
76
  * operation: 'edit',
66
77
  * viewerRole: 'admin',
67
- * availableFields: Object.keys(existingData)
68
78
  * });
69
79
  *
70
- * // Render custom form
80
+ * // Inputs for written editable fields; read-only display for the others
81
+ * // (`written`: from form state, else from form.record)
71
82
  * editFields.map(({ name, config, editable }) => (
72
83
  * editable
73
84
  * ? <Input key={name} {...config} />
@@ -78,7 +89,7 @@ export interface GetFieldsForOperationOptions {
78
89
  * @see {@link AnyEntity} for entity definition structure
79
90
  * @see {@link RenderableField} for return type
80
91
  *
81
- * @version 0.1.0
92
+ * @version 0.2.0
82
93
  * @since 0.0.1
83
94
  * @author AMBROISE PARK Consulting
84
95
  */
@@ -1 +1 @@
1
- {"version":3,"file":"getFieldsForOperation.d.ts","sourceRoot":"","sources":["../../../src/forms/utils/getFieldsForOperation.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AAEH,OAAO,EAGL,KAAK,SAAS,EACd,KAAK,WAAW,EAChB,KAAK,SAAS,EACf,MAAM,gBAAgB,CAAC;AAIxB,+EAA+E;AAC/E,MAAM,MAAM,iBAAiB,GACzB,SAAS,GACT,SAAS,CAAC,QAAQ,CAAC,GACnB,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC;AAE3C,oDAAoD;AACpD,MAAM,WAAW,eAAe,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS;IAC9D,qBAAqB;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,0BAA0B;IAC1B,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC;IACvB,qDAAqD;IACrD,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,kCAAkC;AAClC,MAAM,WAAW,4BAA4B;IAC3C,0BAA0B;IAC1B,SAAS,EAAE,QAAQ,GAAG,MAAM,CAAC;IAC7B,4EAA4E;IAC5E,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;CAC5B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,iBAAiB,EACzB,OAAO,EAAE,4BAA4B,GACpC,eAAe,EAAE,CA+DnB"}
1
+ {"version":3,"file":"getFieldsForOperation.d.ts","sourceRoot":"","sources":["../../../src/forms/utils/getFieldsForOperation.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AAEH,OAAO,EAIL,KAAK,SAAS,EACd,KAAK,WAAW,EAEhB,KAAK,SAAS,EACf,MAAM,gBAAgB,CAAC;AAExB,+EAA+E;AAC/E,MAAM,MAAM,iBAAiB,GACzB,SAAS,GACT,SAAS,CAAC,QAAQ,CAAC,GACnB,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC;AAE3C,oDAAoD;AACpD,MAAM,WAAW,eAAe,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS;IAC9D,qBAAqB;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,0BAA0B;IAC1B,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC;IACvB,qDAAqD;IACrD,QAAQ,EAAE,OAAO,CAAC;IAClB;;;;;;OAMG;IACH,OAAO,EAAE,OAAO,CAAC;IACjB;;;;OAIG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,kCAAkC;AAClC,MAAM,WAAW,4BAA4B;IAC3C,0BAA0B;IAC1B,SAAS,EAAE,QAAQ,GAAG,MAAM,CAAC;IAC7B,4EAA4E;IAC5E,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;CAC5B;AAkCD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,iBAAiB,EACzB,OAAO,EAAE,4BAA4B,GACpC,eAAe,EAAE,CAuCnB"}
@@ -1 +1 @@
1
- import{EDITABLE as c,isFieldVisible as E}from"@donotdev/core";import{isFieldEditable as m}from"./isFieldEditable";function g(e,r){const{operation:t,viewerRole:b,availableFields:o}=r,a=b??"guest",f=e&&typeof e=="object"&&"fields"in e&&"name"in e?e.fields:e,p=Object.entries(f),s=[];for(const[n,u]of p){const i=u,l=i.visibility||"guest";if(!E(l,a)||i.editable===c.GENERATED||i.editable===c.COMPUTED||t==="create"&&l==="technical"||t==="edit"&&o&&!o.includes(n))continue;let d=m(i.editable,a,t);t==="edit"&&l==="technical"&&i.editable===void 0&&(d=!1),s.push({name:n,config:i,editable:d})}return s}export{g as getFieldsForOperation};
1
+ import{describeEntity as m,describeField as F,isFieldVisible as g}from"@donotdev/core";const f=new WeakMap;function v(t){if("fields"in t&&"name"in t&&typeof t.name=="string"){const i=t;return{fields:i.fields,descriptors:m(i).fields}}const s=t;let e=f.get(s);return e||(e=Object.fromEntries(Object.entries(s).map(([i,n])=>[i,F(i,n,"<fields>")])),f.set(s,e)),{fields:s,descriptors:e}}function w(t,s){const{operation:e,viewerRole:i,availableFields:n}=s,d=i??"guest",{fields:p,descriptors:b}=v(t),l=[];for(const[o,u]of Object.entries(p)){const r=b[o],c=r.visibleAt;if(!g(c,d)||e==="create"&&c==="technical"||r.write==="never"&&c!=="technical"||e==="edit"&&n&&!n.includes(o))continue;const a=r.editableFor(d,e);l.push({name:o,config:u,editable:a,written:a||r.write==="derived"})}return l}export{w as getFieldsForOperation};
@@ -6,6 +6,7 @@
6
6
  * @since 0.0.1
7
7
  * @author AMBROISE PARK Consulting
8
8
  */
9
+ export { EMPTY_VALUE, fromInputValue } from './emptyValue';
9
10
  export { isFieldEditable } from './isFieldEditable';
10
11
  export type { ViewerRole } from './isFieldEditable';
11
12
  export { getFieldsForOperation } from './getFieldsForOperation';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/forms/utils/index.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,YAAY,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,YAAY,EACV,eAAe,EACf,4BAA4B,EAC5B,iBAAiB,GAClB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,YAAY,EACV,eAAe,EACf,gBAAgB,EAChB,eAAe,GAChB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/forms/utils/index.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AAEH,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,YAAY,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,YAAY,EACV,eAAe,EACf,4BAA4B,EAC5B,iBAAiB,GAClB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,YAAY,EACV,eAAe,EACf,gBAAgB,EAChB,eAAe,GAChB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC"}
@@ -1 +1 @@
1
- import{isFieldEditable as a}from"./isFieldEditable";import{getFieldsForOperation as t}from"./getFieldsForOperation";import{validateEntity as e}from"./validateEntity";import{translateFieldLabel as i,translateLabel as l}from"./translateFieldLabel";export{t as getFieldsForOperation,a as isFieldEditable,i as translateFieldLabel,l as translateLabel,e as validateEntity};
1
+ import{EMPTY_VALUE as a,fromInputValue as t}from"./emptyValue";import{isFieldEditable as e}from"./isFieldEditable";import{getFieldsForOperation as s}from"./getFieldsForOperation";import{validateEntity as i}from"./validateEntity";import{translateFieldLabel as r,translateLabel as l}from"./translateFieldLabel";export{a as EMPTY_VALUE,t as fromInputValue,s as getFieldsForOperation,e as isFieldEditable,r as translateFieldLabel,l as translateLabel,i as validateEntity};
@@ -1,41 +1,40 @@
1
- import type { Editable } from '@donotdev/core';
1
+ import type { AnyEntity, FieldOperation } from '@donotdev/core';
2
2
  /** Viewer role type - used for editability checks */
3
3
  export type ViewerRole = 'public' | 'guest' | 'user' | 'admin' | 'super';
4
4
  /**
5
- * Determines if a field is editable by the current viewer.
5
+ * Determines if a field is edited as an input by the current viewer, from the
6
+ * entity descriptor (`describeEntity(entity).fields[name].editableFor`): the same
7
+ * rule as forms, grids and URL prefills.
8
+ *
9
+ * - Only the `user` write class is editable: `editable: 'generated'`, `'computed'`,
10
+ * `false`, hidden fields and backend names (`id`, `createdAt`, ...) never are
11
+ * - `editable` unset / `true`: editable, except technical fields (read-only)
12
+ * - `'create-only'`: editable on create only
13
+ * - a role: `hasRoleAccess(viewerRole, role)` (guest < user < admin < super)
6
14
  *
7
15
  * NOTE: Visibility is handled by backend - this function only handles editability (UI concern).
8
16
  *
9
- * @param editable - Field's editable configuration
17
+ * @param entity - Entity from `defineEntity()`
18
+ * @param fieldName - Field name (key in `entity.fields`)
10
19
  * @param viewerRole - Current viewer's role
11
20
  * @param operation - Form operation type
12
21
  * @returns Whether the field should be rendered as an input (true) or read-only (false)
22
+ * @throws When `entity` has no field `fieldName`
13
23
  *
14
24
  * @example
15
25
  * ```typescript
16
- * // Default editable
17
- * isFieldEditable(undefined, 'user', 'create'); // true
18
- *
19
- * // Role-based (uses hierarchy: guest < user < admin < super)
20
- * isFieldEditable('admin', 'user', 'edit'); // false
21
- * isFieldEditable('admin', 'admin', 'edit'); // true
22
- * isFieldEditable('user', 'admin', 'edit'); // true (admin >= user)
23
- * isFieldEditable('super', 'admin', 'edit'); // false (admin < super)
24
- *
25
- * // Create-only field (`EDITABLE` from `@donotdev/core`; string literals still valid)
26
- * isFieldEditable(EDITABLE.CREATE_ONLY, 'user', 'create'); // true
27
- * isFieldEditable(EDITABLE.CREATE_ONLY, 'user', 'edit'); // false
28
- *
29
- * // Generated/computed — always false (excluded from forms)
30
- * isFieldEditable(EDITABLE.GENERATED, 'admin', 'create'); // false
31
- * isFieldEditable(EDITABLE.COMPUTED, 'admin', 'edit'); // false
26
+ * // fields: { title: {}, status: { editable: 'admin' }, sku: { editable: 'create-only' } }
27
+ * isFieldEditable(productEntity, 'title', 'user', 'edit'); // true
28
+ * isFieldEditable(productEntity, 'status', 'user', 'edit'); // false (user < admin)
29
+ * isFieldEditable(productEntity, 'sku', 'admin', 'edit'); // false (create only)
30
+ * isFieldEditable(productEntity, 'createdAt', 'super', 'edit'); // false (backend-generated)
32
31
  * ```
33
32
  *
34
- * @see {@link Editable} for editable configuration options
33
+ * @see `Editable` (`@donotdev/core`) for editable configuration options
35
34
  *
36
- * @version 0.1.0
35
+ * @version 0.2.0
37
36
  * @since 0.0.1
38
37
  * @author AMBROISE PARK Consulting
39
38
  */
40
- export declare function isFieldEditable(editable: Editable | undefined, viewerRole: string, operation: 'create' | 'edit'): boolean;
39
+ export declare function isFieldEditable(entity: AnyEntity, fieldName: string, viewerRole: string, operation: FieldOperation): boolean;
41
40
  //# sourceMappingURL=isFieldEditable.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"isFieldEditable.d.ts","sourceRoot":"","sources":["../../../src/forms/utils/isFieldEditable.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAE/C,qDAAqD;AACrD,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC;AAEzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,QAAQ,GAAG,SAAS,EAC9B,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,QAAQ,GAAG,MAAM,GAC3B,OAAO,CAoBT"}
1
+ {"version":3,"file":"isFieldEditable.d.ts","sourceRoot":"","sources":["../../../src/forms/utils/isFieldEditable.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAEhE,qDAAqD;AACrD,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC;AAEzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,SAAS,EACjB,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,cAAc,GACxB,OAAO,CAQT"}
@@ -1 +1 @@
1
- import{EDITABLE as E,hasRoleAccess as s}from"@donotdev/core";function r(t,i,o){return t===void 0||t===!0?!0:t===!1||t===E.GENERATED||t===E.COMPUTED?!1:t===E.CREATE_ONLY?o==="create":typeof t=="string"?s(i,t):!0}export{r as isFieldEditable};
1
+ import{describeEntity as d}from"@donotdev/core";function n(e,i,r,o){const t=d(e).fields[i];if(!t)throw new Error(`isFieldEditable: entity "${e.name}" has no field "${i}".`);return t.editableFor(r,o)}export{n as isFieldEditable};
@@ -0,0 +1,19 @@
1
+ import type { AnyEntity } from '@donotdev/core';
2
+ /**
3
+ * Fields the viewer may write on the entity for an operation, from the entity
4
+ * descriptor: visible fields the form writes (`user` fields editable for the role
5
+ * and operation, `derived` / `editable: 'computed'` fields) and their i18n
6
+ * companions (`<name>I18n`). Generated, technical, `editable: false` and
7
+ * role-denied fields are never written by forms or grids.
8
+ *
9
+ * @param entity - The entity
10
+ * @param viewerRole - The viewer's role
11
+ * @param operation - `'create'` (inserts) or `'edit'` (patches)
12
+ * @returns The writable field names (companions included)
13
+ *
14
+ * @version 0.2.0
15
+ * @since 0.2.5
16
+ * @author AMBROISE PARK Consulting
17
+ */
18
+ export declare function writableFields(entity: AnyEntity, viewerRole: string, operation: 'create' | 'edit'): Set<string>;
19
+ //# sourceMappingURL=writableFields.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"writableFields.d.ts","sourceRoot":"","sources":["../../../src/forms/utils/writableFields.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAIhD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,SAAS,EACjB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,QAAQ,GAAG,MAAM,GAC3B,GAAG,CAAC,MAAM,CAAC,CAUb"}
@@ -0,0 +1 @@
1
+ import{describeEntity as a}from"@donotdev/core";import{getFieldsForOperation as s}from"./getFieldsForOperation";function m(t,r,o){const{fields:i}=a(t);return new Set(s(t,{operation:o,viewerRole:r}).filter(e=>e.written).flatMap(e=>{const n=i[e.name]?.companion;return n?[e.name,n]:[e.name]}))}export{m as writableFields};
@@ -12,4 +12,6 @@ export type { UseRelatedItemsOptions, UseRelatedItemsReturn, } from './useRelate
12
12
  export { useFieldConditions } from './useFieldConditions';
13
13
  export { useReferenceResolver } from './useReferenceResolver';
14
14
  export type { ReferenceData } from './useReferenceResolver';
15
+ export { useChildRows, useJoinedForm } from './useChildRows';
16
+ export type { ChildRowsParent, UseChildRowsOptions, UseChildRowsReturn, } from './useChildRows';
15
17
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hooks/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,YAAY,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAE1E,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAEvD,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,YAAY,EACV,yBAAyB,EACzB,wBAAwB,GACzB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,YAAY,EACV,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,YAAY,EACV,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,YAAY,EACV,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE1D,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,YAAY,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hooks/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,YAAY,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAE1E,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAEvD,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,YAAY,EACV,yBAAyB,EACzB,wBAAwB,GACzB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,YAAY,EACV,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,YAAY,EACV,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,YAAY,EACV,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE1D,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,YAAY,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAE5D,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC7D,YAAY,EACV,eAAe,EACf,mBAAmB,EACnB,kBAAkB,GACnB,MAAM,gBAAgB,CAAC"}
@@ -1 +1 @@
1
- import{useFileUpload as e}from"./useFileUpload";import{useEntityFavorites as s}from"./useEntityFavorites";import{useCrudFilters as r}from"./useCrudFilters";import{useCrudPageSize as o}from"./useCrudPageSize";import{useRelatedItems as i}from"./useRelatedItems";import{useFieldConditions as a}from"./useFieldConditions";import{useReferenceResolver as t}from"./useReferenceResolver";export{r as useCrudFilters,o as useCrudPageSize,s as useEntityFavorites,a as useFieldConditions,e as useFileUpload,t as useReferenceResolver,i as useRelatedItems};
1
+ import{useFileUpload as e}from"./useFileUpload";import{useEntityFavorites as s}from"./useEntityFavorites";import{useCrudFilters as o}from"./useCrudFilters";import{useCrudPageSize as r}from"./useCrudPageSize";import{useRelatedItems as i}from"./useRelatedItems";import{useFieldConditions as a}from"./useFieldConditions";import{useReferenceResolver as t}from"./useReferenceResolver";import{useChildRows as u,useJoinedForm as m}from"./useChildRows";export{u as useChildRows,o as useCrudFilters,r as useCrudPageSize,s as useEntityFavorites,a as useFieldConditions,e as useFileUpload,m as useJoinedForm,t as useReferenceResolver,i as useRelatedItems};
@@ -0,0 +1,161 @@
1
+ import type { AnyEntity, BulkResult, EntityExtensions, InferEntityRow } from '@donotdev/core';
2
+ import type { ChildRowsAccess } from '../forms/childRows';
3
+ import type { RenderableField } from '../forms/utils/getFieldsForOperation';
4
+ import type { ChildRowEdits, OpenRecordForm } from '../stores';
5
+ /** Parent of the child rows: the child's reference field and the parent record id. */
6
+ export interface ChildRowsParent {
7
+ /** Reference field of the child entity pointing at the parent (e.g. `'campaignId'`) */
8
+ field: string;
9
+ /** Parent record id, or `null` while the parent is not created yet (no rows) */
10
+ value: string | null;
11
+ }
12
+ /** Options for {@link useChildRows}. */
13
+ export interface UseChildRowsOptions {
14
+ /**
15
+ * Viewer role for the entity rules (access, editable fields). Default: the
16
+ * joined form's `viewerRole`, else `'guest'` (most restrictive).
17
+ */
18
+ viewerRole?: string;
19
+ /**
20
+ * 1:1 extensions of the rows (e.g. `{ offer: { entity: productOfferEntity,
21
+ * field: 'productId' } }`): read in one batched query per loaded set, merged
22
+ * under the key (`row.offer.priceExclVat`), edited and validated as
23
+ * `offer.priceExclVat`, written with the rows (update, or insert of a missing
24
+ * extension). A viewer without access to an extension entity gets none of it.
25
+ * Use the same `extend` on every instance of the same rows; keep its keys.
26
+ * @since 0.2.5
27
+ */
28
+ extend?: EntityExtensions;
29
+ }
30
+ /** Return type of {@link useChildRows}. */
31
+ export interface UseChildRowsReturn<T extends {
32
+ id: string;
33
+ }> {
34
+ /**
35
+ * Saved rows with unsaved edits applied, then added rows; removed rows hidden.
36
+ * Extensions are merged under their key (`row.offer`, `null` when missing)
37
+ * and as flat `key.field` values.
38
+ */
39
+ items: T[];
40
+ /** The same rows without cell changes (a DataTable's data under `edits.changes`) */
41
+ base: T[];
42
+ /** Unsaved edits: cell values by row id (extension fields `key.field`), added rows, removed row ids */
43
+ edits: ChildRowEdits;
44
+ /** Edited cells + added rows + removed rows */
45
+ pendingCount: number;
46
+ /** Whether anything is unsaved */
47
+ hasEdits: boolean;
48
+ /**
49
+ * Invalid fields of the edited rows, checked on every change against the
50
+ * database contract: the resulting row (stored row merged with its edits, an
51
+ * added row as added; extensions the same) against the schema of its
52
+ * resulting status (`draft` → draft schema, otherwise the full create schema,
53
+ * required fields included): `errors[rowId][fieldKey]` = translated message, field keys as
54
+ * cells address them (`offer.priceExclVat`). Empty when all are valid. A Save
55
+ * (the form's, or `save()`) is blocked while it is not empty.
56
+ * @since 0.2.5
57
+ */
58
+ errors: Record<string, Record<string, string>>;
59
+ /**
60
+ * Add rows (pre-minted ids, schema defaults, the parent id set). Only fields
61
+ * the viewer may set on create (extension fields `key.field` included).
62
+ * Returns the new ids.
63
+ */
64
+ add: (values: Array<Partial<T> & Record<string, unknown>>) => string[];
65
+ /**
66
+ * Set field values of a row (saved or added), extension fields as
67
+ * `key.field`. A value equal to the saved one drops the pending change.
68
+ * Ordering: `update(id, { sortOrder })`.
69
+ */
70
+ update: (id: string, patch: Partial<T> & Record<string, unknown>) => void;
71
+ /**
72
+ * Logical delete (CRUD rule 3): added rows are dropped, saved rows get
73
+ * `{ status: 'deleted' }` on Save. `delete` is the hard delete.
74
+ */
75
+ remove: (ids: readonly string[]) => void;
76
+ /** Hard delete: added rows are dropped, saved rows are deleted on Save. */
77
+ delete: (ids: readonly string[]) => void;
78
+ /** Drop every unsaved edit. */
79
+ discard: () => void;
80
+ /**
81
+ * Standalone only (no form open on the parent): write this instance's edits.
82
+ * Rejects without writing while `errors` is not empty (message: the count of
83
+ * rows to fix). Without extensions one `bulk` (partial success: rows that fail
84
+ * stay unsaved); with extensions one `bulkAcross` (rejects as a whole, edits
85
+ * kept). On success exactly what it sent leaves the edits at once; edits made
86
+ * during the save stay pending. Throws when joined: the form's Save writes
87
+ * joined rows.
88
+ */
89
+ save: () => Promise<BulkResult | void>;
90
+ /** Refetch the saved rows. */
91
+ refresh: () => Promise<void>;
92
+ /** True during the initial fetch (rows or extensions) */
93
+ loading: boolean;
94
+ /** Fetch error, or null */
95
+ error: Error | null;
96
+ /** True when an open form edits the parent record: its draft and Save own the edits */
97
+ joined: boolean;
98
+ /** What the viewer may do (entity `access`); all false = read-only */
99
+ access: ChildRowsAccess;
100
+ /**
101
+ * Extension fields the viewer may see, prefixed (`offer.priceExclVat`), for
102
+ * columns or custom displays; `editable` when the viewer may write them.
103
+ */
104
+ extensionFields: RenderableField[];
105
+ }
106
+ /**
107
+ * The edit form the child rows of `parent` join: the latest `useEntityForm` (edit
108
+ * mode) opened on that parent record, or `null`. The parent collection comes
109
+ * from the child field's `validation.reference`.
110
+ *
111
+ * @param entity - The child entity
112
+ * @param parent - The child's parent field and the parent record id (`undefined`: none)
113
+ * @returns The open form, or `null` when none edits that record
114
+ *
115
+ * @example
116
+ * ```tsx
117
+ * const joined = useJoinedForm(campaignProductEntity, { field: 'campaignId', value: campaign.id }) !== null;
118
+ * ```
119
+ */
120
+ export declare function useJoinedForm(entity: AnyEntity, parent: ChildRowsParent | undefined): OpenRecordForm | null;
121
+ /**
122
+ * A record's child rows, edited with the record and saved by its Save.
123
+ *
124
+ * **Joined (automatic):** when an edit form (`useEntityForm` / `EntityFormRenderer`)
125
+ * is open on the parent record, the rows join it: unsaved edits live in that
126
+ * form's draft (restored, discarded and kept on a failed save with it), the
127
+ * form's Save writes them (default writer, or `form.pendingWrites()` in the
128
+ * app's `onValid`), they are validated with the fields before the page leaves,
129
+ * and cleared then refetched after a successful save. Every `useChildRows` on
130
+ * the same form, entity and parent sees the same rows. The latest form opened
131
+ * on the record wins. All the parent's rows are loaded (client-side list).
132
+ *
133
+ * **Standalone:** no such form, or no `parent` (every record of the entity):
134
+ * edits stay in memory for this instance; `save()` writes them.
135
+ *
136
+ * **1:1 extensions (`extend`):** see {@link UseChildRowsOptions.extend}.
137
+ *
138
+ * Entity rules: the viewer's `access` gates add / edit / remove (calls throw
139
+ * when not allowed), only fields the viewer may write are set, drafts read back
140
+ * from the browser are validated, edits of rows that no longer exist are dropped.
141
+ *
142
+ * @param entity - The child entity
143
+ * @param parent - The child's reference field and the parent record id (`null` before the parent exists; omitted: every record)
144
+ * @param options - See {@link UseChildRowsOptions}
145
+ * @returns See {@link UseChildRowsReturn}
146
+ *
147
+ * @example
148
+ * ```tsx
149
+ * const rows = useChildRows(campaignProductEntity, { field: 'campaignId', value: campaign.id });
150
+ * rows.items.map((row) => <ProductLine key={row.id} row={row} onChange={(patch) => rows.update(row.id, patch)} />);
151
+ * <Button onClick={() => rows.add([{ productId }])}>Add</Button>
152
+ *
153
+ * // Products with their private offer, all records (no parent)
154
+ * const products = useChildRows(productEntity, undefined, {
155
+ * extend: { offer: { entity: productOfferEntity, field: 'productId' } },
156
+ * });
157
+ * products.update(id, { 'offer.priceExclVat': 12 });
158
+ * ```
159
+ */
160
+ export declare function useChildRows<E extends AnyEntity>(entity: E, parent?: ChildRowsParent, options?: UseChildRowsOptions): UseChildRowsReturn<InferEntityRow<E>>;
161
+ //# sourceMappingURL=useChildRows.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useChildRows.d.ts","sourceRoot":"","sources":["../../src/hooks/useChildRows.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EACV,SAAS,EACT,UAAU,EACV,gBAAgB,EAChB,cAAc,EACf,MAAM,gBAAgB,CAAC;AAkBxB,OAAO,KAAK,EAGV,eAAe,EAEhB,MAAM,oBAAoB,CAAC;AAS5B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sCAAsC,CAAC;AAI5E,OAAO,KAAK,EAAE,aAAa,EAAmB,cAAc,EAAE,MAAM,WAAW,CAAC;AAKhF,sFAAsF;AACtF,MAAM,WAAW,eAAe;IAC9B,uFAAuF;IACvF,KAAK,EAAE,MAAM,CAAC;IACd,gFAAgF;IAChF,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB;AAED,wCAAwC;AACxC,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;;;;OAQG;IACH,MAAM,CAAC,EAAE,gBAAgB,CAAC;CAC3B;AAED,2CAA2C;AAC3C,MAAM,WAAW,kBAAkB,CAAC,CAAC,SAAS;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE;IAC1D;;;;OAIG;IACH,KAAK,EAAE,CAAC,EAAE,CAAC;IACX,oFAAoF;IACpF,IAAI,EAAE,CAAC,EAAE,CAAC;IACV,uGAAuG;IACvG,KAAK,EAAE,aAAa,CAAC;IACrB,+CAA+C;IAC/C,YAAY,EAAE,MAAM,CAAC;IACrB,kCAAkC;IAClC,QAAQ,EAAE,OAAO,CAAC;IAClB;;;;;;;;;OASG;IACH,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAC/C;;;;OAIG;IACH,GAAG,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,KAAK,MAAM,EAAE,CAAC;IACvE;;;;OAIG;IACH,MAAM,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;IAC1E;;;OAGG;IACH,MAAM,EAAE,CAAC,GAAG,EAAE,SAAS,MAAM,EAAE,KAAK,IAAI,CAAC;IACzC,2EAA2E;IAC3E,MAAM,EAAE,CAAC,GAAG,EAAE,SAAS,MAAM,EAAE,KAAK,IAAI,CAAC;IACzC,+BAA+B;IAC/B,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB;;;;;;;;OAQG;IACH,IAAI,EAAE,MAAM,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC;IACvC,8BAA8B;IAC9B,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7B,yDAAyD;IACzD,OAAO,EAAE,OAAO,CAAC;IACjB,2BAA2B;IAC3B,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IACpB,uFAAuF;IACvF,MAAM,EAAE,OAAO,CAAC;IAChB,sEAAsE;IACtE,MAAM,EAAE,eAAe,CAAC;IACxB;;;OAGG;IACH,eAAe,EAAE,eAAe,EAAE,CAAC;CACpC;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,SAAS,EACjB,MAAM,EAAE,eAAe,GAAG,SAAS,GAClC,cAAc,GAAG,IAAI,CAavB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,wBAAgB,YAAY,CAAC,CAAC,SAAS,SAAS,EAC9C,MAAM,EAAE,CAAC,EACT,MAAM,CAAC,EAAE,eAAe,EACxB,OAAO,CAAC,EAAE,mBAAmB,GAC5B,kBAAkB,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC"}
@@ -0,0 +1 @@
1
+ "use client";import{useEffect as W,useMemo as Ee,useRef as ge,useState as B}from"react";import{generateUUID as Re,REMOVED_STATUS as Ce,useTranslation as Se}from"@donotdev/core";import{EMPTY_CHILD_EDITS as M,applyChildEdits as xe,childEditsBatches as ee,childEditsErrors as te,childRowsAccess as je,countChildEdits as Oe,hasChildEdits as I,parentCollectionOf as $e,parseChildEdits as ke,rebaseChildEdits as ne,reconcileChildEdits as Me,removeChildRows as se,setChildValues as re,writableFields as ie}from"../forms/childRows";import{extensionFieldName as Ie,extensionFields as De,extensionWritable as Fe,extensionsSignature as Te,resolveExtensions as Ue,splitExtensionField as P}from"../forms/extend";import{translateFieldLabel as qe}from"../forms/utils/translateFieldLabel";import{buildSchemaDefaults as Ae}from"../forms/utils/buildInitialValues";import{childRowsKey as Ke,extensionMintKey as Le,useFormStore as R}from"../stores";import{getCrudServiceInstance as Ve,useCrud as _e}from"../useCrud";import{useCrudList as We}from"../useCrudList";import{useExtensionRows as Be}from"./useExtensionRows";function oe(i,d){const C=d?$e(i,d.field):null,f=d?.value??null;return R(c=>{if(C===null||f===null)return null;for(let w=c.openRecords.length-1;w>=0;w--){const g=c.openRecords[w];if(g.collection===C&&g.recordId===f)return g}return null})}function Pe(i,d,C={}){const f=oe(i,d),c=C.viewerRole??f?.viewerRole??"guest",w=je(i,c),g=d?d.value:void 0,D=g!==null,h=d&&d.value!==null?{field:d.field,value:d.value}:void 0,ae=Te(C.extend),m=Ee(()=>Ue(i,C.extend,c),[i,ae,c]),{t:F}=Se(["crud",i.namespace,...m.map(e=>e.entity.namespace)]),p=We(i.collection,{entity:i,enabled:D,pagination:"client",...d&&{queryOptions:{where:[{field:d.field,operator:"==",value:g}]}}}),{bulk:le}=_e(i.collection,{entity:i}),H=D&&p.data!==null&&!p.loading&&!p.error,x=Be(m,p.items.map(e=>e.id),H),J=Object.values(x).some(e=>e.loading),de=Object.values(x).find(e=>e.error)?.error??null,u=f&&h?Ke(f.formKey,h.value,i.collection,h.field):null,ce=R(e=>u===null?void 0:e.childEdits[u]),[N,T]=B(M),[ue,j]=B(!1),y=u===null?N:ce??M,S=e=>{if(u===null||!f){T(e);return}const t=R.getState().childEdits[u]??M,n=e(t);n!==t&&(R.getState().setChildEdits(u,I(n)?n:null),f.changed())},O={},U=m.length===0?p.items:p.items.map(e=>{const t={...e};for(const n of m){if(!n.readable)continue;const l=x[n.key]?.byRecord.get(e.id)??null;if(t[n.key]=l,!!l){(O[e.id]??={})[n.key]=l.id;for(const[s,r]of Object.entries(l))t[Ie(n.key,s)]=r}}return t}),q=xe(U,y),A=q.base,fe=m.length===0?q.items:q.items.map(e=>{const t=y.changes[e.id];if(!t)return e;const n={...e};for(const[l,s]of Object.entries(t)){const r=P(l);if(!r)continue;const[o,v]=r,E=n[o];n[o]={...typeof E=="object"&&E!==null?E:{},[v]:s}}return n}),$={entity:i,...h&&{parent:h},extensions:m,extensionIds:O,savedRows:new Map(U.map(e=>[e.id,e])),mintId:e=>R.getState().mintId(e)},K=e=>{const t=P(e),n=t?m.find(l=>l.key===t[0]):void 0;return n&&t?{entity:n.entity,field:t[1]}:{entity:i,field:e}},L=e=>{const t={};for(const[n,l]of Object.entries(e)){t[n]={};for(const[s,r]of Object.entries(l)){const o=K(s),v=(E,a)=>F(E,{ns:o.entity.namespace,...a});t[n][s]=F(r==="required"?"crud:childRows.required":"crud:childRows.invalidValue",{field:qe(o.field,o.entity.fields[o.field],v)})}}return t},Y=L(te($,y,c)),z=Object.keys(Y).length,b=ge({context:$,viewerRole:c,messagesOf:L,describe:K});b.current={context:$,viewerRole:c,messagesOf:L,describe:K};const[G]=B(()=>({entity:i,describe:e=>b.current.describe(e),errors:e=>b.current.messagesOf(te(b.current.context,e,b.current.viewerRole)),batches:e=>ee(b.current.context,e,b.current.viewerRole)}));W(()=>{if(u===null)return;const e=R.getState();e.setChildWriter(u,G);const t=e.childDrafts[u];if(t!==void 0){e.setChildDraft(u,null);try{const n=ke(b.current.context,t,b.current.viewerRole);e.setChildEdits(u,I(n)?n:null)}catch{}}},[u,G,i.collection]);const V=m.flatMap(e=>Object.entries(O).flatMap(([t,n])=>n[e.key]?[Le(e.entity.collection,t)]:[])),he=V.join("|");W(()=>{V.length>0&&R.getState().releaseMintedIds(V)},[he]);const Q=H&&!J,X=f?f.submitting:ue;W(()=>{!Q||X||S(e=>Me(e,U))},[Q,X,p.items,x,u,f]);const _=()=>{if(g===null)throw new Error(`useChildRows(${i.name}): the parent record is not created yet (parent.value is null).`)},Z=e=>new Set(m.flatMap(t=>[...Fe(t,c,e!==null&&O[e]?.[t.key]?"edit":"create")])),me=e=>{if(_(),!w.create)throw new Error(`useChildRows(${i.name}): the viewer may not add rows.`);const t=ie(i,c,"create"),n=new Set([...t,...Z(null)]);for(const r of e){const o=Object.keys(r).filter(v=>v!==d?.field&&!n.has(v));if(o.length>0)throw new Error(`useChildRows(${i.name}): fields not writable on create: ${o.join(", ")}.`)}const l=Ae(i,t),s=e.map(r=>({...l,...r,id:Re(),...h&&{[h.field]:h.value}}));return S(r=>({...r,added:[...r.added,...s]})),s.map(r=>r.id)},we=(e,t)=>{_();const n=A.find(o=>o.id===e);if(!n)throw new Error(`useChildRows(${i.name}): no row "${e}".`);const l=y.added.some(o=>o.id===e);if(Object.keys(t).some(o=>!P(o))&&!(l?w.create:w.update))throw new Error(`useChildRows(${i.name}): the viewer may not edit rows.`);const s=new Set([...ie(i,c,l?"create":"edit"),...Z(l?null:e)]),r=Object.keys(t).filter(o=>!s.has(o));if(r.length>0)throw new Error(`useChildRows(${i.name}): fields not writable: ${r.join(", ")}.`);S(o=>re(o,n,t))},pe=e=>{const t=new Set(y.added.map(n=>n.id));if(!w.delete&&e.some(n=>!t.has(n)))throw new Error(`useChildRows(${i.name}): the viewer may not delete rows.`);S(n=>se(n,e))},ve=e=>{const t=new Set(y.added.map(s=>s.id)),n=e.filter(s=>!t.has(s));if(n.length>0&&!w.update)throw new Error(`useChildRows(${i.name}): the viewer may not remove rows.`);const l=n.map(s=>{const r=A.find(o=>o.id===s);if(!r)throw new Error(`useChildRows(${i.name}): no row "${s}".`);return r});S(s=>l.reduce((r,o)=>re(r,o,{status:Ce}),se(s,e.filter(r=>t.has(r)))))},ye=()=>S(()=>M),be=async()=>{if(f)throw new Error(`useChildRows(${i.name}).save(): the rows are joined to the form open on the parent; its Save writes them.`);if(_(),z>0)throw new Error(F("crud:childRows.invalidRows",{count:z}));const e=N;if(m.length>0){const s=Ve();if(!s)throw new Error(`useChildRows(${i.name}).save(): the CRUD service is not ready.`);j(!0);try{await s.bulkAcross(ee($,e,c)),T(r=>ne(r,e));return}finally{j(!1)}}const t=new Set(e.added.map(s=>s.id)),n=new Set(e.removed),l=Object.entries(e.changes).filter(([s])=>!t.has(s)&&!n.has(s)).map(([s,r])=>({id:s,patch:r}));j(!0);try{const s=await le({inserts:e.added.map(({id:a,...k})=>({...k,...e.changes[a],...h&&{[h.field]:h.value}})),updates:l,deletes:e.removed}),r=new Set(s.failed.flatMap(a=>{const k=a.op==="insert"&&a.index!==void 0?e.added[a.index]:void 0;return k?[k.id]:[]})),o=new Set(s.failed.flatMap(a=>a.op!=="insert"&&a.id!==void 0?[a.id]:[])),v=a=>r.has(a)||o.has(a),E={changes:Object.fromEntries(Object.entries(e.changes).filter(([a])=>!v(a))),added:e.added.filter(a=>!v(a.id)),removed:e.removed.filter(a=>!v(a))};return T(a=>I(E)?ne(a,E):a),s}finally{j(!1)}};return{items:fe,base:A,edits:y,pendingCount:Oe(y),hasEdits:I(y),errors:Y,add:me,update:we,remove:ve,delete:pe,discard:ye,save:be,refresh:p.refresh,loading:D&&(p.loading||J),error:p.error??de,joined:u!==null,access:w,extensionFields:m.flatMap(e=>De(e,c,"edit"))}}export{Pe as useChildRows,oe as useJoinedForm};