@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.
- package/dist/CrudService.bulk.d.ts +13 -14
- package/dist/CrudService.bulk.d.ts.map +1 -1
- package/dist/CrudService.bulk.js +1 -1
- package/dist/CrudService.bulkAcross.d.ts +12 -7
- package/dist/CrudService.bulkAcross.d.ts.map +1 -1
- package/dist/CrudService.bulkAcross.js +1 -1
- package/dist/CrudService.bulkReconciliation.d.ts +4 -0
- package/dist/CrudService.bulkReconciliation.d.ts.map +1 -0
- package/dist/CrudService.bulkReconciliation.js +1 -0
- package/dist/CrudService.cache.d.ts +1 -1
- package/dist/CrudService.cache.d.ts.map +1 -1
- package/dist/CrudService.cache.js +1 -1
- package/dist/CrudService.d.ts +35 -6
- package/dist/CrudService.d.ts.map +1 -1
- package/dist/CrudService.js +1 -1
- package/dist/CrudService.mutations.d.ts +3 -3
- package/dist/CrudService.mutations.d.ts.map +1 -1
- package/dist/CrudService.mutations.js +1 -1
- package/dist/CrudService.optimistic.d.ts +2 -2
- package/dist/CrudService.optimistic.d.ts.map +1 -1
- package/dist/CrudService.optimistic.js +1 -1
- package/dist/CrudService.subscriptions.js +1 -1
- package/dist/CrudService.writeRules.d.ts +57 -0
- package/dist/CrudService.writeRules.d.ts.map +1 -0
- package/dist/CrudService.writeRules.js +1 -0
- package/dist/CrudService.writeSchema.d.ts +64 -0
- package/dist/CrudService.writeSchema.d.ts.map +1 -0
- package/dist/CrudService.writeSchema.js +1 -0
- package/dist/CrudStore.d.ts +10 -1
- package/dist/CrudStore.d.ts.map +1 -1
- package/dist/CrudStore.js +1 -1
- package/dist/FieldRegistry.d.ts +1 -1
- package/dist/FieldRegistry.d.ts.map +1 -1
- package/dist/adapters/FunctionsAdapter.d.ts +3 -3
- package/dist/adapters/FunctionsAdapter.d.ts.map +1 -1
- package/dist/adapters/FunctionsAdapter.js +1 -1
- package/dist/components/CrudButton.d.ts +3 -2
- package/dist/components/CrudButton.d.ts.map +1 -1
- package/dist/components/CrudCard.d.ts.map +1 -1
- package/dist/components/CrudCard.js +1 -1
- package/dist/components/DateFilter.js +1 -1
- package/dist/components/EntityFilters.d.ts +23 -4
- package/dist/components/EntityFilters.d.ts.map +1 -1
- package/dist/components/EntityFilters.js +1 -1
- package/dist/components/FormFieldRenderer.d.ts +21 -4
- package/dist/components/FormFieldRenderer.d.ts.map +1 -1
- package/dist/components/FormFieldRenderer.js +1 -1
- package/dist/components/FormLayout.d.ts.map +1 -1
- package/dist/components/FormLayout.js +1 -1
- package/dist/components/SortableCardList.d.ts +47 -0
- package/dist/components/SortableCardList.d.ts.map +1 -0
- package/dist/components/SortableCardList.js +1 -0
- package/dist/components/YearFilter.js +1 -1
- package/dist/components/controlled/complex/ControlledAddressField.d.ts.map +1 -1
- package/dist/components/controlled/complex/ControlledAddressField.js +1 -1
- package/dist/components/controlled/complex/ControlledDateField.d.ts.map +1 -1
- package/dist/components/controlled/complex/ControlledDateField.js +1 -1
- package/dist/components/controlled/complex/ControlledFieldArrayField.d.ts +9 -0
- package/dist/components/controlled/complex/ControlledFieldArrayField.d.ts.map +1 -1
- package/dist/components/controlled/complex/ControlledFieldArrayField.js +1 -1
- package/dist/components/controlled/complex/ControlledMultiInputField.d.ts.map +1 -1
- package/dist/components/controlled/complex/ControlledMultiInputField.js +1 -1
- package/dist/components/controlled/complex/ControlledTimestampField.d.ts.map +1 -1
- package/dist/components/controlled/complex/ControlledTimestampField.js +1 -1
- package/dist/components/controlled/fieldOptions.d.ts +9 -0
- package/dist/components/controlled/fieldOptions.d.ts.map +1 -1
- package/dist/components/controlled/fieldOptions.js +1 -1
- package/dist/components/controlled/file/ControlledImageField.js +1 -1
- package/dist/components/controlled/input/ControlledCurrencyField.d.ts.map +1 -1
- package/dist/components/controlled/input/ControlledCurrencyField.js +1 -1
- package/dist/components/controlled/input/ControlledDurationField.js +1 -1
- package/dist/components/controlled/input/ControlledNumberField.d.ts.map +1 -1
- package/dist/components/controlled/input/ControlledNumberField.js +1 -1
- package/dist/components/controlled/input/ControlledPasswordField.d.ts.map +1 -1
- package/dist/components/controlled/input/ControlledPasswordField.js +1 -1
- package/dist/components/controlled/input/ControlledPhoneField.d.ts.map +1 -1
- package/dist/components/controlled/input/ControlledPhoneField.js +1 -1
- package/dist/components/controlled/input/ControlledPriceField.d.ts.map +1 -1
- package/dist/components/controlled/input/ControlledPriceField.js +1 -1
- package/dist/components/controlled/input/ControlledRatingField.js +1 -1
- package/dist/components/controlled/input/ControlledTextField.d.ts.map +1 -1
- package/dist/components/controlled/input/ControlledTextField.js +1 -1
- package/dist/components/controlled/input/ControlledTextareaField.d.ts.map +1 -1
- package/dist/components/controlled/input/ControlledTextareaField.js +1 -1
- package/dist/components/controlled/select/ControlledComboboxField.d.ts.map +1 -1
- package/dist/components/controlled/select/ControlledComboboxField.js +1 -1
- package/dist/components/controlled/select/ControlledDropdownField.d.ts.map +1 -1
- package/dist/components/controlled/select/ControlledDropdownField.js +1 -1
- package/dist/components/controlled/select/ControlledMultiDropdownField.d.ts.map +1 -1
- package/dist/components/controlled/select/ControlledMultiDropdownField.js +1 -1
- package/dist/components/controlled/select/ControlledReferenceField.d.ts.map +1 -1
- package/dist/components/controlled/select/ControlledReferenceField.js +1 -1
- package/dist/components/controlled/select/ControlledYearField.d.ts.map +1 -1
- package/dist/components/controlled/select/ControlledYearField.js +1 -1
- package/dist/components/fields/display/BadgeFieldDisplay.js +1 -1
- package/dist/components/fields/display/CheckboxFieldDisplay.js +1 -1
- package/dist/components/fields/display/MapFieldDisplay.js +1 -1
- package/dist/components/fields/display/NumberFieldDisplay.js +1 -1
- package/dist/components/fields/display/PasswordFieldDisplay.js +1 -1
- package/dist/components/fields/display/TextFieldDisplay.js +1 -1
- package/dist/components/form/fields/AddressFieldComponent.d.ts +3 -1
- package/dist/components/form/fields/AddressFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/AddressFieldComponent.js +1 -1
- package/dist/components/form/fields/ComboboxComponent.d.ts +2 -0
- package/dist/components/form/fields/ComboboxComponent.d.ts.map +1 -1
- package/dist/components/form/fields/ComboboxComponent.js +1 -1
- package/dist/components/form/fields/CurrencyFieldComponent.d.ts +2 -0
- package/dist/components/form/fields/CurrencyFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/CurrencyFieldComponent.js +1 -1
- package/dist/components/form/fields/DateFieldComponent.d.ts +2 -0
- package/dist/components/form/fields/DateFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/DateFieldComponent.js +1 -1
- package/dist/components/form/fields/DocumentFieldComponent.js +1 -1
- package/dist/components/form/fields/DropdownComponent.d.ts +2 -0
- package/dist/components/form/fields/DropdownComponent.d.ts.map +1 -1
- package/dist/components/form/fields/DropdownComponent.js +1 -1
- package/dist/components/form/fields/DurationFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/DurationFieldComponent.js +1 -1
- package/dist/components/form/fields/FileFieldComponent.js +1 -1
- package/dist/components/form/fields/GdprConsentFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/GdprConsentFieldComponent.js +1 -1
- package/dist/components/form/fields/GeoPointFieldComponent.js +1 -1
- package/dist/components/form/fields/ImageFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/ImageFieldComponent.js +1 -1
- package/dist/components/form/fields/MultiDropdownComponent.d.ts +2 -0
- package/dist/components/form/fields/MultiDropdownComponent.d.ts.map +1 -1
- package/dist/components/form/fields/MultiDropdownComponent.js +1 -1
- package/dist/components/form/fields/MultiInputTextFieldComponent.d.ts +2 -0
- package/dist/components/form/fields/MultiInputTextFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/MultiInputTextFieldComponent.js +1 -1
- package/dist/components/form/fields/NumberFieldComponent.d.ts +2 -0
- package/dist/components/form/fields/NumberFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/NumberFieldComponent.js +1 -1
- package/dist/components/form/fields/PasswordFieldComponent.d.ts +2 -0
- package/dist/components/form/fields/PasswordFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/PasswordFieldComponent.js +1 -1
- package/dist/components/form/fields/PhoneNumberComponent.d.ts +11 -1
- package/dist/components/form/fields/PhoneNumberComponent.d.ts.map +1 -1
- package/dist/components/form/fields/PhoneNumberComponent.js +1 -1
- package/dist/components/form/fields/PriceFieldComponent.d.ts +2 -0
- package/dist/components/form/fields/PriceFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/PriceFieldComponent.js +1 -1
- package/dist/components/form/fields/RangeFieldComponent.js +1 -1
- package/dist/components/form/fields/ReferenceFieldComponent.d.ts +3 -1
- package/dist/components/form/fields/ReferenceFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/ReferenceFieldComponent.js +1 -1
- package/dist/components/form/fields/RichTextComponent.js +1 -1
- package/dist/components/form/fields/TextAreaComponent.d.ts +2 -0
- package/dist/components/form/fields/TextAreaComponent.d.ts.map +1 -1
- package/dist/components/form/fields/TextAreaComponent.js +1 -1
- package/dist/components/form/fields/TextFieldComponent.d.ts +3 -1
- package/dist/components/form/fields/TextFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/TextFieldComponent.js +1 -1
- package/dist/components/form/fields/TimestampFieldComponent.d.ts +2 -0
- package/dist/components/form/fields/TimestampFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/TimestampFieldComponent.js +1 -1
- package/dist/components/index.d.ts +2 -0
- package/dist/components/index.d.ts.map +1 -1
- package/dist/components/index.js +1 -1
- package/dist/fieldTypeRegistry.d.ts +2 -2
- package/dist/fieldTypeRegistry.d.ts.map +1 -1
- package/dist/fieldTypeRegistry.js +1 -1
- package/dist/fieldTypeRegistry.store.d.ts +0 -2
- package/dist/fieldTypeRegistry.store.d.ts.map +1 -1
- package/dist/fieldTypeRegistry.store.js +1 -1
- package/dist/fieldTypeRegistry.types.d.ts +8 -9
- package/dist/fieldTypeRegistry.types.d.ts.map +1 -1
- package/dist/forms/FormNavigation.d.ts +24 -0
- package/dist/forms/FormNavigation.d.ts.map +1 -0
- package/dist/forms/FormNavigation.js +1 -0
- package/dist/forms/childRows.d.ts +184 -0
- package/dist/forms/childRows.d.ts.map +1 -0
- package/dist/forms/childRows.js +1 -0
- package/dist/forms/extend.d.ts +88 -0
- package/dist/forms/extend.d.ts.map +1 -0
- package/dist/forms/extend.js +1 -0
- package/dist/forms/hooks/useEntityField.d.ts +11 -5
- package/dist/forms/hooks/useEntityField.d.ts.map +1 -1
- package/dist/forms/hooks/useEntityField.js +1 -1
- package/dist/forms/hooks/useEntityForm.d.ts +50 -5
- package/dist/forms/hooks/useEntityForm.d.ts.map +1 -1
- package/dist/forms/hooks/useEntityForm.js +1 -1
- package/dist/forms/hooks/useFormDraftState.d.ts +53 -0
- package/dist/forms/hooks/useFormDraftState.d.ts.map +1 -0
- package/dist/forms/hooks/useFormDraftState.js +1 -0
- package/dist/forms/index.d.ts +6 -2
- package/dist/forms/index.d.ts.map +1 -1
- package/dist/forms/index.js +1 -1
- package/dist/forms/types.d.ts +171 -25
- package/dist/forms/types.d.ts.map +1 -1
- package/dist/forms/utils/buildInitialValues.d.ts +32 -17
- package/dist/forms/utils/buildInitialValues.d.ts.map +1 -1
- package/dist/forms/utils/buildInitialValues.js +1 -1
- package/dist/forms/utils/conditionAwareResolver.d.ts +35 -0
- package/dist/forms/utils/conditionAwareResolver.d.ts.map +1 -0
- package/dist/forms/utils/conditionAwareResolver.js +1 -0
- package/dist/forms/utils/emptyValue.d.ts +34 -0
- package/dist/forms/utils/emptyValue.d.ts.map +1 -0
- package/dist/forms/utils/emptyValue.js +1 -0
- package/dist/forms/utils/getFieldsForOperation.d.ts +30 -19
- package/dist/forms/utils/getFieldsForOperation.d.ts.map +1 -1
- package/dist/forms/utils/getFieldsForOperation.js +1 -1
- package/dist/forms/utils/index.d.ts +1 -0
- package/dist/forms/utils/index.d.ts.map +1 -1
- package/dist/forms/utils/index.js +1 -1
- package/dist/forms/utils/isFieldEditable.d.ts +21 -22
- package/dist/forms/utils/isFieldEditable.d.ts.map +1 -1
- package/dist/forms/utils/isFieldEditable.js +1 -1
- package/dist/forms/utils/writableFields.d.ts +19 -0
- package/dist/forms/utils/writableFields.d.ts.map +1 -0
- package/dist/forms/utils/writableFields.js +1 -0
- package/dist/hooks/index.d.ts +2 -0
- package/dist/hooks/index.d.ts.map +1 -1
- package/dist/hooks/index.js +1 -1
- package/dist/hooks/useChildRows.d.ts +161 -0
- package/dist/hooks/useChildRows.d.ts.map +1 -0
- package/dist/hooks/useChildRows.js +1 -0
- package/dist/hooks/useCrudFilters.d.ts +21 -1
- package/dist/hooks/useCrudFilters.d.ts.map +1 -1
- package/dist/hooks/useCrudFilters.js +1 -1
- package/dist/hooks/useExtensionRows.d.ts +24 -0
- package/dist/hooks/useExtensionRows.d.ts.map +1 -0
- package/dist/hooks/useExtensionRows.js +1 -0
- package/dist/hooks/useFieldConditions.d.ts +2 -2
- package/dist/hooks/useFieldConditions.d.ts.map +1 -1
- package/dist/hooks/useFieldConditions.js +1 -1
- package/dist/hooks/useReferenceResolver.d.ts +4 -1
- package/dist/hooks/useReferenceResolver.d.ts.map +1 -1
- package/dist/hooks/useReferenceResolver.js +1 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/registerBuiltinFieldTypes.d.ts +2 -0
- package/dist/registerBuiltinFieldTypes.d.ts.map +1 -1
- package/dist/registerBuiltinFieldTypes.js +1 -1
- package/dist/stores/FormStore.d.ts +116 -5
- package/dist/stores/FormStore.d.ts.map +1 -1
- package/dist/stores/FormStore.js +1 -1
- package/dist/stores/UploadStore.js +1 -1
- package/dist/stores/index.d.ts +1 -1
- package/dist/stores/index.d.ts.map +1 -1
- package/dist/stores/index.js +1 -1
- package/dist/symbol-index.json +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types.d.ts +38 -6
- package/dist/types.d.ts.map +1 -1
- package/dist/useCrud.d.ts +7 -5
- package/dist/useCrud.d.ts.map +1 -1
- package/dist/useCrud.js +1 -1
- package/dist/useCrudDoc.js +1 -1
- package/dist/utils/clientListProcessing.d.ts +9 -12
- package/dist/utils/clientListProcessing.d.ts.map +1 -1
- package/dist/utils/clientListProcessing.js +1 -1
- package/dist/utils/collections.d.ts.map +1 -1
- package/dist/utils/collections.js +1 -1
- package/dist/utils/filterUrl.d.ts +45 -0
- package/dist/utils/filterUrl.d.ts.map +1 -0
- package/dist/utils/filterUrl.js +1 -0
- package/dist/utils/matchesFilter.d.ts +27 -3
- package/dist/utils/matchesFilter.d.ts.map +1 -1
- package/dist/utils/matchesFilter.js +1 -1
- package/dist/utils/uploadValidation.js +1 -1
- package/dist/utils/useRowTranslator.js +1 -1
- package/guidelines/COMPONENTS.md +82 -11
- package/guidelines/CRUD.md +242 -7
- package/guidelines/GOTCHAS.md +17 -1
- package/package.json +3 -3
package/guidelines/CRUD.md
CHANGED
|
@@ -28,6 +28,8 @@ export const productEntity = defineEntity({
|
|
|
28
28
|
|
|
29
29
|
**Auto-added fields:** `id`, `createdAt`, `updatedAt`, `createdById`, `updatedById`, `status`.
|
|
30
30
|
|
|
31
|
+
**Field help:** `hint: 'hints.slug'` (a key of the entity namespace) puts an (i) after the field's label in entity forms: hover or focus shows the translated text, a tap pins it on touch screens. Opt-in: no `hint`, no (i). Shown by the fields with a floating label (text, textarea, number, currency, password, phone, select, combobox, multiselect, reference, year, date, timestamp, multi-text, address, price); checkbox, switch, radio, rating, range and upload fields do not show it yet.
|
|
32
|
+
|
|
31
33
|
**Reference fields** (`type: 'reference'`, `validation: { reference: 'brands' }`) show labels, not ids, in `EntityList` and the form combobox with no app code. `defineEntity()` registers every entity under its collection, and the reference reads the target entity with its own schema (access, visibility, field mapping). Label: `options.fieldSpecific.labelFields` or `displayField`, else the first of `name`, `title`, `label`, `displayName`. A collection with no defined entity keeps showing the raw id (dev warning).
|
|
32
34
|
|
|
33
35
|
See `lookup_symbol("defineEntity")` for all options (scope, access, ownership, uniqueKeys, validation).
|
|
@@ -44,7 +46,18 @@ The `status` field is auto-added by `defineEntity()` with sensible defaults:
|
|
|
44
46
|
| `required` | `true` | Yes |
|
|
45
47
|
|
|
46
48
|
**Default options:** `draft`, `available`, `deleted` - always present, cannot be removed.
|
|
47
|
-
**Default value:** `available`.
|
|
49
|
+
**Default value:** `available`. A form, `add()` or a bulk insert is a draft only when you pass `status: 'draft'`; a draft skips `required` validation only: what is filled in keeps its format (`TOTO` is not a phone number, even in a draft).
|
|
50
|
+
|
|
51
|
+
**Validation rules (schemas from `createSchemas`):**
|
|
52
|
+
- **Required** = filled in: `null`, `undefined` and `''` are rejected (forms and grids store an emptied field as `null`).
|
|
53
|
+
- **create** (status other than `draft`): every required field filled in, every value in format.
|
|
54
|
+
- **draft** (`status: 'draft'`, created or edited): required fields may be empty; values in format.
|
|
55
|
+
- **update** (edit of a non-draft record): only the fields that change are validated (rule 2); a field left out or unchanged is not checked, so a record with a legacy empty required field saves until that field is edited. A required field the edit empties is rejected. Leaving `draft` or `deleted` for a strict status checks the whole record (rule 5).
|
|
56
|
+
- **CRUD rules (SSOT: `@donotdev/core`, `core/schemas/src/common/crud/`).** Every write (forms, `useCrud`, `bulk`, `bulkAcross`, child rows, server functions, entity store) goes through `prepareCreate` / `prepareUpdate` / `prepareRemove`; reads through `hiddenStatusesFor` / `isReadableBy`. No site composes a rule itself.
|
|
57
|
+
**Status matrix (SSOT: `STATUS_MATRIX`, `@donotdev/types`).** One table says what each status can do: `draft` (read: admin, saveIncomplete, holdIncomplete), `available` (read: guest, isDefault), `deleted` (read: admin, holdIncomplete, isRemoved). App-added statuses behave like `available`. Code asks it (`statusCan(status, capability)`, `statusReadableBy(status, role)`, `statusesThat(capability)`), never names a status; the entity-derived types (rows, forms, inputs) read the same columns.
|
|
58
|
+
1. Create validates everything. 2. Update validates what changes (a required field it sends cannot be emptied, except on a draft). 3. `delete(id)` is the hard delete; `remove(id)` the logical delete (the `isRemoved` status, nothing else validated). 4. A row is read only by roles that reach its status's `read` role. 5. A status that `saveIncomplete` saves without its required fields; leaving a status that may `holdIncomplete` for one that may not checks the whole record. 6. Apps add statuses; they are strict like `available`. 7. No status sent → the `isDefault` status; the caller overrides it (`defaultValues.status`, payload `status`). 8. Fields the entity does not have are not written and warn the user (client toast, server log). 9. Field behaviour comes from the entity (`editable`, `visibility`, `computed` / `generated`).
|
|
59
|
+
An update needs the stored row (its status, and the whole-record check): writers take the caller's (`bulkAcross` update `stored`, the form's `record`), else the cache, else read it once.
|
|
60
|
+
- **`tel`:** international (`+` country code, 8 to 15 digits, as E.164: `+33 6 12 34 56 78`, `+33612345678`) or French national (`06 12 34 56 78`, `0612345678`, `06.12.34.56.78`); spaces, dots or dashes between digits. `validation.pattern` replaces the rule. The phone field stores `<dial code> <number>`, nothing when no number is typed.
|
|
48
61
|
|
|
49
62
|
If you don't define `status` in your fields at all, the full default is added automatically. If you define it, your properties are merged on top of defaults:
|
|
50
63
|
|
|
@@ -144,7 +157,7 @@ Drop components on a page. Entity drives the UI - no configuration needed.
|
|
|
144
157
|
|
|
145
158
|
Use `lookup_symbol("ComponentName")` for full props.
|
|
146
159
|
|
|
147
|
-
**`EntityList` rows:** open-link icon (real `<a href>`, Ctrl/Cmd-click opens a tab; with `onClick` it is a button) · checkbox (bulk select; the header selects every filtered row across pages) · the list fields, **edited in their cells by default** (text, number, select, radio, reference). Checked rows take one value per field from the bulk bar, or are deleted together ("Delete selected", one `bulk({ deletes })`); Save writes every cell change in one `bulk({ updates })`; rows that fail stay pending (still marked) with an error count, saved rows leave the pending set. `editable={false}`: read-only cells, a row click opens the record.
|
|
160
|
+
**`EntityList` rows:** open-link icon (real `<a href>`, Ctrl/Cmd-click opens a tab; with `onClick` it is a button) · checkbox (bulk select; the header selects every filtered row across pages) · the list fields, **edited in their cells by default** (text, number, select, radio, reference). Checked rows take one value per field from the bulk bar, or are deleted together ("Delete selected", one `bulk({ deletes })`); Save writes every cell change in one `bulk({ updates })`; rows that fail stay pending (still marked) with an error count, saved rows leave the pending set. `editable={false}`: read-only list — read-only cells, no Add, no row selection and no delete; a row click (or the open icon) opens the record.
|
|
148
161
|
|
|
149
162
|
**Nested list (parent → children)**, e.g. the products of a brand on the brand page:
|
|
150
163
|
|
|
@@ -152,7 +165,134 @@ Use `lookup_symbol("ComponentName")` for full props.
|
|
|
152
165
|
<EntityList entity={productEntity} basePath="/produits" parent={{ field: 'brandId', value: brandId }} />
|
|
153
166
|
```
|
|
154
167
|
|
|
155
|
-
Lists only that parent's children (server-side `where`), hides the parent column and filter; the add button opens `/produits/new?brandId=…` and `EntityFormRenderer` (create) prefills `brandId` from the URL. `parent.field` must be a `reference` field (throws otherwise). URL prefill only accepts reference fields the viewer may set on create, with an id-shaped value.
|
|
168
|
+
Lists only that parent's children (server-side `where`), hides the parent column and filter; the add button opens `/produits/new?brandId=…` and `EntityFormRenderer` (create) prefills `brandId` from the URL. `parent.field` must be a `reference` field (throws otherwise). URL prefill only accepts reference fields the viewer may set on create, with an id-shaped value. When an edit form is open on that parent record, the list joins it instead — see [Child rows](#child-rows-saved-with-their-record).
|
|
169
|
+
|
|
170
|
+
**Overrides (optional):** `extraColumns` — app columns after the list fields, `{ key, title, render(row), align? }`, `render` gets the row with its unsaved edits applied (computed values); `actions` — app toolbar content (it can call `useChildRows` on the same entity + parent). Web only: the Expo `EntityList` throws when given either.
|
|
171
|
+
|
|
172
|
+
---
|
|
173
|
+
|
|
174
|
+
## Child rows (saved with their record)
|
|
175
|
+
|
|
176
|
+
On a record's page, its child rows (1:N, including link tables N:M with data on the link) are edited, added and removed, kept with the record's unsaved edits, and saved by the record's Save. Opt-in by usage: nothing changes for pages that do not put an editable child list next to an open edit form of its parent.
|
|
177
|
+
|
|
178
|
+
```tsx
|
|
179
|
+
// Zero wiring: the form's default writer saves the campaign and its products.
|
|
180
|
+
<EntityFormRenderer entity={campaignEntity} defaultValues={campaign} successPath={null} />
|
|
181
|
+
<EntityList entity={campaignProductEntity} parent={{ field: 'campaignId', value: campaign?.id ?? null }} />
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
- **Join (automatic).** The parent collection is the child field's `validation.reference`. A mounted `useEntityForm` in edit mode (also inside `EntityFormRenderer`) registers its record in `FormStore`; child rows of that record join the **latest** form opened on it (when it closes, the previous one is the target again). Joined edits live in that form's draft: autosaved, restored with it ("Draft restored" toast), reset by its Discard / `resetForm`, kept when the save fails (also after an optimistic leave).
|
|
185
|
+
- **`EntityList` with `parent`, joined** (the list is `editable`, the default, and an edit form is open on the parent; `editable={false}` lists never join): no own Save, delete waits for the form's Save, pending count + Discard shown, every line of the parent shown (no filters section, search, export or pagination). Add, never a navigation: link table (the child has exactly one reference field besides the parent's) → dialog with `EntityFilters` (for the viewer's role, with its own filter state: the lists of that collection keep theirs) + text search + selectable list of the other side's records, deleted (`status: 'deleted'`) and already-linked ones excluded, multi-select → unsaved rows (the other side's entity must be defined with `defineEntity`, throws otherwise); any other child → one blank row (schema defaults). Without an open form on the parent: exactly the standalone behaviour above (own Save, immediate delete, add opens the create page).
|
|
186
|
+
- **Create mode:** `parent.value: null` (record not saved yet) → the list only shows "Create the draft before adding …" (`crud:childRows.createFirst`). Rows are added after the first save.
|
|
187
|
+
- **Saving.** `form.handleSubmit()` **without** `onValid` (or `EntityFormRenderer` without `onSubmit`) is the default writer: the record (update, or add on create) with the fields the form writes for the viewer (inputs editable for them, `editable: 'computed'` fields, `<name>I18n` companions; on create also the caller's `defaultValues.status` when the viewer may not edit status), plus the joined rows (inserts with pre-minted ids, updates, deletes), in **one `bulkAcross`**. **With** `onValid` the app writes as before and takes the rows' writes from `form.pendingWrites()` (one batch per child collection); if joined rows have edits and `pendingWrites()` was not read during the submit, the submit fails with an explicit error (no silent loss). `EntityFormRenderer`'s `onSubmit` has no form handle: omit it when rows join, or build the page with `useEntityForm`.
|
|
188
|
+
- **Validation (reactive, the record form's rules):** a grid is a shortcut onto the same records. Every add / update is checked with the CRUD rules (extension rows the same, merged with their stored extension; a missing extension: its defaults and edits): an added row with `prepareCreate`, an edited row with `prepareUpdate` on its stored row (only the changed fields, unless it is a draft or leaves draft for a visible status). Only fields the viewer can see are checked; only rows with edits. `rows.errors[rowId][fieldKey]` holds the translated message (`crud:childRows.required` / `invalidValue`); the list marks those cells (DataTable `cellErrors`). A Save with invalid rows is blocked before the optimistic leave with **one** message, the count of rows to fix (`crud:childRows.invalidRows`): the form error (formId set), else a toast; `rows.save()` rejects with it.
|
|
189
|
+
- **After success:** joined edits are cleared and the rows refetched, also when the save stays on the page (`successPath: null`). Edits made while the write was in flight stay.
|
|
190
|
+
- **Partial failure (non-atomic adapters):** after a rejected save the rows refetch; rows that were written leave the edits, rows that were not stay unsaved (same rule as the standalone list). Atomicity is the adapter's (`{ execution: 'atomic' }`) or the app's choice (app writer).
|
|
191
|
+
- **Entity rules:** `entity.access` gates add / edit / remove for the viewer (the form's `viewerRole`, or `useChildRows`' `viewerRole` option); only fields the viewer may write are set; drafts read back from browser storage are validated (shape, writable fields, value types, record-id shape) and edits of rows that no longer exist are dropped.
|
|
192
|
+
|
|
193
|
+
**Custom display — `useChildRows(entity, parent?, options?)`** (`@donotdev/crud`; no `parent` = every record of the entity, standalone, never joined; `options`: `viewerRole`, `extend` — see [1:1 extension](#11-extension-extend)): the same rows for any UI. Every `useChildRows` on the same form + child entity + parent sees the same rows (the page's button and the table agree).
|
|
194
|
+
|
|
195
|
+
```tsx
|
|
196
|
+
const rows = useChildRows(supplyOrderLineEntity, { field: 'supplyOrderId', value: order.id });
|
|
197
|
+
rows.items; // saved rows + unsaved edits applied, added rows, removed rows hidden
|
|
198
|
+
rows.add([{ productId, unitsOrdered: 6 }]); // returns the new ids
|
|
199
|
+
rows.update(id, { unitsOrdered: 12 }); // ordering: update(id, { sortOrder })
|
|
200
|
+
rows.remove(ids); // logical delete on Save; rows.delete(ids): hard delete
|
|
201
|
+
rows.discard();
|
|
202
|
+
rows.hasEdits; rows.pendingCount; rows.loading; rows.error; rows.access; // { create, update, delete }
|
|
203
|
+
rows.joined; // true when an open form edits the parent record
|
|
204
|
+
rows.save(); // standalone only (no form): writes this instance's edits (one bulk; with extend one bulkAcross); throws when joined or while rows.errors is not empty
|
|
205
|
+
rows.errors; // { [rowId]: { [fieldKey]: message } }, updated on every change
|
|
206
|
+
rows.base; rows.edits; rows.extensionFields; // table data under edits.changes, the edits, visible extension fields
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
`form.pendingWrites()` also carries the form's own 1:1 extensions (below).
|
|
210
|
+
|
|
211
|
+
App writer with joined rows:
|
|
212
|
+
|
|
213
|
+
```tsx
|
|
214
|
+
const form = useEntityForm(campaignEntity, { formId: 'campaign', operation: 'edit', defaultValues: campaign, viewerRole, successPath: null });
|
|
215
|
+
const save = form.handleSubmit(async (values) => {
|
|
216
|
+
await bulkAcross([
|
|
217
|
+
{ collection: campaignEntity.collection, updates: [{ id: campaign.id, patch: toPatch(values) }], schemas: { update } },
|
|
218
|
+
...form.pendingWrites(),
|
|
219
|
+
]);
|
|
220
|
+
});
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
Standalone `useChildRows` (no form on the parent): edits stay in memory for that instance (not persisted); `save()` writes exactly the edits it snapshots in one `bulk` (partial success: rows that fail stay unsaved). On success what it sent leaves the edits at once (no wait for a refetch); edits made during the save stay pending; on failure everything stays. `useJoinedForm(entity, parent)` returns the open form the rows join, or `null`.
|
|
224
|
+
|
|
225
|
+
---
|
|
226
|
+
|
|
227
|
+
## 1:1 extension (`extend`)
|
|
228
|
+
|
|
229
|
+
A record split across two tables (e.g. `products` public + `product_offers` private, unique `productId`) is read, edited and saved as one.
|
|
230
|
+
|
|
231
|
+
```tsx
|
|
232
|
+
const extend = { offer: { entity: productOfferEntity, field: 'productId' } };
|
|
233
|
+
useChildRows(productEntity, { field: 'brandId', value: brand.id }, { extend }); // a brand's products
|
|
234
|
+
useChildRows(productEntity, undefined, { extend }); // all products
|
|
235
|
+
useEntityForm(productEntity, { formId: 'product', operation: 'edit', defaultValues: product, viewerRole, extend });
|
|
236
|
+
<EntityList entity={productEntity} parent={{ field: 'brandId', value: brand.id }} extend={extend} />
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
- **Spec:** `extend: { [key]: { entity, field } }` — `field` is the extension entity's `reference` to the extended collection (throws otherwise); `key` must not contain `.` nor be a field of the extended entity. Keep the same keys while mounted (throws when they change); use the same `extend` on every `useChildRows` of the same rows.
|
|
240
|
+
- **Read:** one batched query per loaded set (`field in [ids]`, chunked by 30 — Firestore's `in` limit), cached under the extension collection (refetched when it is invalidated, merged with its optimistic writes). Rows get the extension under the key (`row.offer.priceExclVat`, `row.offer === null` when missing) and as flat `offer.priceExclVat` values. The form reads the edited record's extension and waits for it before initializing.
|
|
241
|
+
- **Fields:** extension fields are addressed with the key prefix — `offer.priceExclVat` — in `form.fields` (`FormFieldRenderer`, values under `values.offer`), list cells, edits (`rows.update(id, { 'offer.priceExclVat': 12 })`), validation, drafts and uploads. No name collisions (id, status, audit fields stay apart). The extension's id, link field, `status` and backend-generated fields are never shown nor written by the viewer. Extension fields' `conditions` read the extension's values (`RenderableField.scope`).
|
|
242
|
+
- **Stable ids:** every id a write mints (a new record on create, a missing extension row) is the same on repeated `pendingWrites()` calls and retries until the write succeeds (kept in `FormStore.mintedIds`, released on success / once the row is loaded), so a retry never inserts twice.
|
|
243
|
+
- **Write:** extension patches go in the same writes — the form's default writer and `form.pendingWrites()`, the joined rows, `rows.save()`: update of the existing extension row, or **insert of a missing one on Save** (link field = the record; schema defaults). On create the extension insert depends on the record insert (`dependsOn`): the default writer pre-mints the record id; an app writer passes it: `form.pendingWrites({ recordId })`. An added child row always gets its extension (when the viewer may create it).
|
|
244
|
+
- **Validation:** like the record's own fields (edit = the update schema, draft = the draft schema, insert = the create schema; a missing extension is inserted, so its required fields apply).
|
|
245
|
+
- **Entity rules:** a viewer without `access.read` on the extension entity gets no extension fields (same as a hidden field), never an error and never its data (nothing is read). Without `access.create` / `access.update` its fields are read-only (no insert / update).
|
|
246
|
+
- **`EntityList` with `extend`:** the list is a display of `useChildRows` — joined to an open parent form as above, or standalone: filters, search, pagination, export and its own Save (rows and extensions in one `bulkAcross`; deletes wait for that Save). Extension columns = the extension entity's `listFields` (all its visible fields without), prefixed. Web only (Expo throws).
|
|
247
|
+
|
|
248
|
+
---
|
|
249
|
+
|
|
250
|
+
## Custom Forms: `useEntityForm` Contract
|
|
251
|
+
|
|
252
|
+
Prefer `EntityFormRenderer` from `@donotdev/ui` for a complete entity form. Use `useEntityForm` from `@donotdev/crud` when a custom layout is needed.
|
|
253
|
+
|
|
254
|
+
**Translations are automatic. Do not pass `t` for normal framework usage.** `useEntityForm` binds `[entity.namespace, 'crud']` itself, including language changes and SSR request language. Each entity form resolves its own namespace, including several entities on one page.
|
|
255
|
+
|
|
256
|
+
```tsx
|
|
257
|
+
import { useAuth } from '@donotdev/auth';
|
|
258
|
+
import { useEntityForm } from '@donotdev/crud';
|
|
259
|
+
|
|
260
|
+
const viewerRole = useAuth('userRole');
|
|
261
|
+
const form = useEntityForm(productEntity, {
|
|
262
|
+
formId: 'product-create',
|
|
263
|
+
operation: 'create',
|
|
264
|
+
viewerRole,
|
|
265
|
+
});
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
**Override only when intentional:** To bypass the default entity + CRUD namespace resolution, supply your own `t`. It replaces the default translator completely; it is not merged with it.
|
|
269
|
+
|
|
270
|
+
```tsx
|
|
271
|
+
const { t: tCustom } = useTranslation('custom-form');
|
|
272
|
+
const form = useEntityForm(productEntity, {
|
|
273
|
+
formId: 'product-custom',
|
|
274
|
+
operation: 'create',
|
|
275
|
+
viewerRole,
|
|
276
|
+
t: tCustom,
|
|
277
|
+
});
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
- **Each entity gets its own translator automatically.** A page editing shop settings and admin settings needs no translation wiring for either form.
|
|
281
|
+
- **Pass `form.t` to field renderers.** `FormFieldRenderer` takes `name`, `config`, `control` and `t`; `DisplayFieldRenderer` takes `name`, `config`, `value` and `t`. Labels, hints, select options and field-array child fields need the same entity translator. Never copy entity strings/options into page locales to hide a missing `t`.
|
|
282
|
+
- **Pass the real `viewerRole`.** Omission means `'guest'`, not the signed-in user's role: a guest form writes only guest-visible fields. Use the returned fields' `editable` / `written` flags and `useFieldConditions` for live visibility/required/disabled/readonly conditions in custom layouts.
|
|
283
|
+
- **Form state = the fields the form writes** (`FormValues<E, Op>`, from the entity descriptor): inputs editable for the viewer and operation, `editable: 'computed'` fields, their `<name>I18n` companions, and `id` on edit. Generated, `editable: false` and role-denied fields never enter form state, the local draft or the payload; `form.getValues('<such field>')` is `undefined`. Technical fields (`visibility: 'technical'`) never enter it on create; on edit only a technical field with a role in `editable` (`editable: 'admin'`) does, for a viewer who sees technical fields (admin and above) and holds that role (an optional key in `FormValues<E, 'edit'>`); technical fields with `editable` unset / `true` / `'create-only'` never do. So the scope field (`entity.scope`: technical, `create-only`) is never in form state: the save injects it (`injectScope`). With `extend`, each 1:1 extension's values sit under its key (`values.offer`, typed `FormValues<E, Op, X>`: the extension's written fields without its link field and `status`, with `id` when its row exists; key optional). The resolver validates and outputs only these fields, so `handleSubmit(onValid)` passes `onValid` a `FormValues<E, Op, X>`; `EntityFormRenderer`'s `onSubmit` / `onSecondarySubmit` get the same projection. Form state (React Hook Form's `TFieldValues`: `control`, `watch`, `getValues`, `setValue`, `onInvalid`'s errors) is typed `EntityFormState<E, X>` = `FormValues<E, FieldOperation, X>` (both operations); `Op` keys only the submitted values (RHF's `TTransformedValues`: `onValid`'s argument). RHF's types are invariant in their field values and covariant in the submitted ones, so every form of `E`, `create` or `edit`, is an `EntityFormReturn<E>`: helpers take `<E extends AnyEntity>(form: EntityFormReturn<E>)`, components typed `control: Control<EntityFormState<E>>` take its `control`; a helper taking a form with `extend` declares `X` (`EntityFormReturn<E, FieldOperation, X>`). `useEntityField`, `useFieldConditions` and `FormFieldRenderer` take any form of `E`.
|
|
284
|
+
- **`form.record`** is the stored row the edit started from (`defaultValues` on edit, 1:1 extension rows under their key; `undefined` on create). It is saved with the local draft and restored with it: read a concurrency token from `form.record` (`form.record?.revision`), not from form state, so a restored draft keeps its base version. A restored draft whose base row's `updatedAt` differs from the stored row's is a **conflict**: a persistent warning (`crud:draft.conflict`) with Discard; `form.record` stays the draft's base, so a revision-checked save refuses instead of overwriting. A draft saved for edits made after a successful save has no base row: on return, the stored row is the base. Display fields the form does not write from `form.record` (`EntityFormRenderer` does: technical, `editable: false` and role-denied fields read-only from the record; computed fields read-only from form state).
|
|
285
|
+
- **`defaultValues`:** on edit the stored row as read (`InferEntityRow<E>`, accepted as-is: no `?? ''` needed); on create `Partial<CreateInput<E>>` (caller defaults, e.g. `status: 'draft'`, a parent reference).
|
|
286
|
+
- **`editable: 'computed'`** fields are shown read-only and written: the value a field component sets with `setValue` is saved by the default writer and passed to `onValid`.
|
|
287
|
+
- **Give each form a stable, unique `formId`.** This scopes drafts, upload orchestration and form status; several forms on one page must not share it.
|
|
288
|
+
- **Edit stored values.** Read with `useCrudDoc(entity, id, { translate: false })` before passing `defaultValues`; do not save translated record content back as the default-language value.
|
|
289
|
+
- **Submit through `form.handleSubmit`.** It validates/orchestrates the form; your submit callback performs the CRUD write (or omit it: `form.handleSubmit()` is the default writer, record + joined child rows in one `bulkAcross` — see [Child rows](#child-rows-saved-with-their-record); with a callback, add `form.pendingWrites()` to your write when child rows join the form or `extend` is set; record + 1:1 extensions with `extend`, see [1:1 extension](#11-extension-extend)). Reject on a failed write so submission does not acknowledge it as saved. Success acknowledges the editor snapshot taken before async validation, with pending upload previews replaced by the submitted stored assets. Upload normalization alone stays clean; later edits (including changes to upload fields) stay visible, dirty and in the local draft. Right before your callback runs, the editor is written to the local draft (no 3s autosave wait), so a rejected write keeps every edit even if the page has unmounted; success clears it.
|
|
290
|
+
- **Saving leaves the page by default (optimistic).** Once validation and uploads pass, the form navigates to `successPath` before your callback runs: omitted = the previous breadcrumb (nearest existing parent route, else `/`), a path = that path. If the callback rejects, it navigates back to the page it left and the draft restores the edits. Same option on `EntityFormRenderer` (`successPath`). Router access comes from `@donotdev/ui` (`UIProviders` fills crud's `FormNavigationProvider`); without it the form stays. Pass `successPath: null` to stay: dialogs, wizards, settings pages, create flows that open the new record, pages with other unsaved state (e.g. pending table edits), and **every** form of a nested submit (leaving unmounts the inner form and cancels its save). Per submit: `form.handleSubmit(onValid, onInvalid, { successPath })` overrides the hook option for that submit (key present wins, `undefined` = previous breadcrumb) — e.g. Save on a draft passes `null`, Publish on the same form passes nothing.
|
|
291
|
+
- **Page state saved by the same Save goes in the form's draft.** `const [ids, setIds] = useFormDraftState(form, 'productIds', initialIds, { parse })` is `useState` kept in the form's draft: autosaved with it, written at submit, restored with the form ("Draft restored" toast), reset by Discard / `resetForm`, cleared on success, kept on failure (also after the page left optimistically). Use it for product lists or pending table edits a page Save writes; values must be JSON. A value different from `initial` is an edit (it keeps the draft like a dirty field). `parse` (required) validates the value read back from browser storage (untrusted, possibly from an older page version) and may adjust it (e.g. drop pending edits that already equal the loaded record); if it throws, the slot keeps `initial` and a warning is logged.
|
|
292
|
+
- **A draft exists only while the page holds edits.** Edited = a field dirty in React Hook Form (against `defaultValues`, which always stay the base: the stored record on edit, the caller/schema defaults on create), a `useFormDraftState` slot different from its initial value, or joined child rows with edits. Autosave and the submit-time save write the draft only then, and clear it otherwise. A restored draft is applied as dirty edits on top of the base (`isDirty` / `dirtyFields` are right at once); one with no edit against the base is cleared without a toast.
|
|
293
|
+
- **Create defaults do not disable drafts.** With `operation: 'create'`, caller defaults override schema defaults, then restored drafts merge onto that base (nested objects merge; arrays replace). Discard restores the schema/caller base. Draft autosaving is browser-local only, including edits made while a submission is pending; it performs no CRUD writes. Leaving the page (unmount) writes a pending 3s autosave immediately, so an accidental leave keeps the last edits; the "Draft restored" toast offers Discard on return. There is no leave-time prompt.
|
|
294
|
+
|
|
295
|
+
**GOTCHA:** Do not override `t` with the page translator merely because it is in scope. That bypasses the entity namespace. Use the returned `form.t` for entity fields; keep the page's translator for page headings and actions.
|
|
156
296
|
|
|
157
297
|
---
|
|
158
298
|
|
|
@@ -319,6 +459,98 @@ try {
|
|
|
319
459
|
|
|
320
460
|
See `lookup_symbol("BulkOperations")`, `lookup_symbol("BulkResult")`, `lookup_symbol("BulkCollisionError")`.
|
|
321
461
|
|
|
462
|
+
### Cross-collection `bulkAcross`
|
|
463
|
+
|
|
464
|
+
**Toasts:** one success toast `crud:messages.updateSuccess` named after the first batch's collection (the primary record, like `bulk`), or `options.successMessage` (translated by the caller); the error toast is named the same way.
|
|
465
|
+
|
|
466
|
+
By default `bulkAcross(batches, options?)` is ordered partial-success bulk, **not a database
|
|
467
|
+
transaction**. Each batch supplies its collection, schemas and optional
|
|
468
|
+
`dependsOn`; independent batches run in parallel waves. Success returns
|
|
469
|
+
`{ results: Record<string, BulkResult> }` unchanged.
|
|
470
|
+
|
|
471
|
+
A rejection or non-empty `failed` stops subsequent waves. All bounded timeout
|
|
472
|
+
outcomes in the started wave settle before all optimistic changes are reverted;
|
|
473
|
+
only then are collections invalidated/refetched. Raw attempts are observed, not
|
|
474
|
+
awaited indefinitely. Any raw attempt settling after rollback or successful
|
|
475
|
+
confirmation queues an authoritative refetch, serialized behind initial/late
|
|
476
|
+
refetches, with no stale optimistic patches. Late refetch errors are caught and
|
|
477
|
+
reported, never substituted for the original write error. The call rejects through
|
|
478
|
+
the existing `handleError` normalization (not guaranteed error identity), rather
|
|
479
|
+
than returning partial results. Written rows remain written: a product insert
|
|
480
|
+
survives a dependent offer failure. Optimistic rollback is not database rollback.
|
|
481
|
+
Refetch failures cannot guarantee a fresh cache.
|
|
482
|
+
|
|
483
|
+
Cross-collection bulk writes use the existing timeout without automatic retry:
|
|
484
|
+
a timeout/network failure may have committed already. Late reconciliation prevents
|
|
485
|
+
stale cache races, not duplicate writes; do not blindly resubmit the whole operation. A forever-pending
|
|
486
|
+
raw attempt does not delay caller completion/loading cleanup after bounded outcomes
|
|
487
|
+
and initial refetches; its commit status remains unknown until settlement. Refetch
|
|
488
|
+
completion behavior is unchanged. Global retry policy/provider guarantees are
|
|
489
|
+
separate preexisting work.
|
|
490
|
+
|
|
491
|
+
For a single database commit, request `{ execution: 'atomic' }`. The configured
|
|
492
|
+
adapter must advertise the atomic capability or the call rejects before optimistic
|
|
493
|
+
changes, including for empty requests. The service preflights the complete request,
|
|
494
|
+
then executes its snapshot-bound plan once without retry; legacy void preflight uses
|
|
495
|
+
`execute(prepared)`. Malformed non-void plans reject before optimism.
|
|
496
|
+
`AtomicBulkError.outcome` is `not-committed` only
|
|
497
|
+
when definitive; `unknown` requires authoritative reconciliation, not replay.
|
|
498
|
+
Pre-mint referenced IDs; no automatic reference remapping occurs. Provider-owned
|
|
499
|
+
emulator and security-rule tests remain the gate for deployment guarantees. See
|
|
500
|
+
`docs/architecture/BULK_ACROSS.md`.
|
|
501
|
+
|
|
502
|
+
**F05 — request-aware acknowledgements.** `validateBulkOutcome` uses additive
|
|
503
|
+
`BulkOutcomeSchema` to preserve per-row `failed` (insert index; update/delete ID)
|
|
504
|
+
and checks exactly one outcome per submitted operation, counts, multiplicity and
|
|
505
|
+
update/delete order before confirmations or downstream waves. Omitted `failed`
|
|
506
|
+
is legacy complete-success only after those checks; malformed/incomplete replies
|
|
507
|
+
mean unknown commit status, not proof of rollback. Cleanup removes this call's
|
|
508
|
+
pending optimistic entries before authoritative refetch; original write errors
|
|
509
|
+
must survive reconciliation errors. Functions/REST/GraphQL decoding preserves
|
|
510
|
+
failures when present. The legacy GraphQL selection/SDL exposes only success ID
|
|
511
|
+
arrays: partial replies without failure identities reject, rather than silently
|
|
512
|
+
succeed. Server-generated insert ID correspondence/order remains unprovable
|
|
513
|
+
without an input-index echo; explicit insert IDs are not a universal provider
|
|
514
|
+
guarantee. F05 does not close these legacy provider protocol gaps.
|
|
515
|
+
|
|
516
|
+
---
|
|
517
|
+
|
|
518
|
+
## 9. Filters (`EntityFilters`, `useCrudFilters`, `applyFilters`)
|
|
519
|
+
|
|
520
|
+
`EntityFilters` (`@donotdev/crud`) builds one filter per filterable field of `fieldsToFilter` (default: `listFields`, else all fields) visible to `viewerRole`, and reads/writes the filter state of `useCrudFilters({ collection: filterKey ?? entity.collection })`. `useCrudList` / `useCrudCardList` (and `EntityList` / `EntityCardList`) apply the state of their collection with `applyFilters`: every field filter must match (AND across fields).
|
|
521
|
+
|
|
522
|
+
**Matching per filter type** (`getFilterType(field.type)`, `matchesFilter`):
|
|
523
|
+
|
|
524
|
+
| Filter type | Field types | UI | Match |
|
|
525
|
+
|---|---|---|---|
|
|
526
|
+
| `select` | `select`, `combobox`, `radio`, `boolean`, `checkbox`, `switch` | Multi-select of `validation.options` (translated labels; else the values in the data) | Exact, case-sensitive value; several selected values = OR (`['serum', 'essence']`) |
|
|
527
|
+
| `multiselect` | `multiselect` | Multi-select of `validation.options` | Any of the row's items is selected (`['dry','oily']` matches `['oily']`) |
|
|
528
|
+
| `reference` | `reference` (custom types with `validation.reference`: register `filterType: 'reference'`) | Multi-select of the ids in the data, labelled like list cells (`useReferenceResolver`: `labelFields` / `displayField`; raw id until resolved or when the document is unknown) | Exact id; several = OR |
|
|
529
|
+
| `text`, `address` | text-like types, `address` | One value among the data's values | Case-insensitive substring (`address`: of `formatted_address`) |
|
|
530
|
+
| `range` | number, price (`amount`), date, year... | Min/max | Inclusive; min-only excludes empty values, max-only keeps them |
|
|
531
|
+
| `rating` | `rating` | Stars | At least the value |
|
|
532
|
+
|
|
533
|
+
Options are counted per stored value from the rows matching the other filters (array values: per item) and disabled at 0. Chips show the option's translated label / the reference's resolved label. A multi-select shows its selection: the label of one value, `filters.selected` (`{{count}} selected`, pluralised) for several. A filter state value may be a string or an array for option fields (`setFilters({ type: 'toner' })` still works); `EntityFilters` writes arrays.
|
|
534
|
+
|
|
535
|
+
**Wildcard value** (`field.filter.wildcard`, since 0.3.0): a stored value meaning "every option".
|
|
536
|
+
|
|
537
|
+
```typescript
|
|
538
|
+
skinTypes: { name: 'skinTypes', type: 'multiselect', filter: { wildcard: 'all' }, validation: { options: [...] }, ... }
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
`all` is not offered as a filter choice; a row holding it (value or array item) matches any selection of that field and counts for every option. Applies to `select`, `multiselect` and `reference` filters (`applyFilters`, `EntityFilters`; direct `matchesFilter` callers pass `field.filter` as 4th argument).
|
|
542
|
+
|
|
543
|
+
**URL sync** (since 0.3.0): a filter state syncs with the URL when its key is the collection of an entity defined with `defineEntity` (the page list's state). Pickers and dialogs with a custom `filterKey` never touch the URL.
|
|
544
|
+
|
|
545
|
+
| | |
|
|
546
|
+
|---|---|
|
|
547
|
+
| Write | `setFilters` → `history.replaceState` after 500ms (router state and hash kept), dropped if the page changed meanwhile. Only the entity's own `f_*` params are rewritten. |
|
|
548
|
+
| Read | Page mount (`useCrudFilters` effect: render never writes the store; the first client render already shows the URL's filters), and every URL change: back/forward, router navigations, links (Navigation API `currententrychange`; without it, `popstate` + mount). A URL without params clears the state. Server render and hydration: no filters (no hydration mismatch), the URL's apply right after. |
|
|
549
|
+
| Format | `f_<field>=<value>` percent-encoded (commas safe). Option fields (`select`, `multiselect`, `reference`): one param per value, always read back as an array (`?f_type=serum&f_type=essence`). Ranges: `f_<field>_min` / `f_<field>_max`. Text: one param, a string. Field types decide, not the value. |
|
|
550
|
+
| Opt-out / in | `useCrudFilters({ collection: 'products', urlSync: false })` (or `<EntityFilters urlSync={false} />`); a custom key: `<EntityFilters filterKey="products#dialog" urlSync />` (`useCrudFilters` needs `entity` then). Store level: `useCrudStore.getState().setFilterUrlSync(key, entity \| null)`. |
|
|
551
|
+
|
|
552
|
+
One URL-synced state per page: another collection's list on the same page reads the same `f_<field>` params when field names coincide (e.g. `f_status`); set `urlSync: false` on it.
|
|
553
|
+
|
|
322
554
|
---
|
|
323
555
|
|
|
324
556
|
## What's Available
|
|
@@ -372,8 +604,9 @@ See `lookup_symbol("BulkOperations")`, `lookup_symbol("BulkResult")`, `lookup_sy
|
|
|
372
604
|
| `useCrudDoc` | One document, reactive to every edit/delete (detail pages) |
|
|
373
605
|
| `useCrudList` | Real-time list with search, filters, sort applied |
|
|
374
606
|
| `useCrudCardList` | Same as `useCrudList`, optimized for public card views |
|
|
375
|
-
| `useCrudFilters` | Filter state per collection, auto-consumed by list hooks |
|
|
607
|
+
| `useCrudFilters` | Filter state per collection (URL-synced for entity collections, see [Filters](#9-filters-entityfilters-usecrudfilters-applyfilters)), auto-consumed by list hooks |
|
|
376
608
|
| `useEntityForm` | Form state for custom form layouts |
|
|
609
|
+
| `useChildRows` | A record's child rows, joined to the form open on it and saved by its Save |
|
|
377
610
|
| `useEntityField` | Single-field control for custom form layouts |
|
|
378
611
|
| `useEntityFavorites` | Local favorites (localStorage) |
|
|
379
612
|
| `useRelatedItems` | Fetch related items by reference field |
|
|
@@ -385,10 +618,10 @@ See `lookup_symbol("BulkOperations")`, `lookup_symbol("BulkResult")`, `lookup_sy
|
|
|
385
618
|
| Utility | One-liner |
|
|
386
619
|
|---------|-----------|
|
|
387
620
|
| `formatValue` | Format any field value for display |
|
|
388
|
-
| `applyFilters` / `applySearch` / `applySort` | Processing pipeline (what `useCrudList` does internally) |
|
|
621
|
+
| `applyFilters` / `applySearch` / `applySort` | Processing pipeline (what `useCrudList` does internally); `matchesFilter` one value ([Filters](#9-filters-entityfilters-usecrudfilters-applyfilters)) |
|
|
389
622
|
| `registerFieldType` | Register custom field type |
|
|
390
623
|
| `validateEntity` | Validate entity data against schemas |
|
|
391
|
-
| `isFieldEditable` / `getFieldsForOperation` | Field
|
|
624
|
+
| `isFieldEditable(entity, field, role, op)` / `getFieldsForOperation` | Field editability / form fields, from the entity descriptor |
|
|
392
625
|
|
|
393
626
|
### Routing (`@donotdev/ui`)
|
|
394
627
|
|
|
@@ -449,7 +682,9 @@ registerFieldType({
|
|
|
449
682
|
});
|
|
450
683
|
```
|
|
451
684
|
|
|
452
|
-
Then use in entity: `tier: { name: 'tier', label: 'tier', type: 'statusTier', visibility: 'guest' }`
|
|
685
|
+
Then use in entity, with its value shape: `tier: { name: 'tier', label: 'tier', type: 'statusTier', visibility: 'guest', validation: { schema: v.picklist(['basic', 'premium']) } }`
|
|
686
|
+
|
|
687
|
+
`registerFieldType` is UI-only (client code, invisible to server functions and generators): the entity says the stored value. A custom type needs `validation.schema` (Valibot schema of the stored value) or `validation.reference` (referenced collection: the value is an id). Without either, `defineEntity` throws, naming `entity.field`. Value order, everywhere: `validation.schema` > `validation.reference` > built-in type (`BUILTIN_VALUES`, `@donotdev/core`).
|
|
453
688
|
|
|
454
689
|
Custom display formatters render cards/lists only: entity SEO (`deriveEntitySeo`, also on the Next server) shows a custom type's raw value. For a translated label in both, use the field's `options.displayValue` (or the entity `seo.title`).
|
|
455
690
|
|
package/guidelines/GOTCHAS.md
CHANGED
|
@@ -6,6 +6,8 @@ Common mistakes related to entity definition, forms, fields, and CRUD operations
|
|
|
6
6
|
|
|
7
7
|
## CRUD [Phase 2, 3]
|
|
8
8
|
|
|
9
|
+
**GOTCHA: Do not override `useEntityForm` translations accidentally.** The hook automatically binds `[entity.namespace, 'crud']`; normal usage requires no `t` option, even on multi-entity pages. Pass its returned `form.t` to field renderers. Supply your own `options.t` only to intentionally bypass that namespace resolution: it replaces the default translator completely. Passing a page-bound `t` can therefore hide entity labels/options. Never copy entity strings into page locales. The hook still defaults `viewerRole` to `'guest'`, so pass the actual role. See CRUD → Custom Forms.
|
|
10
|
+
|
|
9
11
|
**Never `get(id)` / `query()` in a `useEffect` to render data.** Effects don't run on the server: on Next.js (SSR) the page HTML is a loader, invisible to crawlers and AI search. Use `useCrudDoc(entity, id)` for one record, `useCrudList` / `useCrudCardList` for lists: they read through the CRUD cache, which the server fills during the render.
|
|
10
12
|
|
|
11
13
|
**Hidden fields are auto-added by `defineEntity()` - don't define them manually:**
|
|
@@ -27,6 +29,20 @@ status: { visibility: 'technical' }
|
|
|
27
29
|
|
|
28
30
|
**Scope field is auto-added** when `scope` is configured. Don't manually define the scope field (e.g., `companyId`).
|
|
29
31
|
|
|
32
|
+
**Empty is `null`, never `''`.** Entity forms store an empty text input as `null` (form state, validated data, adapter payload); `''` exists only in the DOM. An optional field left empty passes its format rules; a `required` field left empty fails.
|
|
33
|
+
|
|
34
|
+
**Field `type` is a closed union.** Built-ins plus the custom types declared in `CustomFieldOptionsMap` (module augmentation of `@donotdev/core`). A typo or an undeclared custom type fails typecheck; a declared type with no `registerFieldType()` throws at render. No text-input fallback.
|
|
35
|
+
|
|
36
|
+
**`datetime-local` stores an ISO instant, displays local time.** The form shows the viewer's local wall time and saves `toISOString()` (UTC). Do not convert in the app.
|
|
37
|
+
|
|
38
|
+
**Filters on option fields are exact, not substring.** `select` / `radio` / `multiselect` / `reference` filters match the stored code or id exactly (`toner` never matches `toner_pad`); only text filters are substring. A stored "suits everything" value (`['all']`) needs `filter: { wildcard: 'all' }` on the field, never an extra filter option. See CRUD.md "Filters".
|
|
39
|
+
|
|
40
|
+
**Picker / dialog filters: give `EntityFilters` a `filterKey`.** Without it, the dialog shares (and URL-syncs) the page list's filter state. A custom key never touches the URL unless `urlSync` is set. See CRUD.md "Filters" (URL sync).
|
|
41
|
+
|
|
42
|
+
**Several forms on one record: give each a stable `formId`.** The auto-saved draft key includes it.
|
|
43
|
+
|
|
44
|
+
**A field the form does not render must not be `required` without a value.** Form validation uses the static `validation`: a required field hidden by `visibility` (role), `editable` or `conditions.visible` fails on submit unless its value comes in through `defaultValues`. The scope field is the exception: the form injects it from the scope provider before validating, as `add()` does.
|
|
45
|
+
|
|
30
46
|
**Custom form fields MUST use framework's `useController`:**
|
|
31
47
|
|
|
32
48
|
```typescript
|
|
@@ -43,6 +59,6 @@ import { useController } from '@donotdev/crud';
|
|
|
43
59
|
|
|
44
60
|
**File uploads are deferred** - files upload on form submit, not on selection. Images show optimistic blob URLs.
|
|
45
61
|
|
|
46
|
-
**Generated
|
|
62
|
+
**Generated fields are excluded from forms; computed fields are shown read-only.** Fields with `editable: 'generated'` (DB-generated columns) are left out of create and edit forms and never written. Fields with `editable: 'computed'` (UI-derived values) are shown read-only by `getFieldsForOperation` (`editable: false`, `written: true`), kept in form state and written by the default writer. Use `'generated'` for PostgreSQL `GENERATED ALWAYS` columns. Use `'computed'` for fields derived from other form values.
|
|
47
63
|
|
|
48
64
|
**Entity namespace defaults to `entity-{name}`** (lowercase). Translation files must match: `locales/entity-product_en.json`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@donotdev/crud",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -56,8 +56,8 @@
|
|
|
56
56
|
"@dnd-kit/core": "^6.3.1",
|
|
57
57
|
"@dnd-kit/sortable": "^10.0.0",
|
|
58
58
|
"@dnd-kit/utilities": "^3.2.2",
|
|
59
|
-
"@donotdev/components": "^0.
|
|
60
|
-
"@donotdev/core": "^0.
|
|
59
|
+
"@donotdev/components": "^0.3.0",
|
|
60
|
+
"@donotdev/core": "^0.3.0",
|
|
61
61
|
"react-easy-crop": "^5.5.7"
|
|
62
62
|
},
|
|
63
63
|
"peerDependencies": {
|