@rebasepro/cms 0.26.0 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/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/DefaultDrawer.js +3 -2
- package/dist/components/DefaultDrawer.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/HomePage/ContentHomePage.js +3 -2
- package/dist/components/HomePage/ContentHomePage.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":"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,OAAO;CACX,CAAC;CASD,MAAM,EAAE,eAAe,uBAAuB;CAC9C,MAAM,mBAAmB,cACf,WAAW,SAAS,WAAW,SAC/B;EAAE,GAAG,oBAAoB;GAAE;GAAe;EAAmB,GAAG,MAAM,UAAU;EAAG,GAAG;CAAY,IAClG,CAAC,GAC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A,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;EAC/E,OAAO;CACX,CAAC;CASD,MAAM,EAAE,eAAe,uBAAuB;CAC9C,MAAM,mBAAmB,cACf,WAAW,SAAS,WAAW,SAC/B;EAAE,GAAG,oBAAoB;GAAE;GAAe;EAAmB,GAAG,MAAM,UAAU;EAAG,GAAG;CAAY,IAClG,C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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}`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FieldBlock.js","names":[],"sources":["../../../src/form/components/FieldBlock.tsx"],"sourcesContent":["import type { Property } from \"@rebasepro/types\";\nimport type { PropertySpan } from \"@rebasepro/cms-types\";\nimport React from \"react\";\nimport { cls, ErrorBoundary, Typography } from \"@rebasepro/ui\";\nimport { getIconForProperty } from \"../../util/property_utils\";\nimport { PropertyKeyHint } from \"../../components/PropertyKeyHint\";\n\n/**\n * Grid placement for a span.\n *\n * Written out as literal class strings rather than composed, because Tailwind\n * scans source text: a template literal would produce classes that exist at\n * runtime and were never generated into the stylesheet.\n *\n * Below the column breakpoint every field takes the single available column, so\n * the side panel, the dialog and mobile all get a plain stack.\n *\n * Lives here rather than in the form, because the read-only rendering of a\n * record places its fields on the same grid — a record that changes shape when\n * you press Edit is the bug this whole layout exists to avoid.\n */\nexport function spanClass(span: PropertySpan): string {\n switch (span) {\n case 1: return \"@2xl/col:col-span-1\";\n case 2: return \"@2xl/col:col-span-2\";\n case 3: return \"@2xl/col:col-span-3\";\n case 4: return \"@2xl/col:col-span-4\";\n }\n}\n\n/**\n * Does this property's editor supply its own heading?\n *\n * Arrays, maps, `oneOf` blocks and key-value editors render as a collapsible\n * panel whose header *is* the label — hiding it would leave a panel you cannot\n * identify or, worse, cannot expand. Those keep their own; everything else gets\n * its label from {@link FieldBlock}, which is what makes a text field and a\n * select finally agree on where a label goes.\n *\n * Exported because the layout resolver's span rules and this rule have to stay\n * in step: the self-labelling types are exactly the ones that take a full row.\n */\nexport function isSelfLabellingProperty(property: Property | undefined): boolean {\n if (!property) return false;\n switch (property.type) {\n case \"map\":\n // `spreadChildren` inlines the children into the parent grid, so\n // there is no panel and therefore no header to reuse as the label.\n return !property.admin?.spreadChildren;\n case \"array\": {\n // Most arrays render as an expandable panel whose header is the\n // label — `repeat`, `block`, `custom_array`, `multi_references`.\n // The exceptions are the ones that resolve to an inline control:\n // an enum array is a multi-select and a storage array is a\n // dropzone, and both take their label from the form.\n //\n // This mirrors `getFieldConfig`'s array branch. Getting it backwards\n // is visible: an array of plain strings is a `repeat` panel, and\n // treating it as inline printed \"Available Locales\" twice, once\n // from the form and once from the panel's own header.\n if (property.oneOf) return true;\n if (Array.isArray(property.of) || !property.of) return true;\n const of = property.of;\n if (of.type === \"string\" && (of.enum || of.storage)) return false;\n if (of.type === \"number\" && of.enum) return false;\n return true;\n }\n default:\n return false;\n }\n}\n\n/**\n * The type icon in a field label, in px.\n *\n * Matched to the label's 13px rather than taken from `iconSize.smallest` (16),\n * which is sized for buttons. Exported so the surfaces that draw a label\n * themselves — the additional-field cards, the rail — can stay in step.\n */\nexport const LABEL_ICON_SIZE = 14;\n\nexport interface FieldBlockProps {\n propertyKey: string;\n property?: Property;\n /** Rendered by the form rather than by the field, unless self-labelling. */\n showLabel: boolean;\n /**\n * The control draws its label inside its own box — the one-line fields of a\n * record form (see `labelsInsideControl`). The block then draws no label\n * row, but it still owns what goes under the box: the description, indented\n * to the value inside the box, and the property's key, on that same line.\n */\n labelInside?: boolean;\n /**\n * Which of the two renderings this block frames.\n *\n * The **label is identical in both** — same size, same weight, same colour,\n * same type icon, same required marker. A field is the same field whether or\n * not you are editing it, and a record whose labels restyle themselves under\n * Edit reads as two different screens.\n *\n * What `\"read\"` drops is the *description*, which is not part of the label:\n * it is input help. \"Sum of all line items before tax and shipping\" under a\n * number that is visibly a sum tells a reader nothing, and a line of it\n * under every field is what a record has instead of room.\n */\n mode?: \"edit\" | \"read\";\n /**\n * Label text, when there is no property to take it from.\n *\n * For additional fields, which are columns a collection computes rather\n * than stores. They go on the same grid as the properties and so have to\n * carry the same label — drawing their own is how they ended up a size out\n * and a couple of pixels off from the field beside them.\n */\n label?: string;\n /** Type icon, when there is no property to derive one from. */\n icon?: React.ReactNode;\n children: React.ReactNode;\n}\n\n/**\n * One field's worth of the form grid: label, control, description.\n *\n * The same block frames the read-only rendering of a record, so a field sits in\n * the same place, at the same width, under the same label whether or not you are\n * editing it — see {@link EntityViewBinding}.\n *\n * The label is one size down from the control it names (13px against the body's\n * 14) with its icon matched to it at 14px. Labels are scaffolding: you read them\n * to find the value, then read the value. Setting them at body size made a\n * column of records scan as a column of field names with data attached.\n */\nexport function FieldBlock({\n propertyKey,\n property,\n showLabel,\n labelInside = false,\n mode = \"edit\",\n label,\n icon,\n children\n}: FieldBlockProps) {\n\n const reading = mode === \"read\";\n const description = property?.description?.trim();\n const required = Boolean(property?.validation?.required);\n const footed = labelInside && !reading;\n\n return (\n // Top-aligned: with the description below the control, every label is a\n // single line, so the controls line up on their own. (Bottom-aligning\n // was only needed while the description sat between label and control.)\n <div\n id={`form_field_${propertyKey}`}\n // With the label inside the control there is no label row to hover\n // for the key; the whole field reveals it instead.\n className={cls(\"relative flex flex-col min-w-0\", footed && \"group/label\")}>\n\n {showLabel && (\n <div className={cls(\n \"group/label flex items-center gap-1.5 min-w-0 font-medium leading-tight mb-1.5\",\n // Primary, not secondary: the label names the field and the\n // reference sets its labels in the primary ink; the type icon\n // beside it stays muted so the name carries the row.\n \"text-[13px] text-text-primary dark:text-text-primary-dark\"\n )}>\n {/* Small and quiet: enough to tell a number from a\n relation at a glance, not enough to compete with the\n field name. Matched to the label's 13px rather than\n left at the 16px `smallest` token, which put the\n heaviest mark on the row on the least important\n thing in it. */}\n {(property || icon) && (\n <span className={\"shrink-0 text-text-disabled dark:text-text-disabled-dark\"}>\n {property ? getIconForProperty(property, LABEL_ICON_SIZE) : icon}\n </span>\n )}\n <span className={\"truncate\"}>{property?.name ?? label ?? propertyKey}</span>\n {required && <span className={\"text-red-500 dark:text-red-500 -ml-1\"}>*</span>}\n {/* In the row, not over it. This was a tooltip on the\n label and on the control, which opened whenever a\n field took focus and covered the label being read. */}\n {property && <PropertyKeyHint propertyKey={propertyKey}/>}\n </div>\n )}\n\n {/* `data-field-control` names the slot for anything measuring the\n control itself. A class cannot: the label row carries\n `min-w-0` too, and a selector for it measured the label. */}\n <div className={\"min-w-0\"} data-field-control={\"\"}>\n <ErrorBoundary>\n {children}\n </ErrorBoundary>\n </div>\n\n {/* Under the control, where it reads as a note about the thing you\n just filled in rather than a subtitle of the next label. */}\n {showLabel && description && !reading && (\n <Typography variant={\"caption\"}\n color={\"disabled\"}\n className={\"mt-1.5 ml-0.5 leading-snug\"}>\n {description}\n </Typography>\n )}\n\n {/* A label drawn inside the box: the description is indented to\n the value, as the binding's own error line is (`ml-3.5`), and\n the key sits at the end of that line. A field with no\n description has no line to put it on, so the key hangs in the\n row gap below the box rather than reserving a line under every\n field for something only a hover shows. */}\n {footed && (description || property) && (\n <div className={cls(\n \"flex items-start gap-2 min-w-0 ml-3.5\",\n description ? \"mt-1.5\" : \"absolute top-full right-0 mt-1\"\n )}>\n {description && (\n <Typography variant={\"caption\"}\n color={\"disabled\"}\n className={\"grow min-w-0 leading-snug\"}>\n {description}\n </Typography>\n )}\n {property && <PropertyKeyHint propertyKey={propertyKey}\n className={description ? \"ml-auto shrink-0\" : undefined}/>}\n </div>\n )}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,UAAU,MAA4B;CAClD,QAAQ,MAAR;EACI,KAAK,GAAG,OAAO;EACf,KAAK,GAAG,OAAO;EACf,KAAK,GAAG,OAAO;EACf,KAAK,GAAG,OAAO;CACnB;AACJ;;;;;;;;;;;;;AAcA,SAAgB,wBAAwB,UAAyC;CAC7E,IAAI,CAAC,UAAU,OAAO;CACtB,QAAQ,SAAS,MAAjB;EACI,KAAK,OAGD,OAAO,CAAC,SAAS,OAAO;EAC5B,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c,WAAW,gCAC7B;cAHA,CAIK,eACG,oBAAC,YAAD;KAAY,SAAS;KACjB,OAAO;KACP,WAAW;eACV;IACO,CAAA,GAEf,YAAY,oBAAC,iBAAD;KAA8B;KACvC,WAAW,cAAc,qBAAqB,KAAA;IAAW,CAAA,CAC5D;;EAER;;AAEb"}
|
|
1
|
+
{"version":3,"file":"FieldBlock.js","names":[],"sources":["../../../src/form/components/FieldBlock.tsx"],"sourcesContent":["import type { Property } from \"@rebasepro/types\";\nimport type { PropertySpan } from \"@rebasepro/cms-types\";\nimport React from \"react\";\nimport { cls, ErrorBoundary, Typography } from \"@rebasepro/ui\";\nimport { isReadOnly } from \"@rebasepro/app\";\nimport { getIconForProperty } from \"../../util/property_utils\";\nimport { PropertyKeyHint } from \"../../components/PropertyKeyHint\";\n\n/**\n * Grid placement for a span.\n *\n * Written out as literal class strings rather than composed, because Tailwind\n * scans source text: a template literal would produce classes that exist at\n * runtime and were never generated into the stylesheet.\n *\n * Below the column breakpoint every field takes the single available column, so\n * the side panel, the dialog and mobile all get a plain stack.\n *\n * Lives here rather than in the form, because the read-only rendering of a\n * record places its fields on the same grid — a record that changes shape when\n * you press Edit is the bug this whole layout exists to avoid.\n */\nexport function spanClass(span: PropertySpan): string {\n switch (span) {\n case 1: return \"@2xl/col:col-span-1\";\n case 2: return \"@2xl/col:col-span-2\";\n case 3: return \"@2xl/col:col-span-3\";\n case 4: return \"@2xl/col:col-span-4\";\n }\n}\n\n/**\n * Does this property's editor supply its own heading?\n *\n * Arrays, maps, `oneOf` blocks and key-value editors render as a collapsible\n * panel whose header *is* the label — hiding it would leave a panel you cannot\n * identify or, worse, cannot expand. Those keep their own; everything else gets\n * its label from {@link FieldBlock}, which is what makes a text field and a\n * select finally agree on where a label goes.\n *\n * Exported because the layout resolver's span rules and this rule have to stay\n * in step: the self-labelling types are exactly the ones that take a full row.\n */\nexport function isSelfLabellingProperty(property: Property | undefined): boolean {\n if (!property) return false;\n switch (property.type) {\n case \"map\":\n // `spreadChildren` inlines the children into the parent grid, so\n // there is no panel and therefore no header to reuse as the label.\n return !property.admin?.spreadChildren;\n case \"array\": {\n // Most arrays render as an expandable panel whose header is the\n // label — `repeat`, `block`, `custom_array`, `multi_references`.\n // The exceptions are the ones that resolve to an inline control:\n // an enum array is a multi-select and a storage array is a\n // dropzone, and both take their label from the form.\n //\n // This mirrors `getFieldConfig`'s array branch. Getting it backwards\n // is visible: an array of plain strings is a `repeat` panel, and\n // treating it as inline printed \"Available Locales\" twice, once\n // from the form and once from the panel's own header.\n if (property.oneOf) return true;\n if (Array.isArray(property.of) || !property.of) return true;\n const of = property.of;\n if (of.type === \"string\" && (of.enum || of.storage)) return false;\n if (of.type === \"number\" && of.enum) return false;\n return true;\n }\n default:\n return false;\n }\n}\n\n/**\n * The type icon in a field label, in px.\n *\n * Matched to the label's 13px rather than taken from `iconSize.smallest` (16),\n * which is sized for buttons. Exported so the surfaces that draw a label\n * themselves — the additional-field cards, the rail — can stay in step.\n */\nexport const LABEL_ICON_SIZE = 14;\n\nexport interface FieldBlockProps {\n propertyKey: string;\n property?: Property;\n /** Rendered by the form rather than by the field, unless self-labelling. */\n showLabel: boolean;\n /**\n * The control draws its label inside its own box — the one-line fields of a\n * record form (see `labelsInsideControl`). The block then draws no label\n * row, but it still owns what goes under the box: the description, indented\n * to the value inside the box, and the property's key, on that same line.\n */\n labelInside?: boolean;\n /**\n * Which of the two renderings this block frames.\n *\n * The **label is identical in both** — same size, same weight, same colour,\n * same type icon, same required marker. A field is the same field whether or\n * not you are editing it, and a record whose labels restyle themselves under\n * Edit reads as two different screens.\n *\n * What `\"read\"` drops is the *description*, which is not part of the label:\n * it is input help. \"Sum of all line items before tax and shipping\" under a\n * number that is visibly a sum tells a reader nothing, and a line of it\n * under every field is what a record has instead of room.\n */\n mode?: \"edit\" | \"read\";\n /**\n * Label text, when there is no property to take it from.\n *\n * For additional fields, which are columns a collection computes rather\n * than stores. They go on the same grid as the properties and so have to\n * carry the same label — drawing their own is how they ended up a size out\n * and a couple of pixels off from the field beside them.\n */\n label?: string;\n /** Type icon, when there is no property to derive one from. */\n icon?: React.ReactNode;\n children: React.ReactNode;\n}\n\n/**\n * One field's worth of the form grid: label, control, description.\n *\n * The same block frames the read-only rendering of a record, so a field sits in\n * the same place, at the same width, under the same label whether or not you are\n * editing it — see {@link EntityViewBinding}.\n *\n * The label is one size down from the control it names (13px against the body's\n * 14) with its icon matched to it at 14px. Labels are scaffolding: you read them\n * to find the value, then read the value. Setting them at body size made a\n * column of records scan as a column of field names with data attached.\n */\nexport function FieldBlock({\n propertyKey,\n property,\n showLabel,\n labelInside = false,\n mode = \"edit\",\n label,\n icon,\n children\n}: FieldBlockProps) {\n\n const reading = mode === \"read\";\n const description = property?.description?.trim();\n // Only where someone can supply the value: on a read-only field the marker\n // asks for input nobody can give, and `validation.required` there states\n // what the column holds, which the form need not shout about.\n const required = Boolean(property?.validation?.required) && !(property && isReadOnly(property));\n const footed = labelInside && !reading;\n\n return (\n // Top-aligned: with the description below the control, every label is a\n // single line, so the controls line up on their own. (Bottom-aligning\n // was only needed while the description sat between label and control.)\n <div\n id={`form_field_${propertyKey}`}\n // With the label inside the control there is no label row to hover\n // for the key; the whole field reveals it instead.\n className={cls(\"relative flex flex-col min-w-0\", footed && \"group/label\")}>\n\n {showLabel && (\n <div className={cls(\n \"group/label flex items-center gap-1.5 min-w-0 font-medium leading-tight mb-1.5\",\n // Primary, not secondary: the label names the field and the\n // reference sets its labels in the primary ink; the type icon\n // beside it stays muted so the name carries the row.\n \"text-[13px] text-text-primary dark:text-text-primary-dark\"\n )}>\n {/* Small and quiet: enough to tell a number from a\n relation at a glance, not enough to compete with the\n field name. Matched to the label's 13px rather than\n left at the 16px `smallest` token, which put the\n heaviest mark on the row on the least important\n thing in it. */}\n {(property || icon) && (\n <span className={\"shrink-0 text-text-disabled dark:text-text-disabled-dark\"}>\n {property ? getIconForProperty(property, LABEL_ICON_SIZE) : icon}\n </span>\n )}\n <span className={\"truncate\"}>{property?.name ?? label ?? propertyKey}</span>\n {required && <span className={\"text-red-500 dark:text-red-500 -ml-1\"}>*</span>}\n {/* In the row, not over it. This was a tooltip on the\n label and on the control, which opened whenever a\n field took focus and covered the label being read. */}\n {property && <PropertyKeyHint propertyKey={propertyKey}/>}\n </div>\n )}\n\n {/* `data-field-control` names the slot for anything measuring the\n control itself. A class cannot: the label row carries\n `min-w-0` too, and a selector for it measured the label. */}\n <div className={\"min-w-0\"} data-field-control={\"\"}>\n <ErrorBoundary>\n {children}\n </ErrorBoundary>\n </div>\n\n {/* Under the control, where it reads as a note about the thing you\n just filled in rather than a subtitle of the next label. */}\n {showLabel && description && !reading && (\n <Typography variant={\"caption\"}\n color={\"disabled\"}\n className={\"mt-1.5 ml-0.5 leading-snug\"}>\n {description}\n </Typography>\n )}\n\n {/* A label drawn inside the box: the description is indented to\n the value, as the binding's own error line is (`ml-3.5`), and\n the key sits at the end of that line. A field with no\n description has no line to put it on, so the key hangs in the\n row gap below the box rather than reserving a line under every\n field for something only a hover shows. */}\n {footed && (description || property) && (\n <div className={cls(\n \"flex items-start gap-2 min-w-0 ml-3.5\",\n description ? \"mt-1.5\" : \"absolute top-full right-0 mt-1\"\n )}>\n {description && (\n <Typography variant={\"caption\"}\n color={\"disabled\"}\n className={\"grow min-w-0 leading-snug\"}>\n {description}\n </Typography>\n )}\n {property && <PropertyKeyHint propertyKey={propertyKey}\n className={description ? \"ml-auto shrink-0\" : undefined}/>}\n </div>\n )}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,UAAU,MAA4B;CAClD,QAAQ,MAAR;EACI,KAAK,GAAG,OAAO;EACf,KAAK,GAAG,OAAO;EACf,KAAK,GAAG,OAAO;EACf,KAAK,GAAG,OAAO;CACnB;AACJ;;;;;;;;;;;;;AAcA,SAAgB,wBAAwB,UAAyC;CAC7E,IAAI,CAAC,UAAU,OAAO;CACtB,QAAQ,SAAS,MAAjB;EACI,KAAK,OAGD,OAAO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,WAAW,eAAe,aACvB,qBAAC,OAAD;IAAK,WAAW,IACZ,yCACA,cAAc,WAAW,gCAC7B;cAHA,CAIK,eACG,oBAAC,YAAD;KAAY,SAAS;KACjB,OAAO;KACP,WAAW;eACV;IACO,CAAA,GAEf,YAAY,oBAAC,iBAAD;KAA8B;KACvC,WAAW,cAAc,qBAAqB,KAAA;IAAW,CAAA,CAC5D;;EAER;;AAEb"}
|
|
@@ -85,9 +85,11 @@ function MapEditView({ value, initialValue, setValue, fieldName, disabled }) {
|
|
|
85
85
|
}];
|
|
86
86
|
return row;
|
|
87
87
|
}));
|
|
88
|
+
const key = internalState.find((row) => row[0] === id)?.[1].key;
|
|
89
|
+
if (!key) return;
|
|
88
90
|
setValue({
|
|
89
91
|
...value ?? {},
|
|
90
|
-
[
|
|
92
|
+
[key]: getDefaultValueFortype(type)
|
|
91
93
|
});
|
|
92
94
|
};
|
|
93
95
|
return /* @__PURE__ */ jsxs("div", {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"KeyValueFieldBinding.js","names":[],"sources":["../../../src/form/field_bindings/KeyValueFieldBinding.tsx"],"sourcesContent":["import type { FieldProps } from \"../../types/fields\";\nimport type { MapProperty } from \"@rebasepro/types\";\nimport React, { useEffect, useState } from \"react\";\nimport { DataType, GeoPoint } from \"@rebasepro/types\";\n\nimport { ArrayContainer } from \"../../components/ArrayContainer\";\nimport { FieldHelperText } from \"../components/FieldHelperText\";\nimport { LabelWithIcon } from \"../components/LabelWithIcon\";\nimport {\n BooleanSwitchWithLabel,\n Button,\n ChevronDownIcon,\n cls,\n DateTimeField,\n defaultBorderMixin,\n ExpandablePanel,\n IconButton,\n iconSize,\n Menu,\n MenuItem,\n MinusIcon,\n PlusIcon,\n TextField,\n Typography\n} from \"@rebasepro/ui\";\nimport { getIconForProperty } from \"../../util/property_utils\";\nimport { useCustomizationController, useTranslation } from \"@rebasepro/app\";\nimport { getIn } from \"@rebasepro/forms\";\nimport { getDefaultValueFortype } from \"@rebasepro/common\";\n\ntype MapEditViewRowState = [number, {\n key: string,\n type: DataType\n}];\n\n/**\n * Field that allows edition of key value pairs.\n *\n * @group Form fields\n */\nexport function KeyValueFieldBinding({\n propertyKey,\n value,\n showError,\n error,\n disabled,\n property,\n setValue,\n minimalistView,\n includeDescription,\n underlyingValueHasChanged,\n autoFocus,\n context\n }: FieldProps<MapProperty>) {\n\n const expanded = (property.admin?.expanded === undefined ? true : property.admin?.expanded) || autoFocus;\n\n if (!property.keyValue) {\n throw Error(`Your property ${propertyKey} needs to have the 'keyValue' prop in order to use this field binding`);\n }\n\n const initialValues = getIn(context.formex.initialValues, propertyKey) as Record<string, unknown> | undefined;\n\n const mapFormView = <MapEditView value={value}\n setValue={setValue}\n disabled={disabled}\n initialValue={initialValues}\n fieldName={property.name ?? propertyKey}/>;\n\n const title = <LabelWithIcon\n propertyKey={propertyKey}\n icon={getIconForProperty(property, \"small\")}\n required={property.validation?.required}\n title={property.name ?? propertyKey}\n className={\"text-text-secondary dark:text-text-secondary-dark\"}/>;\n\n return (\n <>\n\n {!minimalistView && <ExpandablePanel initiallyExpanded={expanded}\n title={title}\n innerClassName={\"px-2 md:px-4 pb-2 md:pb-4 pt-1 md:pt-2\"}>{mapFormView}</ExpandablePanel>}\n\n {minimalistView && mapFormView}\n\n <FieldHelperText includeDescription={includeDescription}\n showError={showError}\n error={error}\n disabled={disabled}\n property={property}/>\n\n </>\n );\n}\n\ninterface MapEditViewParams<T extends Record<string, unknown>> {\n value?: T;\n initialValue?: T;\n setValue: (value: (T | null)) => void;\n fieldName?: string,\n disabled?: boolean\n}\n\nfunction MapEditView<T extends Record<string, unknown>>({\n value,\n initialValue,\n setValue,\n fieldName,\n disabled\n }: MapEditViewParams<T>) {\n const [internalState, setInternalState] = React.useState<MapEditViewRowState[]>(\n Object.keys(initialValue ?? {}).map((key) => [getRandomId(), {\n key,\n type: gettype(initialValue?.[key]) ?? \"string\"\n }])\n );\n const { t } = useTranslation();\n\n useEffect(() => {\n const currentKeys = internalState.map(([id, { key }]) => key);\n const newKeys = Object.entries(value ?? {}).filter(([key, v]) => v !== undefined).map(([key]) => key);\n const keysToAdd = newKeys.filter((key) => !currentKeys.includes(key));\n // A row without a name yet is the form's alone: it is not in the value.\n const keysToRemove = currentKeys.filter((key) => key !== \"\" && !newKeys.includes(key));\n const newRowIds = [...internalState];\n keysToAdd.forEach((key) => {\n newRowIds.push([getRandomId(), {\n key,\n type: gettype(value?.[key]) ?? \"string\"\n }]);\n });\n keysToRemove.forEach((key) => {\n const index = newRowIds.findIndex(([id, { key: k }]) => k === key);\n newRowIds.splice(index, 1);\n });\n setInternalState(newRowIds);\n }, [value]);\n\n const updatetype = (id: number, type: DataType) => {\n if (!id) {\n console.warn(\"No key selected for data type update\");\n return;\n }\n setInternalState(internalState.map((row) => {\n if (row[0] === id) {\n return [row[0], {\n key: row[1].key,\n type\n }];\n }\n return row;\n }));\n setValue({\n ...(value ?? {} as T),\n [internalState.find((row) => row[0] === id)?.[1].key ?? \"\"]: getDefaultValueFortype(type)\n })\n };\n\n return <div className=\"py-1 flex flex-col gap-1\">\n {internalState\n .map(([id, {\n key: fieldKey,\n type\n }], index) => {\n const entryValue = fieldKey ? value?.[fieldKey] : \"\";\n const onFieldKeyChange = (newKey: string) => {\n\n setInternalState(internalState.map((currentId) => {\n if (currentId[0] === id) {\n return [id, {\n key: newKey ?? \"\",\n type: currentId[1].type\n }];\n }\n return currentId;\n }));\n\n if (typeof value === \"object\" && newKey in value) {\n // if the key is already there, don't delete the previous value\n return;\n }\n\n const newValue = { ...(value ?? {}) } as T;\n if (typeof initialValue === \"object\" && fieldKey in initialValue) {\n (newValue as Record<string, unknown>)[fieldKey] = undefined; // set to undefined to remove from the object, the driver will remove it from the backend\n } else {\n delete (newValue as Record<string, unknown>)[fieldKey];\n }\n setValue({\n ...newValue,\n [newKey ?? \"\"]: entryValue\n });\n };\n return <MapKeyValueRow id={id}\n key={id}\n fieldKey={fieldKey}\n value={value ?? {} as T}\n onDeleteClick={() => {\n const newValue = { ...(value ?? {}) as T };\n if (initialValue && fieldKey in initialValue) {\n (newValue as Record<string, unknown>)[fieldKey] = undefined;\n } else {\n delete (newValue as Record<string, unknown>)[fieldKey];\n }\n setInternalState(internalState.filter((currentId) => currentId[0] !== id));\n setValue({\n ...newValue\n });\n }}\n onFieldKeyChange={onFieldKeyChange}\n setValue={setValue}\n entryValue={entryValue}\n type={type}\n disabled={disabled}\n updatetype={updatetype}/>;\n }\n )}\n\n <Button variant={\"text\"}\n size={\"small\"}\n className=\"w-full\"\n disabled={disabled}\n startIcon={<PlusIcon/>}\n onClick={(e) => {\n e.preventDefault();\n // Only a row: written into the value as `{ \"\": null }`, a\n // record saved before the key was named stored an entry\n // under the empty key.\n setInternalState([...internalState, [getRandomId(), {\n key: \"\",\n type: \"string\"\n }]]);\n }\n }>\n {fieldName ? t(\"add_to_field\", { fieldName }) : t(\"add\")}\n </Button>\n\n </div>;\n}\n\nfunction MapKeyValueRow<T extends Record<string, unknown>>({\n id,\n fieldKey,\n value,\n onFieldKeyChange,\n onDeleteClick,\n setValue,\n entryValue,\n type,\n updatetype,\n disabled\n }: {\n id: number,\n fieldKey: string,\n value: T,\n onFieldKeyChange: (newKey: string) => void,\n onDeleteClick: () => void,\n setValue: (value: (T | null)) => void,\n entryValue: unknown,\n type: DataType,\n disabled?: boolean,\n updatetype: (id: number, type: DataType) => void\n}) {\n\n const { locale } = useCustomizationController();\n const { t } = useTranslation();\n\n function buildInput(entryValue: unknown, fieldKey: string, type: DataType) {\n if (type === \"string\" || type === \"number\") {\n return <TextField\n key={type}\n aria-label={fieldKey ? `${t(\"value\")}: ${fieldKey}` : t(\"value\")}\n placeholder={\"value\"}\n value={entryValue as string | number | undefined}\n type={type === \"number\" ? \"number\" : \"text\"}\n size={\"medium\"}\n disabled={disabled || !fieldKey}\n onChange={(event) => {\n if (type === \"number\") {\n const numberValue = event.target.value ? parseFloat(event.target.value) : undefined;\n if (numberValue && isNaN(numberValue)) {\n setValue({\n ...value,\n [fieldKey]: null\n });\n } else if (numberValue !== undefined && numberValue !== null) {\n setValue({\n ...value,\n [fieldKey]: numberValue\n });\n } else {\n setValue({\n ...value,\n [fieldKey]: null\n });\n }\n } else {\n setValue({\n ...value,\n [fieldKey]: event.target.value\n });\n }\n }}/>;\n } else if (type === \"date\") {\n return <DateTimeField value={entryValue as Date | null | undefined}\n size={\"medium\"}\n locale={locale}\n disabled={disabled || !fieldKey}\n onChange={(date) => {\n setValue({\n ...value,\n [fieldKey]: date\n });\n }}/>;\n } else if (type === \"boolean\") {\n return <BooleanSwitchWithLabel value={entryValue as boolean | null}\n size={\"medium\"}\n position={\"start\"}\n disabled={disabled || !fieldKey}\n onValueChange={(newValue) => {\n setValue({\n ...value,\n [fieldKey]: newValue\n });\n }}/>;\n } else if (type === \"array\") {\n const arrayValue = (entryValue as string[]) || [];\n return <div\n className={cls(defaultBorderMixin, \"ml-2 pl-2 border-l border-solid\")}>\n <ArrayContainer value={arrayValue}\n newDefaultEntry={\"\"}\n droppableId={id.toString()}\n addLabel={fieldKey ? t(\"add_to_field\", { fieldName: fieldKey }) : t(\"add\")}\n size={\"small\"}\n disabled={disabled || !fieldKey}\n canAddElements={true}\n onValueChange={(newValue) => {\n setValue({\n ...value,\n [fieldKey]: newValue\n });\n }}\n buildEntry={({\n index,\n internalId\n }) => {\n return <ArrayKeyValueRow\n index={index}\n id={internalId}\n value={arrayValue[index]}\n disabled={disabled || !fieldKey}\n setValue={(newValue) => {\n const newArrayValue = [...arrayValue] as unknown[];\n newArrayValue[index] = newValue;\n setValue({\n ...value,\n [fieldKey]: newArrayValue\n });\n }}\n />\n }}/>\n </div>;\n } else if (type === \"map\") {\n return <div\n className={cls(defaultBorderMixin, \"ml-2 pl-2 border-l border-solid\")}>\n <MapEditView value={entryValue as Record<string, unknown> | undefined}\n fieldName={fieldKey}\n setValue={(updatedValue) => {\n setValue({\n ...value,\n [fieldKey]: updatedValue\n });\n }}/>\n </div>;\n } else {\n return <Typography\n variant={\"caption\"}>\n {`Data type ${type} not supported yet`}\n </Typography>;\n }\n }\n\n function doUpdatetype(type: DataType) {\n updatetype(id, type);\n }\n\n return (<>\n <Typography key={id.toString()}\n component={\"div\"}\n className=\"font-mono flex flex-row gap-1\">\n <div className=\"w-[300px] max-w-[30%]\">\n <TextField\n value={fieldKey}\n aria-label={t(\"key\")}\n placeholder={\"key\"}\n disabled={disabled || (entryValue !== undefined && entryValue !== null && entryValue !== \"\")}\n size={\"medium\"}\n onChange={(event) => {\n onFieldKeyChange(event.target.value);\n }}/>\n </div>\n\n <div className=\"grow\">\n {(type !== \"map\" && type !== \"array\") && buildInput(entryValue, fieldKey, type)}\n </div>\n <div className={\"flex flex-col\"}>\n <Menu\n trigger={<IconButton aria-label={t(\"change_value_type\")} size={\"smallest\"}>\n <ChevronDownIcon size={iconSize.small}/>\n </IconButton>}\n >\n <MenuItem dense\n onClick={() => doUpdatetype(\"string\")}>string</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"number\")}>number</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"boolean\")}>boolean</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"date\")}>date</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"map\")}>map</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"array\")}>array</MenuItem>\n </Menu>\n\n <IconButton aria-label=\"delete\"\n size={\"smallest\"}\n onClick={onDeleteClick}>\n <MinusIcon size={iconSize.smallest}/>\n </IconButton>\n </div>\n </Typography>\n\n {(type === \"map\" || type === \"array\") && buildInput(entryValue, fieldKey, type)}\n\n </>\n\n );\n}\n\nfunction ArrayKeyValueRow<T>({\n id,\n index,\n value,\n setValue\n }: {\n id: number,\n index: number,\n value: T,\n setValue: (value: T | null) => void,\n disabled?: boolean,\n}) {\n const { t } = useTranslation();\n\n const { locale } = useCustomizationController();\n const [selectedtype, setSelectedtype] = useState<DataType>(gettype(value) ?? \"string\");\n\n function doUpdatetype(type: DataType) {\n setSelectedtype(type);\n }\n\n function buildInput(entryValue: unknown, type: DataType) {\n if (type === \"string\" || type === \"number\") {\n return <TextField value={entryValue as string | number | undefined}\n aria-label={`Value ${index + 1}`}\n type={type === \"number\" ? \"number\" : \"text\"}\n size={\"medium\"}\n onChange={(event) => {\n if (type === \"number\") {\n const numberValue = event.target.value ? parseFloat(event.target.value) : undefined;\n if (numberValue && isNaN(numberValue)) {\n setValue(null);\n } else if (numberValue !== undefined && numberValue !== null) {\n setValue(numberValue as T);\n } else {\n setValue(null);\n }\n } else {\n setValue(event.target.value as T);\n }\n }}/>;\n } else if (type === \"date\") {\n return <DateTimeField value={entryValue as Date | null | undefined}\n size={\"medium\"}\n locale={locale}\n onChange={(date) => {\n setValue(date as T);\n }}/>;\n } else if (type === \"boolean\") {\n return <BooleanSwitchWithLabel value={entryValue as boolean | null}\n size={\"small\"}\n position={\"start\"}\n onValueChange={(v) => {\n setValue(v as T);\n }}/>;\n } else if (type === \"array\") {\n return <Typography variant={\"caption\"}>\n Arrays of arrays are not supported.\n </Typography>;\n } else if (type === \"map\") {\n const mapValue = (entryValue && typeof entryValue === \"object\") ? (entryValue as Record<string, unknown>) : undefined;\n return <div className={cls(defaultBorderMixin, \"ml-2 pl-2 border-l border-solid\")}>\n <MapEditView value={mapValue}\n setValue={(updatedValue) => {\n setValue(updatedValue as T | null);\n }}/>\n </div>;\n } else {\n return <Typography\n variant={\"caption\"}>\n {`Data type ${type} not supported yet`}\n </Typography>;\n }\n }\n\n return (<>\n <Typography key={id.toString()}\n component={\"div\"}\n className=\"font-mono flex min-h-12 flex-row gap-1 items-center\">\n\n <div className=\"grow\">\n {selectedtype !== \"map\" && buildInput(value, selectedtype)}\n </div>\n\n <Menu\n trigger={<IconButton aria-label={t(\"change_value_type\")} size={\"small\"}\n className=\"h-7 w-7\">\n <ChevronDownIcon/>\n </IconButton>}>\n <MenuItem dense\n onClick={() => doUpdatetype(\"string\")}>string</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"number\")}>number</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"boolean\")}>boolean</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"map\")}>map</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"date\")}>date</MenuItem>\n </Menu>\n\n </Typography>\n\n {selectedtype === \"map\" && buildInput(value, selectedtype)}\n\n </>\n\n );\n}\n\nfunction getRandomId() {\n return Math.floor(Math.random() * Math.floor(Number.MAX_SAFE_INTEGER));\n}\n\nfunction gettype(value: unknown): DataType | undefined {\n if (typeof value === \"string\" || value === null) {\n return \"string\";\n } else if (typeof value === \"number\") {\n return \"number\";\n } else if (typeof value === \"boolean\") {\n return \"boolean\";\n } else if (Array.isArray(value)) {\n return \"array\";\n } else if (value instanceof Date) {\n return \"date\";\n } else if (value && typeof value === \"object\" && \"isEntityReference\" in value && typeof (value as Record<string, unknown>).isEntityReference === \"function\" && (value as Record<string, (...args: unknown[]) => unknown>).isEntityReference()) {\n return \"reference\";\n } else if (value instanceof GeoPoint) {\n return \"geopoint\";\n } else if (typeof value === \"object\") {\n return \"map\";\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwCA,SAAgB,qBAAqB,EACI,aACA,OACA,WACA,OACA,UACA,UACA,UACA,gBACA,oBACA,2BACA,WACA,WACwB;CAE7D,MAAM,YAAY,SAAS,OAAO,aAAa,KAAA,IAAY,OAAO,SAAS,OAAO,aAAa;CAE/F,IAAI,CAAC,SAAS,UACV,MAAM,MAAM,iBAAiB,YAAY,sEAAsE;CAKnH,MAAM,cAAc,oBAAC,aAAD;EAAoB;EACG;EACA;EACV,cALX,MAAM,QAAQ,OAAO,eAAe,WAKX;EACd,WAAW,SAAS,QAAQ;CAAa,CAAA;CAE1E,MAAM,QAAQ,oBAAC,eAAD;EACG;EACb,MAAM,mBAAmB,UAAU,OAAO;EAC1C,UAAU,SAAS,YAAY;EAC/B,OAAO,SAAS,QAA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CACnD,IAAI,OAAO,UAAU,YAAY,UAAU,MACvC,OAAO;MACJ,IAAI,OAAO,UAAU,UACxB,OAAO;MACJ,IAAI,OAAO,UAAU,WACxB,OAAO;MACJ,IAAI,MAAM,QAAQ,KAAK,GAC1B,OAAO;MACJ,IAAI,iBAAiB,MACxB,OAAO;MACJ,IAAI,SAAS,OAAO,UAAU,YAAY,uBAAuB,SAAS,OAAQ,MAAkC,sBAAsB,cAAe,MAA0D,kBAAkB,GACxO,OAAO;MACJ,IAAI,iBAAiB,UACxB,OAAO;MACJ,IAAI,OAAO,UAAU,UACxB,OAAO;AAIf"}
|
|
1
|
+
{"version":3,"file":"KeyValueFieldBinding.js","names":[],"sources":["../../../src/form/field_bindings/KeyValueFieldBinding.tsx"],"sourcesContent":["import type { FieldProps } from \"../../types/fields\";\nimport type { MapProperty } from \"@rebasepro/types\";\nimport React, { useEffect, useState } from \"react\";\nimport { DataType, GeoPoint } from \"@rebasepro/types\";\n\nimport { ArrayContainer } from \"../../components/ArrayContainer\";\nimport { FieldHelperText } from \"../components/FieldHelperText\";\nimport { LabelWithIcon } from \"../components/LabelWithIcon\";\nimport {\n BooleanSwitchWithLabel,\n Button,\n ChevronDownIcon,\n cls,\n DateTimeField,\n defaultBorderMixin,\n ExpandablePanel,\n IconButton,\n iconSize,\n Menu,\n MenuItem,\n MinusIcon,\n PlusIcon,\n TextField,\n Typography\n} from \"@rebasepro/ui\";\nimport { getIconForProperty } from \"../../util/property_utils\";\nimport { useCustomizationController, useTranslation } from \"@rebasepro/app\";\nimport { getIn } from \"@rebasepro/forms\";\nimport { getDefaultValueFortype } from \"@rebasepro/common\";\n\ntype MapEditViewRowState = [number, {\n key: string,\n type: DataType\n}];\n\n/**\n * Field that allows edition of key value pairs.\n *\n * @group Form fields\n */\nexport function KeyValueFieldBinding({\n propertyKey,\n value,\n showError,\n error,\n disabled,\n property,\n setValue,\n minimalistView,\n includeDescription,\n underlyingValueHasChanged,\n autoFocus,\n context\n }: FieldProps<MapProperty>) {\n\n const expanded = (property.admin?.expanded === undefined ? true : property.admin?.expanded) || autoFocus;\n\n if (!property.keyValue) {\n throw Error(`Your property ${propertyKey} needs to have the 'keyValue' prop in order to use this field binding`);\n }\n\n const initialValues = getIn(context.formex.initialValues, propertyKey) as Record<string, unknown> | undefined;\n\n const mapFormView = <MapEditView value={value}\n setValue={setValue}\n disabled={disabled}\n initialValue={initialValues}\n fieldName={property.name ?? propertyKey}/>;\n\n const title = <LabelWithIcon\n propertyKey={propertyKey}\n icon={getIconForProperty(property, \"small\")}\n required={property.validation?.required}\n title={property.name ?? propertyKey}\n className={\"text-text-secondary dark:text-text-secondary-dark\"}/>;\n\n return (\n <>\n\n {!minimalistView && <ExpandablePanel initiallyExpanded={expanded}\n title={title}\n innerClassName={\"px-2 md:px-4 pb-2 md:pb-4 pt-1 md:pt-2\"}>{mapFormView}</ExpandablePanel>}\n\n {minimalistView && mapFormView}\n\n <FieldHelperText includeDescription={includeDescription}\n showError={showError}\n error={error}\n disabled={disabled}\n property={property}/>\n\n </>\n );\n}\n\ninterface MapEditViewParams<T extends Record<string, unknown>> {\n value?: T;\n initialValue?: T;\n setValue: (value: (T | null)) => void;\n fieldName?: string,\n disabled?: boolean\n}\n\nfunction MapEditView<T extends Record<string, unknown>>({\n value,\n initialValue,\n setValue,\n fieldName,\n disabled\n }: MapEditViewParams<T>) {\n const [internalState, setInternalState] = React.useState<MapEditViewRowState[]>(\n Object.keys(initialValue ?? {}).map((key) => [getRandomId(), {\n key,\n type: gettype(initialValue?.[key]) ?? \"string\"\n }])\n );\n const { t } = useTranslation();\n\n useEffect(() => {\n const currentKeys = internalState.map(([id, { key }]) => key);\n const newKeys = Object.entries(value ?? {}).filter(([key, v]) => v !== undefined).map(([key]) => key);\n const keysToAdd = newKeys.filter((key) => !currentKeys.includes(key));\n // A row without a name yet is the form's alone: it is not in the value.\n const keysToRemove = currentKeys.filter((key) => key !== \"\" && !newKeys.includes(key));\n const newRowIds = [...internalState];\n keysToAdd.forEach((key) => {\n newRowIds.push([getRandomId(), {\n key,\n type: gettype(value?.[key]) ?? \"string\"\n }]);\n });\n keysToRemove.forEach((key) => {\n const index = newRowIds.findIndex(([id, { key: k }]) => k === key);\n newRowIds.splice(index, 1);\n });\n setInternalState(newRowIds);\n }, [value]);\n\n const updatetype = (id: number, type: DataType) => {\n if (!id) {\n console.warn(\"No key selected for data type update\");\n return;\n }\n setInternalState(internalState.map((row) => {\n if (row[0] === id) {\n return [row[0], {\n key: row[1].key,\n type\n }];\n }\n return row;\n }));\n // A row with no key yet is not in the value, and choosing its type does\n // not put it there: `{ \"\": … }` would be saved as an entry under the\n // empty key.\n const key = internalState.find((row) => row[0] === id)?.[1].key;\n if (!key) return;\n setValue({\n ...(value ?? {} as T),\n [key]: getDefaultValueFortype(type)\n })\n };\n\n return <div className=\"py-1 flex flex-col gap-1\">\n {internalState\n .map(([id, {\n key: fieldKey,\n type\n }], index) => {\n const entryValue = fieldKey ? value?.[fieldKey] : \"\";\n const onFieldKeyChange = (newKey: string) => {\n\n setInternalState(internalState.map((currentId) => {\n if (currentId[0] === id) {\n return [id, {\n key: newKey ?? \"\",\n type: currentId[1].type\n }];\n }\n return currentId;\n }));\n\n if (typeof value === \"object\" && newKey in value) {\n // if the key is already there, don't delete the previous value\n return;\n }\n\n const newValue = { ...(value ?? {}) } as T;\n if (typeof initialValue === \"object\" && fieldKey in initialValue) {\n (newValue as Record<string, unknown>)[fieldKey] = undefined; // set to undefined to remove from the object, the driver will remove it from the backend\n } else {\n delete (newValue as Record<string, unknown>)[fieldKey];\n }\n setValue({\n ...newValue,\n [newKey ?? \"\"]: entryValue\n });\n };\n return <MapKeyValueRow id={id}\n key={id}\n fieldKey={fieldKey}\n value={value ?? {} as T}\n onDeleteClick={() => {\n const newValue = { ...(value ?? {}) as T };\n if (initialValue && fieldKey in initialValue) {\n (newValue as Record<string, unknown>)[fieldKey] = undefined;\n } else {\n delete (newValue as Record<string, unknown>)[fieldKey];\n }\n setInternalState(internalState.filter((currentId) => currentId[0] !== id));\n setValue({\n ...newValue\n });\n }}\n onFieldKeyChange={onFieldKeyChange}\n setValue={setValue}\n entryValue={entryValue}\n type={type}\n disabled={disabled}\n updatetype={updatetype}/>;\n }\n )}\n\n <Button variant={\"text\"}\n size={\"small\"}\n className=\"w-full\"\n disabled={disabled}\n startIcon={<PlusIcon/>}\n onClick={(e) => {\n e.preventDefault();\n // Only a row: written into the value as `{ \"\": null }`, a\n // record saved before the key was named stored an entry\n // under the empty key.\n setInternalState([...internalState, [getRandomId(), {\n key: \"\",\n type: \"string\"\n }]]);\n }\n }>\n {fieldName ? t(\"add_to_field\", { fieldName }) : t(\"add\")}\n </Button>\n\n </div>;\n}\n\nfunction MapKeyValueRow<T extends Record<string, unknown>>({\n id,\n fieldKey,\n value,\n onFieldKeyChange,\n onDeleteClick,\n setValue,\n entryValue,\n type,\n updatetype,\n disabled\n }: {\n id: number,\n fieldKey: string,\n value: T,\n onFieldKeyChange: (newKey: string) => void,\n onDeleteClick: () => void,\n setValue: (value: (T | null)) => void,\n entryValue: unknown,\n type: DataType,\n disabled?: boolean,\n updatetype: (id: number, type: DataType) => void\n}) {\n\n const { locale } = useCustomizationController();\n const { t } = useTranslation();\n\n function buildInput(entryValue: unknown, fieldKey: string, type: DataType) {\n if (type === \"string\" || type === \"number\") {\n return <TextField\n key={type}\n aria-label={fieldKey ? `${t(\"value\")}: ${fieldKey}` : t(\"value\")}\n placeholder={\"value\"}\n value={entryValue as string | number | undefined}\n type={type === \"number\" ? \"number\" : \"text\"}\n size={\"medium\"}\n disabled={disabled || !fieldKey}\n onChange={(event) => {\n if (type === \"number\") {\n const numberValue = event.target.value ? parseFloat(event.target.value) : undefined;\n if (numberValue && isNaN(numberValue)) {\n setValue({\n ...value,\n [fieldKey]: null\n });\n } else if (numberValue !== undefined && numberValue !== null) {\n setValue({\n ...value,\n [fieldKey]: numberValue\n });\n } else {\n setValue({\n ...value,\n [fieldKey]: null\n });\n }\n } else {\n setValue({\n ...value,\n [fieldKey]: event.target.value\n });\n }\n }}/>;\n } else if (type === \"date\") {\n return <DateTimeField value={entryValue as Date | null | undefined}\n size={\"medium\"}\n locale={locale}\n disabled={disabled || !fieldKey}\n onChange={(date) => {\n setValue({\n ...value,\n [fieldKey]: date\n });\n }}/>;\n } else if (type === \"boolean\") {\n return <BooleanSwitchWithLabel value={entryValue as boolean | null}\n size={\"medium\"}\n position={\"start\"}\n disabled={disabled || !fieldKey}\n onValueChange={(newValue) => {\n setValue({\n ...value,\n [fieldKey]: newValue\n });\n }}/>;\n } else if (type === \"array\") {\n const arrayValue = (entryValue as string[]) || [];\n return <div\n className={cls(defaultBorderMixin, \"ml-2 pl-2 border-l border-solid\")}>\n <ArrayContainer value={arrayValue}\n newDefaultEntry={\"\"}\n droppableId={id.toString()}\n addLabel={fieldKey ? t(\"add_to_field\", { fieldName: fieldKey }) : t(\"add\")}\n size={\"small\"}\n disabled={disabled || !fieldKey}\n canAddElements={true}\n onValueChange={(newValue) => {\n setValue({\n ...value,\n [fieldKey]: newValue\n });\n }}\n buildEntry={({\n index,\n internalId\n }) => {\n return <ArrayKeyValueRow\n index={index}\n id={internalId}\n value={arrayValue[index]}\n disabled={disabled || !fieldKey}\n setValue={(newValue) => {\n const newArrayValue = [...arrayValue] as unknown[];\n newArrayValue[index] = newValue;\n setValue({\n ...value,\n [fieldKey]: newArrayValue\n });\n }}\n />\n }}/>\n </div>;\n } else if (type === \"map\") {\n return <div\n className={cls(defaultBorderMixin, \"ml-2 pl-2 border-l border-solid\")}>\n <MapEditView value={entryValue as Record<string, unknown> | undefined}\n fieldName={fieldKey}\n setValue={(updatedValue) => {\n setValue({\n ...value,\n [fieldKey]: updatedValue\n });\n }}/>\n </div>;\n } else {\n return <Typography\n variant={\"caption\"}>\n {`Data type ${type} not supported yet`}\n </Typography>;\n }\n }\n\n function doUpdatetype(type: DataType) {\n updatetype(id, type);\n }\n\n return (<>\n <Typography key={id.toString()}\n component={\"div\"}\n className=\"font-mono flex flex-row gap-1\">\n <div className=\"w-[300px] max-w-[30%]\">\n <TextField\n value={fieldKey}\n aria-label={t(\"key\")}\n placeholder={\"key\"}\n disabled={disabled || (entryValue !== undefined && entryValue !== null && entryValue !== \"\")}\n size={\"medium\"}\n onChange={(event) => {\n onFieldKeyChange(event.target.value);\n }}/>\n </div>\n\n <div className=\"grow\">\n {(type !== \"map\" && type !== \"array\") && buildInput(entryValue, fieldKey, type)}\n </div>\n <div className={\"flex flex-col\"}>\n <Menu\n trigger={<IconButton aria-label={t(\"change_value_type\")} size={\"smallest\"}>\n <ChevronDownIcon size={iconSize.small}/>\n </IconButton>}\n >\n <MenuItem dense\n onClick={() => doUpdatetype(\"string\")}>string</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"number\")}>number</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"boolean\")}>boolean</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"date\")}>date</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"map\")}>map</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"array\")}>array</MenuItem>\n </Menu>\n\n <IconButton aria-label=\"delete\"\n size={\"smallest\"}\n onClick={onDeleteClick}>\n <MinusIcon size={iconSize.smallest}/>\n </IconButton>\n </div>\n </Typography>\n\n {(type === \"map\" || type === \"array\") && buildInput(entryValue, fieldKey, type)}\n\n </>\n\n );\n}\n\nfunction ArrayKeyValueRow<T>({\n id,\n index,\n value,\n setValue\n }: {\n id: number,\n index: number,\n value: T,\n setValue: (value: T | null) => void,\n disabled?: boolean,\n}) {\n const { t } = useTranslation();\n\n const { locale } = useCustomizationController();\n const [selectedtype, setSelectedtype] = useState<DataType>(gettype(value) ?? \"string\");\n\n function doUpdatetype(type: DataType) {\n setSelectedtype(type);\n }\n\n function buildInput(entryValue: unknown, type: DataType) {\n if (type === \"string\" || type === \"number\") {\n return <TextField value={entryValue as string | number | undefined}\n aria-label={`Value ${index + 1}`}\n type={type === \"number\" ? \"number\" : \"text\"}\n size={\"medium\"}\n onChange={(event) => {\n if (type === \"number\") {\n const numberValue = event.target.value ? parseFloat(event.target.value) : undefined;\n if (numberValue && isNaN(numberValue)) {\n setValue(null);\n } else if (numberValue !== undefined && numberValue !== null) {\n setValue(numberValue as T);\n } else {\n setValue(null);\n }\n } else {\n setValue(event.target.value as T);\n }\n }}/>;\n } else if (type === \"date\") {\n return <DateTimeField value={entryValue as Date | null | undefined}\n size={\"medium\"}\n locale={locale}\n onChange={(date) => {\n setValue(date as T);\n }}/>;\n } else if (type === \"boolean\") {\n return <BooleanSwitchWithLabel value={entryValue as boolean | null}\n size={\"small\"}\n position={\"start\"}\n onValueChange={(v) => {\n setValue(v as T);\n }}/>;\n } else if (type === \"array\") {\n return <Typography variant={\"caption\"}>\n Arrays of arrays are not supported.\n </Typography>;\n } else if (type === \"map\") {\n const mapValue = (entryValue && typeof entryValue === \"object\") ? (entryValue as Record<string, unknown>) : undefined;\n return <div className={cls(defaultBorderMixin, \"ml-2 pl-2 border-l border-solid\")}>\n <MapEditView value={mapValue}\n setValue={(updatedValue) => {\n setValue(updatedValue as T | null);\n }}/>\n </div>;\n } else {\n return <Typography\n variant={\"caption\"}>\n {`Data type ${type} not supported yet`}\n </Typography>;\n }\n }\n\n return (<>\n <Typography key={id.toString()}\n component={\"div\"}\n className=\"font-mono flex min-h-12 flex-row gap-1 items-center\">\n\n <div className=\"grow\">\n {selectedtype !== \"map\" && buildInput(value, selectedtype)}\n </div>\n\n <Menu\n trigger={<IconButton aria-label={t(\"change_value_type\")} size={\"small\"}\n className=\"h-7 w-7\">\n <ChevronDownIcon/>\n </IconButton>}>\n <MenuItem dense\n onClick={() => doUpdatetype(\"string\")}>string</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"number\")}>number</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"boolean\")}>boolean</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"map\")}>map</MenuItem>\n <MenuItem dense\n onClick={() => doUpdatetype(\"date\")}>date</MenuItem>\n </Menu>\n\n </Typography>\n\n {selectedtype === \"map\" && buildInput(value, selectedtype)}\n\n </>\n\n );\n}\n\nfunction getRandomId() {\n return Math.floor(Math.random() * Math.floor(Number.MAX_SAFE_INTEGER));\n}\n\nfunction gettype(value: unknown): DataType | undefined {\n if (typeof value === \"string\" || value === null) {\n return \"string\";\n } else if (typeof value === \"number\") {\n return \"number\";\n } else if (typeof value === \"boolean\") {\n return \"boolean\";\n } else if (Array.isArray(value)) {\n return \"array\";\n } else if (value instanceof Date) {\n return \"date\";\n } else if (value && typeof value === \"object\" && \"isEntityReference\" in value && typeof (value as Record<string, unknown>).isEntityReference === \"function\" && (value as Record<string, (...args: unknown[]) => unknown>).isEntityReference()) {\n return \"reference\";\n } else if (value instanceof GeoPoint) {\n return \"geopoint\";\n } else if (typeof value === \"object\") {\n return \"map\";\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwCA,SAAgB,qBAAqB,EACI,aACA,OACA,WACA,OACA,UACA,UACA,UACA,gBACA,oBACA,2BACA,WACA,WACwB;CAE7D,MAAM,YAAY,SAAS,OAAO,aAAa,KAAA,IAAY,OAAO,SAAS,OAAO,aAAa;CAE/F,IAAI,CAAC,SAAS,UACV,MAAM,MAAM,iBAAiB,YAAY,sEAAsE;CAKnH,MAAM,cAAc,oBAAC,aAAD;EAAoB;EACG;EACA;EACV,cALX,MAAM,QAAQ,OAAO,eAAe,WAKX;EACd,WAAW,SAAS,QAAQ;CAAa,CAAA;CAE1E,MAAM,QAAQ,oBAAC,eAAD;EACG;EACb,MAAM,mBAAmB,UAAU,OAAO;EAC1C,UAAU,SAAS,YAAY;EAC/B,OAAO,SAAS,QAAQ;EACxB,WAAW;CAAqD,CAAA;CAEpE,OACI,qBAAA,UAAA,EAAA,UAAA;EAEK,CAAC,kBAAkB,oBAAC,iBAAD;GAAiB,mBAAmB;GACZ;GACP,gBAAgB;aAA2C;EAA6B,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OAAO;MACJ,IAAI,MAAM,QAAQ,KAAK,GAC1B,OAAO;MACJ,IAAI,iBAAiB,MACxB,OAAO;MACJ,IAAI,SAAS,OAAO,UAAU,YAAY,uBAAuB,SAAS,OAAQ,MAAkC,sBAAsB,cAAe,MAA0D,kBAAkB,GACxO,OAAO;MACJ,IAAI,iBAAiB,UACxB,OAAO;MACJ,IAAI,OAAO,UAAU,UACxB,OAAO;AAIf"}
|
|
@@ -24,7 +24,6 @@ function ReadOnlyFieldBinding({ propertyKey, value, error, showError, minimalist
|
|
|
24
24
|
className: "pointer-events-none absolute top-1 left-0 text-text-secondary dark:text-text-secondary-dark",
|
|
25
25
|
children: /* @__PURE__ */ jsx(LabelWithIcon, {
|
|
26
26
|
icon: getIconForProperty(property, "small"),
|
|
27
|
-
required: property.validation?.required,
|
|
28
27
|
title: property.name ?? propertyKey
|
|
29
28
|
})
|
|
30
29
|
}), /* @__PURE__ */ jsx("div", {
|
|
@@ -47,7 +46,6 @@ function ReadOnlyFieldBinding({ propertyKey, value, error, showError, minimalist
|
|
|
47
46
|
!minimalistView && !hideLabel && /* @__PURE__ */ jsx(LabelWithIcon, {
|
|
48
47
|
propertyKey,
|
|
49
48
|
icon: getIconForProperty(property, "small"),
|
|
50
|
-
required: property.validation?.required,
|
|
51
49
|
title: property.name ?? propertyKey,
|
|
52
50
|
className: "h-8 text-text-secondary dark:text-text-secondary-dark ml-3"
|
|
53
51
|
}),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ReadOnlyFieldBinding.js","names":[],"sources":["../../../src/form/field_bindings/ReadOnlyFieldBinding.tsx"],"sourcesContent":["import type { FieldProps } from \"../../types/fields\";\nimport type { Property } from \"@rebasepro/types\";\nimport React from \"react\";\n\nimport { PropertyPreview } from \"../../preview\";\nimport { FieldHelperText } from \"../components/FieldHelperText\";\nimport { LabelWithIcon } from \"../components/LabelWithIcon\";\nimport { cls, ErrorBoundary, InputLabel } from \"@rebasepro/ui\";\nimport { getIconForProperty } from \"../../util/property_utils\";\nimport { readOnlyLabelsInside } from \"../label_placement\";\n\n/**\n *\n * Simply render the non-editable preview of a field\n *\n * This is one of the internal components that get mapped natively inside forms\n * and tables to the specified properties.\n * @group Form fields\n */\nexport function ReadOnlyFieldBinding({\n propertyKey,\n value,\n error,\n showError,\n minimalistView,\n property,\n includeDescription,\n hideLabel,\n context,\n size = \"large\"\n}: FieldProps<Property>) {\n\n // if (!context.entityId)\n // throw new Error(\"ReadOnlyFieldBinding: Entity id is null\");\n\n const skipCardWrapper = property.type === \"relation\" || property.type === \"reference\";\n\n // A one-line value at the form's size is drawn like the one-line fields\n // around it: the same 64px box, the label shrunk into its top edge. It keeps\n // the outline and drops the fill — that is what says it cannot be edited.\n if (!minimalistView && !hideLabel && size === \"large\" && readOnlyLabelsInside(property)) {\n return (\n <>\n <div className={\"relative w-full min-h-[66px] rounded-lg border border-hairline-strong px-3 pt-8 pb-2 text-base\"}>\n {/* `left-0` is the box's padding edge, where a text field's\n label starts; left to its static position it would\n start after the `px-3`, 12px too far in. */}\n <InputLabel shrink\n className={\"pointer-events-none absolute top-1 left-0 text-text-secondary dark:text-text-secondary-dark\"}>\n <LabelWithIcon\n icon={getIconForProperty(property, \"small\")}\n
|
|
1
|
+
{"version":3,"file":"ReadOnlyFieldBinding.js","names":[],"sources":["../../../src/form/field_bindings/ReadOnlyFieldBinding.tsx"],"sourcesContent":["import type { FieldProps } from \"../../types/fields\";\nimport type { Property } from \"@rebasepro/types\";\nimport React from \"react\";\n\nimport { PropertyPreview } from \"../../preview\";\nimport { FieldHelperText } from \"../components/FieldHelperText\";\nimport { LabelWithIcon } from \"../components/LabelWithIcon\";\nimport { cls, ErrorBoundary, InputLabel } from \"@rebasepro/ui\";\nimport { getIconForProperty } from \"../../util/property_utils\";\nimport { readOnlyLabelsInside } from \"../label_placement\";\n\n/**\n *\n * Simply render the non-editable preview of a field\n *\n * This is one of the internal components that get mapped natively inside forms\n * and tables to the specified properties.\n * @group Form fields\n */\nexport function ReadOnlyFieldBinding({\n propertyKey,\n value,\n error,\n showError,\n minimalistView,\n property,\n includeDescription,\n hideLabel,\n context,\n size = \"large\"\n}: FieldProps<Property>) {\n\n // if (!context.entityId)\n // throw new Error(\"ReadOnlyFieldBinding: Entity id is null\");\n\n const skipCardWrapper = property.type === \"relation\" || property.type === \"reference\";\n\n // No required marker on either label: the asterisk asks the person filling\n // the form for a value, and nobody fills this one in. `validation.required`\n // on a read-only field is about the column (NOT NULL), not about them.\n\n // A one-line value at the form's size is drawn like the one-line fields\n // around it: the same 64px box, the label shrunk into its top edge. It keeps\n // the outline and drops the fill — that is what says it cannot be edited.\n if (!minimalistView && !hideLabel && size === \"large\" && readOnlyLabelsInside(property)) {\n return (\n <>\n <div className={\"relative w-full min-h-[66px] rounded-lg border border-hairline-strong px-3 pt-8 pb-2 text-base\"}>\n {/* `left-0` is the box's padding edge, where a text field's\n label starts; left to its static position it would\n start after the `px-3`, 12px too far in. */}\n <InputLabel shrink\n className={\"pointer-events-none absolute top-1 left-0 text-text-secondary dark:text-text-secondary-dark\"}>\n <LabelWithIcon\n icon={getIconForProperty(property, \"small\")}\n title={property.name ?? propertyKey}/>\n </InputLabel>\n <div className={\"min-h-6 flex items-center overflow-x-auto no-scrollbar opacity-80\"}>\n <ErrorBoundary>\n <PropertyPreview propertyKey={propertyKey}\n value={value}\n property={property}\n hideLabel\n size={\"medium\"}/>\n </ErrorBoundary>\n </div>\n </div>\n\n <FieldHelperText includeDescription={includeDescription}\n showError={showError}\n error={error}\n property={property}/>\n </>\n );\n }\n\n return (\n\n <>\n\n {!minimalistView && !hideLabel && <LabelWithIcon\n propertyKey={propertyKey}\n icon={getIconForProperty(property, \"small\")}\n title={property.name ?? propertyKey}\n className={\"h-8 text-text-secondary dark:text-text-secondary-dark ml-3\"}/>\n }\n\n <div\n className={cls(\n \"w-full overflow-x-scroll no-scrollbar flex items-center\",\n skipCardWrapper\n ? \"\"\n // `px-3` is what `TextField` gives its input, so a\n // read-only value starts on the same vertical line as\n // the text beside it. It was `px-4 md:px-6`, which in a\n // one-column span spent a sixth of the box on empty\n // margin and pushed short values towards the middle.\n : cls(\"rounded-lg border border-hairline-strong px-3 text-sm opacity-80\", {\n // The height an editable field of the form's `size`\n // renders at — the kit's control height plus its 1px\n // hairline on each side — so a row holding one of\n // each has its baselines and bottom edges agree. This\n // was a fixed `min-h-12` (48px) with the page's 16px\n // text: 2px short of a `large` text field, 14px taller\n // than a `small` one, and a size above every input's\n // `text-sm` at either.\n \"min-h-[34px]\": size === \"small\",\n \"min-h-[42px]\": size === \"medium\",\n \"min-h-[50px]\": size === \"large\"\n })\n )}>\n\n <ErrorBoundary>\n {/* The field is labelled either just above by this\n component, or by the `FieldBlock` that asked for\n `hideLabel` — never by the preview. `BooleanPreview`\n prints the property name beside its checkbox, so a\n read-only boolean read as \"Procesado por LLM\" over a\n checkbox saying \"Procesado por LLM\", wrapped over two\n lines in a one-column span. */}\n <PropertyPreview propertyKey={propertyKey}\n value={value}\n property={property}\n hideLabel={hideLabel || !minimalistView}\n size={\"medium\"}/>\n </ErrorBoundary>\n\n </div>\n\n <FieldHelperText includeDescription={includeDescription}\n showError={showError}\n error={error}\n property={property}/>\n\n </>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmBA,SAAgB,qBAAqB,EACjC,aACA,OACA,OACA,WACA,gBACA,UACA,oBACA,WACA,SACA,OAAO,WACc;CAKrB,MAAM,kBAAkB,SAAS,SAAS,cAAc,SAAS,SAAS;CAS1E,IAAI,CAAC,kBAAkB,CAAC,aAAa,SAAS,WAAW,qBAAqB,QAAQ,GAClF,OACI,qBAAA,UAAA,EAAA,UAAA,CACI,qBAAC,OAAD;EAAK,WAAW;YAAhB,CAII,oBAAC,YAAD;GAAY,QAAA;GACR,WAAW;aACX,oBAAC,eAAD;IACI,MAAM,mBAAmB,UAAU,OAAO;IAC1C,OAAO,SAAS,QAAQ;GAAa,CAAA;EACjC,CAAA,GACZ,oBAAC,OAAD;GAAK,WAAW;aACZ,oBAAC,eAAD,EAAA,UACI,oBAAC,iBAAD;IAA8B;IACnB;IACG;IACV,WAAA;IACA,MAAM;GAAU,CAAA,EACT,CAAA;EACd,CAAA,CACJ;KAEL,oBAAC,iBAAD;EAAqC;EACtB;EACJ;EACG;CAAU,CAAA,CAC1B,EAAA,CAAA;CAIV,OAEI,qBAAA,UAAA,EAAA,UAAA;EAEK,CAAC,kBAAkB,CAAC,aAAa,oBAAC,eAAD;GACjB;GACb,MAAM,mBAAmB,UAAU,OAAO;GAC1C,OAAO,SAAS,QAAQ;GACxB,WAAW;EAA8D,CAAA;EAG7E,oBAAC,OAAD;GACI,WAAW,IACP,2DACA,kBACM,KAMA,IAAI,oEAAoE;IAStE,gBAAgB,SAAS;IACzB,gBAAgB,SAAS;IACzB,gBAAgB,SAAS;GAC7B,CAAC,CACT;aAEA,oBAAC,eAAD,EAAA,UAQI,oBAAC,iBAAD;IAA8B;IACnB;IACG;IACV,WAAW,aAAa,CAAC;IACzB,MAAM;GAAU,CAAA,EACT,CAAA;EAEd,CAAA;EAEL,oBAAC,iBAAD;GAAqC;GACtB;GACJ;GACG;EAAU,CAAA;CAE1B,EAAA,CAAA;AAEV"}
|
|
@@ -22,6 +22,7 @@ function TextFieldBinding({ propertyKey, value, setValue, error, showError, disa
|
|
|
22
22
|
url = property.admin?.urlPreview ?? property.url;
|
|
23
23
|
}
|
|
24
24
|
const displayValue = value !== void 0 && value !== null ? String(value) : "";
|
|
25
|
+
const inputValue = typeof value === "number" ? value : displayValue;
|
|
25
26
|
const handleClearClick = useCallback((e) => {
|
|
26
27
|
e.stopPropagation();
|
|
27
28
|
e.preventDefault();
|
|
@@ -30,7 +31,7 @@ function TextFieldBinding({ propertyKey, value, setValue, error, showError, disa
|
|
|
30
31
|
const onChange = (event) => {
|
|
31
32
|
if (inputType === "number") {
|
|
32
33
|
const numberValue = event.target.value ? parseFloat(event.target.value) : void 0;
|
|
33
|
-
if (numberValue && isNaN(numberValue)) setValue(null);
|
|
34
|
+
if (numberValue !== void 0 && Number.isNaN(numberValue)) setValue(null);
|
|
34
35
|
else if (numberValue !== void 0 && numberValue !== null) setValue(numberValue);
|
|
35
36
|
else setValue(null);
|
|
36
37
|
} else setValue(event.target.value === "" ? null : event.target.value);
|
|
@@ -77,7 +78,7 @@ function TextFieldBinding({ propertyKey, value, setValue, error, showError, disa
|
|
|
77
78
|
]
|
|
78
79
|
}) : /* @__PURE__ */ jsx(TextField, {
|
|
79
80
|
size,
|
|
80
|
-
value:
|
|
81
|
+
value: inputValue,
|
|
81
82
|
onChange,
|
|
82
83
|
autoFocus,
|
|
83
84
|
label,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TextFieldBinding.js","names":[],"sources":["../../../src/form/field_bindings/TextFieldBinding.tsx"],"sourcesContent":["import { useTranslation } from \"@rebasepro/app\";\nimport type { FieldProps } from \"../../types/fields\";\nimport type { NumberProperty, StringProperty } from \"@rebasepro/types\";\nimport React, { useCallback } from \"react\";\n\nimport {\n cls,\n Collapse,\n fieldBackgroundHoverMixin,\n fieldBackgroundMixin,\n IconButton,\n InputLabel,\n TextareaAutosize,\n TextField,\n XIcon\n} from \"@rebasepro/ui\";\nimport { PreviewType } from \"@rebasepro/cms-types\";\nimport { FieldHelperText } from \"../components/FieldHelperText\";\nimport { LabelWithIcon } from \"../components/LabelWithIcon\";\nimport { PropertyPreview } from \"../../preview\";\nimport { getIconForProperty } from \"../../util/property_utils\";\n\n/**\n * Generic text field.\n * This is one of the internal components that get mapped natively inside forms\n * and tables to the specified properties.\n * @group Form fields\n */\nexport function TextFieldBinding<T extends string | number>({\n propertyKey,\n value,\n setValue,\n error,\n showError,\n disabled,\n autoFocus,\n property,\n includeDescription,\n hideLabel,\n size = \"large\"\n }: FieldProps<StringProperty | NumberProperty>) {\n const { t } = useTranslation();\n\n let multiline: boolean | undefined;\n let url: boolean | PreviewType | undefined;\n if (property.type === \"string\") {\n multiline = property.admin?.multiline;\n // `url: true` alone earns the preview. A form field holding a URL that\n // renders as plain text is one you have to select and copy to follow,\n // and the property has already said what it is.\n url = property.admin?.urlPreview ?? property.url;\n }\n\n const displayValue = (value !== undefined && value !== null) ? String(value) : \"\";\n\n const handleClearClick = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n setValue(null);\n }, [setValue]);\n\n const onChange = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n if (inputType === \"number\") {\n const numberValue = event.target.value ? parseFloat(event.target.value) : undefined;\n if (numberValue && isNaN(numberValue)) {\n setValue(null);\n } else if (numberValue !== undefined && numberValue !== null) {\n setValue(numberValue as T);\n } else {\n setValue(null);\n }\n } else {\n // Emptied is NULL. Writing `\"\"` over a NULL the user only typed\n // into and deleted made `isNull` filters stop matching the row,\n // and collided on an optional unique column; `required` already\n // reads `\"\"` as missing.\n setValue(event.target.value === \"\" ? null : event.target.value as T);\n }\n };\n\n const isMultiline = Boolean(multiline);\n\n let inputType: \"number\" | \"email\" | \"url\" | undefined = undefined;\n if (property.type === \"number\") {\n inputType = \"number\";\n } else if (property.type === \"string\") {\n if (property.email) inputType = \"email\";\n else if (property.admin?.urlPreview || property.url) inputType = \"url\";\n }\n\n // `undefined` rather than an empty element: TextField and the multiline box\n // both reserve a label row whenever `label` is truthy, so a null-rendering\n // element would leave the gap behind without the text.\n const label = hideLabel\n ? undefined\n : (\n <LabelWithIcon\n icon={getIconForProperty(property, \"small\")}\n required={property.validation?.required || property.isId === true}\n title={property.name ?? propertyKey}/>\n );\n\n // A value under a label inside the box is set at 16px, the FireCMS field:\n // the 64px box is sized for a 24px line. Everywhere a text field stands\n // without its label — a table cell, a dense dialog — it keeps the kit's 14.\n const valueText = label && size === \"large\" ? \"text-base\" : undefined;\n\n // The control needs a name of its own in two cases, and between them they\n // cover every text field in an entity form:\n //\n // - `hideLabel`, which the form sets for anything FieldBlock labels for it\n // (`hideLabel: !selfLabelling`). FieldBlock draws the name in a <span>\n // inside a <div> — not a <label>, and pointing at nothing — so suppressing\n // the field's own label left the input with no accessible name at all and\n // a screen reader fell back to reading its value back to you.\n // - the multiline branch below, which never associated anything: its label\n // is a decorative absolutely-positioned <div>, so it is unnamed whether or\n // not the form also drew one.\n //\n // The single-line TextField is already handled by the kit when a label is\n // present — it wires `aria-labelledby` — so it only needs this as a fallback.\n const accessibleName = property.name ?? propertyKey;\n return (<>\n {isMultiline ? (\n <div className={cls(\n \"rounded-lg relative max-w-full min-h-[64px]\",\n fieldBackgroundMixin,\n fieldBackgroundHoverMixin,\n showError && error ? \"border border-red-500 dark:border-red-600\" : \"\"\n )}>\n {/* The single-line field's shrunk label, at the same spot:\n this was its own 14px label pinned to the top, a size up\n from the label of the field above it. Always shrunk —\n the box is tall, and a label resting in its middle would\n sit on the text. */}\n {label && <InputLabel shrink\n className={cls(\n \"pointer-events-none absolute top-1\",\n showError && error\n ? \"text-red-500 dark:text-red-600\"\n : \"text-text-secondary dark:text-text-secondary-dark\"\n )}>\n {label}\n </InputLabel>}\n <TextareaAutosize\n value={displayValue}\n onChange={onChange}\n autoFocus={autoFocus}\n disabled={disabled}\n aria-label={accessibleName}\n className={cls(\n \"rounded-md resize-none w-full outline-none text-sm bg-transparent min-h-[64px] px-3\",\n valueText,\n label ? \"pt-8 pb-2\" : \"py-2\",\n disabled && \"outline-none opacity-50 text-surface-accent-600 dark:text-surface-accent-500\",\n showError && error ? \"text-red-500 dark:text-red-600\" : \"\"\n )}\n />\n {property.admin?.clearable && (\n <div\n className=\"flex flex-row justify-center items-center absolute h-full right-0 top-0 mr-4\">\n <IconButton aria-label={t(\"clear\")} onClick={handleClearClick}>\n <XIcon/>\n </IconButton>\n </div>\n )}\n </div>\n ) : (\n <TextField\n size={size}\n value={displayValue}\n onChange={onChange}\n autoFocus={autoFocus}\n label={label}\n aria-label={label ? undefined : accessibleName}\n type={inputType}\n disabled={disabled}\n endAdornment={\n property.admin?.clearable && <IconButton aria-label={t(\"clear\")}\n onClick={handleClearClick}>\n <XIcon/>\n </IconButton>\n }\n error={showError ? !!error : undefined}\n inputClassName={cls(valueText, error && \"text-red-500 dark:text-red-600\")}/>\n )}\n <FieldHelperText includeDescription={includeDescription}\n showError={showError}\n error={error}\n disabled={disabled}\n property={property}/>\n\n {url && <Collapse\n className=\"mt-1 ml-1\"\n in={Boolean(value)}>\n <PropertyPreview\n value={value}\n property={property}\n size={size}/>\n </Collapse>}\n\n </>\n );\n\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,SAAgB,iBAA4C,EACI,aACA,OACA,UACA,OACA,WACA,UACA,WACA,UACA,oBACA,WACA,OAAO,WACqC;CACxG,MAAM,EAAE,MAAM,eAAe;CAE7B,IAAI;CACJ,IAAI;CACJ,IAAI,SAAS,SAAS,UAAU;EAC5B,YAAY,SAAS,OAAO;EAI5B,MAAM,SAAS,OAAO,cAAc,SAAS;CACjD;CAEA,MAAM,eAAgB,UAAU,KAAA,KAAa,UAAU,OAAQ,OAAO,KAAK,IAAI;CAE/E,MAAM,mBAAmB,aAAa,MAAwB;EAC1D,EAAE,gBAAgB;EAClB,EAAE,eAAe;EACjB,SAAS,IAAI;CACjB,GAAG,CAAC,QAAQ,CAAC;CAEb,MAAM,YAAY,UAAqE;EACnF,IAAI,cAAc,UAAU;GACxB,MAAM,cAAc,MAAM,OAAO,QAAQ,WAAW,MAAM,OAAO,KAAK,IAAI,KAAA;GAC1E,IAAI,eAAe,MAAM,WAAW,GAChC,SAAS,IAAI;QACV,IAAI,gBAAgB,KAAA,KAAa,gBAAgB,MACpD,SAAS,WAAgB;QAEzB,SAAS,IAAI;EAErB,OAKI,SAAS,MAAM,OAAO,UAAU,KAAK,OAAO,MAAM,OAAO,KAAU;CAE3E;CAEA,MAAM,cAAc,QAAQ,SAAS;CAErC,IAAI,YAAoD,KAAA;CACxD,IAAI,SAAS,SAAS,UAClB,YAAY;MACT,IAAI,SAAS,SAAS;MACrB,SAAS,OAAO,YAAY;OAC3B,IAAI,SAAS,OAAO,cAAc,SAAS,KAAK,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AAQ,KAAK;aACjB,oBAAC,iBAAD;IACW;IACG;IACJ;GAAM,CAAA;EACV,CAAA;CAEZ,EAAA,CAAA;AAGV"}
|
|
1
|
+
{"version":3,"file":"TextFieldBinding.js","names":[],"sources":["../../../src/form/field_bindings/TextFieldBinding.tsx"],"sourcesContent":["import { useTranslation } from \"@rebasepro/app\";\nimport type { FieldProps } from \"../../types/fields\";\nimport type { NumberProperty, StringProperty } from \"@rebasepro/types\";\nimport React, { useCallback } from \"react\";\n\nimport {\n cls,\n Collapse,\n fieldBackgroundHoverMixin,\n fieldBackgroundMixin,\n IconButton,\n InputLabel,\n TextareaAutosize,\n TextField,\n XIcon\n} from \"@rebasepro/ui\";\nimport { PreviewType } from \"@rebasepro/cms-types\";\nimport { FieldHelperText } from \"../components/FieldHelperText\";\nimport { LabelWithIcon } from \"../components/LabelWithIcon\";\nimport { PropertyPreview } from \"../../preview\";\nimport { getIconForProperty } from \"../../util/property_utils\";\n\n/**\n * Generic text field.\n * This is one of the internal components that get mapped natively inside forms\n * and tables to the specified properties.\n * @group Form fields\n */\nexport function TextFieldBinding<T extends string | number>({\n propertyKey,\n value,\n setValue,\n error,\n showError,\n disabled,\n autoFocus,\n property,\n includeDescription,\n hideLabel,\n size = \"large\"\n }: FieldProps<StringProperty | NumberProperty>) {\n const { t } = useTranslation();\n\n let multiline: boolean | undefined;\n let url: boolean | PreviewType | undefined;\n if (property.type === \"string\") {\n multiline = property.admin?.multiline;\n // `url: true` alone earns the preview. A form field holding a URL that\n // renders as plain text is one you have to select and copy to follow,\n // and the property has already said what it is.\n url = property.admin?.urlPreview ?? property.url;\n }\n\n const displayValue = (value !== undefined && value !== null) ? String(value) : \"\";\n // A number goes to the input as a number. React leaves a number input\n // alone while its text reads as the value (`\"1.0\" == 1`); handed `\"1\"`, it\n // compares strings and rewrites `\"1.0\"` to `\"1\"` as the zero is typed, so\n // `1.05` could not be entered.\n const inputValue: string | number = typeof value === \"number\" ? value : displayValue;\n\n const handleClearClick = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n setValue(null);\n }, [setValue]);\n\n const onChange = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n if (inputType === \"number\") {\n const numberValue = event.target.value ? parseFloat(event.target.value) : undefined;\n if (numberValue !== undefined && Number.isNaN(numberValue)) {\n setValue(null);\n } else if (numberValue !== undefined && numberValue !== null) {\n setValue(numberValue as T);\n } else {\n setValue(null);\n }\n } else {\n // Emptied is NULL. Writing `\"\"` over a NULL the user only typed\n // into and deleted made `isNull` filters stop matching the row,\n // and collided on an optional unique column; `required` already\n // reads `\"\"` as missing.\n setValue(event.target.value === \"\" ? null : event.target.value as T);\n }\n };\n\n const isMultiline = Boolean(multiline);\n\n let inputType: \"number\" | \"email\" | \"url\" | undefined = undefined;\n if (property.type === \"number\") {\n inputType = \"number\";\n } else if (property.type === \"string\") {\n if (property.email) inputType = \"email\";\n else if (property.admin?.urlPreview || property.url) inputType = \"url\";\n }\n\n // `undefined` rather than an empty element: TextField and the multiline box\n // both reserve a label row whenever `label` is truthy, so a null-rendering\n // element would leave the gap behind without the text.\n const label = hideLabel\n ? undefined\n : (\n <LabelWithIcon\n icon={getIconForProperty(property, \"small\")}\n required={property.validation?.required || property.isId === true}\n title={property.name ?? propertyKey}/>\n );\n\n // A value under a label inside the box is set at 16px, the FireCMS field:\n // the 64px box is sized for a 24px line. Everywhere a text field stands\n // without its label — a table cell, a dense dialog — it keeps the kit's 14.\n const valueText = label && size === \"large\" ? \"text-base\" : undefined;\n\n // The control needs a name of its own in two cases, and between them they\n // cover every text field in an entity form:\n //\n // - `hideLabel`, which the form sets for anything FieldBlock labels for it\n // (`hideLabel: !selfLabelling`). FieldBlock draws the name in a <span>\n // inside a <div> — not a <label>, and pointing at nothing — so suppressing\n // the field's own label left the input with no accessible name at all and\n // a screen reader fell back to reading its value back to you.\n // - the multiline branch below, which never associated anything: its label\n // is a decorative absolutely-positioned <div>, so it is unnamed whether or\n // not the form also drew one.\n //\n // The single-line TextField is already handled by the kit when a label is\n // present — it wires `aria-labelledby` — so it only needs this as a fallback.\n const accessibleName = property.name ?? propertyKey;\n return (<>\n {isMultiline ? (\n <div className={cls(\n \"rounded-lg relative max-w-full min-h-[64px]\",\n fieldBackgroundMixin,\n fieldBackgroundHoverMixin,\n showError && error ? \"border border-red-500 dark:border-red-600\" : \"\"\n )}>\n {/* The single-line field's shrunk label, at the same spot:\n this was its own 14px label pinned to the top, a size up\n from the label of the field above it. Always shrunk —\n the box is tall, and a label resting in its middle would\n sit on the text. */}\n {label && <InputLabel shrink\n className={cls(\n \"pointer-events-none absolute top-1\",\n showError && error\n ? \"text-red-500 dark:text-red-600\"\n : \"text-text-secondary dark:text-text-secondary-dark\"\n )}>\n {label}\n </InputLabel>}\n <TextareaAutosize\n value={displayValue}\n onChange={onChange}\n autoFocus={autoFocus}\n disabled={disabled}\n aria-label={accessibleName}\n className={cls(\n \"rounded-md resize-none w-full outline-none text-sm bg-transparent min-h-[64px] px-3\",\n valueText,\n label ? \"pt-8 pb-2\" : \"py-2\",\n disabled && \"outline-none opacity-50 text-surface-accent-600 dark:text-surface-accent-500\",\n showError && error ? \"text-red-500 dark:text-red-600\" : \"\"\n )}\n />\n {property.admin?.clearable && (\n <div\n className=\"flex flex-row justify-center items-center absolute h-full right-0 top-0 mr-4\">\n <IconButton aria-label={t(\"clear\")} onClick={handleClearClick}>\n <XIcon/>\n </IconButton>\n </div>\n )}\n </div>\n ) : (\n <TextField\n size={size}\n value={inputValue}\n onChange={onChange}\n autoFocus={autoFocus}\n label={label}\n aria-label={label ? undefined : accessibleName}\n type={inputType}\n disabled={disabled}\n endAdornment={\n property.admin?.clearable && <IconButton aria-label={t(\"clear\")}\n onClick={handleClearClick}>\n <XIcon/>\n </IconButton>\n }\n error={showError ? !!error : undefined}\n inputClassName={cls(valueText, error && \"text-red-500 dark:text-red-600\")}/>\n )}\n <FieldHelperText includeDescription={includeDescription}\n showError={showError}\n error={error}\n disabled={disabled}\n property={property}/>\n\n {url && <Collapse\n className=\"mt-1 ml-1\"\n in={Boolean(value)}>\n <PropertyPreview\n value={value}\n property={property}\n size={size}/>\n </Collapse>}\n\n </>\n );\n\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,SAAgB,iBAA4C,EACI,aACA,OACA,UACA,OACA,WACA,UACA,WACA,UACA,oBACA,WACA,OAAO,WACqC;CACxG,MAAM,EAAE,MAAM,eAAe;CAE7B,IAAI;CACJ,IAAI;CACJ,IAAI,SAAS,SAAS,UAAU;EAC5B,YAAY,SAAS,OAAO;EAI5B,MAAM,SAAS,OAAO,cAAc,SAAS;CACjD;CAEA,MAAM,eAAgB,UAAU,KAAA,KAAa,UAAU,OAAQ,OAAO,KAAK,IAAI;CAK/E,MAAM,aAA8B,OAAO,UAAU,WAAW,QAAQ;CAExE,MAAM,mBAAmB,aAAa,MAAwB;EAC1D,EAAE,gBAAgB;EAClB,EAAE,eAAe;EACjB,SAAS,IAAI;CACjB,GAAG,CAAC,QAAQ,CAAC;CAEb,MAAM,YAAY,UAAqE;EACnF,IAAI,cAAc,UAAU;GACxB,MAAM,cAAc,MAAM,OAAO,QAAQ,WAAW,MAAM,OAAO,KAAK,IAAI,KAAA;GAC1E,IAAI,gBAAgB,KAAA,KAAa,OAAO,MAAM,WAAW,GACrD,SAAS,IAAI;QACV,IAAI,gBAAgB,KAAA,KAAa,gBAAgB,MACpD,SAAS,WAAgB;QAEzB,SAAS,IAAI;EAErB,OAKI,SAAS,MAAM,OAAO,UAAU,KAAK,OAAO,MAAM,OAAO,KAAU;CAE3E;CAEA,MAAM,cAAc,QAAQ,SAAS;CAErC,IAAI,YAAoD,KAAA;CACxD,IAAI,SAAS,SAAS,UAClB,YAAY;MACT,IAAI,SAAS,SAAS;MACrB,SAAS,OAAO,YAAY;OAC3B,IAAI,SAAS,OAAO,cAAc,SAAS,KAAK,YAAY;CAAA;CAMrE,MAAM,QAAQ,YACR,KAAA,IAEE,oBAAC,eAAD;EACI,MA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;CAEZ,EAAA,CAAA;AAGV"}
|
package/dist/form/validation.js
CHANGED
|
@@ -127,7 +127,7 @@ function getZodStringSchema({ property, parentProperty, customFieldValidator, na
|
|
|
127
127
|
if (validation.min || validation.min === 0) schema = schema.refine((value) => value == null || typeof value === "string" && value.length >= validation.min, { message: `${fieldLabel(property, name)} must be min ${validation.min} characters long` });
|
|
128
128
|
if (validation.max || validation.max === 0) schema = schema.refine((value) => value == null || typeof value === "string" && value.length <= validation.max, { message: `${fieldLabel(property, name)} must be max ${validation.max} characters long` });
|
|
129
129
|
if (validation.matches) {
|
|
130
|
-
const regExp =
|
|
130
|
+
const regExp = toMatchesPattern(validation.matches);
|
|
131
131
|
if (regExp) schema = schema.refine((value) => value == null || typeof value === "string" && regExp.test(value), { message: validation.matchesMessage ?? "Invalid format" });
|
|
132
132
|
}
|
|
133
133
|
if (validation.length !== void 0) schema = schema.refine((value) => value == null || typeof value === "string" && value.length === validation.length, { message: `${fieldLabel(property, name)} must be exactly ${validation.length} characters long` });
|
|
@@ -147,6 +147,17 @@ function getZodStringSchema({ property, parentProperty, customFieldValidator, na
|
|
|
147
147
|
return schema;
|
|
148
148
|
}
|
|
149
149
|
/**
|
|
150
|
+
* `validation.matches` as a regex that answers the same for the same value
|
|
151
|
+
* every time. A `g` or `y` regex keeps `lastIndex` between `test` calls, so a
|
|
152
|
+
* value it accepted once it refused on the next validation; the flags are
|
|
153
|
+
* dropped, as the server's write validation drops them.
|
|
154
|
+
*/
|
|
155
|
+
function toMatchesPattern(matches) {
|
|
156
|
+
const regExp = typeof matches === "string" ? hydrateRegExp(matches) : matches;
|
|
157
|
+
if (!regExp) return void 0;
|
|
158
|
+
return regExp.global || regExp.sticky ? new RegExp(regExp.source, regExp.flags.replace(/[gy]/g, "")) : regExp;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
150
161
|
* A string's declared transforms — `trim`, `lowercase`, `uppercase` — applied.
|
|
151
162
|
* The one definition of them: validation judges its result, and
|
|
152
163
|
* {@link applyValueTransforms} writes it.
|