@rebasepro/cms 0.27.0 → 0.28.1
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/collection_editor/serializable_utils.js +5 -2
- package/dist/collection_editor/serializable_utils.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/EnumForm.d.ts +17 -0
- package/dist/collection_editor/ui/collection_editor/EnumForm.js +31 -17
- package/dist/collection_editor/ui/collection_editor/EnumForm.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/EnumPropertyField.js +6 -5
- package/dist/collection_editor/ui/collection_editor/properties/EnumPropertyField.js.map +1 -1
- package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js +3 -2
- package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionListViewBinding.js +32 -16
- package/dist/components/CollectionViewBinding/CollectionListViewBinding.js.map +1 -1
- package/dist/components/DetailViewBinding.js +4 -3
- package/dist/components/DetailViewBinding.js.map +1 -1
- package/dist/components/EditViewBinding.js +23 -5
- package/dist/components/EditViewBinding.js.map +1 -1
- package/dist/components/EntityPreviewBinding.js +1 -0
- package/dist/components/EntityPreviewBinding.js.map +1 -1
- package/dist/components/SelectableTable/filters/StringNumberFilterField.js +3 -3
- package/dist/components/SelectableTable/filters/StringNumberFilterField.js.map +1 -1
- package/dist/components/SidePanelBinding.js +7 -6
- package/dist/components/SidePanelBinding.js.map +1 -1
- package/dist/components/app/Scaffold.js +16 -1
- package/dist/components/app/Scaffold.js.map +1 -1
- package/dist/components/history/EntityHistoryView.js +2 -1
- package/dist/components/history/EntityHistoryView.js.map +1 -1
- package/dist/data_export/export/export.js +3 -3
- package/dist/data_export/export/export.js.map +1 -1
- package/dist/data_import/import/ImportCollectionAction.js +10 -12
- package/dist/data_import/import/ImportCollectionAction.js.map +1 -1
- package/dist/data_import/utils/id_column.d.ts +19 -0
- package/dist/data_import/utils/id_column.js +19 -1
- package/dist/data_import/utils/id_column.js.map +1 -1
- package/dist/data_import/utils/transforms.js +24 -7
- package/dist/data_import/utils/transforms.js.map +1 -1
- package/dist/form/EntityForm.d.ts +1 -1
- package/dist/form/EntityForm.js +14 -4
- package/dist/form/EntityForm.js.map +1 -1
- package/dist/form/EntityFormBinding.js +12 -8
- package/dist/form/EntityFormBinding.js.map +1 -1
- package/dist/form/components/FieldBlock.js +2 -1
- package/dist/form/components/FieldBlock.js.map +1 -1
- package/dist/form/field_bindings/KeyValueFieldBinding.js +3 -1
- package/dist/form/field_bindings/KeyValueFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/ReadOnlyFieldBinding.js +0 -2
- package/dist/form/field_bindings/ReadOnlyFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/TextFieldBinding.js +3 -2
- package/dist/form/field_bindings/TextFieldBinding.js.map +1 -1
- package/dist/form/validation.js +12 -1
- package/dist/form/validation.js.map +1 -1
- package/dist/hooks/navigation/url_segments.d.ts +33 -0
- package/dist/hooks/navigation/url_segments.js +56 -0
- package/dist/hooks/navigation/url_segments.js.map +1 -0
- package/dist/hooks/navigation/useBuildUrlController.js +4 -2
- package/dist/hooks/navigation/useBuildUrlController.js.map +1 -1
- package/dist/hooks/useBuildSidePanel.js +6 -5
- package/dist/hooks/useBuildSidePanel.js.map +1 -1
- package/dist/hooks/useHistory.js +4 -3
- package/dist/hooks/useHistory.js.map +1 -1
- package/dist/routes/RebaseRoute.js +20 -30
- package/dist/routes/RebaseRoute.js.map +1 -1
- package/dist/util/navigation_utils.js +4 -3
- package/dist/util/navigation_utils.js.map +1 -1
- package/package.json +9 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EntityForm.js","names":[],"sources":["../../src/form/EntityForm.tsx"],"sourcesContent":["\nimport type { AdditionalFieldDelegateProps } from \"@rebasepro/cms-types\";\nimport type { FormContext, PropertyFieldBindingProps } from \"../types/fields\";\nimport React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { Entity, EntityStatus, EntityValues } from \"@rebasepro/types\";\nimport type { Properties, Property } from \"@rebasepro/types\";\nimport type { EntityFormProps } from \"../types/components/EntityFormProps\";\nimport { deepEqual as equal } from \"fast-equals\";\n\nimport { ErrorBoundary, isKeyHandled } from \"@rebasepro/ui\";\nimport { AlignLeftIcon, useDebouncedCallback } from \"@rebasepro/ui\";\nimport { effectiveAccess, getCopyValues, getDefaultValuesFor } from \"@rebasepro/common\";\nimport { isDisabled, isHidden, isReadOnly } from \"@rebasepro/app\";\nimport { useAuthController, useCustomizationController, useRebaseContext, useTranslation } from \"@rebasepro/app\";\n\nimport { getFormFieldKeys, resolveFormLayout } from \"@rebasepro/app\";\nimport type { ResolvedFormField } from \"@rebasepro/app\";\nimport { Alert, Button, CircularProgressCenter, cls, defaultBorderMixin, Dialog, DialogActions, DialogContent, DialogTitle, paperMixin, Typography } from \"@rebasepro/ui\";\nimport { Formex, FormexController, useCreateFormex } from \"@rebasepro/forms\";\n\nimport { FieldBlock, isSelfLabellingProperty, LABEL_ICON_SIZE, spanClass } from \"./components/FieldBlock\";\nimport { labelsInsideControl } from \"./label_placement\";\nimport { AdditionalFieldValue } from \"../components/AdditionalFieldValue\";\nimport { FormRail, RecordMeta } from \"./components/FormRail\";\nimport { FormSections } from \"./components/FormSections\";\nimport { useRailVisible } from \"./components/useRailVisible\";\nimport { PropertyFieldBinding } from \"./PropertyFieldBinding\";\nimport { flattenKeys } from \"@rebasepro/app\";\nimport { ErrorFocus } from \"./components/ErrorFocus\";\nimport { applyValueTransforms, CustomFieldValidator, getEntitySchema, uniqueValueErrors } from \"./validation\";\nimport { formViewer, resolveFormProperty, resolvePropertiesForValidation, withoutUnwritableDefaults } from \"./resolve_form_properties\";\nimport { EntityFormActions } from \"./EntityFormActions\";\nimport type { EntityFormActionsProps } from \"../types/components/EntityFormActionsProps\";\nimport { LocalChangesMenu } from \"./components/LocalChangesMenu\";\nimport { useUndoableDiscard } from \"./useUndoableDiscard\";\nimport { ownsKeystroke, registerKeyboardScope } from \"./form_keyboard_scope\";\nimport { createFormUploadTracker, FormUploadsContext } from \"./form_uploads\";\n\nimport {\n getChangedProperties,\n overlayEdit,\n serverViolationErrors,\n withoutUnsetNulls,\n zodToFormErrors\n} from \"./form_utils\";\n\n/**\n * Headless entity form component.\n *\n * Renders a form for a entity collection without any admin or backend dependencies.\n * All backend concerns (save, caching, analytics, plugin slots) are provided via\n * callback props. For admin-connected usage, use {@link EntityFormBinding} instead.\n *\n * @group Components\n */\nexport function EntityForm<M extends Record<string, unknown>>({\n path,\n entityId: entityIdProp,\n collection,\n onValuesModified,\n onIdChange,\n onSaved,\n entity,\n initialDirtyValues,\n onFormContextReady,\n initialStatus,\n className,\n onStatusChange,\n onEntityChange,\n openEntityMode = \"full_screen\",\n formex: formexProp,\n disabled: disabledProp,\n Builder,\n parentCollectionSlugs,\n parentEntityIds,\n EntityFormActionsComponent = EntityFormActions,\n showDefaultActions = true,\n navigateBack: navigateBackProp,\n children,\n // Headless callback props\n onSubmit: onSubmitProp,\n onValuesChangeDeferred: onValuesChangeDeferredProp,\n onReset: onResetProp,\n uniqueFieldValidator: uniqueFieldValidatorProp,\n lockedPropertyKeys,\n // Slots\n beforeFields,\n afterFields,\n pluginActions: pluginActionsProp,\n // Local changes (managed externally)\n computedInitialValues,\n hasLocalChanges: hasLocalChangesProp,\n localChangesData,\n manualApplyLocalChanges,\n localChangesCacheKey,\n onClearLocalChanges\n}: EntityFormProps<M>) {\n\n const navigateBack = useCallback(() => {\n if (navigateBackProp) {\n navigateBackProp();\n }\n }, [navigateBackProp]);\n\n const authController = useAuthController();\n const [status, setStatus] = useState<EntityStatus>(initialStatus);\n\n const updateStatus = (status: EntityStatus) => {\n setStatus(status);\n onStatusChange?.(status);\n };\n\n /**\n * The autosave due: what it writes, and the whole form it was taken from\n * — which is what validation judges.\n */\n const [valuesToBeSaved, setValuesToBeSaved] = useState<{ toSave: EntityValues<M>, values: M } | undefined>(undefined);\n useDebouncedCallback(valuesToBeSaved, () => {\n if (!valuesToBeSaved || !onSubmitProp) return;\n const pending = valuesToBeSaved;\n setIsSavingAutoSave(true);\n // An autosave is a save, and is held to what Save is held to. It\n // wrote every edit unchecked; a form that does not validate now shows\n // why, and writes nothing until it does.\n validateForSave(pending.values)\n .then((errors) => {\n if (Object.keys(errors).length > 0) {\n formex.validate();\n return;\n }\n return onSubmitProp(pending.toSave, formex);\n })\n .catch((e) => {\n console.error(e);\n setSavingError(e);\n // The fields the server refused, marked as a Save marks them;\n // an autosave has no submit to make them show, so it counts one.\n const fieldErrors = serverViolationErrors(e, Object.keys(collection.properties ?? {}));\n if (Object.keys(fieldErrors).length > 0) {\n for (const [key, message] of Object.entries(fieldErrors)) formex.setFieldError(key, message);\n formex.setSubmitCount(formex.submitCount + 1);\n }\n })\n .finally(() => setIsSavingAutoSave(false));\n }, false, 2000);\n\n /**\n * The properties the record changed underneath an edit of the user's own,\n * keyed to the value they changed to — each one shown as \"updated\n * elsewhere\" while the form still holds something else. Filled by the\n * effect that follows the baseline, below.\n */\n const [underlyingChanges, setUnderlyingChanges] = useState<Record<string, unknown>>({});\n\n /**\n * Rules the stored record already broke, on fields this edit leaves alone —\n * shown, and not held against the save. Keyed like `formex.errors`.\n */\n const [predatingViolations, setPredatingViolations] = useState<Record<string, unknown>>({});\n\n const initialEntityId: string | number | undefined = useMemo(() => {\n if (status === \"new\" || status === \"copy\") {\n return undefined;\n } else {\n return entityIdProp;\n }\n }, [entityIdProp, status]);\n\n const [entityId, setEntityId] = useState<string | number | undefined>(initialEntityId);\n const [savingError, setSavingError] = useState<Error | undefined>();\n const [isSavingAutoSave, setIsSavingAutoSave] = useState<boolean>(false);\n const [discardDialogOpen, setDiscardDialogOpen] = useState<boolean>(false);\n\n const discard = useUndoableDiscard();\n\n const autoSave = collection.formAutoSave;\n\n // Use externally computed initial values if provided, otherwise compute from entity + collection\n const baseInitialValues = useMemo(() => {\n if (computedInitialValues !== undefined) {\n return computedInitialValues;\n }\n // Fallback: compute from entity/collection (requires authController from context)\n // In headless mode without computedInitialValues, use entity values or defaults\n if (status === \"copy\" && entity) {\n return getCopyValues(collection, entity.values ?? getDefaultValuesFor(collection.properties));\n }\n if (status === \"existing\" && entity) {\n return entity.values ?? getDefaultValuesFor(collection.properties);\n }\n return getDefaultValuesFor(collection.properties);\n }, [computedInitialValues, collection, status, entity]);\n\n const [localChangesCleared, setLocalChangesCleared] = useState<boolean>(false);\n\n const hasLocalChanges = hasLocalChangesProp !== undefined\n ? (hasLocalChangesProp && !localChangesCleared)\n : false;\n\n const onSubmit = (values: EntityValues<M>, formexController: FormexController<EntityValues<M>>) => {\n\n setSavingError(undefined);\n\n if (status === \"existing\") {\n if (!entity?.id) throw Error(\"Form misconfiguration when saving, no id for existing entity\");\n } else if (status !== \"new\" && status !== \"copy\") {\n throw Error(\"New FormType added, check EntityForm\");\n }\n\n if (!onSubmitProp) {\n console.warn(\"EntityForm: no onSubmit callback provided. Form submission has no effect.\");\n formexController.setSubmitting(false);\n return;\n }\n\n return Promise.resolve(save(values))\n ?.then((savedEntity) => {\n if (savedEntity) {\n formexController.resetForm({\n values: savedEntity.values || values,\n submitCount: 0,\n touched: {}\n });\n }\n })\n .finally(() => {\n formexController.setSubmitting(false);\n });\n };\n\n /**\n * What the form opens showing, when that is not what is stored — an edit\n * carried over from the side panel's \"open full screen\", or a draft\n * restored from the local-changes backup.\n *\n * The merge is deliberately *not* folded into the baseline. `mergeDeep`\n * used to produce a single `initialValues` that served as both, with a\n * `initialDirty: true` bolted on beside it to say what the baseline could\n * no longer show — and that flag survived exactly one render, because the\n * record's data arriving replaced the baseline and the form recomputed\n * dirty as false against a baseline that already contained the edit.\n *\n * Read once, at mount: this is a handoff, and re-reading it every render\n * tied the form to a cache that is cleared as soon as it has been consumed.\n */\n const initialModifiedValues = useRef(\n initialDirtyValues && Object.keys(initialDirtyValues).length > 0\n ? overlayEdit(baseInitialValues as Partial<M>, initialDirtyValues as Partial<M>)\n : undefined\n ).current;\n\n /**\n * Every key of the handed-over edit, marked touched. Read once, at mount,\n * like the edit itself: it was rebuilt on every render — a key-value map\n * of 1,000 entries cost ~60 ms per keystroke — by a spread that copied the\n * map once per key.\n */\n const [initialTouched] = useState<Record<string, boolean>>(() => {\n const touched: Record<string, boolean> = {};\n if (initialDirtyValues) {\n for (const key of flattenKeys(initialDirtyValues)) touched[key] = true;\n }\n return touched;\n });\n\n // A Save waits for a file still uploading: its path reaches the values\n // only when the upload ends. See `form_uploads.ts`.\n const [uploadTracker] = useState(createFormUploadTracker);\n\n const internalFormex = useCreateFormex<M>({\n initialValues: baseInitialValues as M,\n beforeSubmit: uploadTracker.wait,\n initialModifiedValues: initialModifiedValues as M | undefined,\n debugId: `EntityForm:${path}/${entityIdProp}`,\n initialTouched,\n onSubmit,\n onReset: () => {\n setUnderlyingChanges({});\n onResetProp?.();\n // The stored values — a reset returns the form to them, and by now\n // that is the baseline whether or not it was at mount.\n onValuesModified?.(false, baseInitialValues as M);\n },\n onValuesChangeDeferred: onValuesChangeDeferredProp,\n validation: (values) => validateForSave(values)\n });\n const formex: FormexController<M> = formexProp ?? internalFormex;\n\n /**\n * The errors that stop a save of `values`. Formex runs it on submit, and\n * the autosave runs it before each write.\n */\n async function validateForSave(values: M): Promise<Record<string, string>> {\n const errors = await validationErrorsFor(values);\n if (status !== \"existing\" || !entity?.values || Object.keys(errors).length === 0) {\n setPredatingViolations({});\n return errors;\n }\n // A record stored before a rule existed still breaks it, and the\n // server — which judges only what is sent — would take an\n // unrelated edit. So a field the user did not change, that the\n // stored record already broke, is a warning and not a refusal. A\n // field they changed must be valid, and so must one their edit\n // made invalid: a rule that reads the edited value is the edit's.\n const edited = getChangedProperties<M>(values, entity.values as Partial<M>);\n const storedErrors = await validationErrorsFor(entity.values as M);\n const blocking: Record<string, string> = {};\n const predating: Record<string, string> = {};\n for (const [key, error] of Object.entries(errors)) {\n if (!(key in edited) && key in storedErrors) predating[key] = error;\n else blocking[key] = error;\n }\n setPredatingViolations(predating);\n return blocking;\n }\n\n // One form takes a shortcut: the one the focus is in, else the one\n // mounted last (the top panel). Registered once per mount, so the order\n // is the order the forms opened in. See `form_keyboard_scope.ts`.\n const keyboardScope = useRef<ReturnType<typeof registerKeyboardScope> | undefined>(undefined);\n useEffect(() => {\n const scope = registerKeyboardScope(() => formElementRef.current);\n keyboardScope.current = scope;\n return () => {\n scope.unregister();\n keyboardScope.current = undefined;\n };\n }, []);\n\n useEffect(() => {\n\n const handleKeyDown = (e: KeyboardEvent) => {\n // A layer above the form (a dialog, a menu) already acted on it.\n if (isKeyHandled(e)) return;\n if (!keyboardScope.current || !ownsKeystroke(keyboardScope.current, e)) return;\n const isUndo = (e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === \"z\";\n const isRedo =\n ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key.toLowerCase() === \"z\") ||\n ((e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === \"y\");\n const isSave = (e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"s\";\n\n if (isSave && !disabled && formex.dirty) {\n e.preventDefault();\n formex.handleSubmit();\n } else if (isUndo && formex.canUndo) {\n e.preventDefault();\n formex.undo();\n } else if (isRedo && formex.canRedo) {\n e.preventDefault();\n formex.redo();\n }\n };\n\n window.addEventListener(\"keydown\", handleKeyDown);\n return () => window.removeEventListener(\"keydown\", handleKeyDown);\n\n }, [formex]);\n\n const afterSave = (updatedEntity: Entity<M>) => {\n onResetProp?.();\n onValuesModified?.(false, updatedEntity.values);\n onEntityChange?.(updatedEntity);\n updateStatus(\"existing\");\n setEntityId(updatedEntity.id);\n\n if (onSaved) {\n onSaved({\n entity: updatedEntity,\n status,\n path,\n entityId: updatedEntity.id,\n collection\n });\n }\n };\n\n // What the form opened with counts as saved: a New form nobody touched\n // has nothing to autosave. Seeded with `entity?.values`, which a new\n // record does not have, the first autosave wrote a record of defaults.\n const lastSavedValues = useRef<EntityValues<M> | undefined>(baseInitialValues as EntityValues<M>);\n const save = async (values: EntityValues<M>): Promise<Entity<M> | void> => {\n // The string transforms a property declares change what is written;\n // validation has already judged the transformed value.\n const writtenValues = applyValueTransforms(values, collection.properties);\n // An existing record sends only what changed; a new one or a copy\n // sends what it holds, less what the user could not have written.\n const valuesToSave = status === \"existing\"\n ? getChangedProperties<M>(writtenValues, entity?.values || {}) as EntityValues<M>\n : withoutUnwritableDefaults<M>(\n status === \"new\"\n ? withoutUnsetNulls(writtenValues, baseInitialValues as Partial<M>)\n : writtenValues,\n baseInitialValues as Partial<M>,\n collection.properties,\n formViewer(authController)\n ) as EntityValues<M>;\n\n if (status === \"existing\" && Object.keys(valuesToSave).length === 0 && entity) {\n return Promise.resolve(entity);\n }\n\n lastSavedValues.current = values;\n\n if (!onSubmitProp) {\n return;\n }\n\n const autoSaveEnabled = autoSave ?? false;\n\n if (autoSaveEnabled) {\n setValuesToBeSaved({ toSave: valuesToSave, values: values as M });\n return Promise.resolve();\n }\n\n return Promise.resolve(onSubmitProp(valuesToSave as M, formex))\n .then((result) => {\n if (result) {\n afterSave(result as Entity<M>);\n }\n return result as Entity<M> | void;\n })\n .catch(e => {\n console.error(e);\n setSavingError(e);\n // The fields the server refused, marked where the user can\n // see them — not only the sentence in the footer.\n const fieldErrors = serverViolationErrors(e, Object.keys(collection.properties ?? {}));\n for (const [key, message] of Object.entries(fieldErrors)) formex.setFieldError(key, message);\n });\n };\n\n const disabled = formex.isSubmitting || Boolean(disabledProp);\n\n // The context an `additionalFields` Builder is documented to receive, and\n // the one `CollectionTableBinding` already hands it. This form used to pass\n // its own `FormContext` instead, laundered through\n // `formContext as unknown as AdditionalFieldDelegateProps[\"context\"]` —\n // two unrelated types, so a Builder reading anything off `RebaseContext`\n // worked in the table view and read `undefined` in the form.\n const rebaseContext = useRebaseContext();\n\n const formContext: FormContext<M> = {\n setFieldValue: useCallback((key: string, value: unknown) => formex.setFieldValue(key, value), []),\n values: formex.values,\n collection,\n entityId: entityId as string,\n path,\n save,\n submit: formex.handleSubmit,\n formex,\n entity,\n savingError,\n status,\n openEntityMode,\n disabled,\n isSaving: formex.isSubmitting || isSavingAutoSave\n };\n\n /**\n * The context the fields get. Not `formContext`: that one is a new object\n * per render, and a field memoised on its own value would re-render for it\n * on every keystroke anywhere in the form.\n *\n * This one changes identity only with what a field may draw from it — the\n * record, its status, the form's `version` (a reset or re-seed) — and reads\n * `values`, `formex` and `save` through a ref, so a field that did not\n * re-render still sees the current ones from its callbacks (a storage path\n * builder, a markdown file name). A field that reads another field's value\n * *while rendering* has to re-render with it; `PropertyFieldBinding` keeps\n * those — custom `Field`s, `dynamicProps`, `conditions` — on that path.\n */\n const latestRef = useRef({ formex, save });\n latestRef.current = { formex, save };\n const isSaving = formex.isSubmitting || isSavingAutoSave;\n const fieldContext: FormContext<M> = useMemo(() => ({\n get values() {\n return latestRef.current.formex.values;\n },\n get formex() {\n return latestRef.current.formex;\n },\n setFieldValue: formContext.setFieldValue,\n save: (values: M) => latestRef.current.save(values),\n submit: () => latestRef.current.formex.handleSubmit(),\n collection,\n entityId: entityId as string,\n path,\n entity,\n savingError,\n status,\n openEntityMode,\n disabled,\n isSaving\n // `formex.version` is a key, not an input: a reset or re-seed has to\n // hand the fields a new context even though nothing above reads it.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [formContext.setFieldValue, collection, entityId, path, entity, savingError, status, openEntityMode, disabled, isSaving, formex.version]);\n\n useEffect(() => {\n onFormContextReady?.(formContext);\n // `formex.version` only moves on `resetForm`, so these deps used to hand\n // the container one snapshot at mount and never another. That was\n // invisible while Save lived inside the form and read `formex` directly;\n // once the identity bar owned Save, its `dirty` was frozen false and the\n // button never enabled — for any field, not just the one that exposed\n // it. Custom entity views read `formContext.values` through the same\n // channel and were reading a stale copy too.\n //\n // Deps are the state *transitions* a container cares about, not\n // `formex.values`: re-publishing on every keystroke would re-render the\n // whole entity view per character.\n }, [\n formex.version, collection, entityId, path,\n formex.dirty, formex.isSubmitting, formex.submitCount, isSavingAutoSave\n ]);\n\n const actionsDisabled = disabled || formex.isSubmitting || (status === \"existing\" && !formex.dirty) || Boolean(disabledProp);\n\n // The record's title is resolved by the container that renders the identity\n // bar (see `useEntityDisplayTitle`), not here — the form no longer draws a\n // heading of its own.\n\n const modified = formex.dirty;\n\n useEffect(() => {\n if (!autoSave) {\n onValuesModified?.(modified, formex.values);\n }\n }, [formex.dirty]);\n\n // Default no-op unique field validator — always passes\n const defaultUniqueFieldValidator: CustomFieldValidator = useCallback(async () => true, []);\n\n const uniqueFieldValidator: CustomFieldValidator = useMemo(() => {\n if (uniqueFieldValidatorProp) {\n return uniqueFieldValidatorProp as CustomFieldValidator;\n }\n return defaultUniqueFieldValidator;\n }, [uniqueFieldValidatorProp, defaultUniqueFieldValidator]);\n\n const customizationController = useCustomizationController();\n const { t } = useTranslation();\n\n async function validationErrorsFor(values: M): Promise<Record<string, string>> {\n const properties = validationPropertiesFor(values);\n const result = await getEntitySchema(entityId, properties, uniqueFieldValidator).safeParseAsync(values);\n const errors: Record<string, string> = result.success ? {} : zodToFormErrors(result.error);\n // `validation.unique` asks the data source, so it runs here — on\n // submit — and only for values this edit changed that are otherwise\n // valid. It was built and threaded through, and never called.\n const notUnique = await uniqueValueErrors({\n properties,\n values,\n storedValues: status === \"existing\" ? entity?.values : undefined,\n entityId,\n errors,\n validator: uniqueFieldValidator\n });\n return { ...errors, ...notUnique };\n }\n\n /**\n * What the save is judged against: the properties as the form shows them\n * for these values — `dynamicProps` and `conditions` applied — and only\n * the ones the user can change. Built per call because both depend on the\n * values being judged.\n */\n function validationPropertiesFor(values: M) {\n return resolvePropertiesForValidation<M>({\n properties: collection.properties,\n isNew: status === \"new\" || status === \"copy\",\n values,\n previousValues: baseInitialValues as Partial<M>,\n path,\n entityId,\n propertyConfigs: customizationController.propertyConfigs,\n authController\n });\n }\n\n useOnAutoSave(autoSave, formex, lastSavedValues, save);\n\n /**\n * The record changed while the form was open: someone else saved it, and\n * the listener delivered the new version as a new baseline.\n *\n * An unmodified form follows it whole — formex does that. A modified one\n * keeps the edit, and formex keeps *everything* it holds: a property the\n * user never changed would still show the old value, differ from the new\n * stored one, and be written back by the next save, reverting the other\n * change without a word.\n *\n * So each top-level property that changed underneath is judged on its own,\n * against the baseline the form last followed. One the user has not changed\n * follows the record. One the user has changed keeps the edit — that is\n * what a save writes — and is marked as updated elsewhere, so the overwrite\n * is not a surprise.\n */\n const followedBaseline = useRef(baseInitialValues);\n useEffect(() => {\n const previous: Record<string, unknown> = followedBaseline.current ?? {};\n const next: Record<string, unknown> = baseInitialValues ?? {};\n followedBaseline.current = baseInitialValues;\n if (previous === next) return;\n\n const current: Record<string, unknown> = formex.values;\n if (equal(previous, current)) return;\n\n const conflicts: Record<string, unknown> = {};\n const changedUnderneath = new Set([...Object.keys(previous), ...Object.keys(next)]);\n for (const key of changedUnderneath) {\n if (equal(previous[key], next[key])) {\n changedUnderneath.delete(key);\n } else if (equal(current[key], previous[key])) {\n formex.setFieldValue(key, next[key]);\n } else if (!equal(current[key], next[key])) {\n conflicts[key] = next[key];\n }\n }\n if (changedUnderneath.size === 0) return;\n\n setUnderlyingChanges(prev => {\n const updated = { ...prev };\n changedUnderneath.forEach(key => {\n if (key in conflicts) updated[key] = conflicts[key];\n else delete updated[key];\n });\n return updated;\n });\n }, [baseInitialValues]);\n\n const formFieldKeys = getFormFieldKeys(collection);\n\n const layout = useMemo(() => resolveFormLayout({\n collection,\n fieldKeys: formFieldKeys,\n status\n }), [collection, formFieldKeys.join(\",\"), status]);\n\n const formElementRef = useRef<HTMLFormElement>(null);\n // Measured, not a breakpoint: the rail holds fields the resolver moved\n // out of the column, so when it cannot be shown they have to come back.\n const railVisible = useRailVisible(formElementRef);\n const showRail = !Builder && layout.hasRail && railVisible;\n\n // Collapsed sections are per-section-key so a renamed title keeps its state,\n // and initial state comes from the config rather than being forced open.\n const [collapsedSections, setCollapsedSections] = useState<Set<string>>(\n () => new Set(layout.sections.filter(s => s.collapsed).map(s => s.key))\n );\n const toggleSection = useCallback((key: string) => {\n setCollapsedSections(prev => {\n const next = new Set(prev);\n if (next.has(key)) next.delete(key); else next.add(key);\n return next;\n });\n }, []);\n\n const errorKeys = useMemo(\n () => new Set(formex.submitCount > 0 ? Object.keys(formex.errors) : []),\n [formex.errors, formex.submitCount]\n );\n\n // Autofocus lands on the first field the user can actually type into. Tracked\n // across the whole layout rather than per section, so a collapsed leading\n // group does not steal it.\n const autoFocusKey = useMemo(() => {\n if (status !== \"new\" && status !== \"copy\") return undefined;\n const ordered = [...layout.sections.flatMap(s => s.fields), ...layout.sidebar];\n return ordered.find(field => {\n const property = collection.properties?.[field.key];\n return property ? !isFieldDisabled(field.key, property) : false;\n })?.key;\n }, [layout, collection, status, disabledProp, lockedPropertyKeys]);\n\n function isFieldDisabled(key: string, property: NonNullable<typeof collection.properties[string]>): boolean {\n const isNew = status === \"new\" || status === \"copy\";\n const isStringOrNumber = property.type === \"string\" || property.type === \"number\";\n const isIdAndAuto = isStringOrNumber && \"isId\" in property && typeof property.isId === \"string\" && property.isId !== \"manual\";\n return Boolean(\n disabledProp\n || (!autoSave && formex.isSubmitting)\n || isReadOnly(property)\n || isDisabled(property)\n || (!isNew && \"isId\" in property && Boolean(property.isId))\n || (isNew && isIdAndAuto)\n || (isNew && lockedPropertyKeys?.includes(key))\n );\n }\n\n const renderField = (field: ResolvedFormField): React.ReactNode => {\n\n if (field.additional) {\n const additionalField = collection.additionalFields?.find(f => f.key === field.key);\n if (!additionalField || !entity) return null;\n\n const AdditionalFieldBuilder = additionalField.Builder;\n if (!AdditionalFieldBuilder && !additionalField.value) {\n throw new Error(\"When using additional fields you need to provide a Builder or a value\");\n }\n const child = AdditionalFieldBuilder\n ? <AdditionalFieldBuilder entity={entity} context={rebaseContext}/>\n : <div className={\"w-full\"}>\n <AdditionalFieldValue\n field={additionalField}\n entity={entity}\n context={rebaseContext}/>\n </div>;\n\n return (\n // Through FieldBlock like every other cell, so a computed\n // column is labelled at the same size, with the same gap to its\n // box, as the property next to it on the grid.\n <div key={`additional_${field.key}`}\n className={spanClass(field.span)}>\n <FieldBlock propertyKey={field.key}\n showLabel={true}\n label={additionalField.name}\n icon={<AlignLeftIcon size={LABEL_ICON_SIZE}/>}>\n <div className={cls(paperMixin, \"w-full min-h-12 p-4 md:p-6 overflow-x-auto no-scrollbar\")}>\n {child}\n </div>\n </FieldBlock>\n </div>\n );\n }\n\n const property = collection.properties?.[field.key];\n if (!property) {\n console.warn(`Property ${field.key} not found in collection ${collection.name} in properties or additional fields. Skipping.`);\n return null;\n }\n // A field a rule hides for these values, or that this user may not\n // read, takes its label with it: the binding renders nothing, and a\n // heading over nothing is worse.\n if (property.conditions?.hidden || effectiveAccess(property)) {\n const shown = resolveFormProperty({\n propertyKey: field.key,\n property,\n values: formex.values,\n previousValues: baseInitialValues as Partial<M>,\n path,\n entityId,\n propertyConfigs: customizationController.propertyConfigs,\n ignoreMissingFields: true,\n authController\n });\n if (!shown || isHidden(shown)) return null;\n }\n\n const underlyingValueHasChanged: boolean =\n field.key in underlyingChanges &&\n !equal(formex.values[field.key], underlyingChanges[field.key]);\n\n const disabled = isFieldDisabled(field.key, property);\n // Three places a label can be. The panel-style editors carry their own\n // header. The one-line controls draw it inside their box, FireCMS-style,\n // so they all stand the same height. Everything else — multi-selects,\n // uploads, markdown, relations — is labelled above by FieldBlock.\n const selfLabelling = isSelfLabellingProperty(property);\n const labelInside = !selfLabelling\n && labelsInsideControl(property, customizationController.propertyConfigs);\n\n const cmsFormFieldProps: PropertyFieldBindingProps<M> = {\n propertyKey: field.key,\n disabled,\n property,\n // FieldBlock owns the description now, so the binding must not\n // repeat it — it still renders validation errors, which belong\n // against the control rather than under the label.\n includeDescription: false,\n hideLabel: !selfLabelling && !labelInside,\n underlyingValueHasChanged: underlyingValueHasChanged && !autoSave,\n context: fieldContext,\n partOfArray: false,\n minimalistView: false,\n // One height for every control in the form. Left to their own\n // defaults, a text field came out 48px, a select 44 and a switch 64.\n // `large`: the record-form density — a 64px box with the label\n // inside and a 16px value, or a 48px box under a label. 0.20.0 took\n // the form to `small` (32px) to match the reference, and the fields\n // read as cramped next to what they had been; see DESIGN.md \"Form\n // density\".\n size: \"large\",\n autoFocus: autoFocusKey === field.key\n };\n\n return (\n <div key={`field_${field.key}`} className={spanClass(field.span)}>\n <FieldBlock propertyKey={field.key}\n property={property}\n showLabel={!selfLabelling && !labelInside}\n labelInside={labelInside}>\n <PropertyFieldBinding {...cmsFormFieldProps}/>\n </FieldBlock>\n </div>\n );\n };\n\n const formFields = () => {\n\n if (Builder) {\n // Its own boundary: a Builder is usually a lazy chunk, and without\n // one, loading it suspends the nearest boundary above the record\n // view — which takes the identity bar down with the form.\n return <Suspense fallback={<CircularProgressCenter/>}>\n <Builder\n collection={collection}\n parentCollectionSlugs={parentCollectionSlugs}\n parentEntityIds={parentEntityIds}\n entity={entity}\n modifiedValues={formex.values}\n formContext={formContext}\n />\n </Suspense>;\n }\n\n const sections = showRail || !layout.sidebar.length\n ? layout.sections\n : [\n ...layout.sections,\n // Trailing, not leading. Beside the column these read as\n // peripheral; stacked above it they pushed the record's own name\n // below its status, which is the wrong thing to meet first.\n // Settings come after the content they apply to.\n {\n key: \"__rail\",\n title: \"Settings\",\n collapsible: false,\n collapsed: false,\n fields: layout.sidebar\n }\n ];\n\n return <>\n <FormSections\n sections={sections}\n collapsed={collapsedSections}\n onToggle={toggleSection}\n errorKeys={errorKeys}\n renderField={renderField}/>\n\n {/* Folded back with the rail's fields, and for the same reason. The\n rail renders only where it has been measured to fit, so on the\n split pane, the side panel and the dialog this block was dropped\n outright and the record's id was nowhere on screen but the\n truncated chip in the bar. */}\n {!showRail && layout.showRecordMeta && status === \"existing\" && entity && (\n <div className={cls(\"mt-8 pt-5 border-t max-w-sm\", defaultBorderMixin)}>\n <RecordMeta entity={entity as Entity<Record<string, unknown>>}/>\n </div>\n )}\n </>;\n };\n\n const formRef = useRef<HTMLDivElement>(null);\n\n const hasFormErrors = Object.keys(formex.errors).length > 0 && formex.submitCount > 0;\n\n const predatingViolationLines = useMemo(\n () => errorLines(predatingViolations, collection.properties),\n [predatingViolations, collection.properties]\n );\n\n const formView = <ErrorBoundary>\n <>\n {beforeFields}\n\n {/* The title, the `path/id` chip and the 72px gap under them used to\n live here — 219px above the first field, carrying nothing, and\n scrolling the record's identity away on the first wheel click.\n It is now in the persistent bar, where it stays put. */}\n\n {!entity?.values && initialStatus === \"existing\" &&\n <Alert color={\"warning\"} size={\"small\"} outerClassName={\"w-full mb-4 text-xs\"}>\n {t(\"entity_does_not_exist\")}\n </Alert>}\n\n {children}\n\n {initialEntityId && !entity && initialStatus !== \"new\" && <Alert color={\"info\"} size={\"small\"}>\n {t(\"entity_does_not_exist\")}\n </Alert>}\n\n {hasFormErrors && <Alert color={\"error\"} size={\"small\"} outerClassName={\"w-full mt-2\"}>\n {t(\"fix_errors_before_saving\")}\n </Alert>}\n\n {predatingViolationLines.length > 0 &&\n <Alert color={\"warning\"} size={\"small\"} outerClassName={\"w-full mt-2\"}>\n <Typography variant={\"caption\"} component={\"div\"}>\n {t(\"form_predating_rule_violations\")}\n </Typography>\n <ul className={\"list-disc pl-5 mt-1\"}>\n {predatingViolationLines.map(({ path: errorPath, label, message }) =>\n <li key={errorPath}><Typography variant={\"caption\"}>{`${label}: ${message}`}</Typography></li>)}\n </ul>\n </Alert>}\n\n {formContext && <>\n <div ref={formRef}>\n {formFields()}\n <ErrorFocus containerRef={formRef}/>\n </div>\n </>}\n\n {afterFields}\n\n <Dialog open={discardDialogOpen} onOpenChange={setDiscardDialogOpen} maxWidth={\"sm\"}>\n <DialogTitle>{status === \"existing\" ? \"Discard changes?\" : \"Clear form?\"}</DialogTitle>\n <DialogContent>\n <Typography>\n {status === \"existing\"\n ? \"All unsaved changes will be lost. \"\n : \"All entered values will be cleared. \"}\n You can bring them back with Undo (⌘Z / Ctrl+Z), or from\n the notification, for as long as this form stays open.\n </Typography>\n </DialogContent>\n <DialogActions>\n <Button variant={\"text\"} onClick={() => setDiscardDialogOpen(false)}>\n Cancel\n </Button>\n <Button variant={\"filled\"} color={\"error\"} onClick={() => {\n setDiscardDialogOpen(false);\n discard(formex, status, baseInitialValues);\n }}>\n {status === \"existing\" ? \"Discard\" : \"Clear\"}\n </Button>\n </DialogActions>\n </Dialog>\n </>\n </ErrorBoundary>;\n\n useEffect(() => {\n if (entityId && onIdChange)\n onIdChange(entityId);\n }, [entityId, onIdChange]);\n\n if (!collection || !path) {\n throw Error(\"INTERNAL: Collection and path must be defined in form context\");\n }\n\n const EntityFormActionsRender = EntityFormActionsComponent as React.FC<EntityFormActionsProps>;\n\n const dialogActions = <EntityFormActionsRender\n collection={collection}\n path={path}\n entity={entity}\n savingError={savingError}\n formex={formex as FormexController<Record<string, unknown>>}\n disabled={actionsDisabled}\n status={status}\n pluginActions={pluginActionsProp ?? []}\n openEntityMode={openEntityMode}\n showDefaultActions={showDefaultActions}\n navigateBack={navigateBack}\n formContext={formContext as FormContext<Record<string, unknown>>}\n />;\n\n return (\n <Formex value={formex}>\n <FormUploadsContext.Provider value={uploadTracker}>\n <form\n ref={formElementRef}\n onSubmit={formex.handleSubmit}\n onReset={(e) => {\n e.preventDefault();\n if (formex.dirty) {\n setDiscardDialogOpen(true);\n } else {\n formex.resetForm({ values: baseInitialValues as M });\n }\n }}\n noValidate\n className={cls(\"@container/form flex-1 flex flex-col w-full min-h-0\", className)}>\n\n {/* The actions bar is a sibling of this row rather than absolutely\n positioned over it, so the scroll area ends where the bar\n begins. As an overlay it hid the last field, and the bottom\n padding that compensated was a guess at its height. */}\n <div className={\"flex-1 min-h-0 flex flex-row w-full\"}>\n\n {/* Main column. Its own container scope, so a field's span\n answers to the column it sits in rather than to the window —\n the same form renders at four very different widths. */}\n {/* `items-start`: the column is a flex item, so without it the cross-axis\n default stretches it to the scroller's height. Its content then\n overflows its own box and the bottom padding sits at the bottom of\n the *viewport* instead of after the last field — which is why the\n form appeared to have no padding however large `pb-*` grew. */}\n <div className={\"flex-1 min-w-0 overflow-y-auto flex justify-center items-start\"}>\n <div\n id={`form_${path}`}\n className={cls(\n // Two rules widen the column, and they answer to\n // different things on purpose. `@7xl/form` measures\n // the form itself: full screen on a laptop is ~1400px\n // of form, which after the 304px rail leaves room for\n // the wider column with real gutters either side — and\n // it stays 768 in the split pane and the side panel,\n // which never get that wide. `2xl` is the older\n // viewport rule, kept so a panel on a large monitor\n // does not get *narrower* than it is today.\n \"@container/col w-full max-w-3xl @7xl/form:max-w-4xl 2xl:max-w-4xl flex flex-col\",\n openEntityMode === \"dialog\"\n ? \"pt-5 pb-8 px-6 sm:px-8\"\n : \"pt-6 pb-12 px-5 sm:px-8\"\n )}>\n\n {manualApplyLocalChanges && hasLocalChanges && localChangesCacheKey &&\n <div className={\"flex justify-end mb-3\"}>\n <LocalChangesMenu<M>\n cacheKey={localChangesCacheKey}\n properties={collection.properties}\n cachedData={localChangesData as Partial<M>}\n formex={formex}\n onClearLocalChanges={() => {\n setLocalChangesCleared(true);\n onClearLocalChanges?.();\n }}\n />\n </div>}\n\n {formView}\n\n </div>\n </div>\n\n {showRail && <FormRail\n fields={layout.sidebar}\n showRecordMeta={layout.showRecordMeta && status === \"existing\"}\n entity={entity as Entity<Record<string, unknown>> | undefined}\n renderField={renderField}/>}\n </div>\n\n {dialogActions}\n\n </form>\n </FormUploadsContext.Provider>\n\n </Formex>\n );\n}\n\nfunction useOnAutoSave<M extends Record<string, unknown>>(autoSave: undefined | boolean, formex: FormexController<M>, lastSavedValues: React.MutableRefObject<EntityValues<M> | undefined>, save: (values: EntityValues<M>) => Promise<Entity<M> | void>) {\n useEffect(() => {\n if (!autoSave) return;\n if (formex.values && !equal(formex.values, lastSavedValues.current)) {\n save(formex.values);\n }\n }, [autoSave, formex.values]);\n}\n\n/**\n * A nested error map — the shape `zodToFormErrors` builds — as one line per\n * failing field, labelled with the property's name.\n */\nfunction errorLines(\n errors: Record<string, unknown>,\n properties: Properties\n): { path: string; label: string; message: string }[] {\n const lines: { path: string; label: string; message: string }[] = [];\n const walk = (value: unknown, path: string[], label: string[], props: Properties | undefined) => {\n if (typeof value === \"string\") {\n lines.push({ path: path.join(\".\"), label: label.join(\" › \"), message: value });\n return;\n }\n if (!value || typeof value !== \"object\") return;\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n const property = props?.[key] as Property | undefined;\n const childProps = property?.type === \"map\" ? property.properties as Properties | undefined : undefined;\n walk(child, [...path, key], [...label, property?.name ?? key], childProps);\n }\n };\n walk(errors, [], [], properties);\n return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,SAAgB,WAA8C,EAC1D,MACA,UAAU,cACV,YACA,kBACA,YACA,SACA,QACA,oBACA,oBACA,eACA,WACA,gBACA,gBACA,iBAAiB,eACjB,QAAQ,YACR,UAAU,cACV,SACA,uBACA,iBACA,6BAA6B,mBAC7B,qBAAqB,MACrB,cAAc,kBACd,UAEA,UAAU,cACV,wBAAwB,4BACxB,SAAS,aACT,sBAAsB,0BACtB,oBAEA,cACA,aACA,eAAe,mBAEf,uBACA,iBAAiB,qBACjB,kBACA,yBACA,sBACA,uBACmB;CAEnB,MAAM,eAAe,kBAAkB;EACnC,IAAI,kBACA,iBAAiB;CAEzB,GAAG,CAAC,gBAAgB,CAAC;CAErB,MAAM,iBAAiB,kBAAkB;CACzC,MAAM,CAAC,QAAQ,aAAa,SAAuB,aAAa;CAEhE,MAAM,gBAAgB,WAAyB;EAC3C,UAAU,MAAM;EAChB,iBAAiB,MAAM;CAC3B;;;;;CAMA,MAAM,CAAC,iBAAiB,sBAAsB,SAA6D,KAAA,CAAS;CACpH,qBAAqB,uBAAuB;EACxC,IAAI,CAAC,mBAAmB,CAAC,cAAc;EACvC,MAAM,UAAU;EAChB,oBAAoB,IAAI;EAIxB,gBAAgB,QAAQ,MAAM,CAAC,CAC1B,MAAM,WAAW;GACd,IAAI,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,GAAG;IAChC,OAAO,SAAS;IAChB;GACJ;GACA,OAAO,aA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AAgB,OAAO,GAC9D,KAAK,OAAO,MAAM;CAE1B,GAAG,CAAC,UAAU,OAAO,MAAM,CAAC;AAChC;;;;;AAMA,SAAS,WACL,QACA,YACkD;CAClD,MAAM,QAA4D,CAAC;CACnE,MAAM,QAAQ,OAAgB,MAAgB,OAAiB,UAAkC;EAC7F,IAAI,OAAO,UAAU,UAAU;GAC3B,MAAM,KAAK;IAAE,MAAM,KAAK,KAAK,GAAG;IAAG,OAAO,MAAM,KAAK,KAAK;IAAG,SAAS;GAAM,CAAC;GAC7E;EACJ;EACA,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU;EACzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAgC,GAAG;GACzE,MAAM,WAAW,QAAQ;GACzB,MAAM,aAAa,UAAU,SAAS,QAAQ,SAAS,aAAuC,KAAA;GAC9F,KAAK,OAAO,CAAC,GAAG,MAAM,GAAG,GAAG,CAAC,GAAG,OAAO,UAAU,QAAQ,GAAG,GAAG,UAAU;EAC7E;CACJ;CACA,KAAK,QAAQ,CAAC,GAAG,CAAC,GAAG,UAAU;CAC/B,OAAO;AACX"}
|
|
1
|
+
{"version":3,"file":"EntityForm.js","names":[],"sources":["../../src/form/EntityForm.tsx"],"sourcesContent":["\nimport type { AdditionalFieldDelegateProps } from \"@rebasepro/cms-types\";\nimport type { FormContext, PropertyFieldBindingProps } from \"../types/fields\";\nimport React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { Entity, EntityStatus, EntityValues } from \"@rebasepro/types\";\nimport type { Properties, Property } from \"@rebasepro/types\";\nimport type { EntityFormProps } from \"../types/components/EntityFormProps\";\nimport { deepEqual as equal } from \"fast-equals\";\n\nimport { ErrorBoundary, isKeyHandled } from \"@rebasepro/ui\";\nimport { AlignLeftIcon, useDebouncedCallback } from \"@rebasepro/ui\";\nimport { effectiveAccess, getCopyValues, getDefaultValuesFor, hasEntityId } from \"@rebasepro/common\";\nimport { isDisabled, isHidden, isReadOnly } from \"@rebasepro/app\";\nimport { useAuthController, useCustomizationController, useRebaseContext, useTranslation } from \"@rebasepro/app\";\n\nimport { getFormFieldKeys, resolveFormLayout } from \"@rebasepro/app\";\nimport type { ResolvedFormField } from \"@rebasepro/app\";\nimport { Alert, Button, CircularProgressCenter, cls, defaultBorderMixin, Dialog, DialogActions, DialogContent, DialogTitle, paperMixin, Typography } from \"@rebasepro/ui\";\nimport { Formex, FormexController, useCreateFormex } from \"@rebasepro/forms\";\n\nimport { FieldBlock, isSelfLabellingProperty, LABEL_ICON_SIZE, spanClass } from \"./components/FieldBlock\";\nimport { labelsInsideControl } from \"./label_placement\";\nimport { AdditionalFieldValue } from \"../components/AdditionalFieldValue\";\nimport { FormRail, RecordMeta } from \"./components/FormRail\";\nimport { FormSections } from \"./components/FormSections\";\nimport { useRailVisible } from \"./components/useRailVisible\";\nimport { PropertyFieldBinding } from \"./PropertyFieldBinding\";\nimport { flattenKeys } from \"@rebasepro/app\";\nimport { ErrorFocus } from \"./components/ErrorFocus\";\nimport { applyValueTransforms, CustomFieldValidator, getEntitySchema, uniqueValueErrors } from \"./validation\";\nimport { formViewer, resolveFormProperty, resolvePropertiesForValidation, withoutUnwritableDefaults } from \"./resolve_form_properties\";\nimport { EntityFormActions } from \"./EntityFormActions\";\nimport type { EntityFormActionsProps } from \"../types/components/EntityFormActionsProps\";\nimport { LocalChangesMenu } from \"./components/LocalChangesMenu\";\nimport { useUndoableDiscard } from \"./useUndoableDiscard\";\nimport { ownsKeystroke, registerKeyboardScope } from \"./form_keyboard_scope\";\nimport { createFormUploadTracker, FormUploadsContext } from \"./form_uploads\";\n\nimport {\n getChangedProperties,\n overlayEdit,\n serverViolationErrors,\n withoutUnsetNulls,\n zodToFormErrors\n} from \"./form_utils\";\n\n/**\n * Headless entity form component.\n *\n * Renders a form for a entity collection without any admin or backend dependencies.\n * All backend concerns (save, caching, analytics, plugin slots) are provided via\n * callback props. For admin-connected usage, use {@link EntityFormBinding} instead.\n *\n * @group Components\n */\nexport function EntityForm<M extends Record<string, unknown>>({\n path,\n entityId: entityIdProp,\n collection,\n onValuesModified,\n onIdChange,\n onSaved,\n entity: entityProp,\n initialDirtyValues,\n onFormContextReady,\n initialStatus,\n className,\n onStatusChange,\n onEntityChange,\n openEntityMode = \"full_screen\",\n formex: formexProp,\n disabled: disabledProp,\n Builder,\n parentCollectionSlugs,\n parentEntityIds,\n EntityFormActionsComponent = EntityFormActions,\n showDefaultActions = true,\n navigateBack: navigateBackProp,\n children,\n // Headless callback props\n onSubmit: onSubmitProp,\n onValuesChangeDeferred: onValuesChangeDeferredProp,\n onReset: onResetProp,\n uniqueFieldValidator: uniqueFieldValidatorProp,\n lockedPropertyKeys,\n // Slots\n beforeFields,\n afterFields,\n pluginActions: pluginActionsProp,\n // Local changes (managed externally)\n computedInitialValues,\n hasLocalChanges: hasLocalChangesProp,\n localChangesData,\n manualApplyLocalChanges,\n localChangesCacheKey,\n onClearLocalChanges\n}: EntityFormProps<M>) {\n\n const navigateBack = useCallback(() => {\n if (navigateBackProp) {\n navigateBackProp();\n }\n }, [navigateBackProp]);\n\n const authController = useAuthController();\n const [status, setStatus] = useState<EntityStatus>(initialStatus);\n\n /**\n * The record as this form last saved it. A create turns the form into the\n * editor of the record it made, and the `entity` prop names that record\n * only once the caller has caught up — a caller that never does (the form\n * used on its own) left an \"existing\" form with no record: it re-seeded\n * itself with the defaults and refused the next Save.\n */\n const [savedEntity, setSavedEntity] = useState<Entity<M> | undefined>(undefined);\n const entity = entityProp ?? (status === \"existing\" ? savedEntity : undefined);\n\n const updateStatus = (status: EntityStatus) => {\n setStatus(status);\n onStatusChange?.(status);\n };\n\n /**\n * The autosave due: what it writes, and the whole form it was taken from\n * — which is what validation judges.\n */\n const [valuesToBeSaved, setValuesToBeSaved] = useState<{ toSave: EntityValues<M>, values: M } | undefined>(undefined);\n useDebouncedCallback(valuesToBeSaved, () => {\n if (!valuesToBeSaved || !onSubmitProp) return;\n const pending = valuesToBeSaved;\n setIsSavingAutoSave(true);\n // An autosave is a save, and is held to what Save is held to. It\n // wrote every edit unchecked; a form that does not validate now shows\n // why, and writes nothing until it does.\n validateForSave(pending.values)\n .then((errors) => {\n if (Object.keys(errors).length > 0) {\n formex.validate();\n return;\n }\n return onSubmitProp(pending.toSave, formex);\n })\n .catch((e) => {\n console.error(e);\n setSavingError(e);\n // The fields the server refused, marked as a Save marks them;\n // an autosave has no submit to make them show, so it counts one.\n const fieldErrors = serverViolationErrors(e, Object.keys(collection.properties ?? {}));\n if (Object.keys(fieldErrors).length > 0) {\n for (const [key, message] of Object.entries(fieldErrors)) formex.setFieldError(key, message);\n formex.setSubmitCount(formex.submitCount + 1);\n }\n })\n .finally(() => setIsSavingAutoSave(false));\n }, false, 2000);\n\n /**\n * The properties the record changed underneath an edit of the user's own,\n * keyed to the value they changed to — each one shown as \"updated\n * elsewhere\" while the form still holds something else. Filled by the\n * effect that follows the baseline, below.\n */\n const [underlyingChanges, setUnderlyingChanges] = useState<Record<string, unknown>>({});\n\n /**\n * Rules the stored record already broke, on fields this edit leaves alone —\n * shown, and not held against the save. Keyed like `formex.errors`.\n */\n const [predatingViolations, setPredatingViolations] = useState<Record<string, unknown>>({});\n\n const initialEntityId: string | number | undefined = useMemo(() => {\n if (status === \"new\" || status === \"copy\") {\n return undefined;\n } else {\n return entityIdProp;\n }\n }, [entityIdProp, status]);\n\n const [entityId, setEntityId] = useState<string | number | undefined>(initialEntityId);\n const [savingError, setSavingError] = useState<Error | undefined>();\n const [isSavingAutoSave, setIsSavingAutoSave] = useState<boolean>(false);\n const [discardDialogOpen, setDiscardDialogOpen] = useState<boolean>(false);\n\n const discard = useUndoableDiscard();\n\n const autoSave = collection.formAutoSave;\n\n // Use externally computed initial values if provided, otherwise compute from entity + collection\n const baseInitialValues = useMemo(() => {\n if (computedInitialValues !== undefined) {\n return computedInitialValues;\n }\n // Fallback: compute from entity/collection (requires authController from context)\n // In headless mode without computedInitialValues, use entity values or defaults\n if (status === \"copy\" && entity) {\n return getCopyValues(collection, entity.values ?? getDefaultValuesFor(collection.properties));\n }\n if (status === \"existing\" && entity) {\n return entity.values ?? getDefaultValuesFor(collection.properties);\n }\n return getDefaultValuesFor(collection.properties);\n }, [computedInitialValues, collection, status, entity]);\n\n const [localChangesCleared, setLocalChangesCleared] = useState<boolean>(false);\n\n const hasLocalChanges = hasLocalChangesProp !== undefined\n ? (hasLocalChangesProp && !localChangesCleared)\n : false;\n\n const onSubmit = (values: EntityValues<M>, formexController: FormexController<EntityValues<M>>) => {\n\n setSavingError(undefined);\n\n if (status === \"existing\") {\n if (!entity?.id) throw Error(\"Form misconfiguration when saving, no id for existing entity\");\n } else if (status !== \"new\" && status !== \"copy\") {\n throw Error(\"New FormType added, check EntityForm\");\n }\n\n if (!onSubmitProp) {\n console.warn(\"EntityForm: no onSubmit callback provided. Form submission has no effect.\");\n formexController.setSubmitting(false);\n return;\n }\n\n return Promise.resolve(save(values))\n ?.then((savedEntity) => {\n if (savedEntity) {\n formexController.resetForm({\n values: savedEntity.values || values,\n submitCount: 0,\n touched: {}\n });\n }\n })\n .finally(() => {\n formexController.setSubmitting(false);\n });\n };\n\n /**\n * What the form opens showing, when that is not what is stored — an edit\n * carried over from the side panel's \"open full screen\", or a draft\n * restored from the local-changes backup.\n *\n * The merge is deliberately *not* folded into the baseline. `mergeDeep`\n * used to produce a single `initialValues` that served as both, with a\n * `initialDirty: true` bolted on beside it to say what the baseline could\n * no longer show — and that flag survived exactly one render, because the\n * record's data arriving replaced the baseline and the form recomputed\n * dirty as false against a baseline that already contained the edit.\n *\n * Read once, at mount: this is a handoff, and re-reading it every render\n * tied the form to a cache that is cleared as soon as it has been consumed.\n */\n const initialModifiedValues = useRef(\n initialDirtyValues && Object.keys(initialDirtyValues).length > 0\n ? overlayEdit(baseInitialValues as Partial<M>, initialDirtyValues as Partial<M>)\n : undefined\n ).current;\n\n /**\n * Every key of the handed-over edit, marked touched. Read once, at mount,\n * like the edit itself: it was rebuilt on every render — a key-value map\n * of 1,000 entries cost ~60 ms per keystroke — by a spread that copied the\n * map once per key.\n */\n const [initialTouched] = useState<Record<string, boolean>>(() => {\n const touched: Record<string, boolean> = {};\n if (initialDirtyValues) {\n for (const key of flattenKeys(initialDirtyValues)) touched[key] = true;\n }\n return touched;\n });\n\n // A Save waits for a file still uploading: its path reaches the values\n // only when the upload ends. See `form_uploads.ts`.\n const [uploadTracker] = useState(createFormUploadTracker);\n\n const internalFormex = useCreateFormex<M>({\n initialValues: baseInitialValues as M,\n beforeSubmit: uploadTracker.wait,\n initialModifiedValues: initialModifiedValues as M | undefined,\n debugId: `EntityForm:${path}/${entityIdProp}`,\n initialTouched,\n onSubmit,\n onReset: () => {\n setUnderlyingChanges({});\n onResetProp?.();\n // The stored values — a reset returns the form to them, and by now\n // that is the baseline whether or not it was at mount.\n onValuesModified?.(false, baseInitialValues as M);\n },\n onValuesChangeDeferred: onValuesChangeDeferredProp,\n validation: (values) => validateForSave(values)\n });\n const formex: FormexController<M> = formexProp ?? internalFormex;\n\n /**\n * The errors that stop a save of `values`. Formex runs it on submit, and\n * the autosave runs it before each write.\n */\n async function validateForSave(values: M): Promise<Record<string, string>> {\n const errors = await validationErrorsFor(values);\n if (status !== \"existing\" || !entity?.values || Object.keys(errors).length === 0) {\n setPredatingViolations({});\n return errors;\n }\n // A record stored before a rule existed still breaks it, and the\n // server — which judges only what is sent — would take an\n // unrelated edit. So a field the user did not change, that the\n // stored record already broke, is a warning and not a refusal. A\n // field they changed must be valid, and so must one their edit\n // made invalid: a rule that reads the edited value is the edit's.\n const edited = getChangedProperties<M>(values, entity.values as Partial<M>);\n const storedErrors = await validationErrorsFor(entity.values as M);\n const blocking: Record<string, string> = {};\n const predating: Record<string, string> = {};\n for (const [key, error] of Object.entries(errors)) {\n if (!(key in edited) && key in storedErrors) predating[key] = error;\n else blocking[key] = error;\n }\n setPredatingViolations(predating);\n return blocking;\n }\n\n // One form takes a shortcut: the one the focus is in, else the one\n // mounted last (the top panel). Registered once per mount, so the order\n // is the order the forms opened in. See `form_keyboard_scope.ts`.\n const keyboardScope = useRef<ReturnType<typeof registerKeyboardScope> | undefined>(undefined);\n useEffect(() => {\n const scope = registerKeyboardScope(() => formElementRef.current);\n keyboardScope.current = scope;\n return () => {\n scope.unregister();\n keyboardScope.current = undefined;\n };\n }, []);\n\n useEffect(() => {\n\n const handleKeyDown = (e: KeyboardEvent) => {\n // A layer above the form (a dialog, a menu) already acted on it.\n if (isKeyHandled(e)) return;\n if (!keyboardScope.current || !ownsKeystroke(keyboardScope.current, e)) return;\n const isUndo = (e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === \"z\";\n const isRedo =\n ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key.toLowerCase() === \"z\") ||\n ((e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === \"y\");\n const isSave = (e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"s\";\n\n if (isSave && !disabled && formex.dirty) {\n e.preventDefault();\n formex.handleSubmit();\n } else if (isUndo && formex.canUndo) {\n e.preventDefault();\n formex.undo();\n } else if (isRedo && formex.canRedo) {\n e.preventDefault();\n formex.redo();\n }\n };\n\n window.addEventListener(\"keydown\", handleKeyDown);\n return () => window.removeEventListener(\"keydown\", handleKeyDown);\n\n }, [formex]);\n\n const afterSave = (updatedEntity: Entity<M>) => {\n setSavedEntity(updatedEntity);\n onResetProp?.();\n onValuesModified?.(false, updatedEntity.values);\n onEntityChange?.(updatedEntity);\n updateStatus(\"existing\");\n setEntityId(updatedEntity.id);\n\n if (onSaved) {\n onSaved({\n entity: updatedEntity,\n status,\n path,\n entityId: updatedEntity.id,\n collection\n });\n }\n };\n\n // What the form opened with counts as saved: a New form nobody touched\n // has nothing to autosave. Seeded with `entity?.values`, which a new\n // record does not have, the first autosave wrote a record of defaults.\n const lastSavedValues = useRef<EntityValues<M> | undefined>(baseInitialValues as EntityValues<M>);\n const save = async (values: EntityValues<M>): Promise<Entity<M> | void> => {\n // The string transforms a property declares change what is written;\n // validation has already judged the transformed value.\n const writtenValues = applyValueTransforms(values, collection.properties);\n // An existing record sends only what changed; a new one or a copy\n // sends what it holds, less what the user could not have written.\n const valuesToSave = status === \"existing\"\n ? getChangedProperties<M>(writtenValues, entity?.values || {}) as EntityValues<M>\n : withoutUnwritableDefaults<M>(\n status === \"new\"\n ? withoutUnsetNulls(writtenValues, baseInitialValues as Partial<M>)\n : writtenValues,\n baseInitialValues as Partial<M>,\n collection.properties,\n formViewer(authController)\n ) as EntityValues<M>;\n\n if (status === \"existing\" && Object.keys(valuesToSave).length === 0 && entity) {\n return Promise.resolve(entity);\n }\n\n lastSavedValues.current = values;\n\n if (!onSubmitProp) {\n return;\n }\n\n const autoSaveEnabled = autoSave ?? false;\n\n if (autoSaveEnabled) {\n setValuesToBeSaved({ toSave: valuesToSave, values: values as M });\n return Promise.resolve();\n }\n\n return Promise.resolve(onSubmitProp(valuesToSave as M, formex))\n .then((result) => {\n if (result) {\n afterSave(result as Entity<M>);\n }\n return result as Entity<M> | void;\n })\n .catch(e => {\n console.error(e);\n setSavingError(e);\n // The fields the server refused, marked where the user can\n // see them — not only the sentence in the footer.\n const fieldErrors = serverViolationErrors(e, Object.keys(collection.properties ?? {}));\n for (const [key, message] of Object.entries(fieldErrors)) formex.setFieldError(key, message);\n });\n };\n\n const disabled = formex.isSubmitting || Boolean(disabledProp);\n\n // The context an `additionalFields` Builder is documented to receive, and\n // the one `CollectionTableBinding` already hands it. This form used to pass\n // its own `FormContext` instead, laundered through\n // `formContext as unknown as AdditionalFieldDelegateProps[\"context\"]` —\n // two unrelated types, so a Builder reading anything off `RebaseContext`\n // worked in the table view and read `undefined` in the form.\n const rebaseContext = useRebaseContext();\n\n const formContext: FormContext<M> = {\n setFieldValue: useCallback((key: string, value: unknown) => formex.setFieldValue(key, value), []),\n values: formex.values,\n collection,\n entityId: entityId as string,\n path,\n save,\n submit: formex.handleSubmit,\n formex,\n entity,\n savingError,\n status,\n openEntityMode,\n disabled,\n isSaving: formex.isSubmitting || isSavingAutoSave\n };\n\n /**\n * The context the fields get. Not `formContext`: that one is a new object\n * per render, and a field memoised on its own value would re-render for it\n * on every keystroke anywhere in the form.\n *\n * This one changes identity only with what a field may draw from it — the\n * record, its status, the form's `version` (a reset or re-seed) — and reads\n * `values`, `formex` and `save` through a ref, so a field that did not\n * re-render still sees the current ones from its callbacks (a storage path\n * builder, a markdown file name). A field that reads another field's value\n * *while rendering* has to re-render with it; `PropertyFieldBinding` keeps\n * those — custom `Field`s, `dynamicProps`, `conditions` — on that path.\n */\n const latestRef = useRef({ formex, save });\n latestRef.current = { formex, save };\n const isSaving = formex.isSubmitting || isSavingAutoSave;\n const fieldContext: FormContext<M> = useMemo(() => ({\n get values() {\n return latestRef.current.formex.values;\n },\n get formex() {\n return latestRef.current.formex;\n },\n setFieldValue: formContext.setFieldValue,\n save: (values: M) => latestRef.current.save(values),\n submit: () => latestRef.current.formex.handleSubmit(),\n collection,\n entityId: entityId as string,\n path,\n entity,\n savingError,\n status,\n openEntityMode,\n disabled,\n isSaving\n // `formex.version` is a key, not an input: a reset or re-seed has to\n // hand the fields a new context even though nothing above reads it.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [formContext.setFieldValue, collection, entityId, path, entity, savingError, status, openEntityMode, disabled, isSaving, formex.version]);\n\n useEffect(() => {\n onFormContextReady?.(formContext);\n // `formex.version` only moves on `resetForm`, so these deps used to hand\n // the container one snapshot at mount and never another. That was\n // invisible while Save lived inside the form and read `formex` directly;\n // once the identity bar owned Save, its `dirty` was frozen false and the\n // button never enabled — for any field, not just the one that exposed\n // it. Custom entity views read `formContext.values` through the same\n // channel and were reading a stale copy too.\n //\n // Deps are the state *transitions* a container cares about, not\n // `formex.values`: re-publishing on every keystroke would re-render the\n // whole entity view per character.\n }, [\n formex.version, collection, entityId, path,\n formex.dirty, formex.isSubmitting, formex.submitCount, isSavingAutoSave\n ]);\n\n const actionsDisabled = disabled || formex.isSubmitting || (status === \"existing\" && !formex.dirty) || Boolean(disabledProp);\n\n // The record's title is resolved by the container that renders the identity\n // bar (see `useEntityDisplayTitle`), not here — the form no longer draws a\n // heading of its own.\n\n const modified = formex.dirty;\n\n useEffect(() => {\n if (!autoSave) {\n onValuesModified?.(modified, formex.values);\n }\n }, [formex.dirty]);\n\n // Default no-op unique field validator — always passes\n const defaultUniqueFieldValidator: CustomFieldValidator = useCallback(async () => true, []);\n\n const uniqueFieldValidator: CustomFieldValidator = useMemo(() => {\n if (uniqueFieldValidatorProp) {\n return uniqueFieldValidatorProp as CustomFieldValidator;\n }\n return defaultUniqueFieldValidator;\n }, [uniqueFieldValidatorProp, defaultUniqueFieldValidator]);\n\n const customizationController = useCustomizationController();\n const { t } = useTranslation();\n\n async function validationErrorsFor(values: M): Promise<Record<string, string>> {\n const properties = validationPropertiesFor(values);\n const result = await getEntitySchema(entityId, properties, uniqueFieldValidator).safeParseAsync(values);\n const errors: Record<string, string> = result.success ? {} : zodToFormErrors(result.error);\n // `validation.unique` asks the data source, so it runs here — on\n // submit — and only for values this edit changed that are otherwise\n // valid. It was built and threaded through, and never called.\n const notUnique = await uniqueValueErrors({\n properties,\n values,\n storedValues: status === \"existing\" ? entity?.values : undefined,\n entityId,\n errors,\n validator: uniqueFieldValidator\n });\n return { ...errors, ...notUnique };\n }\n\n /**\n * What the save is judged against: the properties as the form shows them\n * for these values — `dynamicProps` and `conditions` applied — and only\n * the ones the user can change. Built per call because both depend on the\n * values being judged.\n */\n function validationPropertiesFor(values: M) {\n return resolvePropertiesForValidation<M>({\n properties: collection.properties,\n isNew: status === \"new\" || status === \"copy\",\n values,\n previousValues: baseInitialValues as Partial<M>,\n path,\n entityId,\n propertyConfigs: customizationController.propertyConfigs,\n authController\n });\n }\n\n useOnAutoSave(autoSave, formex, lastSavedValues, save);\n\n /**\n * The record changed while the form was open: someone else saved it, and\n * the listener delivered the new version as a new baseline.\n *\n * An unmodified form follows it whole — formex does that. A modified one\n * keeps the edit, and formex keeps *everything* it holds: a property the\n * user never changed would still show the old value, differ from the new\n * stored one, and be written back by the next save, reverting the other\n * change without a word.\n *\n * So each top-level property that changed underneath is judged on its own,\n * against the baseline the form last followed. One the user has not changed\n * follows the record. One the user has changed keeps the edit — that is\n * what a save writes — and is marked as updated elsewhere, so the overwrite\n * is not a surprise.\n */\n const followedBaseline = useRef(baseInitialValues);\n useEffect(() => {\n const previous: Record<string, unknown> = followedBaseline.current ?? {};\n const next: Record<string, unknown> = baseInitialValues ?? {};\n followedBaseline.current = baseInitialValues;\n if (previous === next) return;\n\n const current: Record<string, unknown> = formex.values;\n if (equal(previous, current)) return;\n\n const conflicts: Record<string, unknown> = {};\n const changedUnderneath = new Set([...Object.keys(previous), ...Object.keys(next)]);\n for (const key of changedUnderneath) {\n if (equal(previous[key], next[key])) {\n changedUnderneath.delete(key);\n } else if (equal(current[key], previous[key])) {\n formex.setFieldValue(key, next[key]);\n } else if (!equal(current[key], next[key])) {\n conflicts[key] = next[key];\n }\n }\n if (changedUnderneath.size === 0) return;\n\n setUnderlyingChanges(prev => {\n const updated = { ...prev };\n changedUnderneath.forEach(key => {\n if (key in conflicts) updated[key] = conflicts[key];\n else delete updated[key];\n });\n return updated;\n });\n }, [baseInitialValues]);\n\n const formFieldKeys = getFormFieldKeys(collection);\n\n const layout = useMemo(() => resolveFormLayout({\n collection,\n fieldKeys: formFieldKeys,\n status\n }), [collection, formFieldKeys.join(\",\"), status]);\n\n const formElementRef = useRef<HTMLFormElement>(null);\n // Measured, not a breakpoint: the rail holds fields the resolver moved\n // out of the column, so when it cannot be shown they have to come back.\n const railVisible = useRailVisible(formElementRef);\n const showRail = !Builder && layout.hasRail && railVisible;\n\n // Collapsed sections are per-section-key so a renamed title keeps its state,\n // and initial state comes from the config rather than being forced open.\n const [collapsedSections, setCollapsedSections] = useState<Set<string>>(\n () => new Set(layout.sections.filter(s => s.collapsed).map(s => s.key))\n );\n const toggleSection = useCallback((key: string) => {\n setCollapsedSections(prev => {\n const next = new Set(prev);\n if (next.has(key)) next.delete(key); else next.add(key);\n return next;\n });\n }, []);\n\n const errorKeys = useMemo(\n () => new Set(formex.submitCount > 0 ? Object.keys(formex.errors) : []),\n [formex.errors, formex.submitCount]\n );\n\n // Autofocus lands on the first field the user can actually type into. Tracked\n // across the whole layout rather than per section, so a collapsed leading\n // group does not steal it.\n const autoFocusKey = useMemo(() => {\n if (status !== \"new\" && status !== \"copy\") return undefined;\n const ordered = [...layout.sections.flatMap(s => s.fields), ...layout.sidebar];\n return ordered.find(field => {\n const property = collection.properties?.[field.key];\n return property ? !isFieldDisabled(field.key, property) : false;\n })?.key;\n }, [layout, collection, status, disabledProp, lockedPropertyKeys]);\n\n function isFieldDisabled(key: string, property: NonNullable<typeof collection.properties[string]>): boolean {\n const isNew = status === \"new\" || status === \"copy\";\n const isStringOrNumber = property.type === \"string\" || property.type === \"number\";\n const isIdAndAuto = isStringOrNumber && \"isId\" in property && typeof property.isId === \"string\" && property.isId !== \"manual\";\n return Boolean(\n disabledProp\n || (!autoSave && formex.isSubmitting)\n || isReadOnly(property)\n || isDisabled(property)\n || (!isNew && \"isId\" in property && Boolean(property.isId))\n || (isNew && isIdAndAuto)\n || (isNew && lockedPropertyKeys?.includes(key))\n );\n }\n\n const renderField = (field: ResolvedFormField): React.ReactNode => {\n\n if (field.additional) {\n const additionalField = collection.additionalFields?.find(f => f.key === field.key);\n if (!additionalField || !entity) return null;\n\n const AdditionalFieldBuilder = additionalField.Builder;\n if (!AdditionalFieldBuilder && !additionalField.value) {\n throw new Error(\"When using additional fields you need to provide a Builder or a value\");\n }\n const child = AdditionalFieldBuilder\n ? <AdditionalFieldBuilder entity={entity} context={rebaseContext}/>\n : <div className={\"w-full\"}>\n <AdditionalFieldValue\n field={additionalField}\n entity={entity}\n context={rebaseContext}/>\n </div>;\n\n return (\n // Through FieldBlock like every other cell, so a computed\n // column is labelled at the same size, with the same gap to its\n // box, as the property next to it on the grid.\n <div key={`additional_${field.key}`}\n className={spanClass(field.span)}>\n <FieldBlock propertyKey={field.key}\n showLabel={true}\n label={additionalField.name}\n icon={<AlignLeftIcon size={LABEL_ICON_SIZE}/>}>\n <div className={cls(paperMixin, \"w-full min-h-12 p-4 md:p-6 overflow-x-auto no-scrollbar\")}>\n {child}\n </div>\n </FieldBlock>\n </div>\n );\n }\n\n const property = collection.properties?.[field.key];\n if (!property) {\n console.warn(`Property ${field.key} not found in collection ${collection.name} in properties or additional fields. Skipping.`);\n return null;\n }\n // A field a rule hides for these values, or that this user may not\n // read, takes its label with it: the binding renders nothing, and a\n // heading over nothing is worse.\n if (property.conditions?.hidden || effectiveAccess(property)) {\n const shown = resolveFormProperty({\n propertyKey: field.key,\n property,\n values: formex.values,\n previousValues: baseInitialValues as Partial<M>,\n path,\n entityId,\n propertyConfigs: customizationController.propertyConfigs,\n ignoreMissingFields: true,\n authController\n });\n if (!shown || isHidden(shown)) return null;\n }\n\n const underlyingValueHasChanged: boolean =\n field.key in underlyingChanges &&\n !equal(formex.values[field.key], underlyingChanges[field.key]);\n\n const disabled = isFieldDisabled(field.key, property);\n // Three places a label can be. The panel-style editors carry their own\n // header. The one-line controls draw it inside their box, FireCMS-style,\n // so they all stand the same height. Everything else — multi-selects,\n // uploads, markdown, relations — is labelled above by FieldBlock.\n const selfLabelling = isSelfLabellingProperty(property);\n const labelInside = !selfLabelling\n && labelsInsideControl(property, customizationController.propertyConfigs);\n\n const cmsFormFieldProps: PropertyFieldBindingProps<M> = {\n propertyKey: field.key,\n disabled,\n property,\n // FieldBlock owns the description now, so the binding must not\n // repeat it — it still renders validation errors, which belong\n // against the control rather than under the label.\n includeDescription: false,\n hideLabel: !selfLabelling && !labelInside,\n underlyingValueHasChanged: underlyingValueHasChanged && !autoSave,\n context: fieldContext,\n partOfArray: false,\n minimalistView: false,\n // One height for every control in the form. Left to their own\n // defaults, a text field came out 48px, a select 44 and a switch 64.\n // `large`: the record-form density — a 64px box with the label\n // inside and a 16px value, or a 48px box under a label. 0.20.0 took\n // the form to `small` (32px) to match the reference, and the fields\n // read as cramped next to what they had been; see DESIGN.md \"Form\n // density\".\n size: \"large\",\n autoFocus: autoFocusKey === field.key\n };\n\n return (\n <div key={`field_${field.key}`} className={spanClass(field.span)}>\n <FieldBlock propertyKey={field.key}\n property={property}\n showLabel={!selfLabelling && !labelInside}\n labelInside={labelInside}>\n <PropertyFieldBinding {...cmsFormFieldProps}/>\n </FieldBlock>\n </div>\n );\n };\n\n const formFields = () => {\n\n if (Builder) {\n // Its own boundary: a Builder is usually a lazy chunk, and without\n // one, loading it suspends the nearest boundary above the record\n // view — which takes the identity bar down with the form.\n return <Suspense fallback={<CircularProgressCenter/>}>\n <Builder\n collection={collection}\n parentCollectionSlugs={parentCollectionSlugs}\n parentEntityIds={parentEntityIds}\n entity={entity}\n modifiedValues={formex.values}\n formContext={formContext}\n />\n </Suspense>;\n }\n\n const sections = showRail || !layout.sidebar.length\n ? layout.sections\n : [\n ...layout.sections,\n // Trailing, not leading. Beside the column these read as\n // peripheral; stacked above it they pushed the record's own name\n // below its status, which is the wrong thing to meet first.\n // Settings come after the content they apply to.\n {\n key: \"__rail\",\n title: \"Settings\",\n collapsible: false,\n collapsed: false,\n fields: layout.sidebar\n }\n ];\n\n return <>\n <FormSections\n sections={sections}\n collapsed={collapsedSections}\n onToggle={toggleSection}\n errorKeys={errorKeys}\n renderField={renderField}/>\n\n {/* Folded back with the rail's fields, and for the same reason. The\n rail renders only where it has been measured to fit, so on the\n split pane, the side panel and the dialog this block was dropped\n outright and the record's id was nowhere on screen but the\n truncated chip in the bar. */}\n {!showRail && layout.showRecordMeta && status === \"existing\" && entity && (\n <div className={cls(\"mt-8 pt-5 border-t max-w-sm\", defaultBorderMixin)}>\n <RecordMeta entity={entity as Entity<Record<string, unknown>>}/>\n </div>\n )}\n </>;\n };\n\n const formRef = useRef<HTMLDivElement>(null);\n\n const hasFormErrors = Object.keys(formex.errors).length > 0 && formex.submitCount > 0;\n\n const predatingViolationLines = useMemo(\n () => errorLines(predatingViolations, collection.properties),\n [predatingViolations, collection.properties]\n );\n\n const formView = <ErrorBoundary>\n <>\n {beforeFields}\n\n {/* The title, the `path/id` chip and the 72px gap under them used to\n live here — 219px above the first field, carrying nothing, and\n scrolling the record's identity away on the first wheel click.\n It is now in the persistent bar, where it stays put. */}\n\n {!entity?.values && initialStatus === \"existing\" &&\n <Alert color={\"warning\"} size={\"small\"} outerClassName={\"w-full mb-4 text-xs\"}>\n {t(\"entity_does_not_exist\")}\n </Alert>}\n\n {children}\n\n {hasEntityId(initialEntityId) && !entity && initialStatus !== \"new\" && <Alert color={\"info\"} size={\"small\"}>\n {t(\"entity_does_not_exist\")}\n </Alert>}\n\n {hasFormErrors && <Alert color={\"error\"} size={\"small\"} outerClassName={\"w-full mt-2\"}>\n {t(\"fix_errors_before_saving\")}\n </Alert>}\n\n {predatingViolationLines.length > 0 &&\n <Alert color={\"warning\"} size={\"small\"} outerClassName={\"w-full mt-2\"}>\n <Typography variant={\"caption\"} component={\"div\"}>\n {t(\"form_predating_rule_violations\")}\n </Typography>\n <ul className={\"list-disc pl-5 mt-1\"}>\n {predatingViolationLines.map(({ path: errorPath, label, message }) =>\n <li key={errorPath}><Typography variant={\"caption\"}>{`${label}: ${message}`}</Typography></li>)}\n </ul>\n </Alert>}\n\n {formContext && <>\n <div ref={formRef}>\n {formFields()}\n <ErrorFocus containerRef={formRef}/>\n </div>\n </>}\n\n {afterFields}\n\n <Dialog open={discardDialogOpen} onOpenChange={setDiscardDialogOpen} maxWidth={\"sm\"}>\n <DialogTitle>{status === \"existing\" ? \"Discard changes?\" : \"Clear form?\"}</DialogTitle>\n <DialogContent>\n <Typography>\n {status === \"existing\"\n ? \"All unsaved changes will be lost. \"\n : \"All entered values will be cleared. \"}\n You can bring them back with Undo (⌘Z / Ctrl+Z), or from\n the notification, for as long as this form stays open.\n </Typography>\n </DialogContent>\n <DialogActions>\n <Button variant={\"text\"} onClick={() => setDiscardDialogOpen(false)}>\n Cancel\n </Button>\n <Button variant={\"filled\"} color={\"error\"} onClick={() => {\n setDiscardDialogOpen(false);\n discard(formex, status, baseInitialValues);\n }}>\n {status === \"existing\" ? \"Discard\" : \"Clear\"}\n </Button>\n </DialogActions>\n </Dialog>\n </>\n </ErrorBoundary>;\n\n useEffect(() => {\n if (hasEntityId(entityId) && onIdChange)\n onIdChange(entityId);\n }, [entityId, onIdChange]);\n\n if (!collection || !path) {\n throw Error(\"INTERNAL: Collection and path must be defined in form context\");\n }\n\n const EntityFormActionsRender = EntityFormActionsComponent as React.FC<EntityFormActionsProps>;\n\n const dialogActions = <EntityFormActionsRender\n collection={collection}\n path={path}\n entity={entity}\n savingError={savingError}\n formex={formex as FormexController<Record<string, unknown>>}\n disabled={actionsDisabled}\n status={status}\n pluginActions={pluginActionsProp ?? []}\n openEntityMode={openEntityMode}\n showDefaultActions={showDefaultActions}\n navigateBack={navigateBack}\n formContext={formContext as FormContext<Record<string, unknown>>}\n />;\n\n return (\n <Formex value={formex}>\n <FormUploadsContext.Provider value={uploadTracker}>\n <form\n ref={formElementRef}\n onSubmit={formex.handleSubmit}\n onReset={(e) => {\n e.preventDefault();\n if (formex.dirty) {\n setDiscardDialogOpen(true);\n } else {\n formex.resetForm({ values: baseInitialValues as M });\n }\n }}\n noValidate\n className={cls(\"@container/form flex-1 flex flex-col w-full min-h-0\", className)}>\n\n {/* The actions bar is a sibling of this row rather than absolutely\n positioned over it, so the scroll area ends where the bar\n begins. As an overlay it hid the last field, and the bottom\n padding that compensated was a guess at its height. */}\n <div className={\"flex-1 min-h-0 flex flex-row w-full\"}>\n\n {/* Main column. Its own container scope, so a field's span\n answers to the column it sits in rather than to the window —\n the same form renders at four very different widths. */}\n {/* `items-start`: the column is a flex item, so without it the cross-axis\n default stretches it to the scroller's height. Its content then\n overflows its own box and the bottom padding sits at the bottom of\n the *viewport* instead of after the last field — which is why the\n form appeared to have no padding however large `pb-*` grew. */}\n <div className={\"flex-1 min-w-0 overflow-y-auto flex justify-center items-start\"}>\n <div\n id={`form_${path}`}\n className={cls(\n // Two rules widen the column, and they answer to\n // different things on purpose. `@7xl/form` measures\n // the form itself: full screen on a laptop is ~1400px\n // of form, which after the 304px rail leaves room for\n // the wider column with real gutters either side — and\n // it stays 768 in the split pane and the side panel,\n // which never get that wide. `2xl` is the older\n // viewport rule, kept so a panel on a large monitor\n // does not get *narrower* than it is today.\n \"@container/col w-full max-w-3xl @7xl/form:max-w-4xl 2xl:max-w-4xl flex flex-col\",\n openEntityMode === \"dialog\"\n ? \"pt-5 pb-8 px-6 sm:px-8\"\n : \"pt-6 pb-12 px-5 sm:px-8\"\n )}>\n\n {manualApplyLocalChanges && hasLocalChanges && localChangesCacheKey &&\n <div className={\"flex justify-end mb-3\"}>\n <LocalChangesMenu<M>\n cacheKey={localChangesCacheKey}\n properties={collection.properties}\n cachedData={localChangesData as Partial<M>}\n formex={formex}\n onClearLocalChanges={() => {\n setLocalChangesCleared(true);\n onClearLocalChanges?.();\n }}\n />\n </div>}\n\n {formView}\n\n </div>\n </div>\n\n {showRail && <FormRail\n fields={layout.sidebar}\n showRecordMeta={layout.showRecordMeta && status === \"existing\"}\n entity={entity as Entity<Record<string, unknown>> | undefined}\n renderField={renderField}/>}\n </div>\n\n {dialogActions}\n\n </form>\n </FormUploadsContext.Provider>\n\n </Formex>\n );\n}\n\nfunction useOnAutoSave<M extends Record<string, unknown>>(autoSave: undefined | boolean, formex: FormexController<M>, lastSavedValues: React.MutableRefObject<EntityValues<M> | undefined>, save: (values: EntityValues<M>) => Promise<Entity<M> | void>) {\n useEffect(() => {\n if (!autoSave) return;\n if (formex.values && !equal(formex.values, lastSavedValues.current)) {\n save(formex.values);\n }\n }, [autoSave, formex.values]);\n}\n\n/**\n * A nested error map — the shape `zodToFormErrors` builds — as one line per\n * failing field, labelled with the property's name.\n */\nfunction errorLines(\n errors: Record<string, unknown>,\n properties: Properties\n): { path: string; label: string; message: string }[] {\n const lines: { path: string; label: string; message: string }[] = [];\n const walk = (value: unknown, path: string[], label: string[], props: Properties | undefined) => {\n if (typeof value === \"string\") {\n lines.push({ path: path.join(\".\"), label: label.join(\" › \"), message: value });\n return;\n }\n if (!value || typeof value !== \"object\") return;\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n const property = props?.[key] as Property | undefined;\n const childProps = property?.type === \"map\" ? property.properties as Properties | undefined : undefined;\n walk(child, [...path, key], [...label, property?.name ?? key], childProps);\n }\n };\n walk(errors, [], [], properties);\n return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,SAAgB,WAA8C,EAC1D,MACA,UAAU,cACV,YACA,kBACA,YACA,SACA,QAAQ,YACR,oBACA,oBACA,eACA,WACA,gBACA,gBACA,iBAAiB,eACjB,QAAQ,YACR,UAAU,cACV,SACA,uBACA,iBACA,6BAA6B,mBAC7B,qBAAqB,MACrB,cAAc,kBACd,UAEA,UAAU,cACV,wBAAwB,4BACxB,SAAS,aACT,sBAAsB,0BACtB,oBAEA,cACA,aACA,eAAe,mBAEf,uBACA,iBAAiB,qBACjB,kBACA,yBACA,sBACA,uBACmB;CAEnB,MAAM,eAAe,kBAAkB;EACnC,IAAI,kBACA,iBAAiB;CAEzB,GAAG,CAAC,gBAAgB,CAAC;CAErB,MAAM,iBAAiB,kBAAkB;CACzC,MAAM,CAAC,QAAQ,aAAa,SAAuB,aAAa;;;;;;;;CAShE,MAAM,CAAC,aAAa,kBAAkB,SAAgC,KAAA,CAAS;CAC/E,MAAM,SAAS,eAAe,WAAW,aAAa,cAAc,KAAA;CAEpE,MAAM,gBAAgB,WAAyB;EAC3C,UAAU,MAAM;EAChB,iBAAiB,MAAM;CAC3B;;;;;CAMA,MAAM,CAAC,iBAAiB,sBAAsB,SAA6D,KAAA,CAAS;CACpH,qBAAqB,uBAAuB;EACxC,IAAI,CAAC,mBAAmB,CAAC,cAAc;EACvC,MAAM,UAAU;EAChB,oBAAoB,IAAI;EAIxB,gBAAgB,QAAQ,MAAM,CAAC,CAC1B,MAAM,WAAW;GACd,IAAI,OAAO,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iD,UAA+B,QAA6B,iBAAsE,MAA8D;CACtP,gBAAgB;EACZ,IAAI,CAAC,UAAU;EACf,IAAI,OAAO,UAAU,CAAC,UAAM,OAAO,QAAQ,gBAAgB,OAAO,GAC9D,KAAK,OAAO,MAAM;CAE1B,GAAG,CAAC,UAAU,OAAO,MAAM,CAAC;AAChC;;;;;AAMA,SAAS,WACL,QACA,YACkD;CAClD,MAAM,QAA4D,CAAC;CACnE,MAAM,QAAQ,OAAgB,MAAgB,OAAiB,UAAkC;EAC7F,IAAI,OAAO,UAAU,UAAU;GAC3B,MAAM,KAAK;IAAE,MAAM,KAAK,KAAK,GAAG;IAAG,OAAO,MAAM,KAAK,KAAK;IAAG,SAAS;GAAM,CAAC;GAC7E;EACJ;EACA,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU;EACzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAgC,GAAG;GACzE,MAAM,WAAW,QAAQ;GACzB,MAAM,aAAa,UAAU,SAAS,QAAQ,SAAS,aAAuC,KAAA;GAC9F,KAAK,OAAO,CAAC,GAAG,MAAM,GAAG,GAAG,CAAC,GAAG,OAAO,UAAU,QAAQ,GAAG,GAAG,UAAU;EAC7E;CACJ;CACA,KAAK,QAAQ,CAAC,GAAG,CAAC,GAAG,UAAU;CAC/B,OAAO;AACX"}
|
|
@@ -5,6 +5,7 @@ import { getInitialEntityValues, getParentLinkValues, getTouchedPropertyValues,
|
|
|
5
5
|
import { EntityForm } from "./EntityForm.js";
|
|
6
6
|
import { useCallback, useMemo, useState } from "react";
|
|
7
7
|
import { jsx } from "react/jsx-runtime";
|
|
8
|
+
import { hasEntityId } from "@rebasepro/common";
|
|
8
9
|
import { getEntityFromCache, getLocalChangesBackup, removeEntityFromCache, removeEntityFromMemoryCache, saveEntityToCache, saveEntityWithCallbacks, useAnalyticsController, useAuthController, useCustomizationController, useData, useSlot, useSnackbarController, useTranslation } from "@rebasepro/app";
|
|
9
10
|
//#region src/form/EntityFormBinding.tsx
|
|
10
11
|
/**
|
|
@@ -35,6 +36,8 @@ function EntityFormBinding({ path, entityId: entityIdProp, collection, entity, i
|
|
|
35
36
|
const context = useAdminContext();
|
|
36
37
|
const analyticsController = useAnalyticsController();
|
|
37
38
|
const [status, setStatus] = useState(initialStatus);
|
|
39
|
+
const [savedEntity, setSavedEntity] = useState(void 0);
|
|
40
|
+
const currentEntity = entity ?? (status === "existing" ? savedEntity : void 0);
|
|
38
41
|
const idKeyValues = useMemo(() => newRecordIdValues(collection, status, entityIdProp), [
|
|
39
42
|
collection,
|
|
40
43
|
status,
|
|
@@ -62,21 +65,21 @@ function EntityFormBinding({ path, entityId: entityIdProp, collection, entity, i
|
|
|
62
65
|
]);
|
|
63
66
|
const lockedPropertyKeys = useMemo(() => Object.keys(parentLinkValues), [parentLinkValues]);
|
|
64
67
|
const baseInitialValues = useMemo(() => ({
|
|
65
|
-
...getInitialEntityValues(authController, collection, path, status,
|
|
68
|
+
...getInitialEntityValues(authController, collection, path, status, currentEntity, customizationController.propertyConfigs),
|
|
66
69
|
...parentLinkValues
|
|
67
70
|
}), [
|
|
68
71
|
authController,
|
|
69
72
|
collection,
|
|
70
73
|
path,
|
|
71
74
|
status,
|
|
72
|
-
|
|
75
|
+
currentEntity,
|
|
73
76
|
customizationController.propertyConfigs,
|
|
74
77
|
parentLinkValues
|
|
75
78
|
]);
|
|
76
79
|
const localChangesBackup = getLocalChangesBackup(collection);
|
|
77
80
|
const autoApplyLocalChanges = localChangesBackup === "auto_apply";
|
|
78
81
|
const manualApplyLocalChanges = localChangesBackup === "manual_apply";
|
|
79
|
-
const localChangesDataRaw = useMemo(() => entityId ? getEntityFromCache(path + "/" + entityId) : getEntityFromCache(path + "#new"), [entityId, path]);
|
|
82
|
+
const localChangesDataRaw = useMemo(() => hasEntityId(entityId) ? getEntityFromCache(path + "/" + entityId) : getEntityFromCache(path + "#new"), [entityId, path]);
|
|
80
83
|
const [localChangesCleared, setLocalChangesCleared] = useState(false);
|
|
81
84
|
const computedInitialValues = useMemo(() => {
|
|
82
85
|
return autoApplyLocalChanges && localChangesDataRaw ? overlayEdit(baseInitialValues, localChangesDataRaw) : baseInitialValues;
|
|
@@ -148,13 +151,14 @@ function EntityFormBinding({ path, entityId: entityIdProp, collection, entity, i
|
|
|
148
151
|
path,
|
|
149
152
|
entityId,
|
|
150
153
|
values,
|
|
151
|
-
previousValues:
|
|
154
|
+
previousValues: currentEntity?.values,
|
|
152
155
|
collection,
|
|
153
156
|
status,
|
|
154
|
-
ifMatch: status === "existing" ?
|
|
157
|
+
ifMatch: status === "existing" ? currentEntity?.etag : void 0,
|
|
155
158
|
data: dataClient,
|
|
156
159
|
context,
|
|
157
160
|
afterSave: (updatedEntity) => {
|
|
161
|
+
setSavedEntity(updatedEntity);
|
|
158
162
|
clearDirtyCache();
|
|
159
163
|
onValuesModified?.(false, updatedEntity.values);
|
|
160
164
|
onEntityChange?.(updatedEntity);
|
|
@@ -193,7 +197,7 @@ function EntityFormBinding({ path, entityId: entityIdProp, collection, entity, i
|
|
|
193
197
|
}, [
|
|
194
198
|
path,
|
|
195
199
|
entityId,
|
|
196
|
-
|
|
200
|
+
currentEntity,
|
|
197
201
|
collection,
|
|
198
202
|
status,
|
|
199
203
|
dataClient,
|
|
@@ -213,7 +217,7 @@ function EntityFormBinding({ path, entityId: entityIdProp, collection, entity, i
|
|
|
213
217
|
where: { [name]: ["==", value] },
|
|
214
218
|
limit: 2
|
|
215
219
|
});
|
|
216
|
-
return (entityId ? data.filter((e) => e.id !== entityId) : data).length === 0;
|
|
220
|
+
return (hasEntityId(entityId) ? data.filter((e) => String(e.id) !== String(entityId)) : data).length === 0;
|
|
217
221
|
} catch (e) {
|
|
218
222
|
console.error("Error checking unique field", e);
|
|
219
223
|
return true;
|
|
@@ -253,7 +257,7 @@ function EntityFormBinding({ path, entityId: entityIdProp, collection, entity, i
|
|
|
253
257
|
path,
|
|
254
258
|
entityId: entityIdProp,
|
|
255
259
|
collection,
|
|
256
|
-
entity,
|
|
260
|
+
entity: currentEntity,
|
|
257
261
|
initialStatus,
|
|
258
262
|
initialDirtyValues,
|
|
259
263
|
onValuesModified,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EntityFormBinding.js","names":[],"sources":["../../src/form/EntityFormBinding.tsx"],"sourcesContent":["\nimport type { PluginFormActionProps, AdminCollection } from \"@rebasepro/cms-types\";\nimport React, { useCallback, useMemo, useState } from \"react\";\nimport { Entity, EntityStatus, EntityValues } from \"@rebasepro/types\";\nimport { AnalyticsEvent } from \"@rebasepro/cms-types\";\nimport type { EntityFormProps, OnUpdateParams } from \"../types/components/EntityFormProps\";\nimport type { EntityFormActionsProps } from \"../types/components/EntityFormActionsProps\";\n\nimport { getLocalChangesBackup } from \"@rebasepro/app\";\n\nimport {\n saveEntityWithCallbacks,\n useAuthController,\n useCustomizationController,\n useData,\n useSnackbarController,\n useTranslation,\n useSlot\n} from \"@rebasepro/app\";\nimport { FormexController } from \"@rebasepro/forms\";\nimport { useAnalyticsController } from \"@rebasepro/app\";\n\nimport {\n getEntityFromCache,\n removeEntityFromCache,\n removeEntityFromMemoryCache,\n saveEntityToCache\n} from \"@rebasepro/app\";\n\nimport { useCollectionRegistryController } from \"../hooks/navigation/contexts/CollectionRegistryContext\";\nimport { useSidePanel } from \"../hooks/useSidePanel\";\nimport { useAdminContext } from \"../hooks/useAdminContext\";\nimport { EntityForm } from \"./EntityForm\";\nimport {\n getInitialEntityValues,\n getParentLinkValues,\n getTouchedPropertyValues,\n getUnappliedLocalChanges,\n overlayEdit\n} from \"./form_utils\";\n\n/**\n * Props for the admin-connected EntityFormBinding wrapper.\n * Extends EntityFormProps — you can pass all the same props as EntityForm,\n * but the binding provides admin context (save, caching, analytics, plugin slots)\n * automatically.\n */\nexport type EntityFormBindingProps<M extends Record<string, unknown>> = Omit<EntityFormProps<M>,\n | \"onSubmit\"\n | \"onValuesChangeDeferred\"\n | \"onReset\"\n | \"uniqueFieldValidator\"\n | \"lockedPropertyKeys\"\n | \"beforeFields\"\n | \"afterFields\"\n | \"pluginActions\"\n | \"computedInitialValues\"\n | \"hasLocalChanges\"\n | \"localChangesData\"\n | \"manualApplyLocalChanges\"\n | \"localChangesCacheKey\"\n | \"onClearLocalChanges\"\n>;\n\n/**\n * admin-connected wrapper around EntityForm.\n *\n * Provides all backend concerns that the headless EntityForm delegates via callbacks:\n * - Save via the data layer (`saveEntityWithCallbacks`)\n * - Unique field validation via the data layer\n * - Entity caching (local changes backup/restore)\n * - Plugin slots (form.before, form.after, form.actions)\n * - Snackbar notifications on save success/error\n * - Analytics events\n * - Navigation via side entity controller\n *\n * Use this component inside the admin (`<RebaseShell>`).\n * For headless usage outside the admin, use `EntityForm` directly.\n *\n * @group Components\n */\nexport function EntityFormBinding<M extends Record<string, unknown>>({\n path,\n entityId: entityIdProp,\n collection,\n entity,\n initialStatus,\n onSaved,\n onValuesModified,\n onEntityChange,\n onStatusChange,\n openEntityMode = \"full_screen\",\n navigateBack: navigateBackProp,\n initialDirtyValues,\n ...restProps\n}: EntityFormBindingProps<M>) {\n\n const { t } = useTranslation();\n const sidePanelController = useSidePanel();\n const collectionRegistryController = useCollectionRegistryController();\n const authController = useAuthController();\n const dataClient = useData();\n const snackbarController = useSnackbarController();\n const customizationController = useCustomizationController();\n const context = useAdminContext();\n const analyticsController = useAnalyticsController();\n\n const [status, setStatus] = useState<EntityStatus>(initialStatus);\n // A new record given an id is created under it — a settings record kept\n // at a known key, a profile keyed by its user. Where the collection\n // declares its key property, the id is that property's value, set and\n // locked; where it declares none, it is the id the record is created with.\n // A copy never keeps the id: it is the original's.\n const idKeyValues = useMemo(\n () => newRecordIdValues(collection, status, entityIdProp),\n [collection, status, entityIdProp]);\n const [entityId, setEntityId] = useState<string | number | undefined>(() => {\n if (status === \"copy\") return undefined;\n if (status === \"new\") return Object.keys(idKeyValues).length > 0 ? undefined : entityIdProp;\n return entityIdProp;\n });\n\n // A record created under `parent/{id}/{relation}` belongs to that parent:\n // the server stamps the link on the create, so the form opens with it set\n // and does not offer it for editing. See `getParentLinkValues`.\n //\n // Keyed on the two callbacks rather than the controller. The controller is\n // a new object whenever its provider renders, which would hand the form a\n // new baseline each time.\n const { getCollection, getParentEntityIds } = collectionRegistryController;\n const parentLinkValues = useMemo(\n () => status === \"new\" || status === \"copy\"\n ? { ...getParentLinkValues({ getCollection, getParentEntityIds }, path, collection), ...idKeyValues }\n : {},\n [getCollection, getParentEntityIds, path, collection, status, idKeyValues]\n );\n const lockedPropertyKeys = useMemo(() => Object.keys(parentLinkValues), [parentLinkValues]);\n\n // --- Compute initial values with local changes ---\n const baseInitialValues = useMemo(\n () => ({\n ...getInitialEntityValues(authController, collection, path, status, entity, customizationController.propertyConfigs),\n ...parentLinkValues\n }),\n [authController, collection, path, status, entity, customizationController.propertyConfigs, parentLinkValues]\n );\n\n const localChangesBackup = getLocalChangesBackup(collection);\n const autoApplyLocalChanges = localChangesBackup === \"auto_apply\";\n const manualApplyLocalChanges = localChangesBackup === \"manual_apply\";\n\n const localChangesDataRaw = useMemo(() => entityId\n ? getEntityFromCache(path + \"/\" + entityId)\n : getEntityFromCache(path + \"#new\"), [entityId, path]);\n\n const [localChangesCleared, setLocalChangesCleared] = useState<boolean>(false);\n\n // `initialDirtyValues` is deliberately *not* merged in here any more. This\n // value is the form's baseline, and an edit folded into the baseline is\n // indistinguishable from saved data — which is how an edit carried over\n // from the side panel arrived reading \"Saved\". {@link EntityForm} applies\n // it as an overlay on the values instead, so the difference survives.\n //\n // The auto-applied local-changes backup is still folded in, unchanged, and\n // has the same shape of problem: a restored draft opens undirty and cannot\n // be saved until a field is touched. Left as it is rather than changed\n // blind, since nothing here exercises that path.\n const computedInitialValues = useMemo(() => {\n return autoApplyLocalChanges && localChangesDataRaw\n ? overlayEdit(baseInitialValues, localChangesDataRaw as Partial<M>)\n : baseInitialValues;\n }, [autoApplyLocalChanges, localChangesDataRaw, baseInitialValues]);\n\n const localChangesData = useMemo(() => {\n if (!localChangesDataRaw) return undefined;\n // What the form opens showing: the baseline plus any edit handed over by\n // the layout this one replaced. See {@link getUnappliedLocalChanges} for\n // why the banner is measured against that and not against the baseline.\n const openingValues = initialDirtyValues\n ? overlayEdit(computedInitialValues, initialDirtyValues)\n : computedInitialValues;\n return getUnappliedLocalChanges(\n localChangesDataRaw as Partial<M>,\n openingValues as Partial<M>\n );\n }, [localChangesDataRaw, computedInitialValues, initialDirtyValues]);\n\n const hasLocalChanges = !localChangesCleared && !!localChangesData && Object.keys(localChangesData as object).length > 0;\n\n const localChangesCacheKey = useMemo(() => {\n return (status === \"new\" || status === \"copy\") ? path + \"#new\" : path + \"/\" + entityId;\n }, [status, path, entityId]);\n\n // --- Navigate back ---\n const navigateBack = useCallback(() => {\n if (navigateBackProp) {\n navigateBackProp();\n return;\n }\n if (openEntityMode === \"side_panel\" || openEntityMode === \"dialog\") {\n sidePanelController.close();\n } else {\n window.history.back();\n }\n }, [navigateBackProp, openEntityMode, sidePanelController]);\n\n // --- Cache operations ---\n const clearDirtyCache = useCallback(() => {\n if (status === \"new\" || status === \"copy\") {\n removeEntityFromMemoryCache(path + \"#new\");\n removeEntityFromCache(path + \"#new\");\n } else {\n removeEntityFromMemoryCache(path + \"/\" + entityId);\n removeEntityFromCache(path + \"/\" + entityId);\n }\n }, [status, path, entityId]);\n\n const onReset = useCallback(() => {\n clearDirtyCache();\n }, [clearDirtyCache]);\n\n const onValuesChangeDeferred = useCallback((values: M, controller: FormexController<M>) => {\n const key = (status === \"new\" || status === \"copy\") ? path + \"#new\" : path + \"/\" + entityId;\n if (controller.dirty) {\n const touchedValues = getTouchedPropertyValues(values, controller.touched);\n if (Object.keys(touchedValues).length > 0) {\n saveEntityToCache(key, touchedValues);\n } else {\n removeEntityFromCache(key);\n }\n }\n }, [status, path, entityId]);\n\n // --- Save via data layer ---\n const onSubmit = useCallback(async (values: M, formex: FormexController<M>): Promise<Entity<M> | void> => {\n try {\n const savedEntity = await saveEntityWithCallbacks<M>({\n path,\n entityId,\n values,\n previousValues: entity?.values,\n collection,\n status,\n // The version the form's baseline is — it follows the live\n // record, tag and all — so a save made against a version that\n // someone has since replaced is refused, not written over it.\n ifMatch: status === \"existing\" ? entity?.etag : undefined,\n data: dataClient,\n context,\n afterSave: (updatedEntity: Entity<M>) => {\n clearDirtyCache();\n onValuesModified?.(false, updatedEntity.values);\n onEntityChange?.(updatedEntity);\n setStatus(\"existing\");\n setEntityId(updatedEntity.id);\n onStatusChange?.(\"existing\");\n\n if (onSaved) {\n onSaved({\n entity: updatedEntity,\n status,\n path,\n entityId: updatedEntity.id,\n collection\n });\n }\n },\n afterSaveError: (e: Error) => {\n // Refused because the record moved on between the last\n // version the form saw and this save. The new version is\n // on its way over the listener, and the form rebases the\n // edit onto it, marking what changed underneath.\n // Read by code, not `instanceof`: the error can come from\n // another copy of the types package.\n const changedElsewhere = typeof e === \"object\" && e !== null\n && \"code\" in e && e.code === \"PRECONDITION_FAILED\";\n snackbarController.open({\n type: \"error\",\n title: t(\"error_saving_entity\"),\n message: changedElsewhere ? t(\"error_record_changed_elsewhere\") : e?.message\n });\n console.error(\"Error saving entity\", path, entityId, e);\n }\n });\n\n const autoSave = collection.formAutoSave;\n if (!autoSave) {\n snackbarController.open({\n type: \"success\",\n message: `${collection.singularName ?? collection.name}: ${t(\"saved_correctly\")}`\n });\n }\n\n const eventName: AnalyticsEvent = status === \"new\"\n ? \"new_entity_saved\"\n : (status === \"copy\" ? \"entity_copied\" : (status === \"existing\" ? \"entity_edited\" : \"unmapped_event\"));\n analyticsController.onAnalyticsEvent?.(eventName, { path });\n\n return savedEntity;\n } catch (e: unknown) {\n console.error(e);\n throw e;\n }\n }, [path, entityId, entity, collection, status, dataClient, context, clearDirtyCache, onValuesModified, onEntityChange, onSaved, onStatusChange, snackbarController, analyticsController, t]);\n\n // --- Unique field validation via data layer ---\n const uniqueFieldValidator = useCallback(async ({\n name,\n value\n }: { name: string; value: unknown }) => {\n try {\n const accessor = dataClient.collection(path);\n const { data } = await accessor.find({\n where: { [name]: [\"==\", value] },\n limit: 2\n });\n const otherEntities = entityId ? data.filter(e => e.id !== entityId) : data;\n return otherEntities.length === 0;\n } catch (e: unknown) {\n console.error(\"Error checking unique field\", e);\n return true;\n }\n }, [dataClient, path, entityId]);\n\n // --- Plugin slots ---\n const parentCollectionSlugs = collectionRegistryController.getParentCollectionSlugs(path);\n const parentEntityIds = collectionRegistryController.getParentEntityIds(path);\n\n // Build a minimal formContext for plugin slot props — the full one is built inside EntityForm\n const formActionProps: PluginFormActionProps = useMemo(() => ({\n entityId,\n parentCollectionSlugs,\n parentEntityIds,\n path,\n status,\n collection: collection as AdminCollection,\n context,\n // Genuinely absent here, and `PluginFormActionProps` declares it\n // optional — so this needed no conversion at all. Asserting a\n // `FormContext` onto `undefined` told every plugin slot the opposite of\n // the comment three lines up.\n formContext: undefined,\n openEntityMode,\n disabled: false\n }), [entityId, parentCollectionSlugs, parentEntityIds, path, status, collection, context, openEntityMode]);\n\n // `form.actions` is rendered by the entity view's identity bar, which has\n // the real formContext and does not cost a footer. Rendering it here too\n // would show Autofill twice.\n const pluginFormBefore = useSlot(\"form.before\", formActionProps);\n const pluginFormAfter = useSlot(\"form.after\", formActionProps);\n\n return (\n <EntityForm<M>\n {...restProps}\n path={path}\n entityId={entityIdProp}\n collection={collection}\n entity={entity}\n initialStatus={initialStatus}\n initialDirtyValues={initialDirtyValues}\n // Not handed down: `onSubmit` above reports the save, for Save and\n // autosave alike. The form reporting it too called it twice.\n onValuesModified={onValuesModified}\n onEntityChange={onEntityChange}\n onStatusChange={onStatusChange}\n openEntityMode={openEntityMode}\n navigateBack={navigateBack}\n // Headless callbacks\n onSubmit={onSubmit}\n onValuesChangeDeferred={onValuesChangeDeferred}\n onReset={onReset}\n uniqueFieldValidator={uniqueFieldValidator}\n lockedPropertyKeys={lockedPropertyKeys}\n // Slots\n beforeFields={pluginFormBefore}\n afterFields={pluginFormAfter}\n pluginActions={[]}\n // Local changes\n computedInitialValues={computedInitialValues as Partial<M>}\n hasLocalChanges={hasLocalChanges}\n localChangesData={localChangesData as Partial<M>}\n manualApplyLocalChanges={manualApplyLocalChanges}\n localChangesCacheKey={localChangesCacheKey}\n onClearLocalChanges={() => setLocalChangesCleared(true)}\n />\n );\n}\n\n/**\n * The key property's value for a new record created under a known id: the id,\n * under the one property the collection marks `isId`. Empty when the record\n * is not new, has no id, or the collection declares no single key property —\n * then the id travels as the id the record is created with instead.\n */\nfunction newRecordIdValues(\n collection: AdminCollection,\n status: EntityStatus,\n entityId: string | number | undefined\n): Record<string, unknown> {\n if (status !== \"new\" || entityId === undefined) return {};\n const keys = Object.entries(collection.properties ?? {})\n .filter(([, property]) => typeof property === \"object\" && property !== null && \"isId\" in property && Boolean(property.isId))\n .map(([key]) => key);\n return keys.length === 1 ? { [keys[0]]: entityId } : {};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAiFA,SAAgB,kBAAqD,EACjE,MACA,UAAU,cACV,YACA,QACA,eACA,SACA,kBACA,gBACA,gBACA,iBAAiB,eACjB,cAAc,kBACd,oBACA,GAAG,aACuB;CAE1B,MAAM,EAAE,MAAM,eAAe;CAC7B,MAAM,sBAAsB,aAAa;CACzC,MAAM,+BAA+B,gCAAgC;CACrE,MAAM,iBAAiB,kBAAkB;CACzC,MAAM,aAAa,QAAQ;CAC3B,MAAM,qBAAqB,sBAAsB;CACjD,MAAM,0BAA0B,2BAA2B;CAC3D,MAAM,UAAU,gBAAgB;CAChC,MAAM,sBAAsB,uBAAuB;CAEnD,MAAM,CAAC,QAAQ,aAAa,SAAuB,aAAa;CAMhE,MAAM,cAAc,cACV,kBAAkB,YAAY,QAAQ,YAAY,GACxD;EAAC;EAAY;EAAQ;CAAY,CAAC;CACtC,MAAM,CAAC,UAAU,eAAe,eAA4C;EACxE,IAAI,WAAW,QAAQ,OAAO,KAAA;EAC9B,IAAI,WAAW,OAAO,OAAO,OAAO,KAAK,WAAW,CAAC,CAAC,SAAS,IAAI,KAAA,IAAY;EAC/E,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G;EAAC;EAAY;EAAM;CAAQ,CAAC;CAG/B,MAAM,wBAAwB,6BAA6B,yBAAyB,IAAI;CACxF,MAAM,kBAAkB,6BAA6B,mBAAmB,IAAI;CAG5E,MAAM,kBAAyC,eAAe;EAC1D;EACA;EACA;EACA;EACA;EACY;EACZ;EAKA,aAAa,KAAA;EACb;EACA,UAAU;CACd,IAAI;EAAC;EAAU;EAAuB;EAAiB;EAAM;EAAQ;EAAY;EAAS;CAAc,CAAC;CAKzG,MAAM,mBAAmB,QAAQ,eAAe,eAAe;CAC/D,MAAM,kBAAkB,QAAQ,cAAc,eAAe;CAE7D,OACI,oBAAC,YAAD;EACI,GAAI;EACE;EACN,UAAU;EACE;EACJ;EACO;EACK;EAGF;EACF;EACA;EACA;EACF;EAEJ;EACc;EACf;EACa;EACF;EAEpB,cAAc;EACd,aAAa;EACb,eAAe,CAAC;EAEO;EACN;EACC;EACO;EACH;EACtB,2BAA2B,uBAAuB,IAAI;CACzD,CAAA;AAET;;;;;;;AAQA,SAAS,kBACL,YACA,QACA,UACuB;CACvB,IAAI,WAAW,SAAS,aAAa,KAAA,GAAW,OAAO,CAAC;CACxD,MAAM,OAAO,OAAO,QAAQ,WAAW,cAAc,CAAC,CAAC,CAAC,CACnD,QAAQ,GAAG,cAAc,OAAO,aAAa,YAAY,aAAa,QAAQ,UAAU,YAAY,QAAQ,SAAS,IAAI,CAAC,CAAC,CAC3H,KAAK,CAAC,SAAS,GAAG;CACvB,OAAO,KAAK,WAAW,IAAI,GAAG,KAAK,KAAK,SAAS,IAAI,CAAC;AAC1D"}
|
|
1
|
+
{"version":3,"file":"EntityFormBinding.js","names":[],"sources":["../../src/form/EntityFormBinding.tsx"],"sourcesContent":["\nimport type { PluginFormActionProps, AdminCollection } from \"@rebasepro/cms-types\";\nimport { hasEntityId } from \"@rebasepro/common\";\nimport React, { useCallback, useMemo, useState } from \"react\";\nimport { Entity, EntityStatus, EntityValues } from \"@rebasepro/types\";\nimport { AnalyticsEvent } from \"@rebasepro/cms-types\";\nimport type { EntityFormProps, OnUpdateParams } from \"../types/components/EntityFormProps\";\nimport type { EntityFormActionsProps } from \"../types/components/EntityFormActionsProps\";\n\nimport { getLocalChangesBackup } from \"@rebasepro/app\";\n\nimport {\n saveEntityWithCallbacks,\n useAuthController,\n useCustomizationController,\n useData,\n useSnackbarController,\n useTranslation,\n useSlot\n} from \"@rebasepro/app\";\nimport { FormexController } from \"@rebasepro/forms\";\nimport { useAnalyticsController } from \"@rebasepro/app\";\n\nimport {\n getEntityFromCache,\n removeEntityFromCache,\n removeEntityFromMemoryCache,\n saveEntityToCache\n} from \"@rebasepro/app\";\n\nimport { useCollectionRegistryController } from \"../hooks/navigation/contexts/CollectionRegistryContext\";\nimport { useSidePanel } from \"../hooks/useSidePanel\";\nimport { useAdminContext } from \"../hooks/useAdminContext\";\nimport { EntityForm } from \"./EntityForm\";\nimport {\n getInitialEntityValues,\n getParentLinkValues,\n getTouchedPropertyValues,\n getUnappliedLocalChanges,\n overlayEdit\n} from \"./form_utils\";\n\n/**\n * Props for the admin-connected EntityFormBinding wrapper.\n * Extends EntityFormProps — you can pass all the same props as EntityForm,\n * but the binding provides admin context (save, caching, analytics, plugin slots)\n * automatically.\n */\nexport type EntityFormBindingProps<M extends Record<string, unknown>> = Omit<EntityFormProps<M>,\n | \"onSubmit\"\n | \"onValuesChangeDeferred\"\n | \"onReset\"\n | \"uniqueFieldValidator\"\n | \"lockedPropertyKeys\"\n | \"beforeFields\"\n | \"afterFields\"\n | \"pluginActions\"\n | \"computedInitialValues\"\n | \"hasLocalChanges\"\n | \"localChangesData\"\n | \"manualApplyLocalChanges\"\n | \"localChangesCacheKey\"\n | \"onClearLocalChanges\"\n>;\n\n/**\n * admin-connected wrapper around EntityForm.\n *\n * Provides all backend concerns that the headless EntityForm delegates via callbacks:\n * - Save via the data layer (`saveEntityWithCallbacks`)\n * - Unique field validation via the data layer\n * - Entity caching (local changes backup/restore)\n * - Plugin slots (form.before, form.after, form.actions)\n * - Snackbar notifications on save success/error\n * - Analytics events\n * - Navigation via side entity controller\n *\n * Use this component inside the admin (`<RebaseShell>`).\n * For headless usage outside the admin, use `EntityForm` directly.\n *\n * @group Components\n */\nexport function EntityFormBinding<M extends Record<string, unknown>>({\n path,\n entityId: entityIdProp,\n collection,\n entity,\n initialStatus,\n onSaved,\n onValuesModified,\n onEntityChange,\n onStatusChange,\n openEntityMode = \"full_screen\",\n navigateBack: navigateBackProp,\n initialDirtyValues,\n ...restProps\n}: EntityFormBindingProps<M>) {\n\n const { t } = useTranslation();\n const sidePanelController = useSidePanel();\n const collectionRegistryController = useCollectionRegistryController();\n const authController = useAuthController();\n const dataClient = useData();\n const snackbarController = useSnackbarController();\n const customizationController = useCustomizationController();\n const context = useAdminContext();\n const analyticsController = useAnalyticsController();\n\n const [status, setStatus] = useState<EntityStatus>(initialStatus);\n // The record a create made, until the `entity` prop names it: from the\n // create on, the form edits that record, and a caller that does not hand\n // it back would otherwise leave an \"existing\" form with nothing behind it.\n const [savedEntity, setSavedEntity] = useState<Entity<M> | undefined>(undefined);\n const currentEntity = entity ?? (status === \"existing\" ? savedEntity : undefined);\n // A new record given an id is created under it — a settings record kept\n // at a known key, a profile keyed by its user. Where the collection\n // declares its key property, the id is that property's value, set and\n // locked; where it declares none, it is the id the record is created with.\n // A copy never keeps the id: it is the original's.\n const idKeyValues = useMemo(\n () => newRecordIdValues(collection, status, entityIdProp),\n [collection, status, entityIdProp]);\n const [entityId, setEntityId] = useState<string | number | undefined>(() => {\n if (status === \"copy\") return undefined;\n if (status === \"new\") return Object.keys(idKeyValues).length > 0 ? undefined : entityIdProp;\n return entityIdProp;\n });\n\n // A record created under `parent/{id}/{relation}` belongs to that parent:\n // the server stamps the link on the create, so the form opens with it set\n // and does not offer it for editing. See `getParentLinkValues`.\n //\n // Keyed on the two callbacks rather than the controller. The controller is\n // a new object whenever its provider renders, which would hand the form a\n // new baseline each time.\n const { getCollection, getParentEntityIds } = collectionRegistryController;\n const parentLinkValues = useMemo(\n () => status === \"new\" || status === \"copy\"\n ? { ...getParentLinkValues({ getCollection, getParentEntityIds }, path, collection), ...idKeyValues }\n : {},\n [getCollection, getParentEntityIds, path, collection, status, idKeyValues]\n );\n const lockedPropertyKeys = useMemo(() => Object.keys(parentLinkValues), [parentLinkValues]);\n\n // --- Compute initial values with local changes ---\n const baseInitialValues = useMemo(\n () => ({\n ...getInitialEntityValues(authController, collection, path, status, currentEntity, customizationController.propertyConfigs),\n ...parentLinkValues\n }),\n [authController, collection, path, status, currentEntity, customizationController.propertyConfigs, parentLinkValues]\n );\n\n const localChangesBackup = getLocalChangesBackup(collection);\n const autoApplyLocalChanges = localChangesBackup === \"auto_apply\";\n const manualApplyLocalChanges = localChangesBackup === \"manual_apply\";\n\n const localChangesDataRaw = useMemo(() => hasEntityId(entityId)\n ? getEntityFromCache(path + \"/\" + entityId)\n : getEntityFromCache(path + \"#new\"), [entityId, path]);\n\n const [localChangesCleared, setLocalChangesCleared] = useState<boolean>(false);\n\n // `initialDirtyValues` is deliberately *not* merged in here any more. This\n // value is the form's baseline, and an edit folded into the baseline is\n // indistinguishable from saved data — which is how an edit carried over\n // from the side panel arrived reading \"Saved\". {@link EntityForm} applies\n // it as an overlay on the values instead, so the difference survives.\n //\n // The auto-applied local-changes backup is still folded in, unchanged, and\n // has the same shape of problem: a restored draft opens undirty and cannot\n // be saved until a field is touched. Left as it is rather than changed\n // blind, since nothing here exercises that path.\n const computedInitialValues = useMemo(() => {\n return autoApplyLocalChanges && localChangesDataRaw\n ? overlayEdit(baseInitialValues, localChangesDataRaw as Partial<M>)\n : baseInitialValues;\n }, [autoApplyLocalChanges, localChangesDataRaw, baseInitialValues]);\n\n const localChangesData = useMemo(() => {\n if (!localChangesDataRaw) return undefined;\n // What the form opens showing: the baseline plus any edit handed over by\n // the layout this one replaced. See {@link getUnappliedLocalChanges} for\n // why the banner is measured against that and not against the baseline.\n const openingValues = initialDirtyValues\n ? overlayEdit(computedInitialValues, initialDirtyValues)\n : computedInitialValues;\n return getUnappliedLocalChanges(\n localChangesDataRaw as Partial<M>,\n openingValues as Partial<M>\n );\n }, [localChangesDataRaw, computedInitialValues, initialDirtyValues]);\n\n const hasLocalChanges = !localChangesCleared && !!localChangesData && Object.keys(localChangesData as object).length > 0;\n\n const localChangesCacheKey = useMemo(() => {\n return (status === \"new\" || status === \"copy\") ? path + \"#new\" : path + \"/\" + entityId;\n }, [status, path, entityId]);\n\n // --- Navigate back ---\n const navigateBack = useCallback(() => {\n if (navigateBackProp) {\n navigateBackProp();\n return;\n }\n if (openEntityMode === \"side_panel\" || openEntityMode === \"dialog\") {\n sidePanelController.close();\n } else {\n window.history.back();\n }\n }, [navigateBackProp, openEntityMode, sidePanelController]);\n\n // --- Cache operations ---\n const clearDirtyCache = useCallback(() => {\n if (status === \"new\" || status === \"copy\") {\n removeEntityFromMemoryCache(path + \"#new\");\n removeEntityFromCache(path + \"#new\");\n } else {\n removeEntityFromMemoryCache(path + \"/\" + entityId);\n removeEntityFromCache(path + \"/\" + entityId);\n }\n }, [status, path, entityId]);\n\n const onReset = useCallback(() => {\n clearDirtyCache();\n }, [clearDirtyCache]);\n\n const onValuesChangeDeferred = useCallback((values: M, controller: FormexController<M>) => {\n const key = (status === \"new\" || status === \"copy\") ? path + \"#new\" : path + \"/\" + entityId;\n if (controller.dirty) {\n const touchedValues = getTouchedPropertyValues(values, controller.touched);\n if (Object.keys(touchedValues).length > 0) {\n saveEntityToCache(key, touchedValues);\n } else {\n removeEntityFromCache(key);\n }\n }\n }, [status, path, entityId]);\n\n // --- Save via data layer ---\n const onSubmit = useCallback(async (values: M, formex: FormexController<M>): Promise<Entity<M> | void> => {\n try {\n const savedEntity = await saveEntityWithCallbacks<M>({\n path,\n entityId,\n values,\n previousValues: currentEntity?.values,\n collection,\n status,\n // The version the form's baseline is — it follows the live\n // record, tag and all — so a save made against a version that\n // someone has since replaced is refused, not written over it.\n ifMatch: status === \"existing\" ? currentEntity?.etag : undefined,\n data: dataClient,\n context,\n afterSave: (updatedEntity: Entity<M>) => {\n setSavedEntity(updatedEntity);\n clearDirtyCache();\n onValuesModified?.(false, updatedEntity.values);\n onEntityChange?.(updatedEntity);\n setStatus(\"existing\");\n setEntityId(updatedEntity.id);\n onStatusChange?.(\"existing\");\n\n if (onSaved) {\n onSaved({\n entity: updatedEntity,\n status,\n path,\n entityId: updatedEntity.id,\n collection\n });\n }\n },\n afterSaveError: (e: Error) => {\n // Refused because the record moved on between the last\n // version the form saw and this save. The new version is\n // on its way over the listener, and the form rebases the\n // edit onto it, marking what changed underneath.\n // Read by code, not `instanceof`: the error can come from\n // another copy of the types package.\n const changedElsewhere = typeof e === \"object\" && e !== null\n && \"code\" in e && e.code === \"PRECONDITION_FAILED\";\n snackbarController.open({\n type: \"error\",\n title: t(\"error_saving_entity\"),\n message: changedElsewhere ? t(\"error_record_changed_elsewhere\") : e?.message\n });\n console.error(\"Error saving entity\", path, entityId, e);\n }\n });\n\n const autoSave = collection.formAutoSave;\n if (!autoSave) {\n snackbarController.open({\n type: \"success\",\n message: `${collection.singularName ?? collection.name}: ${t(\"saved_correctly\")}`\n });\n }\n\n const eventName: AnalyticsEvent = status === \"new\"\n ? \"new_entity_saved\"\n : (status === \"copy\" ? \"entity_copied\" : (status === \"existing\" ? \"entity_edited\" : \"unmapped_event\"));\n analyticsController.onAnalyticsEvent?.(eventName, { path });\n\n return savedEntity;\n } catch (e: unknown) {\n console.error(e);\n throw e;\n }\n }, [path, entityId, currentEntity, collection, status, dataClient, context, clearDirtyCache, onValuesModified, onEntityChange, onSaved, onStatusChange, snackbarController, analyticsController, t]);\n\n // --- Unique field validation via data layer ---\n const uniqueFieldValidator = useCallback(async ({\n name,\n value\n }: { name: string; value: unknown }) => {\n try {\n const accessor = dataClient.collection(path);\n const { data } = await accessor.find({\n where: { [name]: [\"==\", value] },\n limit: 2\n });\n const otherEntities = hasEntityId(entityId) ? data.filter(e => String(e.id) !== String(entityId)) : data;\n return otherEntities.length === 0;\n } catch (e: unknown) {\n console.error(\"Error checking unique field\", e);\n return true;\n }\n }, [dataClient, path, entityId]);\n\n // --- Plugin slots ---\n const parentCollectionSlugs = collectionRegistryController.getParentCollectionSlugs(path);\n const parentEntityIds = collectionRegistryController.getParentEntityIds(path);\n\n // Build a minimal formContext for plugin slot props — the full one is built inside EntityForm\n const formActionProps: PluginFormActionProps = useMemo(() => ({\n entityId,\n parentCollectionSlugs,\n parentEntityIds,\n path,\n status,\n collection: collection as AdminCollection,\n context,\n // Genuinely absent here, and `PluginFormActionProps` declares it\n // optional — so this needed no conversion at all. Asserting a\n // `FormContext` onto `undefined` told every plugin slot the opposite of\n // the comment three lines up.\n formContext: undefined,\n openEntityMode,\n disabled: false\n }), [entityId, parentCollectionSlugs, parentEntityIds, path, status, collection, context, openEntityMode]);\n\n // `form.actions` is rendered by the entity view's identity bar, which has\n // the real formContext and does not cost a footer. Rendering it here too\n // would show Autofill twice.\n const pluginFormBefore = useSlot(\"form.before\", formActionProps);\n const pluginFormAfter = useSlot(\"form.after\", formActionProps);\n\n return (\n <EntityForm<M>\n {...restProps}\n path={path}\n entityId={entityIdProp}\n collection={collection}\n entity={currentEntity}\n initialStatus={initialStatus}\n initialDirtyValues={initialDirtyValues}\n // Not handed down: `onSubmit` above reports the save, for Save and\n // autosave alike. The form reporting it too called it twice.\n onValuesModified={onValuesModified}\n onEntityChange={onEntityChange}\n onStatusChange={onStatusChange}\n openEntityMode={openEntityMode}\n navigateBack={navigateBack}\n // Headless callbacks\n onSubmit={onSubmit}\n onValuesChangeDeferred={onValuesChangeDeferred}\n onReset={onReset}\n uniqueFieldValidator={uniqueFieldValidator}\n lockedPropertyKeys={lockedPropertyKeys}\n // Slots\n beforeFields={pluginFormBefore}\n afterFields={pluginFormAfter}\n pluginActions={[]}\n // Local changes\n computedInitialValues={computedInitialValues as Partial<M>}\n hasLocalChanges={hasLocalChanges}\n localChangesData={localChangesData as Partial<M>}\n manualApplyLocalChanges={manualApplyLocalChanges}\n localChangesCacheKey={localChangesCacheKey}\n onClearLocalChanges={() => setLocalChangesCleared(true)}\n />\n );\n}\n\n/**\n * The key property's value for a new record created under a known id: the id,\n * under the one property the collection marks `isId`. Empty when the record\n * is not new, has no id, or the collection declares no single key property —\n * then the id travels as the id the record is created with instead.\n */\nfunction newRecordIdValues(\n collection: AdminCollection,\n status: EntityStatus,\n entityId: string | number | undefined\n): Record<string, unknown> {\n if (status !== \"new\" || entityId === undefined) return {};\n const keys = Object.entries(collection.properties ?? {})\n .filter(([, property]) => typeof property === \"object\" && property !== null && \"isId\" in property && Boolean(property.isId))\n .map(([key]) => key);\n return keys.length === 1 ? { [keys[0]]: entityId } : {};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAkFA,SAAgB,kBAAqD,EACjE,MACA,UAAU,cACV,YACA,QACA,eACA,SACA,kBACA,gBACA,gBACA,iBAAiB,eACjB,cAAc,kBACd,oBACA,GAAG,aACuB;CAE1B,MAAM,EAAE,MAAM,eAAe;CAC7B,MAAM,sBAAsB,aAAa;CACzC,MAAM,+BAA+B,gCAAgC;CACrE,MAAM,iBAAiB,kBAAkB;CACzC,MAAM,aAAa,QAAQ;CAC3B,MAAM,qBAAqB,sBAAsB;CACjD,MAAM,0BAA0B,2BAA2B;CAC3D,MAAM,UAAU,gBAAgB;CAChC,MAAM,sBAAsB,uBAAuB;CAEnD,MAAM,CAAC,QAAQ,aAAa,SAAuB,aAAa;CAIhE,MAAM,CAAC,aAAa,kBAAkB,SAAgC,KAAA,CAAS;CAC/E,MAAM,gBAAgB,WAAW,WAAW,aAAa,cAAc,KAAA;CAMvE,MAAM,cAAc,cACV,kBAAkB,YAAY,QAAQ,YAAY,GACxD;EAAC;EAAY;EAAQ;CAAY,CAAC;CACtC,MAAM,CAAC,UAAU,eAAe,eAA4C;EACxE,IAAI,WAAW,QAAQ,OAAO,KAAA;EAC9B,IAAI,WAAW,OAAO,OAAO,OAAO,KAAK,WAAW,CAAC,CAAC,SAAS,IAAI,KAAA,IAAY;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,SAAS,GAAY;GACjB,QAAQ,MAAM,+BAA+B,CAAC;GAC9C,OAAO;EACX;CACJ,GAAG;EAAC;EAAY;EAAM;CAAQ,CAAC;CAG/B,MAAM,wBAAwB,6BAA6B,yBAAyB,IAAI;CACxF,MAAM,kBAAkB,6BAA6B,mBAAmB,IAAI;CAG5E,MAAM,kBAAyC,eAAe;EAC1D;EACA;EACA;EACA;EACA;EACY;EACZ;EAKA,aAAa,KAAA;EACb;EACA,UAAU;CACd,IAAI;EAAC;EAAU;EAAuB;EAAiB;EAAM;EAAQ;EAAY;EAAS;CAAc,CAAC;CAKzG,MAAM,mBAAmB,QAAQ,eAAe,eAAe;CAC/D,MAAM,kBAAkB,QAAQ,cAAc,eAAe;CAE7D,OACI,oBAAC,YAAD;EACI,GAAI;EACE;EACN,UAAU;EACE;EACZ,QAAQ;EACO;EACK;EAGF;EACF;EACA;EACA;EACF;EAEJ;EACc;EACf;EACa;EACF;EAEpB,cAAc;EACd,aAAa;EACb,eAAe,CAAC;EAEO;EACN;EACC;EACO;EACH;EACtB,2BAA2B,uBAAuB,IAAI;CACzD,CAAA;AAET;;;;;;;AAQA,SAAS,kBACL,YACA,QACA,UACuB;CACvB,IAAI,WAAW,SAAS,aAAa,KAAA,GAAW,OAAO,CAAC;CACxD,MAAM,OAAO,OAAO,QAAQ,WAAW,cAAc,CAAC,CAAC,CAAC,CACnD,QAAQ,GAAG,cAAc,OAAO,aAAa,YAAY,aAAa,QAAQ,UAAU,YAAY,QAAQ,SAAS,IAAI,CAAC,CAAC,CAC3H,KAAK,CAAC,SAAS,GAAG;CACvB,OAAO,KAAK,WAAW,IAAI,GAAG,KAAK,KAAK,SAAS,IAAI,CAAC;AAC1D"}
|
|
@@ -3,6 +3,7 @@ import { PropertyKeyHint } from "../../components/PropertyKeyHint.js";
|
|
|
3
3
|
import "react";
|
|
4
4
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
5
5
|
import { ErrorBoundary, Typography, cls } from "@rebasepro/ui";
|
|
6
|
+
import { isReadOnly } from "@rebasepro/app";
|
|
6
7
|
//#region src/form/components/FieldBlock.tsx
|
|
7
8
|
/**
|
|
8
9
|
* Grid placement for a span.
|
|
@@ -76,7 +77,7 @@ var LABEL_ICON_SIZE = 14;
|
|
|
76
77
|
function FieldBlock({ propertyKey, property, showLabel, labelInside = false, mode = "edit", label, icon, children }) {
|
|
77
78
|
const reading = mode === "read";
|
|
78
79
|
const description = property?.description?.trim();
|
|
79
|
-
const required = Boolean(property?.validation?.required);
|
|
80
|
+
const required = Boolean(property?.validation?.required) && !(property && isReadOnly(property));
|
|
80
81
|
const footed = labelInside && !reading;
|
|
81
82
|
return /* @__PURE__ */ jsxs("div", {
|
|
82
83
|
id: `form_field_${propertyKey}`,
|