@payloadcms/richtext-lexical 3.63.0-canary.5 → 3.63.0-canary.7

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["useLexicalComposerContext","useLexicalEditable","getTranslation","Button","Drawer","EditDepthProvider","Form","formatDrawerSlug","FormSubmit","RenderFields","ShimmerEffect","useConfig","useDocumentForm","useDocumentInfo","useEditDepth","useServerFunctions","useTranslation","abortAndIgnore","$getNodeByKey","deepCopyObjectSimpleWithoutReactComponents","reduceFieldsToValues","React","createContext","useCallback","useEffect","useMemo","useRef","v4","uuid","useEditorConfigContext","useLexicalDrawer","$isInlineBlockNode","InlineBlockComponentContext","initialState","useInlineBlockComponentContext","use","InlineBlockComponent","props","cacheBuster","className","baseClass","formData","nodeKey","editor","isEditable","i18n","t","createdInlineBlock","fieldProps","featureClientSchemaMap","initialLexicalFormState","schemaPath","setCreatedInlineBlock","uuidFromContext","fields","parentDocumentFields","getFormState","editDepth","firstTimeDrawer","setInitialState","useState","id","formState","hasMounted","prevCacheBuster","current","CustomLabel","setCustomLabel","customComponents","BlockLabel","CustomBlock","setCustomBlock","Block","drawerSlug","slug","depth","toggleDrawer","inlineBlockElemElemRef","collectionSlug","getDocPreferences","globalSlug","config","componentMapRenderedBlockPath","blockType","clientSchemaMap","blocksField","clientBlock","blockReferences","blocksMap","blocks","clientBlockFields","getKey","length","undefined","removeInlineBlock","update","remove","blockDisplayName","labels","singular","onChangeAbortControllerRef","AbortController","schemaFieldsPath","abortController","awaitInitialState","state","data","docPermissions","docPreferences","documentFormState","initialBlockData","initialBlockFormState","operation","readOnly","renderAllFields","signal","newFormStateData","node","newData","setFields","onChange","prevFormState","submit","controller","isStateOutOfSync","Object","keys","some","key","value","onFormSubmit","RemoveButton","_jsx","buttonStyle","disabled","icon","onClick","e","preventDefault","round","size","tooltip","label","EditButton","el","InlineBlockContainer","children","filter","Boolean","join","ref","Label","_jsxs","beforeSubmit","disableValidationOnSubmit","onSubmit","title","_Fragment","forceRender","parentIndexPath","parentPath","parentSchemaPath","permissions","programmaticSubmit","height","width"],"sources":["../../../../../src/features/blocks/client/componentInline/index.tsx"],"sourcesContent":["'use client'\n\nimport type { BlocksFieldClient, ClientBlock, Data, FormState } from 'payload'\n\nimport { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'\nimport { useLexicalEditable } from '@lexical/react/useLexicalEditable'\nimport { getTranslation } from '@payloadcms/translations'\nimport {\n Button,\n Drawer,\n EditDepthProvider,\n Form,\n formatDrawerSlug,\n FormSubmit,\n RenderFields,\n ShimmerEffect,\n useConfig,\n useDocumentForm,\n useDocumentInfo,\n useEditDepth,\n useServerFunctions,\n useTranslation,\n} from '@payloadcms/ui'\nimport { abortAndIgnore } from '@payloadcms/ui/shared'\nimport { $getNodeByKey } from 'lexical'\n\nimport './index.scss'\n\nimport { deepCopyObjectSimpleWithoutReactComponents, reduceFieldsToValues } from 'payload/shared'\nimport React, { createContext, useCallback, useEffect, useMemo, useRef } from 'react'\nimport { v4 as uuid } from 'uuid'\n\nimport type { InlineBlockFields } from '../../server/nodes/InlineBlocksNode.js'\n\nimport { useEditorConfigContext } from '../../../../lexical/config/client/EditorConfigProvider.js'\nimport { useLexicalDrawer } from '../../../../utilities/fieldsDrawer/useLexicalDrawer.js'\nimport { $isInlineBlockNode } from '../nodes/InlineBlocksNode.js'\n\ntype Props = {\n /**\n * Can be modified by the node in order to trigger the re-fetch of the initial state based on the\n * formData. This is useful when node.setFields() is explicitly called from outside of the form - in\n * this case, the new field state is likely not reflected in the form state, so we need to re-fetch\n */\n readonly cacheBuster: number\n readonly className: string\n readonly formData: InlineBlockFields\n readonly nodeKey: string\n}\n\ntype InlineBlockComponentContextType = {\n EditButton?: React.FC\n initialState: false | FormState | undefined\n InlineBlockContainer?: React.FC<{ children: React.ReactNode }>\n Label?: React.FC\n nodeKey?: string\n RemoveButton?: React.FC\n}\n\nconst InlineBlockComponentContext = createContext<InlineBlockComponentContextType>({\n initialState: false,\n})\n\nexport const useInlineBlockComponentContext = () => React.use(InlineBlockComponentContext)\n\nexport const InlineBlockComponent: React.FC<Props> = (props) => {\n const { cacheBuster, className: baseClass, formData, nodeKey } = props\n\n const [editor] = useLexicalComposerContext()\n const isEditable = useLexicalEditable()\n const { i18n, t } = useTranslation<object, string>()\n const {\n createdInlineBlock,\n fieldProps: { featureClientSchemaMap, initialLexicalFormState, schemaPath },\n setCreatedInlineBlock,\n uuid: uuidFromContext,\n } = useEditorConfigContext()\n const { fields: parentDocumentFields } = useDocumentForm()\n\n const { getFormState } = useServerFunctions()\n const editDepth = useEditDepth()\n const firstTimeDrawer = useRef(false)\n\n const [initialState, setInitialState] = React.useState<false | FormState | undefined>(\n () => initialLexicalFormState?.[formData.id]?.formState,\n )\n\n const hasMounted = useRef(false)\n const prevCacheBuster = useRef(cacheBuster)\n useEffect(() => {\n if (hasMounted.current) {\n if (prevCacheBuster.current !== cacheBuster) {\n setInitialState(false)\n }\n prevCacheBuster.current = cacheBuster\n } else {\n hasMounted.current = true\n }\n }, [cacheBuster])\n\n const [CustomLabel, setCustomLabel] = React.useState<React.ReactNode | undefined>(\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n initialState?.['_components']?.customComponents?.BlockLabel,\n )\n\n const [CustomBlock, setCustomBlock] = React.useState<React.ReactNode | undefined>(\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n initialState?.['_components']?.customComponents?.Block,\n )\n\n const drawerSlug = formatDrawerSlug({\n slug: `lexical-inlineBlocks-create-${uuidFromContext}-${formData.id}`,\n depth: editDepth,\n })\n const { toggleDrawer } = useLexicalDrawer(drawerSlug, true)\n\n const inlineBlockElemElemRef = useRef<HTMLDivElement | null>(null)\n const { id, collectionSlug, getDocPreferences, globalSlug } = useDocumentInfo()\n const { config } = useConfig()\n\n const componentMapRenderedBlockPath = `${schemaPath}.lexical_internal_feature.blocks.lexical_inline_blocks.${formData.blockType}`\n\n const clientSchemaMap = featureClientSchemaMap['blocks']\n\n const blocksField: BlocksFieldClient = clientSchemaMap?.[\n componentMapRenderedBlockPath\n ]?.[0] as BlocksFieldClient\n\n const clientBlock: ClientBlock | undefined = blocksField.blockReferences\n ? typeof blocksField?.blockReferences?.[0] === 'string'\n ? config.blocksMap[blocksField?.blockReferences?.[0]]\n : blocksField?.blockReferences?.[0]\n : blocksField?.blocks?.[0]\n\n const clientBlockFields = clientBlock?.fields ?? []\n\n // Open drawer on \"mount\"\n useEffect(() => {\n if (!firstTimeDrawer.current && createdInlineBlock?.getKey() === nodeKey) {\n // > 2 because they always have \"id\" and \"blockName\" fields\n if (clientBlockFields.length > 2) {\n toggleDrawer()\n }\n setCreatedInlineBlock?.(undefined)\n firstTimeDrawer.current = true\n }\n }, [clientBlockFields.length, createdInlineBlock, nodeKey, setCreatedInlineBlock, toggleDrawer])\n\n const removeInlineBlock = useCallback(() => {\n editor.update(() => {\n $getNodeByKey(nodeKey)?.remove()\n })\n }, [editor, nodeKey])\n\n const blockDisplayName = clientBlock?.labels?.singular\n ? getTranslation(clientBlock?.labels.singular, i18n)\n : clientBlock?.slug\n\n const onChangeAbortControllerRef = useRef(new AbortController())\n const schemaFieldsPath = `${schemaPath}.lexical_internal_feature.blocks.lexical_inline_blocks.${clientBlock?.slug}.fields`\n\n // Initial state for newly created blocks\n useEffect(() => {\n const abortController = new AbortController()\n\n const awaitInitialState = async () => {\n /*\n * This will only run if a new block is created. For all existing blocks that are loaded when the document is loaded, or when the form is saved,\n * this is not run, as the lexical field RSC will fetch the state server-side and pass it to the client. That way, we avoid unnecessary client-side\n * requests. Though for newly created blocks, we need to fetch the state client-side, as the server doesn't know about the block yet.\n */\n const { state } = await getFormState({\n id,\n collectionSlug,\n data: formData,\n docPermissions: { fields: true },\n docPreferences: await getDocPreferences(),\n documentFormState: deepCopyObjectSimpleWithoutReactComponents(parentDocumentFields),\n globalSlug,\n initialBlockData: formData,\n initialBlockFormState: formData,\n operation: 'update',\n readOnly: !isEditable,\n renderAllFields: true,\n schemaPath: schemaFieldsPath,\n signal: abortController.signal,\n })\n\n if (state) {\n const newFormStateData: InlineBlockFields = reduceFieldsToValues(\n deepCopyObjectSimpleWithoutReactComponents(state),\n true,\n ) as InlineBlockFields\n\n // Things like default values may come back from the server => update the node with the new data\n editor.update(() => {\n const node = $getNodeByKey(nodeKey)\n if (node && $isInlineBlockNode(node)) {\n const newData = newFormStateData\n newData.blockType = formData.blockType\n\n node.setFields(newData, true)\n }\n })\n\n setInitialState(state)\n setCustomLabel(state['_components']?.customComponents?.BlockLabel)\n setCustomBlock(state['_components']?.customComponents?.Block)\n }\n }\n\n if (formData && !initialState) {\n void awaitInitialState()\n }\n\n return () => {\n abortAndIgnore(abortController)\n }\n }, [\n getFormState,\n editor,\n nodeKey,\n isEditable,\n schemaFieldsPath,\n id,\n formData,\n initialState,\n collectionSlug,\n globalSlug,\n getDocPreferences,\n parentDocumentFields,\n ])\n\n /**\n * HANDLE ONCHANGE\n */\n const onChange = useCallback(\n async ({ formState: prevFormState, submit }: { formState: FormState; submit?: boolean }) => {\n abortAndIgnore(onChangeAbortControllerRef.current)\n\n const controller = new AbortController()\n onChangeAbortControllerRef.current = controller\n\n const { state } = await getFormState({\n id,\n collectionSlug,\n docPermissions: {\n fields: true,\n },\n docPreferences: await getDocPreferences(),\n documentFormState: deepCopyObjectSimpleWithoutReactComponents(parentDocumentFields),\n formState: prevFormState,\n globalSlug,\n initialBlockFormState: prevFormState,\n operation: 'update',\n readOnly: !isEditable,\n renderAllFields: submit ? true : false,\n schemaPath: schemaFieldsPath,\n signal: controller.signal,\n })\n\n if (!state) {\n return prevFormState\n }\n\n if (submit) {\n setCustomLabel(state['_components']?.customComponents?.BlockLabel)\n setCustomBlock(state['_components']?.customComponents?.Block)\n }\n\n return state\n },\n [\n getFormState,\n id,\n collectionSlug,\n getDocPreferences,\n parentDocumentFields,\n globalSlug,\n isEditable,\n schemaFieldsPath,\n ],\n )\n // cleanup effect\n useEffect(() => {\n const isStateOutOfSync = (formData: InlineBlockFields, initialState: FormState) => {\n return Object.keys(initialState).some(\n (key) => initialState[key] && formData[key] !== initialState[key].value,\n )\n }\n\n return () => {\n // If the component is unmounted (either via removeInlineBlock or via lexical itself) and the form state got changed before,\n // we need to reset the initial state to force a re-fetch of the initial state when it gets mounted again (e.g. via lexical history undo).\n // Otherwise it would use an outdated initial state.\n if (initialState && isStateOutOfSync(formData, initialState)) {\n setInitialState(false)\n }\n abortAndIgnore(onChangeAbortControllerRef.current)\n }\n }, [formData, initialState])\n\n /**\n * HANDLE FORM SUBMIT\n */\n const onFormSubmit = useCallback(\n (formState: FormState, newData: Data) => {\n newData.blockType = formData.blockType\n\n editor.update(() => {\n const node = $getNodeByKey(nodeKey)\n if (node && $isInlineBlockNode(node)) {\n node.setFields(newData as InlineBlockFields, true)\n }\n })\n },\n [editor, nodeKey, formData],\n )\n\n const RemoveButton = useMemo(\n () => () => (\n <Button\n buttonStyle=\"icon-label\"\n className={`${baseClass}__removeButton`}\n disabled={!isEditable}\n icon=\"x\"\n onClick={(e) => {\n e.preventDefault()\n removeInlineBlock()\n }}\n round\n size=\"small\"\n tooltip={t('lexical:blocks:inlineBlocks:remove', { label: blockDisplayName })}\n />\n ),\n [baseClass, blockDisplayName, isEditable, removeInlineBlock, t],\n )\n\n const EditButton = useMemo(\n () => () => (\n <Button\n buttonStyle=\"icon-label\"\n className={`${baseClass}__editButton`}\n disabled={!isEditable}\n el=\"button\"\n icon=\"edit\"\n onClick={() => {\n toggleDrawer()\n }}\n round\n size=\"small\"\n tooltip={t('lexical:blocks:inlineBlocks:edit', { label: blockDisplayName })}\n />\n ),\n [baseClass, blockDisplayName, isEditable, t, toggleDrawer],\n )\n\n const InlineBlockContainer = useMemo(\n () =>\n ({ children, className }: { children: React.ReactNode; className?: string }) => (\n <div\n className={[`${baseClass}__container`, baseClass + '-' + formData.blockType, className]\n .filter(Boolean)\n .join(' ')}\n ref={inlineBlockElemElemRef}\n >\n {children}\n </div>\n ),\n [baseClass, formData.blockType],\n )\n\n const Label = useMemo(() => {\n if (CustomLabel) {\n return () => CustomLabel\n } else {\n return () => (\n <div>{clientBlock?.labels ? getTranslation(clientBlock?.labels.singular, i18n) : ''}</div>\n )\n }\n }, [CustomLabel, clientBlock?.labels, i18n])\n\n if (!clientBlock) {\n return (\n <InlineBlockContainer className={`${baseClass}-not-found`}>\n <span>Error: Block '{formData.blockType}' not found</span>\n {isEditable ? (\n <div className={`${baseClass}__actions`}>\n <RemoveButton />\n </div>\n ) : null}\n </InlineBlockContainer>\n )\n }\n\n return (\n <Form\n beforeSubmit={[\n async ({ formState }) => {\n // This is only called when form is submitted from drawer\n return await onChange({ formState, submit: true })\n },\n ]}\n disableValidationOnSubmit\n el=\"div\"\n fields={clientBlock?.fields}\n initialState={initialState || {}}\n onChange={[onChange]}\n onSubmit={(formState, data) => {\n onFormSubmit(formState, data)\n toggleDrawer()\n }}\n uuid={uuid()}\n >\n <EditDepthProvider>\n <Drawer\n className={''}\n slug={drawerSlug}\n title={t(`lexical:blocks:inlineBlocks:${formData?.id ? 'edit' : 'create'}`, {\n label: blockDisplayName ?? t('lexical:blocks:inlineBlocks:label'),\n })}\n >\n {initialState ? (\n <>\n <RenderFields\n fields={clientBlock?.fields}\n forceRender\n parentIndexPath=\"\"\n parentPath=\"\" // See Blocks feature path for details as for why this is empty\n parentSchemaPath={schemaFieldsPath}\n permissions={true}\n readOnly={!isEditable}\n />\n <FormSubmit programmaticSubmit={true}>{t('fields:saveChanges')}</FormSubmit>\n </>\n ) : null}\n </Drawer>\n </EditDepthProvider>\n {CustomBlock ? (\n <InlineBlockComponentContext\n value={{\n EditButton,\n initialState,\n InlineBlockContainer,\n Label,\n nodeKey,\n RemoveButton,\n }}\n >\n {CustomBlock}\n </InlineBlockComponentContext>\n ) : (\n <InlineBlockContainer>\n {initialState ? <Label /> : <ShimmerEffect height=\"15px\" width=\"40px\" />}\n {isEditable ? (\n <div className={`${baseClass}__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,UAAA;QACNmF,KAAA,EAAO9G,CAAA,CAAE,+BAA+BL,QAAA,EAAUoB,EAAA,GAAK,SAAS,UAAU,EAAE;UAC1EiF,KAAA,EAAO7C,gBAAA,IAAoBnD,CAAA,CAAE;QAC/B;kBAECb,YAAA,gBACCuH,KAAA,CAAAK,SAAA;kCACEzB,IAAA,CAAC3H,YAAA;YACC6C,MAAA,EAAQgC,WAAA,EAAahC,MAAA;YACrBwG,WAAW;YACXC,eAAA,EAAgB;YAChBC,UAAA,EAAW,GAAG;YAAA;;YACdC,gBAAA,EAAkB3D,gBAAA;YAClB4D,WAAA,EAAa;YACbjD,QAAA,EAAU,CAACrE;2BAEbwF,IAAA,CAAC5H,UAAA;YAAW2J,kBAAA,EAAoB;sBAAOrH,CAAA,CAAE;;aAEzC;;QAGPwB,WAAA,gBACC8D,IAAA,CAACpG,2BAAA;MACCiG,KAAA,EAAO;QACLc,UAAA;QACA9G,YAAA;QACAgH,oBAAA;QACAM,KAAA;QACA7G,OAAA;QACAyF;MACF;gBAEC7D;sBAGHkF,KAAA,CAACP,oBAAA;iBACEhH,YAAA,gBAAemG,IAAA,CAACmB,KAAA,qBAAWnB,IAAA,CAAC1H,aAAA;QAAc0J,MAAA,EAAO;QAAOC,KAAA,EAAM;UAC9DzH,UAAA,gBACC4G,KAAA,CAAC;QAAIjH,SAAA,EAAW,GAAGC,SAAA,WAAoB;gCACrC4F,IAAA,CAACW,UAAA,O,aACDX,IAAA,CAACD,YAAA;WAED;;;AAKd","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["useLexicalComposerContext","useLexicalEditable","getTranslation","Button","Drawer","EditDepthProvider","Form","formatDrawerSlug","FormSubmit","RenderFields","ShimmerEffect","useConfig","useDocumentForm","useDocumentInfo","useEditDepth","useServerFunctions","useTranslation","abortAndIgnore","$getNodeByKey","deepCopyObjectSimpleWithoutReactComponents","reduceFieldsToValues","React","createContext","useCallback","useEffect","useMemo","useRef","v4","uuid","useEditorConfigContext","useLexicalDrawer","$isInlineBlockNode","InlineBlockComponentContext","initialState","useInlineBlockComponentContext","use","InlineBlockComponent","props","cacheBuster","className","baseClass","formData","nodeKey","editor","isEditable","i18n","t","createdInlineBlock","fieldProps","featureClientSchemaMap","initialLexicalFormState","schemaPath","setCreatedInlineBlock","uuidFromContext","fields","parentDocumentFields","getFormState","editDepth","firstTimeDrawer","setInitialState","useState","cachedFormState","id","formState","Object","fromEntries","entries","map","fieldName","fieldState","initialValue","value","hasMounted","prevCacheBuster","current","CustomLabel","setCustomLabel","customComponents","BlockLabel","CustomBlock","setCustomBlock","Block","drawerSlug","slug","depth","toggleDrawer","inlineBlockElemElemRef","collectionSlug","getDocPreferences","globalSlug","config","componentMapRenderedBlockPath","blockType","clientSchemaMap","blocksField","clientBlock","blockReferences","blocksMap","blocks","clientBlockFields","getKey","length","undefined","removeInlineBlock","update","remove","blockDisplayName","labels","singular","onChangeAbortControllerRef","AbortController","schemaFieldsPath","abortController","awaitInitialState","state","data","docPermissions","docPreferences","documentFormState","initialBlockData","initialBlockFormState","operation","readOnly","renderAllFields","signal","newFormStateData","node","newData","setFields","onChange","prevFormState","submit","controller","isStateOutOfSync","keys","some","key","onFormSubmit","RemoveButton","_jsx","buttonStyle","disabled","icon","onClick","e","preventDefault","round","size","tooltip","label","EditButton","el","InlineBlockContainer","children","filter","Boolean","join","ref","Label","_jsxs","beforeSubmit","disableValidationOnSubmit","onSubmit","title","_Fragment","forceRender","parentIndexPath","parentPath","parentSchemaPath","permissions","programmaticSubmit","height","width"],"sources":["../../../../../src/features/blocks/client/componentInline/index.tsx"],"sourcesContent":["'use client'\n\nimport type { BlocksFieldClient, ClientBlock, Data, FormState } from 'payload'\n\nimport { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'\nimport { useLexicalEditable } from '@lexical/react/useLexicalEditable'\nimport { getTranslation } from '@payloadcms/translations'\nimport {\n Button,\n Drawer,\n EditDepthProvider,\n Form,\n formatDrawerSlug,\n FormSubmit,\n RenderFields,\n ShimmerEffect,\n useConfig,\n useDocumentForm,\n useDocumentInfo,\n useEditDepth,\n useServerFunctions,\n useTranslation,\n} from '@payloadcms/ui'\nimport { abortAndIgnore } from '@payloadcms/ui/shared'\nimport { $getNodeByKey } from 'lexical'\n\nimport './index.scss'\n\nimport { deepCopyObjectSimpleWithoutReactComponents, reduceFieldsToValues } from 'payload/shared'\nimport React, { createContext, useCallback, useEffect, useMemo, useRef } from 'react'\nimport { v4 as uuid } from 'uuid'\n\nimport type { InlineBlockFields } from '../../server/nodes/InlineBlocksNode.js'\n\nimport { useEditorConfigContext } from '../../../../lexical/config/client/EditorConfigProvider.js'\nimport { useLexicalDrawer } from '../../../../utilities/fieldsDrawer/useLexicalDrawer.js'\nimport { $isInlineBlockNode } from '../nodes/InlineBlocksNode.js'\n\ntype Props = {\n /**\n * Can be modified by the node in order to trigger the re-fetch of the initial state based on the\n * formData. This is useful when node.setFields() is explicitly called from outside of the form - in\n * this case, the new field state is likely not reflected in the form state, so we need to re-fetch\n */\n readonly cacheBuster: number\n readonly className: string\n readonly formData: InlineBlockFields\n readonly nodeKey: string\n}\n\ntype InlineBlockComponentContextType = {\n EditButton?: React.FC\n initialState: false | FormState | undefined\n InlineBlockContainer?: React.FC<{ children: React.ReactNode }>\n Label?: React.FC\n nodeKey?: string\n RemoveButton?: React.FC\n}\n\nconst InlineBlockComponentContext = createContext<InlineBlockComponentContextType>({\n initialState: false,\n})\n\nexport const useInlineBlockComponentContext = () => React.use(InlineBlockComponentContext)\n\nexport const InlineBlockComponent: React.FC<Props> = (props) => {\n const { cacheBuster, className: baseClass, formData, nodeKey } = props\n\n const [editor] = useLexicalComposerContext()\n const isEditable = useLexicalEditable()\n const { i18n, t } = useTranslation<object, string>()\n const {\n createdInlineBlock,\n fieldProps: { featureClientSchemaMap, initialLexicalFormState, schemaPath },\n setCreatedInlineBlock,\n uuid: uuidFromContext,\n } = useEditorConfigContext()\n const { fields: parentDocumentFields } = useDocumentForm()\n\n const { getFormState } = useServerFunctions()\n const editDepth = useEditDepth()\n const firstTimeDrawer = useRef(false)\n\n const [initialState, setInitialState] = React.useState<false | FormState | undefined>(() => {\n // Initial form state that was calculated server-side. May have stale values\n const cachedFormState = initialLexicalFormState?.[formData.id]?.formState\n if (!cachedFormState) {\n return false\n }\n\n // Merge current formData values into the cached form state\n // This ensures that when the component remounts (e.g., due to view changes), we don't lose user edits\n return Object.fromEntries(\n Object.entries(cachedFormState).map(([fieldName, fieldState]) => [\n fieldName,\n fieldName in formData\n ? {\n ...fieldState,\n initialValue: formData[fieldName],\n value: formData[fieldName],\n }\n : fieldState,\n ]),\n )\n })\n\n const hasMounted = useRef(false)\n const prevCacheBuster = useRef(cacheBuster)\n useEffect(() => {\n if (hasMounted.current) {\n if (prevCacheBuster.current !== cacheBuster) {\n setInitialState(false)\n }\n prevCacheBuster.current = cacheBuster\n } else {\n hasMounted.current = true\n }\n }, [cacheBuster])\n\n const [CustomLabel, setCustomLabel] = React.useState<React.ReactNode | undefined>(\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n initialState?.['_components']?.customComponents?.BlockLabel,\n )\n\n const [CustomBlock, setCustomBlock] = React.useState<React.ReactNode | undefined>(\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n initialState?.['_components']?.customComponents?.Block,\n )\n\n const drawerSlug = formatDrawerSlug({\n slug: `lexical-inlineBlocks-create-${uuidFromContext}-${formData.id}`,\n depth: editDepth,\n })\n const { toggleDrawer } = useLexicalDrawer(drawerSlug, true)\n\n const inlineBlockElemElemRef = useRef<HTMLDivElement | null>(null)\n const { id, collectionSlug, getDocPreferences, globalSlug } = useDocumentInfo()\n const { config } = useConfig()\n\n const componentMapRenderedBlockPath = `${schemaPath}.lexical_internal_feature.blocks.lexical_inline_blocks.${formData.blockType}`\n\n const clientSchemaMap = featureClientSchemaMap['blocks']\n\n const blocksField: BlocksFieldClient = clientSchemaMap?.[\n componentMapRenderedBlockPath\n ]?.[0] as BlocksFieldClient\n\n const clientBlock: ClientBlock | undefined = blocksField.blockReferences\n ? typeof blocksField?.blockReferences?.[0] === 'string'\n ? config.blocksMap[blocksField?.blockReferences?.[0]]\n : blocksField?.blockReferences?.[0]\n : blocksField?.blocks?.[0]\n\n const clientBlockFields = clientBlock?.fields ?? []\n\n // Open drawer on \"mount\"\n useEffect(() => {\n if (!firstTimeDrawer.current && createdInlineBlock?.getKey() === nodeKey) {\n // > 2 because they always have \"id\" and \"blockName\" fields\n if (clientBlockFields.length > 2) {\n toggleDrawer()\n }\n setCreatedInlineBlock?.(undefined)\n firstTimeDrawer.current = true\n }\n }, [clientBlockFields.length, createdInlineBlock, nodeKey, setCreatedInlineBlock, toggleDrawer])\n\n const removeInlineBlock = useCallback(() => {\n editor.update(() => {\n $getNodeByKey(nodeKey)?.remove()\n })\n }, [editor, nodeKey])\n\n const blockDisplayName = clientBlock?.labels?.singular\n ? getTranslation(clientBlock?.labels.singular, i18n)\n : clientBlock?.slug\n\n const onChangeAbortControllerRef = useRef(new AbortController())\n const schemaFieldsPath = `${schemaPath}.lexical_internal_feature.blocks.lexical_inline_blocks.${clientBlock?.slug}.fields`\n\n // Initial state for newly created blocks\n useEffect(() => {\n const abortController = new AbortController()\n\n const awaitInitialState = async () => {\n /*\n * This will only run if a new block is created. For all existing blocks that are loaded when the document is loaded, or when the form is saved,\n * this is not run, as the lexical field RSC will fetch the state server-side and pass it to the client. That way, we avoid unnecessary client-side\n * requests. Though for newly created blocks, we need to fetch the state client-side, as the server doesn't know about the block yet.\n */\n const { state } = await getFormState({\n id,\n collectionSlug,\n data: formData,\n docPermissions: { fields: true },\n docPreferences: await getDocPreferences(),\n documentFormState: deepCopyObjectSimpleWithoutReactComponents(parentDocumentFields),\n globalSlug,\n initialBlockData: formData,\n initialBlockFormState: formData,\n operation: 'update',\n readOnly: !isEditable,\n renderAllFields: true,\n schemaPath: schemaFieldsPath,\n signal: abortController.signal,\n })\n\n if (state) {\n const newFormStateData: InlineBlockFields = reduceFieldsToValues(\n deepCopyObjectSimpleWithoutReactComponents(state),\n true,\n ) as InlineBlockFields\n\n // Things like default values may come back from the server => update the node with the new data\n editor.update(() => {\n const node = $getNodeByKey(nodeKey)\n if (node && $isInlineBlockNode(node)) {\n const newData = newFormStateData\n newData.blockType = formData.blockType\n\n node.setFields(newData, true)\n }\n })\n\n setInitialState(state)\n setCustomLabel(state['_components']?.customComponents?.BlockLabel)\n setCustomBlock(state['_components']?.customComponents?.Block)\n }\n }\n\n if (formData && !initialState) {\n void awaitInitialState()\n }\n\n return () => {\n abortAndIgnore(abortController)\n }\n }, [\n getFormState,\n editor,\n nodeKey,\n isEditable,\n schemaFieldsPath,\n id,\n formData,\n initialState,\n collectionSlug,\n globalSlug,\n getDocPreferences,\n parentDocumentFields,\n ])\n\n /**\n * HANDLE ONCHANGE\n */\n const onChange = useCallback(\n async ({ formState: prevFormState, submit }: { formState: FormState; submit?: boolean }) => {\n abortAndIgnore(onChangeAbortControllerRef.current)\n\n const controller = new AbortController()\n onChangeAbortControllerRef.current = controller\n\n const { state } = await getFormState({\n id,\n collectionSlug,\n docPermissions: {\n fields: true,\n },\n docPreferences: await getDocPreferences(),\n documentFormState: deepCopyObjectSimpleWithoutReactComponents(parentDocumentFields),\n formState: prevFormState,\n globalSlug,\n initialBlockFormState: prevFormState,\n operation: 'update',\n readOnly: !isEditable,\n renderAllFields: submit ? true : false,\n schemaPath: schemaFieldsPath,\n signal: controller.signal,\n })\n\n if (!state) {\n return prevFormState\n }\n\n if (submit) {\n setCustomLabel(state['_components']?.customComponents?.BlockLabel)\n setCustomBlock(state['_components']?.customComponents?.Block)\n }\n\n return state\n },\n [\n getFormState,\n id,\n collectionSlug,\n getDocPreferences,\n parentDocumentFields,\n globalSlug,\n isEditable,\n schemaFieldsPath,\n ],\n )\n // cleanup effect\n useEffect(() => {\n const isStateOutOfSync = (formData: InlineBlockFields, initialState: FormState) => {\n return Object.keys(initialState).some(\n (key) => initialState[key] && formData[key] !== initialState[key].value,\n )\n }\n\n return () => {\n // If the component is unmounted (either via removeInlineBlock or via lexical itself) and the form state got changed before,\n // we need to reset the initial state to force a re-fetch of the initial state when it gets mounted again (e.g. via lexical history undo).\n // Otherwise it would use an outdated initial state.\n if (initialState && isStateOutOfSync(formData, initialState)) {\n setInitialState(false)\n }\n abortAndIgnore(onChangeAbortControllerRef.current)\n }\n }, [formData, initialState])\n\n /**\n * HANDLE FORM SUBMIT\n */\n const onFormSubmit = useCallback(\n (formState: FormState, newData: Data) => {\n newData.blockType = formData.blockType\n\n editor.update(() => {\n const node = $getNodeByKey(nodeKey)\n if (node && $isInlineBlockNode(node)) {\n node.setFields(newData as InlineBlockFields, true)\n }\n })\n },\n [editor, nodeKey, formData],\n )\n\n const RemoveButton = useMemo(\n () => () => (\n <Button\n buttonStyle=\"icon-label\"\n className={`${baseClass}__removeButton`}\n disabled={!isEditable}\n icon=\"x\"\n onClick={(e) => {\n e.preventDefault()\n removeInlineBlock()\n }}\n round\n size=\"small\"\n tooltip={t('lexical:blocks:inlineBlocks:remove', { label: blockDisplayName })}\n />\n ),\n [baseClass, blockDisplayName, isEditable, removeInlineBlock, t],\n )\n\n const EditButton = useMemo(\n () => () => (\n <Button\n buttonStyle=\"icon-label\"\n className={`${baseClass}__editButton`}\n disabled={!isEditable}\n el=\"button\"\n icon=\"edit\"\n onClick={() => {\n toggleDrawer()\n }}\n round\n size=\"small\"\n tooltip={t('lexical:blocks:inlineBlocks:edit', { label: blockDisplayName })}\n />\n ),\n [baseClass, blockDisplayName, isEditable, t, toggleDrawer],\n )\n\n const InlineBlockContainer = useMemo(\n () =>\n ({ children, className }: { children: React.ReactNode; className?: string }) => (\n <div\n className={[`${baseClass}__container`, baseClass + '-' + formData.blockType, className]\n .filter(Boolean)\n .join(' ')}\n ref={inlineBlockElemElemRef}\n >\n {children}\n </div>\n ),\n [baseClass, formData.blockType],\n )\n\n const Label = useMemo(() => {\n if (CustomLabel) {\n return () => CustomLabel\n } else {\n return () => (\n <div>{clientBlock?.labels ? getTranslation(clientBlock?.labels.singular, i18n) : ''}</div>\n )\n }\n }, [CustomLabel, clientBlock?.labels, i18n])\n\n if (!clientBlock) {\n return (\n <InlineBlockContainer className={`${baseClass}-not-found`}>\n <span>Error: Block '{formData.blockType}' not found</span>\n {isEditable ? (\n <div className={`${baseClass}__actions`}>\n <RemoveButton />\n </div>\n ) : null}\n </InlineBlockContainer>\n )\n }\n\n return (\n <Form\n beforeSubmit={[\n async ({ formState }) => {\n // This is only called when form is submitted from drawer\n return await onChange({ formState, submit: true })\n },\n ]}\n disableValidationOnSubmit\n el=\"div\"\n fields={clientBlock?.fields}\n initialState={initialState || {}}\n onChange={[onChange]}\n onSubmit={(formState, data) => {\n onFormSubmit(formState, data)\n toggleDrawer()\n }}\n uuid={uuid()}\n >\n <EditDepthProvider>\n <Drawer\n className={''}\n slug={drawerSlug}\n title={t(`lexical:blocks:inlineBlocks:${formData?.id ? 'edit' : 'create'}`, {\n label: blockDisplayName ?? t('lexical:blocks:inlineBlocks:label'),\n })}\n >\n {initialState ? (\n <>\n <RenderFields\n fields={clientBlock?.fields}\n forceRender\n parentIndexPath=\"\"\n parentPath=\"\" // See Blocks feature path for details as for why this is empty\n parentSchemaPath={schemaFieldsPath}\n permissions={true}\n readOnly={!isEditable}\n />\n <FormSubmit programmaticSubmit={true}>{t('fields:saveChanges')}</FormSubmit>\n </>\n ) : null}\n </Drawer>\n </EditDepthProvider>\n {CustomBlock ? (\n <InlineBlockComponentContext\n value={{\n EditButton,\n initialState,\n InlineBlockContainer,\n Label,\n nodeKey,\n RemoveButton,\n }}\n >\n {CustomBlock}\n </InlineBlockComponentContext>\n ) : (\n <InlineBlockContainer>\n {initialState ? <Label /> : <ShimmerEffect height=\"15px\" width=\"40px\" />}\n {isEditable ? (\n <div className={`${baseClass}__actions`}>\n <EditButton />\n <RemoveButton />\n </div>\n ) : null}\n </InlineBlockContainer>\n )}\n </Form>\n )\n}\n"],"mappings":"AAAA;;;AAIA,SAASA,yBAAyB,QAAQ;AAC1C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d.ts","sourceRoot":"","sources":["../../src/field/Field.tsx"],"names":[],"mappings":"AAeA,OAAO,KAAoD,MAAM,OAAO,CAAA;AAGxE,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAA;AAE7E,OAAO,mCAAmC,CAAA;AAC1C,OAAO,eAAe,CAAA;AACtB,OAAO,cAAc,CAAA;AAErB,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAA;AAO5D,QAAA,MAAM,iBAAiB,EAAE,KAAK,CAAC,EAAE,CAC/B;IACE,QAAQ,CAAC,YAAY,EAAE,2BAA2B,CAAA;CACnD,GAAG,yBAAyB,CAwK9B,CAAA;AAaD,eAAO,MAAM,QAAQ,EAAE,OAAO,iBAAqC,CAAA"}
1
+ {"version":3,"file":"Field.d.ts","sourceRoot":"","sources":["../../src/field/Field.tsx"],"names":[],"mappings":"AAgBA,OAAO,KAAoD,MAAM,OAAO,CAAA;AAGxE,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAA;AAE7E,OAAO,mCAAmC,CAAA;AAC1C,OAAO,eAAe,CAAA;AACtB,OAAO,cAAc,CAAA;AAErB,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAA;AAO5D,QAAA,MAAM,iBAAiB,EAAE,KAAK,CAAC,EAAE,CAC/B;IACE,QAAQ,CAAC,YAAY,EAAE,2BAA2B,CAAA;CACnD,GAAG,yBAAyB,CA4K9B,CAAA;AAaD,eAAO,MAAM,QAAQ,EAAE,OAAO,iBAAqC,CAAA"}
@@ -1,7 +1,7 @@
1
1
  'use client';
2
2
 
3
3
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
4
- import { FieldDescription, FieldError, FieldLabel, RenderCustomComponent, useEditDepth, useEffectEvent, useField } from '@payloadcms/ui';
4
+ import { BulkUploadProvider, FieldDescription, FieldError, FieldLabel, RenderCustomComponent, useEditDepth, useEffectEvent, useField } from '@payloadcms/ui';
5
5
  import { mergeFieldStyles } from '@payloadcms/ui/shared';
6
6
  import { dequal } from 'dequal/lite';
7
7
  import React, { useCallback, useEffect, useMemo, useState } from 'react';
@@ -136,18 +136,21 @@ const RichTextComponent = props => {
136
136
  children: [/*#__PURE__*/_jsxs(ErrorBoundary, {
137
137
  fallbackRender: fallbackRender,
138
138
  onReset: () => {},
139
- children: [BeforeInput, /*#__PURE__*/_jsx(LexicalProvider, {
140
- composerKey: pathWithEditDepth,
141
- editorConfig: editorConfig,
142
- fieldProps: props,
143
- isSmallWidthViewport: isSmallWidthViewport,
144
- onChange: handleChange,
145
- readOnly: disabled,
146
- value: value_0
147
- }, JSON.stringify({
148
- path,
149
- rerenderProviderKey
150
- })), AfterInput]
139
+ children: [BeforeInput, /*#__PURE__*/_jsx(BulkUploadProvider, {
140
+ drawerSlugPrefix: path,
141
+ children: /*#__PURE__*/_jsx(LexicalProvider, {
142
+ composerKey: pathWithEditDepth,
143
+ editorConfig: editorConfig,
144
+ fieldProps: props,
145
+ isSmallWidthViewport: isSmallWidthViewport,
146
+ onChange: handleChange,
147
+ readOnly: disabled,
148
+ value: value_0
149
+ }, JSON.stringify({
150
+ path,
151
+ rerenderProviderKey
152
+ }))
153
+ }), AfterInput]
151
154
  }), /*#__PURE__*/_jsx(RenderCustomComponent, {
152
155
  CustomComponent: Description,
153
156
  Fallback: /*#__PURE__*/_jsx(FieldDescription, {
@@ -1 +1 @@
1
- {"version":3,"file":"Field.js","names":["FieldDescription","FieldError","FieldLabel","RenderCustomComponent","useEditDepth","useEffectEvent","useField","mergeFieldStyles","dequal","React","useCallback","useEffect","useMemo","useState","ErrorBoundary","LexicalProvider","useRunDeprioritized","baseClass","RichTextComponent","props","editorConfig","field","admin","className","description","readOnly","readOnlyFromAdmin","label","localized","required","path","pathFromProps","readOnlyFromTopLevelProps","validate","readOnlyFromProps","editDepth","memoizedValidate","value","validationOptions","customComponents","AfterInput","BeforeInput","Description","Error","Label","disabled","disabledFromField","initialValue","setValue","showError","potentiallyStalePath","isSmallWidthViewport","setIsSmallWidthViewport","rerenderProviderKey","setRerenderProviderKey","prevInitialValueRef","useRef","prevValueRef","updateViewPortWidth","isNextSmallWidthViewport","window","matchMedia","matches","addEventListener","removeEventListener","classes","hideGutter","filter","Boolean","join","pathWithEditDepth","runDeprioritized","handleChange","editorState","updateFieldValue","newState","toJSON","current","styles","handleInitialValueChange","JSON","parse","stringify","Date","Object","is","_jsxs","style","_jsx","CustomComponent","Fallback","fallbackRender","onReset","composerKey","fieldProps","onChange","error","role","color","message","RichText"],"sources":["../../src/field/Field.tsx"],"sourcesContent":["'use client'\nimport type { EditorState, SerializedEditorState } from 'lexical'\n\nimport {\n FieldDescription,\n FieldError,\n FieldLabel,\n RenderCustomComponent,\n useEditDepth,\n useEffectEvent,\n useField,\n} from '@payloadcms/ui'\nimport { mergeFieldStyles } from '@payloadcms/ui/shared'\nimport { dequal } from 'dequal/lite'\nimport { type Validate } from 'payload'\nimport React, { useCallback, useEffect, useMemo, useState } from 'react'\nimport { ErrorBoundary } from 'react-error-boundary'\n\nimport type { SanitizedClientEditorConfig } from '../lexical/config/types.js'\n\nimport '../lexical/theme/EditorTheme.scss'\nimport './bundled.css'\nimport './index.scss'\n\nimport type { LexicalRichTextFieldProps } from '../types.js'\n\nimport { LexicalProvider } from '../lexical/LexicalProvider.js'\nimport { useRunDeprioritized } from '../utilities/useRunDeprioritized.js'\n\nconst baseClass = 'rich-text-lexical'\n\nconst RichTextComponent: React.FC<\n {\n readonly editorConfig: SanitizedClientEditorConfig // With rendered features n stuff\n } & LexicalRichTextFieldProps\n> = (props) => {\n const {\n editorConfig,\n field,\n field: {\n admin: { className, description, readOnly: readOnlyFromAdmin } = {},\n label,\n localized,\n required,\n },\n path: pathFromProps,\n readOnly: readOnlyFromTopLevelProps,\n validate, // Users can pass in client side validation if they WANT to, but it's not required anymore\n } = props\n\n const readOnlyFromProps = readOnlyFromTopLevelProps || readOnlyFromAdmin\n\n const editDepth = useEditDepth()\n\n const memoizedValidate = useCallback<Validate>(\n (value, validationOptions) => {\n if (typeof validate === 'function') {\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n return validate(value, { ...validationOptions, required })\n }\n return true\n },\n // Important: do not add props to the dependencies array.\n // This would cause an infinite loop and endless re-rendering.\n // Removing props from the dependencies array fixed this issue: https://github.com/payloadcms/payload/issues/3709\n [validate, required],\n )\n\n const {\n customComponents: { AfterInput, BeforeInput, Description, Error, Label } = {},\n disabled: disabledFromField,\n initialValue,\n path,\n setValue,\n showError,\n value,\n } = useField<SerializedEditorState>({\n potentiallyStalePath: pathFromProps,\n validate: memoizedValidate,\n })\n\n const disabled = readOnlyFromProps || disabledFromField\n\n const [isSmallWidthViewport, setIsSmallWidthViewport] = useState<boolean>(false)\n const [rerenderProviderKey, setRerenderProviderKey] = useState<Date>()\n\n const prevInitialValueRef = React.useRef<SerializedEditorState | undefined>(initialValue)\n const prevValueRef = React.useRef<SerializedEditorState | undefined>(value)\n\n useEffect(() => {\n const updateViewPortWidth = () => {\n const isNextSmallWidthViewport = window.matchMedia('(max-width: 768px)').matches\n\n if (isNextSmallWidthViewport !== isSmallWidthViewport) {\n setIsSmallWidthViewport(isNextSmallWidthViewport)\n }\n }\n updateViewPortWidth()\n window.addEventListener('resize', updateViewPortWidth)\n\n return () => {\n window.removeEventListener('resize', updateViewPortWidth)\n }\n }, [isSmallWidthViewport])\n\n const classes = [\n baseClass,\n 'field-type',\n className,\n showError && 'error',\n disabled && `${baseClass}--read-only`,\n editorConfig?.admin?.hideGutter !== true && !isSmallWidthViewport\n ? `${baseClass}--show-gutter`\n : null,\n ]\n .filter(Boolean)\n .join(' ')\n\n const pathWithEditDepth = `${path}.${editDepth}`\n\n const runDeprioritized = useRunDeprioritized() // defaults to 500 ms timeout\n\n const handleChange = useCallback(\n (editorState: EditorState) => {\n // Capture `editorState` in the closure so we can safely run later.\n const updateFieldValue = () => {\n const newState = editorState.toJSON()\n prevValueRef.current = newState\n setValue(newState)\n }\n\n // Queue the update for the browser’s idle time (or Safari shim)\n // and let the hook handle debouncing/cancellation.\n void runDeprioritized(updateFieldValue)\n },\n [setValue, runDeprioritized], // `runDeprioritized` is stable (useCallback inside hook)\n )\n\n const styles = useMemo(() => mergeFieldStyles(field), [field])\n\n const handleInitialValueChange = useEffectEvent(\n (initialValue: SerializedEditorState | undefined) => {\n // Object deep equality check here, as re-mounting the editor if\n // the new value is the same as the old one is not necessary.\n // In postgres, the order of keys in JSON objects is not guaranteed to be preserved,\n // so we need to do a deep equality check here that does not care about key order => we use dequal.\n // If we used JSON.stringify, the editor would re-mount every time you save the document, as the order of keys changes => change detected => re-mount.\n if (\n prevValueRef.current !== value &&\n !dequal(\n prevValueRef.current != null\n ? JSON.parse(JSON.stringify(prevValueRef.current))\n : prevValueRef.current,\n value,\n )\n ) {\n prevInitialValueRef.current = initialValue\n prevValueRef.current = value\n setRerenderProviderKey(new Date())\n }\n },\n )\n\n useEffect(() => {\n // Needs to trigger for object reference changes - otherwise,\n // reacting to the same initial value change twice will cause\n // the second change to be ignored, even though the value has changed.\n // That's because initialValue is not kept up-to-date\n if (!Object.is(initialValue, prevInitialValueRef.current)) {\n handleInitialValueChange(initialValue)\n }\n }, [initialValue])\n\n return (\n <div className={classes} key={pathWithEditDepth} style={styles}>\n <RenderCustomComponent\n CustomComponent={Error}\n Fallback={<FieldError path={path} showError={showError} />}\n />\n {Label || <FieldLabel label={label} localized={localized} path={path} required={required} />}\n <div className={`${baseClass}__wrap`}>\n <ErrorBoundary fallbackRender={fallbackRender} onReset={() => {}}>\n {BeforeInput}\n <LexicalProvider\n composerKey={pathWithEditDepth}\n editorConfig={editorConfig}\n fieldProps={props}\n isSmallWidthViewport={isSmallWidthViewport}\n key={JSON.stringify({ path, rerenderProviderKey })} // makes sure lexical is completely re-rendered when initialValue changes, bypassing the lexical-internal value memoization. That way, external changes to the form will update the editor. More infos in PR description (https://github.com/payloadcms/payload/pull/5010)\n onChange={handleChange}\n readOnly={disabled}\n value={value}\n />\n {AfterInput}\n </ErrorBoundary>\n <RenderCustomComponent\n CustomComponent={Description}\n Fallback={<FieldDescription description={description} path={path} />}\n />\n </div>\n </div>\n )\n}\n\nfunction fallbackRender({ error }: { error: Error }) {\n // Call resetErrorBoundary() to reset the error boundary and retry the render.\n\n return (\n <div className=\"errorBoundary\" role=\"alert\">\n <p>Something went wrong:</p>\n <pre style={{ color: 'red' }}>{error.message}</pre>\n </div>\n )\n}\n\nexport const RichText: typeof RichTextComponent = RichTextComponent\n"],"mappings":"AAAA;;;AAGA,SACEA,gBAAgB,EAChBC,UAAU,EACVC,UAAU,EACVC,qBAAqB,EACrBC,YAAY,EACZC,cAAc,EACdC,QAAQ,QACH;AACP,SAASC,gBAAgB,QAAQ;AACjC,SAASC,MAAM,QAAQ;AAEvB,OAAOC,KAAA,IAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ;AACjE,SAASC,aAAa,QAAQ;AAK9B,OAAO;AAKP,SAASC,eAAe,QAAQ;AAChC,SAASC,mBAAmB,QAAQ;AAEpC,MAAMC,SAAA,GAAY;AAElB,MAAMC,iBAAA,GAIDC,KAAA;EACH,MAAM;IACJC,YAAY;IACZC,KAAK;IACLA,KAAA,EAAO;MACLC,KAAA,EAAO;QAAEC,SAAS;QAAEC,WAAW;QAAEC,QAAA,EAAUC;MAAiB,CAAE,GAAG,CAAC,CAAC;MACnEC,KAAK;MACLC,SAAS;MACTC;IAAQ,CACT;IACDC,IAAA,EAAMC,aAAa;IACnBN,QAAA,EAAUO,yBAAyB;IACnCC;EAAQ,CACT,GAAGd,KAAA;EAEJ,MAAMe,iBAAA,GAAoBF,yBAAA,IAA6BN,iBAAA;EAEvD,MAAMS,SAAA,GAAY/B,YAAA;EAElB,MAAMgC,gBAAA,GAAmB1B,WAAA,CACvB,CAAC2B,KAAA,EAAOC,iBAAA;IACN,IAAI,OAAOL,QAAA,KAAa,YAAY;MAClC;MACA,OAAOA,QAAA,CAASI,KAAA,EAA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AE;qBACHA,IAAA,CAAC;MAAID,KAAA,EAAO;QAAEW,KAAA,EAAO;MAAM;gBAAIF,KAAA,CAAMG;;;AAG3C;AAEA,OAAO,MAAMC,QAAA,GAAqClF,iBAAA","ignoreList":[]}
1
+ {"version":3,"file":"Field.js","names":["BulkUploadProvider","FieldDescription","FieldError","FieldLabel","RenderCustomComponent","useEditDepth","useEffectEvent","useField","mergeFieldStyles","dequal","React","useCallback","useEffect","useMemo","useState","ErrorBoundary","LexicalProvider","useRunDeprioritized","baseClass","RichTextComponent","props","editorConfig","field","admin","className","description","readOnly","readOnlyFromAdmin","label","localized","required","path","pathFromProps","readOnlyFromTopLevelProps","validate","readOnlyFromProps","editDepth","memoizedValidate","value","validationOptions","customComponents","AfterInput","BeforeInput","Description","Error","Label","disabled","disabledFromField","initialValue","setValue","showError","potentiallyStalePath","isSmallWidthViewport","setIsSmallWidthViewport","rerenderProviderKey","setRerenderProviderKey","prevInitialValueRef","useRef","prevValueRef","updateViewPortWidth","isNextSmallWidthViewport","window","matchMedia","matches","addEventListener","removeEventListener","classes","hideGutter","filter","Boolean","join","pathWithEditDepth","runDeprioritized","handleChange","editorState","updateFieldValue","newState","toJSON","current","styles","handleInitialValueChange","JSON","parse","stringify","Date","Object","is","_jsxs","style","_jsx","CustomComponent","Fallback","fallbackRender","onReset","drawerSlugPrefix","composerKey","fieldProps","onChange","error","role","color","message","RichText"],"sources":["../../src/field/Field.tsx"],"sourcesContent":["'use client'\nimport type { EditorState, SerializedEditorState } from 'lexical'\n\nimport {\n BulkUploadProvider,\n FieldDescription,\n FieldError,\n FieldLabel,\n RenderCustomComponent,\n useEditDepth,\n useEffectEvent,\n useField,\n} from '@payloadcms/ui'\nimport { mergeFieldStyles } from '@payloadcms/ui/shared'\nimport { dequal } from 'dequal/lite'\nimport { type Validate } from 'payload'\nimport React, { useCallback, useEffect, useMemo, useState } from 'react'\nimport { ErrorBoundary } from 'react-error-boundary'\n\nimport type { SanitizedClientEditorConfig } from '../lexical/config/types.js'\n\nimport '../lexical/theme/EditorTheme.scss'\nimport './bundled.css'\nimport './index.scss'\n\nimport type { LexicalRichTextFieldProps } from '../types.js'\n\nimport { LexicalProvider } from '../lexical/LexicalProvider.js'\nimport { useRunDeprioritized } from '../utilities/useRunDeprioritized.js'\n\nconst baseClass = 'rich-text-lexical'\n\nconst RichTextComponent: React.FC<\n {\n readonly editorConfig: SanitizedClientEditorConfig // With rendered features n stuff\n } & LexicalRichTextFieldProps\n> = (props) => {\n const {\n editorConfig,\n field,\n field: {\n admin: { className, description, readOnly: readOnlyFromAdmin } = {},\n label,\n localized,\n required,\n },\n path: pathFromProps,\n readOnly: readOnlyFromTopLevelProps,\n validate, // Users can pass in client side validation if they WANT to, but it's not required anymore\n } = props\n\n const readOnlyFromProps = readOnlyFromTopLevelProps || readOnlyFromAdmin\n\n const editDepth = useEditDepth()\n\n const memoizedValidate = useCallback<Validate>(\n (value, validationOptions) => {\n if (typeof validate === 'function') {\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n return validate(value, { ...validationOptions, required })\n }\n return true\n },\n // Important: do not add props to the dependencies array.\n // This would cause an infinite loop and endless re-rendering.\n // Removing props from the dependencies array fixed this issue: https://github.com/payloadcms/payload/issues/3709\n [validate, required],\n )\n\n const {\n customComponents: { AfterInput, BeforeInput, Description, Error, Label } = {},\n disabled: disabledFromField,\n initialValue,\n path,\n setValue,\n showError,\n value,\n } = useField<SerializedEditorState>({\n potentiallyStalePath: pathFromProps,\n validate: memoizedValidate,\n })\n\n const disabled = readOnlyFromProps || disabledFromField\n\n const [isSmallWidthViewport, setIsSmallWidthViewport] = useState<boolean>(false)\n const [rerenderProviderKey, setRerenderProviderKey] = useState<Date>()\n\n const prevInitialValueRef = React.useRef<SerializedEditorState | undefined>(initialValue)\n const prevValueRef = React.useRef<SerializedEditorState | undefined>(value)\n\n useEffect(() => {\n const updateViewPortWidth = () => {\n const isNextSmallWidthViewport = window.matchMedia('(max-width: 768px)').matches\n\n if (isNextSmallWidthViewport !== isSmallWidthViewport) {\n setIsSmallWidthViewport(isNextSmallWidthViewport)\n }\n }\n updateViewPortWidth()\n window.addEventListener('resize', updateViewPortWidth)\n\n return () => {\n window.removeEventListener('resize', updateViewPortWidth)\n }\n }, [isSmallWidthViewport])\n\n const classes = [\n baseClass,\n 'field-type',\n className,\n showError && 'error',\n disabled && `${baseClass}--read-only`,\n editorConfig?.admin?.hideGutter !== true && !isSmallWidthViewport\n ? `${baseClass}--show-gutter`\n : null,\n ]\n .filter(Boolean)\n .join(' ')\n\n const pathWithEditDepth = `${path}.${editDepth}`\n\n const runDeprioritized = useRunDeprioritized() // defaults to 500 ms timeout\n\n const handleChange = useCallback(\n (editorState: EditorState) => {\n // Capture `editorState` in the closure so we can safely run later.\n const updateFieldValue = () => {\n const newState = editorState.toJSON()\n prevValueRef.current = newState\n setValue(newState)\n }\n\n // Queue the update for the browser’s idle time (or Safari shim)\n // and let the hook handle debouncing/cancellation.\n void runDeprioritized(updateFieldValue)\n },\n [setValue, runDeprioritized], // `runDeprioritized` is stable (useCallback inside hook)\n )\n\n const styles = useMemo(() => mergeFieldStyles(field), [field])\n\n const handleInitialValueChange = useEffectEvent(\n (initialValue: SerializedEditorState | undefined) => {\n // Object deep equality check here, as re-mounting the editor if\n // the new value is the same as the old one is not necessary.\n // In postgres, the order of keys in JSON objects is not guaranteed to be preserved,\n // so we need to do a deep equality check here that does not care about key order => we use dequal.\n // If we used JSON.stringify, the editor would re-mount every time you save the document, as the order of keys changes => change detected => re-mount.\n if (\n prevValueRef.current !== value &&\n !dequal(\n prevValueRef.current != null\n ? JSON.parse(JSON.stringify(prevValueRef.current))\n : prevValueRef.current,\n value,\n )\n ) {\n prevInitialValueRef.current = initialValue\n prevValueRef.current = value\n setRerenderProviderKey(new Date())\n }\n },\n )\n\n useEffect(() => {\n // Needs to trigger for object reference changes - otherwise,\n // reacting to the same initial value change twice will cause\n // the second change to be ignored, even though the value has changed.\n // That's because initialValue is not kept up-to-date\n if (!Object.is(initialValue, prevInitialValueRef.current)) {\n handleInitialValueChange(initialValue)\n }\n }, [initialValue])\n\n return (\n <div className={classes} key={pathWithEditDepth} style={styles}>\n <RenderCustomComponent\n CustomComponent={Error}\n Fallback={<FieldError path={path} showError={showError} />}\n />\n {Label || <FieldLabel label={label} localized={localized} path={path} required={required} />}\n <div className={`${baseClass}__wrap`}>\n <ErrorBoundary fallbackRender={fallbackRender} onReset={() => {}}>\n {BeforeInput}\n {/* Lexical may be in a drawer. We need to define another BulkUploadProvider to ensure that the bulk upload drawer\n is rendered in the correct depth (not displayed *behind* the current drawer)*/}\n <BulkUploadProvider drawerSlugPrefix={path}>\n <LexicalProvider\n composerKey={pathWithEditDepth}\n editorConfig={editorConfig}\n fieldProps={props}\n isSmallWidthViewport={isSmallWidthViewport}\n key={JSON.stringify({ path, rerenderProviderKey })} // makes sure lexical is completely re-rendered when initialValue changes, bypassing the lexical-internal value memoization. That way, external changes to the form will update the editor. More infos in PR description (https://github.com/payloadcms/payload/pull/5010)\n onChange={handleChange}\n readOnly={disabled}\n value={value}\n />\n </BulkUploadProvider>\n {AfterInput}\n </ErrorBoundary>\n <RenderCustomComponent\n CustomComponent={Description}\n Fallback={<FieldDescription description={description} path={path} />}\n />\n </div>\n </div>\n )\n}\n\nfunction fallbackRender({ error }: { error: Error }) {\n // Call resetErrorBoundary() to reset the error boundary and retry the render.\n\n return (\n <div className=\"errorBoundary\" role=\"alert\">\n <p>Something went wrong:</p>\n <pre style={{ color: 'red' }}>{error.message}</pre>\n </div>\n )\n}\n\nexport const RichText: typeof RichTextComponent = RichTextComponent\n"],"mappings":"AAAA;;;AAGA,SACEA,kBAAkB,EAClBC,gBAAgB,EAChBC,UAAU,EACVC,UAAU,EACVC,qBAAqB,EACrBC,YAAY,EACZC,cAAc,EACdC,QAAQ,QACH;AACP,SAASC,gBAAgB,QAAQ;AACjC,SAASC,MAAM,QAAQ;AAEvB,OAAOC,KAAA,IAASC,WAAW,EAAEC,SAAS,EAAE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aAAA;QAAc6E,cAAA,EAAgBA,cAAA;QAAgBC,OAAA,EAASA,CAAA,MAAO;mBAC5DnD,WAAA,E,aAGD+C,IAAA,CAACzF,kBAAA;UAAmB8F,gBAAA,EAAkB/D,IAAA;oBACpC,aAAA0D,IAAA,CAACzE,eAAA;YACC+E,WAAA,EAAaxB,iBAAA;YACblD,YAAA,EAAcA,YAAA;YACd2E,UAAA,EAAY5E,KAAA;YACZgC,oBAAA,EAAsBA,oBAAA;YAEtB6C,QAAA,EAAUxB,YAAA;YACV/C,QAAA,EAAUoB,QAAA;YACVR,KAAA,EAAOA;aAHF2C,IAAA,CAAKE,SAAS,CAAC;YAAEpD,IAAA;YAAMuB;UAAoB;YAMnDb,UAAA;uBAEHgD,IAAA,CAACrF,qBAAA;QACCsF,eAAA,EAAiB/C,WAAA;QACjBgD,QAAA,eAAUF,IAAA,CAACxF,gBAAA;UAAiBwB,WAAA,EAAaA,WAAA;UAAaM,IAAA,EAAMA;;;;KA3BpCwC,iBAAA;AAgClC;AAEA,SAASqB,eAAe;EAAEM;AAAK,CAAoB;EACjD;EAEA,oBACEX,KAAA,CAAC;IAAI/D,SAAA,EAAU;IAAgB2E,IAAA,EAAK;4BAClCV,IAAA,CAAC;gBAAE;qBACHA,IAAA,CAAC;MAAID,KAAA,EAAO;QAAEY,KAAA,EAAO;MAAM;gBAAIF,KAAA,CAAMG;;;AAG3C;AAEA,OAAO,MAAMC,QAAA,GAAqCnF,iBAAA","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/richtext-lexical",
3
- "version": "3.63.0-canary.5",
3
+ "version": "3.63.0-canary.7",
4
4
  "description": "The officially supported Lexical richtext adapter for Payload",
5
5
  "homepage": "https://payloadcms.com",
6
6
  "repository": {
@@ -374,8 +374,8 @@
374
374
  "react-error-boundary": "4.1.2",
375
375
  "ts-essentials": "10.0.3",
376
376
  "uuid": "10.0.0",
377
- "@payloadcms/ui": "3.63.0-canary.5",
378
- "@payloadcms/translations": "3.63.0-canary.5"
377
+ "@payloadcms/translations": "3.63.0-canary.7",
378
+ "@payloadcms/ui": "3.63.0-canary.7"
379
379
  },
380
380
  "devDependencies": {
381
381
  "@babel/cli": "7.27.2",
@@ -395,15 +395,15 @@
395
395
  "esbuild-sass-plugin": "3.3.1",
396
396
  "swc-plugin-transform-remove-imports": "4.0.4",
397
397
  "@payloadcms/eslint-config": "3.28.0",
398
- "payload": "3.63.0-canary.5"
398
+ "payload": "3.63.0-canary.7"
399
399
  },
400
400
  "peerDependencies": {
401
401
  "@faceless-ui/modal": "3.0.0",
402
402
  "@faceless-ui/scroll-info": "2.0.0",
403
403
  "react": "^19.0.0 || ^19.0.0-rc-65a56d0e-20241020",
404
404
  "react-dom": "^19.0.0 || ^19.0.0-rc-65a56d0e-20241020",
405
- "@payloadcms/next": "3.63.0-canary.5",
406
- "payload": "3.63.0-canary.5"
405
+ "@payloadcms/next": "3.63.0-canary.7",
406
+ "payload": "3.63.0-canary.7"
407
407
  },
408
408
  "engines": {
409
409
  "node": "^18.20.2 || >=20.9.0"
@@ -1,2 +0,0 @@
1
- "use client";import{a as we,e as ke,f as O,h as Te,i as De,j as Le,k as ve,l as Me}from"./chunk-AFXLIYGL.js";import{a as Re,b as R}from"./chunk-BZZVLW4U.js";import{jsx as $,jsxs as ge}from"react/jsx-runtime";import{FieldDescription as Dn,FieldError as Ln,FieldLabel as vn,RenderCustomComponent as bt,useEditDepth as Mn,useEffectEvent as _n,useField as An}from"@payloadcms/ui";import{mergeFieldStyles as Bn}from"@payloadcms/ui/shared";import{dequal as In}from"dequal/lite";import Nt,{useCallback as Pt,useEffect as St,useMemo as On,useState as Rt}from"react";import{ErrorBoundary as Fn}from"react-error-boundary";import"./bundled.css";import{jsx as F}from"react/jsx-runtime";import{LexicalComposer as wn}from"@lexical/react/LexicalComposer.js";import{useEditDepth as kn}from"@payloadcms/ui";import*as xt from"react";import{useMemo as Tn}from"react";import{c as un}from"react/compiler-runtime";import{jsx as E,jsxs as te}from"react/jsx-runtime";import{useLexicalComposerContext as dn}from"@lexical/react/LexicalComposerContext.js";import{LexicalErrorBoundary as mn}from"@lexical/react/LexicalErrorBoundary.js";import{HistoryPlugin as fn}from"@lexical/react/LexicalHistoryPlugin.js";import{OnChangePlugin as pn}from"@lexical/react/LexicalOnChangePlugin.js";import{RichTextPlugin as gn}from"@lexical/react/LexicalRichTextPlugin.js";import{useLexicalEditable as hn}from"@lexical/react/useLexicalEditable";import{BLUR_COMMAND as yn,COMMAND_PRIORITY_LOW as ht,FOCUS_COMMAND as xn}from"lexical";import*as q from"react";import{useEffect as En,useState as Cn}from"react";import{jsx as _e}from"react/jsx-runtime";import"react";var K=({anchorElem:t,clientProps:e,plugin:o})=>o.position==="floatingAnchorElem"&&t?o.Component&&_e(o.Component,{anchorElem:t,clientProps:e}):o.Component&&_e(o.Component,{clientProps:e});import{c as Tt}from"react/compiler-runtime";import{copyToClipboard as Dt}from"@lexical/clipboard";import{useLexicalComposerContext as Lt}from"@lexical/react/LexicalComposerContext.js";import{objectKlassEquals as vt}from"@lexical/utils";import Ae from"bson-objectid";import{COMMAND_PRIORITY_LOW as Mt,COPY_COMMAND as _t}from"lexical";import{useEffect as At}from"react";function Be(){let t=Tt(3),[e]=Lt(),o,r;return t[0]!==e?(o=()=>e.registerCommand(_t,n=>(Dt(e,vt(n,ClipboardEvent)?n:null).then(()=>{if(!(n instanceof ClipboardEvent)||!n.clipboardData)throw new Error("No clipboard event");let u=n.clipboardData.getData("application/x-lexical-editor");if(!u)return!0;let i=JSON.parse(u),s=d=>{if("fields"in d&&typeof d.fields=="object"&&d.fields!==null&&"id"in d.fields?d.fields.id=new Ae.default().toHexString():"id"in d&&(d.id=new Ae.default().toHexString()),d.children)for(let y of d.children)s(y)};for(let d of i.nodes)s(d);let c=JSON.stringify(i);n.clipboardData.setData("application/x-lexical-editor",c)}).catch(u=>{throw n instanceof ClipboardEvent&&n.clipboardData?.setData("application/x-lexical-editor",""),u}),!0),Mt),r=[e],t[0]=e,t[1]=o,t[2]=r):(o=t[1],r=t[2]),At(o,r),null}import{c as Bt}from"react/compiler-runtime";import{useLexicalComposerContext as It}from"@lexical/react/LexicalComposerContext";import{$findMatchingParent as ne,mergeRegister as Ot}from"@lexical/utils";import{$createNodeSelection as Ft,$getEditor as X,$getNearestNodeFromDOMNode as $t,$getSelection as re,$isDecoratorNode as H,$isElementNode as xe,$isLineBreakNode as Kt,$isNodeSelection as ie,$isRangeSelection as Ie,$isRootOrShadowRoot as Ht,$isTextNode as jt,$setSelection as Oe,CLICK_COMMAND as zt,COMMAND_PRIORITY_LOW as W,KEY_ARROW_DOWN_COMMAND as Wt,KEY_ARROW_UP_COMMAND as Yt,KEY_BACKSPACE_COMMAND as Vt,KEY_DELETE_COMMAND as Gt,SELECTION_CHANGE_COMMAND as Ut}from"lexical";import{useEffect as qt}from"react";function Fe(){let t=Bt(3),[e]=It(),o=oo,r,n;return t[0]!==e?(r=()=>Ot(e.registerCommand(zt,to,W),e.registerCommand(Gt,o,W),e.registerCommand(Vt,o,W),e.registerCommand(Ut,eo,W),e.registerCommand(Yt,Xt,W),e.registerCommand(Wt,Jt,W)),n=[e],t[0]=e,t[1]=r,t[2]=n):(r=t[1],n=t[2]),qt(r,n),null}function Jt(t){let e=re();if(ie(e)){t.preventDefault();let i=e.getNodes()[0]?.getNextSibling();if(H(i)){let d=X().getElementByKey(i.getKey());return d&&Z({element:d,node:i}),!0}if(!xe(i))return!0;let s=i.getFirstDescendant()??i;return s&&(ne(s,se)?.selectEnd(),t.preventDefault()),!0}if(!Ie(e))return!1;let r=(e.isBackward()?e.anchor:e.focus).getNode(),n=ne(r,Qt),u=n?.getNextSibling();if(!n||u!==$e(n))return!1;if(H(u)){let i=X().getElementByKey(u.getKey());if(i)return Z({element:i,node:u}),t.preventDefault(),!0}return!1}function Qt(t){return $e(t)!==null}function Xt(t){let e=re();if(ie(e)){let i=e.getNodes()[0]?.getPreviousSibling();if(H(i)){let d=X().getElementByKey(i.getKey());return d?(Z({element:d,node:i}),t.preventDefault(),!0):!1}if(!xe(i))return!1;let s=i.getLastDescendant()??i;return s?(ne(s,se)?.selectStart(),t.preventDefault(),!0):!1}if(!Ie(e))return!1;let r=(e.isBackward()?e.anchor:e.focus).getNode(),n=ne(r,Zt),u=n?.getPreviousSibling();if(!n||u!==Ke(n))return!1;if(H(u)){let i=X().getElementByKey(u.getKey());if(i)return Z({element:i,node:u}),t.preventDefault(),!0}return!1}function Zt(t){return Ke(t)!==null}function eo(){let t=io();return document.querySelector(".decorator-selected")?.classList.remove("decorator-selected"),t?(t.element?.classList.add("decorator-selected"),!0):!1}function to(t){document.querySelector(".decorator-selected")?.classList.remove("decorator-selected");let e=ro(t);if(!e)return!0;let{target:o}=t;return!(o instanceof HTMLElement)||o.isContentEditable||o.closest('button, textarea, input, .react-select, .code-editor, .no-select-decorator, [role="button"]')?Oe(null):Z(e),!0}function oo(t){let e=re();return ie(e)?(t.preventDefault(),e.getNodes().forEach(no),!0):!1}function no(t){t.remove()}function ro(t){if(!(t.target instanceof HTMLElement))return;let e=t.target.closest('[data-lexical-decorator="true"]');if(!(e instanceof HTMLElement))return;let o=$t(e);return H(o)?{element:e,node:o}:void 0}function io(){let t=re();if(!ie(t))return;let e=t.getNodes();if(e.length!==1)return;let o=e[0];return H(o)?{decorator:o,element:X().getElementByKey(o.getKey())}:void 0}function Z({element:t,node:e}){document.querySelector(".decorator-selected")?.classList.remove("decorator-selected");let o=Ft();o.add(e.getKey()),Oe(o),t.scrollIntoView({behavior:"smooth",block:"nearest"}),t.classList.add("decorator-selected")}function se(t){if(H(t)&&!t.isInline())return!0;if(!xe(t)||Ht(t))return!1;let e=t.getFirstChild(),o=e===null||Kt(e)||jt(e)||e.isInline();return!t.isInline()&&t.canBeEmpty()!==!1&&o}function $e(t){let e=t.getNextSibling();for(;e!==null;){if(se(e))return e;e=e.getNextSibling()}return null}function Ke(t){let e=t.getPreviousSibling();for(;e!==null;){if(se(e))return e;e=e.getPreviousSibling()}return null}import{jsx as Ee}from"react/jsx-runtime";import{useLexicalComposerContext as mo}from"@lexical/react/LexicalComposerContext.js";import{$createParagraphNode as fo,isHTMLElement as po}from"lexical";import*as We from"react";import{useCallback as go,useEffect as ze,useRef as ho,useState as yo}from"react";import{createPortal as xo}from"react-dom";var Y=(t,e,o,r,n=50,u=25)=>{let i=0;if(t&&!t.contains(r)){let{bottom:s,left:c,right:d,top:y}=t.getBoundingClientRect(),l=y+window.scrollY,a=s+window.scrollY;if(o<l-u||o>a+u||e<c-n||e>d+n)return-1;(e<c||e>d)&&(i=e<c?e-c:e-d)}return i};import{$getNodeByKey as ae}from"lexical";function V(t){let e=t.getBoundingClientRect(),o=getComputedStyle(t).getPropertyValue("transform");if(!o||o==="none")return e;let r=o.split(",").pop();return e.y=e.y-Number(r?.replace(")","")),e}function le(t){let e=(c,d)=>c?parseFloat(window.getComputedStyle(c)[d]):0,{marginBottom:o,marginTop:r}=window.getComputedStyle(t),n=e(t.previousElementSibling,"marginBottom"),u=e(t.nextElementSibling,"marginTop"),i=Math.max(parseFloat(r),n);return{marginBottom:Math.max(parseFloat(o),u),marginTop:i}}import{$getRoot as so}from"lexical";function j(t){return t.getEditorState().read(()=>so().getChildrenKeys())}var lo=1,ao=-1,He=0,_={props:null,result:null};function co(t,e,o=20){let r=t.x-e.x,n=t.y-e.y;return r*r+n*n<=o*o}function G(t){let{anchorElem:e,cache_threshold:o=20,editor:r,fuzzy:n=!1,horizontalOffset:u=0,point:{x:i,y:s},startIndex:c=0,useEdgeAsDefault:d=!1}=t;if(o>0&&_.props&&_.result&&_.props.fuzzy===t.fuzzy&&_.props.horizontalOffset===t.horizontalOffset&&_.props.useEdgeAsDefault===t.useEdgeAsDefault&&co(_.props.point,t.point,o))return _.result;let y=e.getBoundingClientRect(),l=j(r),a={blockElem:null,blockNode:null,distance:1/0,foundAtIndex:-1,isFoundNodeEmptyParagraph:!1};return r.getEditorState().read(()=>{if(d){let g=r.getElementByKey(l[0]),m=r.getElementByKey(l[l.length-1]);if(g&&m){let[p,f]=[V(g),V(m)];if(s<p.top?(a.blockElem=g,a.distance=p.top-s,a.blockNode=ae(l[0]),a.foundAtIndex=0):s>f.bottom&&(a.distance=s-f.bottom,a.blockNode=ae(l[l.length-1]),a.blockElem=m,a.foundAtIndex=l.length-1),a?.blockElem)return{blockElem:null,isFoundNodeEmptyParagraph:!1}}}let h=c,x=He;for(;h>=0&&h<l.length;){let g=l[h],m=r.getElementByKey(g);if(m===null)break;let p=new O(i+u,s),f=ve.fromDOMRect(V(m)),{marginBottom:C,marginTop:k}=le(m),S=f.generateNewRect({bottom:f.bottom+C,left:y.left,right:y.right,top:f.top-k}),{distance:b,isOnBottomSide:w,isOnTopSide:N}=S.distanceFromPoint(p);if(b===0){a.blockElem=m,a.blockNode=ae(g),a.foundAtIndex=h,a.distance=b,a.blockNode&&a.blockNode.getType()==="paragraph"&&a.blockNode.getTextContent()===""&&(!n&&!t.returnEmptyParagraphs&&(a.blockElem=null,a.blockNode=null),a.isFoundNodeEmptyParagraph=!0);break}else n&&b<a.distance&&(a.blockElem=m,a.blockNode=ae(g),a.distance=b,a.foundAtIndex=h);x===He&&(N?x=ao:w?x=lo:x=1/0),h+=x}}),_.props=t,_.result={blockElem:a.blockElem,blockNode:a.blockNode,foundAtIndex:a.foundAtIndex,isFoundNodeEmptyParagraph:a.isFoundNodeEmptyParagraph},{blockElem:a.blockElem,blockNode:a.blockNode,foundAtIndex:a.foundAtIndex,isFoundNodeEmptyParagraph:a.isFoundNodeEmptyParagraph}}function ce(t,e){return!!t.closest(`.${e}`)}var uo=["IMG","INPUT","TEXTAREA","SELECT","BUTTON","VIDEO","OBJECT","EMBED","IFRAME","HR"];function je(t){if(!t||uo.includes(t.tagName)||t.offsetHeight===0||t.offsetWidth===0)return!1;let e=window.getComputedStyle(t);return!(e.display==="table-cell"||e.position==="absolute"||e.visibility==="hidden"||e.opacity==="0")}function ue(t,e,o,r=0){if(!t){e.style.opacity="0",e.style.transform="translate(-10000px, -10000px)";return}let n=t.getBoundingClientRect(),u=window.getComputedStyle(t),i=e.getBoundingClientRect(),s=o.getBoundingClientRect(),c;if(["LexicalEditorTheme__block","LexicalEditorTheme__upload","LexicalEditorTheme__relationship"].some(l=>t.classList.contains(l)||t.firstElementChild?.classList.contains(l)))c=n.top+8-s.top;else{let l=je(t)?parseInt(u.lineHeight,10):0;c=n.top+(l-i.height)/2-s.top}let y=r;e.style.opacity="1",e.style.transform=`translate(${y}px, ${c}px)`}var Eo="add-block-menu",de=1/0;function Co(t){return t===0?1/0:de>=0&&de<t?de:Math.floor(t/2)}function bo(t,e,o){let r=e.parentElement,{editorConfig:n}=R(),u=n?.admin?.hideGutter?-24:12,i=ho(null),[s,c]=yo(null);ze(()=>{function y(l){let a=l.target;if(!po(a))return;let h=Y(r,l.pageX,l.pageY,a);if(h===-1){c(null);return}if(ce(a,Eo))return;let x=j(t),{blockElem:g,blockNode:m,foundAtIndex:p}=G({anchorElem:e,cache_threshold:0,editor:t,horizontalOffset:-h,point:new O(l.x,l.y),returnEmptyParagraphs:!0,startIndex:Co(x.length),useEdgeAsDefault:!1});de=p,g&&m&&(s?.node!==m||s?.elem!==g)&&c({elem:g,node:m})}return document?.addEventListener("mousemove",y),()=>{document?.removeEventListener("mousemove",y)}},[r,e,t,s]),ze(()=>{i.current&&s?.node&&ue(s?.elem,i.current,e,u)},[e,s,u]);let d=go(y=>{let l=s;l?.node&&(t.update(()=>{let a=!0;if((l?.node.getType()!=="paragraph"||l.node.getTextContent()!=="")&&(a=!1),!a){let h=fo();l?.node.insertAfter(h),setTimeout(()=>{l={elem:t.getElementByKey(h.getKey()),node:h},c(l)},0)}}),setTimeout(()=>{t.update(()=>{t.focus(),l?.node&&"select"in l.node&&typeof l.node.select=="function"&&l.node.select()})},1),setTimeout(()=>{t.dispatchCommand(De,{node:l?.node})},2),y.stopPropagation(),y.preventDefault())},[t,s]);return xo(Ee(We.Fragment,{children:Ee("button",{"aria-label":"Add block",className:"icon add-block-menu",onClick:y=>{d(y)},ref:i,type:"button",children:Ee("div",{className:o?"icon":""})})}),e)}function Ye(t){let{anchorElem:e}=t,o=e===void 0?document.body:e,[r]=mo();return bo(r,o,r._editable)}import{jsx as me,jsxs as Po}from"react/jsx-runtime";import{useLexicalComposerContext as So}from"@lexical/react/LexicalComposerContext.js";import{eventFiles as Ue}from"@lexical/rich-text";import{$getNearestNodeFromDOMNode as qe,$getNodeByKey as Ro,isHTMLElement as Ce}from"lexical";import*as et from"react";import{useEffect as be,useRef as fe,useState as Je}from"react";import{createPortal as wo}from"react-dom";var Ve=0,No=-24;var z=0;function Ge(t,e,o,r,n,u,i,s,c,d=!1){let{height:y,top:l}=r.getBoundingClientRect(),{top:a,width:h}=i.getBoundingClientRect(),{marginBottom:x,marginTop:g}=le(r),m=l,p=u>=l+y/2+window.scrollY,f=!1;if(n?.elem)if(r!==n?.elem)(p&&n?.elem&&n?.elem===r.nextElementSibling||!p&&n?.elem&&n?.elem===r.previousElementSibling)&&(z++,z<200&&(f=!0));else{z++;let b=n?.boundingBox?.y,w=r.getBoundingClientRect().y;(p===n?.isBelow&&b===w||z<200)&&(f=!1)}if(f)return{isBelow:p,willStayInSamePosition:f};d?m+=y/2:p?m+=y+x/2:m-=g/2;let C=0;d||(p?C=-Ve:C=Ve);let k=m-a+C,S=No-e;return o.style.width=`calc(${h}px - ${t})`,o.style.opacity=".8",o.style.transform=`translate(${S}px, calc(${k}px - 2px))`,n?.elem&&(n.elem.style.opacity="",n?.elem===r?p?n.elem.style.marginTop="":n.elem.style.marginBottom="":(n.elem.style.marginBottom="",n.elem.style.marginTop="")),z=0,{isBelow:p,willStayInSamePosition:f}}var ko="draggable-block-menu",Qe="application/x-lexical-drag-block",ee=1/0;function Xe(t){return t===0?1/0:ee>=0&&ee<t?ee:Math.floor(t/2)}function To(t,e){let{transform:o}=e.style;t.setDragImage(e,0,0),setTimeout(()=>{e.style.transform=o})}function Ze(t,e){t&&(t.style.opacity="0"),e&&(e.style.opacity="",e.style.marginBottom="",e.style.marginTop="")}function Do(t,e,o){let r=e.parentElement,n=fe(null),u=fe(null),i=fe(null),s=fe(!1),[c,d]=Je(null),[y,l]=Je(null),{editorConfig:a}=R(),h=a?.admin?.hideGutter?-44:-8;be(()=>{function m(p){let f=p.target;if(!Ce(f))return;let C=Y(r,p.pageX,p.pageY,f);if(C===-1){d(null);return}if(ce(f,ko))return;let k=j(t),{blockElem:S,foundAtIndex:b,isFoundNodeEmptyParagraph:w}=G({anchorElem:e,cache_threshold:0,editor:t,horizontalOffset:-C,point:new O(p.x,p.y),startIndex:Xe(k.length),useEdgeAsDefault:!1,verbose:!1});ee=b,!(!S&&!w)&&c!==S&&d(S)}return document?.addEventListener("mousemove",m),()=>{document?.removeEventListener("mousemove",m)}},[r,e,t,c]),be(()=>{n.current&&ue(c,n.current,e,h)},[e,c,h]),be(()=>{function m(f){if(!s.current)return!1;let[C]=Ue(f);if(C)return!1;let{pageY:k,target:S}=f;if(!Ce(S))return!1;let b=Y(r,f.pageX,f.pageY,S,100,50),w=j(t),{blockElem:N,foundAtIndex:v,isFoundNodeEmptyParagraph:B}=G({anchorElem:e,editor:t,fuzzy:!0,horizontalOffset:-b,point:new O(f.x,f.y),startIndex:Xe(w.length),useEdgeAsDefault:!0,verbose:!0});ee=v;let T=u.current;if(N===null||T===null)return!1;if(c!==N){let{isBelow:D,willStayInSamePosition:J}=Ge(a?.admin?.hideGutter?"0px":"3rem",h+(a?.admin?.hideGutter?n?.current?.getBoundingClientRect()?.width??0:-(n?.current?.getBoundingClientRect()?.width??0)),T,N,y,k,e,f,i,B);f.preventDefault(),J||l({boundingBox:N.getBoundingClientRect(),elem:N,isBelow:D})}else y?.elem&&(Ze(T,y.elem),l({boundingBox:N.getBoundingClientRect(),elem:N,isBelow:!1}));return!0}function p(f){if(!s.current)return!1;let[C]=Ue(f);if(C)return!1;let{dataTransfer:k,pageY:S,target:b}=f,w=k?.getData(Qe)||"";return t.update(()=>{let N=Ro(w);if(!N||!Ce(b))return!1;let v=Y(r,f.pageX,f.pageY,b,100,50),{blockElem:B,isFoundNodeEmptyParagraph:T}=G({anchorElem:e,editor:t,fuzzy:!0,horizontalOffset:-v,point:new O(f.x,f.y),useEdgeAsDefault:!0});if(!B)return!1;let D=qe(B);if(!D)return!1;if(D===N)return!0;let{height:J,top:he}=V(B),I=S>=he+J/2+window.scrollY;T?(D.insertBefore(N),D.remove()):I?D.insertAfter(N):D.insertBefore(N),c!==null&&d(null),document.querySelectorAll(".lexical-block-highlighter").forEach(L=>{L.remove()});let oe=t.getElementByKey(N.getKey());setTimeout(()=>{let L=oe?.getBoundingClientRect();if(!L)return;let P=document.createElement("div");P.className="lexical-block-highlighter",P.style.backgroundColor="var(--theme-elevation-1000",P.style.transition="opacity 0.5s ease-in-out",P.style.zIndex="1",P.style.pointerEvents="none",P.style.boxSizing="border-box",P.style.borderRadius="4px",P.style.position="absolute",document.body.appendChild(P),P.style.opacity="0.1",P.style.height=`${L.height+8}px`,P.style.width=`${L.width+8}px`,P.style.top=`${L.top+window.scrollY-4}px`,P.style.left=`${L.left-4}px`,setTimeout(()=>{P.style.opacity="0",setTimeout(()=>{P.remove()},500)},1e3)},120)}),!0}return document.addEventListener("dragover",m),document.addEventListener("drop",p),()=>{document.removeEventListener("dragover",m),document.removeEventListener("drop",p)}},[r,h,e,t,y,c,a?.admin?.hideGutter]);function x(m){let p=m.dataTransfer;if(!p||!c)return;To(p,c);let f="";t.update(()=>{let C=qe(c);C&&(f=C.getKey())}),s.current=!0,p.setData(Qe,f)}function g(){s.current=!1,y?.elem&&Ze(u.current,y?.elem)}return wo(Po(et.Fragment,{children:[me("button",{"aria-label":"Drag to move",className:"icon draggable-block-menu",draggable:!0,onDragEnd:g,onDragStart:x,ref:n,type:"button",children:me("div",{className:o?"icon":""})}),me("div",{className:"draggable-block-target-line",ref:u}),me("div",{className:"debug-highlight",ref:i})]}),e)}function tt(t){let{anchorElem:e}=t,o=e===void 0?document.body:e,[r]=So();return Do(r,o,r._editable)}import{c as Lo}from"react/compiler-runtime";import{jsx as Ne}from"react/jsx-runtime";import{useLexicalComposerContext as vo}from"@lexical/react/LexicalComposerContext";import{$createParagraphNode as Mo,$getRoot as _o}from"lexical";import"react";var ot="insert-paragraph-at-end",nt=()=>{let t=Lo(2),[e]=vo(),{editorConfig:o}=R();if(o?.admin?.hideInsertParagraphAtEnd)return null;let r;return t[0]!==e?(r=Ne("div",{"aria-label":"Insert Paragraph",className:ot,onClick:()=>{e.update(Ao)},role:"button",tabIndex:0,children:Ne("div",{className:`${ot}-inside`,children:Ne("span",{children:"+"})})}),t[0]=e,t[1]=r):r=t[1],r};function Ao(){let t=Mo();_o().append(t),t.select()}import{c as Bo}from"react/compiler-runtime";import{useLexicalComposerContext as Io}from"@lexical/react/LexicalComposerContext";import*as rt from"react";var it=()=>{let t=Bo(4),{editorConfig:e}=R(),[o]=Io(),r,n;return t[0]!==o||t[1]!==e.features.markdownTransformers?(r=()=>we(o,e.features.markdownTransformers??[]),n=[o,e.features.markdownTransformers],t[0]=o,t[1]=e.features.markdownTransformers,t[2]=r,t[3]=n):(r=t[2],n=t[3]),rt.useEffect(r,n),null};import{useLexicalComposerContext as Oo}from"@lexical/react/LexicalComposerContext";import{$getSelection as Fo,$isRangeSelection as $o,RootNode as Ko}from"lexical";import{useEffect as Ho}from"react";function st(){let[t]=Oo();return Ho(()=>t.registerNodeTransform(Ko,e=>{let o=Fo();if($o(o)){let r=o.anchor.getNode(),n=o.focus.getNode();(!r.isAttached()||!n.isAttached())&&(e.selectEnd(),console.warn("updateEditor: selection has been moved to the end of the editor because the previously selected nodes have been removed and selection wasn't moved to another node. Ensure selection changes after removing/replacing a selected node."))}return!1}),[t]),null}import{useLexicalComposerContext as jo}from"@lexical/react/LexicalComposerContext";import{$getSelection as zo,COMMAND_PRIORITY_LOW as Wo,SELECT_ALL_COMMAND as Yo}from"lexical";import{useEffect as Vo}from"react";function lt(){let[t]=jo();return Vo(()=>t.registerCommand(Yo,()=>{if(zo())return!1;let o=document.activeElement;return o instanceof HTMLInputElement&&o.select(),!0},Wo),[t]),null}import{jsx as U,jsxs as ct}from"react/jsx-runtime";import{useLexicalComposerContext as Uo}from"@lexical/react/LexicalComposerContext.js";import{useTranslation as ut}from"@payloadcms/ui";import{useCallback as qo,useMemo as Jo,useState as Qo}from"react";import"react";import*as dt from"react-dom";import{c as Go}from"react/compiler-runtime";import"react";function at(t,e){let o=Go(4),{maxLength:r,minLength:n}=e,u=r===void 0?75:r,i=n===void 0?1:n,s;return o[0]!==u||o[1]!==i||o[2]!==t?(s=c=>{let{query:d}=c,y="[^"+t+Te+"\\s]",a=new RegExp("(^|\\s|\\()(["+t+"]((?:"+y+"){0,"+u+"}))$").exec(d);if(a!==null){let h=a[1],x=a[3];if(x.length>=i)return{leadOffset:a.index+h.length,matchingString:x,replaceableString:a[2]}}return null},o[0]=u,o[1]=i,o[2]=t,o[3]=s):s=o[3],s}var A="slash-menu-popup";function Xo({isSelected:t,item:e,onClick:o,onMouseEnter:r,ref:n}){let{fieldProps:{featureClientSchemaMap:u,schemaPath:i}}=R(),{i18n:s}=ut(),c=`${A}__item ${A}__item-${e.key}`;t&&(c+=` ${A}__item--selected`);let d=e.key;return e.label&&(d=typeof e.label=="function"?e.label({featureClientSchemaMap:u,i18n:s,schemaPath:i}):e.label),d.length>25&&(d=d.substring(0,25)+"..."),ct("button",{"aria-selected":t,className:c,id:A+"__item-"+e.key,onClick:o,onMouseEnter:r,ref:n,role:"option",tabIndex:-1,type:"button",children:[e?.Icon&&U(e.Icon,{}),U("span",{className:`${A}__item-text`,children:d})]},e.key)}function mt({anchorElem:t=document.body}){let[e]=Uo(),[o,r]=Qo(null),{editorConfig:n}=R(),{i18n:u}=ut(),{fieldProps:{featureClientSchemaMap:i,schemaPath:s}}=R(),c=at("/",{minLength:0}),d=qo(()=>{let l=[];for(let a of n.features.slashMenu.dynamicGroups)if(o){let h=a({editor:e,queryString:o});l=l.concat(h)}return l},[e,o,n?.features]),y=Jo(()=>{let l=[];for(let a of n?.features.slashMenu.groups??[])l.push(a);if(o){l=l.map(h=>{let x=h.items.filter(g=>{let m=g.key;return g.label&&(m=typeof g.label=="function"?g.label({featureClientSchemaMap:i,i18n:u,schemaPath:s}):g.label),new RegExp(o,"gi").exec(m)?!0:g.keywords!=null?g.keywords.some(p=>new RegExp(o,"gi").exec(p)):!1});return x.length?{...h,items:x}:null}),l=l.filter(h=>h!=null);let a=d();for(let h of a){let x=l.find(g=>g.key===h.key);x?l=l.filter(g=>g.key!==h.key):x={...h,items:[]},x?.items?.length&&(x.items=x.items.concat(x.items)),l.push(x)}}return l},[o,n?.features.slashMenu.groups,d,i,u,s]);return U(Le,{anchorElem:t,groups:y,menuRenderFn:(l,{selectedItemKey:a,selectItemAndCleanUp:h,setSelectedItemKey:x})=>l.current&&y.length?dt.createPortal(U("div",{className:A,children:y.map(g=>{let m=g.key;return g.label&&i&&(m=typeof g.label=="function"?g.label({featureClientSchemaMap:i,i18n:u,schemaPath:s}):g.label),ct("div",{className:`${A}__group ${A}__group-${g.key}`,children:[U("div",{className:`${A}__group-title`,children:m}),g.items.map((p,f)=>U(Xo,{index:f,isSelected:a===p.key,item:p,onClick:()=>{x(p.key),h(p)},onMouseEnter:()=>{x(p.key)},ref:C=>{p.ref={current:C}}},p.key))]},g.key)})}),l.current):null,onQueryChange:r,triggerFn:c})}import{c as Zo}from"react/compiler-runtime";import{useLexicalComposerContext as en}from"@lexical/react/LexicalComposerContext";import{TEXT_TYPE_TO_FORMAT as tn,TextNode as on}from"lexical";import{useEffect as nn}from"react";function ft(t){let e=Zo(6),{features:o}=t,[r]=en(),n;e[0]!==r||e[1]!==o.enabledFormats?(n=()=>{let i=rn(o.enabledFormats);if(i.length!==0)return r.registerNodeTransform(on,s=>{i.forEach(c=>{s.hasFormat(c)&&s.toggleFormat(c)})})},e[0]=r,e[1]=o.enabledFormats,e[2]=n):n=e[2];let u;return e[3]!==r||e[4]!==o?(u=[r,o],e[3]=r,e[4]=o,e[5]=u):u=e[5],nn(n,u),null}function rn(t){let e=Object.keys(tn),o=new Set(t);return e.filter(r=>!o.has(r))}import{c as sn}from"react/compiler-runtime";import{jsx as pt}from"react/jsx-runtime";import{useLexicalComposerContext as ln}from"@lexical/react/LexicalComposerContext";import{ContentEditable as an}from"@lexical/react/LexicalContentEditable.js";import{useTranslation as cn}from"@payloadcms/ui";import"react";function gt(t){let e=sn(5),{className:o,editorConfig:r}=t,{t:n}=cn(),[,u]=ln(),{getTheme:i}=u,s;if(e[0]!==o||e[1]!==r?.admin?.placeholder||e[2]!==i||e[3]!==n){let c=i();s=pt(an,{"aria-placeholder":n("lexical:general:placeholder"),className:o??"ContentEditable__root",placeholder:pt("p",{className:c?.placeholder,children:r?.admin?.placeholder??n("lexical:general:placeholder")})}),e[0]=o,e[1]=r?.admin?.placeholder,e[2]=i,e[3]=n,e[4]=s}else s=e[4];return s}var yt=t=>{let e=un(12),{editorConfig:o,editorContainerRef:r,isSmallWidthViewport:n,onChange:u}=t,i=R(),[s]=dn(),c=hn(),[d,y]=Cn(null),l;e[0]===Symbol.for("react.memo_cache_sentinel")?(l=m=>{m!==null&&y(m)},e[0]=l):l=e[0];let a=l,h,x;e[1]!==s||e[2]!==i?(h=()=>{if(!i?.uuid){console.error("Lexical Editor must be used within an EditorConfigProvider");return}i?.parentEditor?.uuid&&i.parentEditor?.registerChild(i.uuid,i);let m=()=>{i.focusEditor(i)},p=()=>{i.blurEditor(i)},f=s.registerCommand(xn,()=>(m(),!0),ht),C=s.registerCommand(yn,()=>(p(),!0),ht);return()=>{f(),C(),i.parentEditor?.unregisterChild?.(i.uuid)}},x=[s,i],e[1]=s,e[2]=i,e[3]=h,e[4]=x):(h=e[3],x=e[4]),En(h,x);let g;return e[5]!==o||e[6]!==r||e[7]!==d||e[8]!==c||e[9]!==n||e[10]!==u?(g=te(q.Fragment,{children:[o.features.plugins?.map(bn),te("div",{className:"editor-container",ref:r,children:[o.features.plugins?.map(Nn),E(gn,{contentEditable:E("div",{className:"editor-scroller",children:E("div",{className:"editor",ref:a,children:E(gt,{editorConfig:o})})}),ErrorBoundary:mn}),E(st,{}),c&&E(nt,{}),E(Fe,{}),E(Be,{}),E(ft,{features:o.features}),E(lt,{}),c&&E(pn,{ignoreSelectionChange:!0,onChange:(m,p,f)=>{(!f.has("focus")||f.size>1)&&u?.(m,p,f)}}),d&&te(q.Fragment,{children:[!n&&c&&te(q.Fragment,{children:[o.admin?.hideDraggableBlockElement?null:E(tt,{anchorElem:d}),o.admin?.hideAddBlockButton?null:E(Ye,{anchorElem:d})]}),o.features.plugins?.map(m=>{if(m.position==="floatingAnchorElem"&&!(m.desktopOnly===!0&&n))return E(K,{anchorElem:d,clientProps:m.clientProps,plugin:m},m.key)}),c&&E(q.Fragment,{children:E(mt,{anchorElem:d})})]}),c&&te(q.Fragment,{children:[E(fn,{}),o?.features?.markdownTransformers?.length>0&&E(it,{})]}),o.features.plugins?.map(Pn),o.features.plugins?.map(Sn)]}),o.features.plugins?.map(Rn)]}),e[5]=o,e[6]=r,e[7]=d,e[8]=c,e[9]=n,e[10]=u,e[11]=g):g=e[11],g};function bn(t){if(t.position==="aboveContainer")return E(K,{clientProps:t.clientProps,plugin:t},t.key)}function Nn(t){if(t.position==="top")return E(K,{clientProps:t.clientProps,plugin:t},t.key)}function Pn(t){if(t.position==="normal")return E(K,{clientProps:t.clientProps,plugin:t},t.key)}function Sn(t){if(t.position==="bottom")return E(K,{clientProps:t.clientProps,plugin:t},t.key)}function Rn(t){if(t.position==="belowContainer")return E(K,{clientProps:t.clientProps,plugin:t},t.key)}var Et=({children:t,providers:e})=>{if(!e?.length)return t;let o=e[0];return e.length>1?F(o,{children:F(Et,{providers:e.slice(1),children:t})}):F(o,{children:t})},Ct=t=>{let{composerKey:e,editorConfig:o,fieldProps:r,isSmallWidthViewport:n,onChange:u,readOnly:i,value:s}=t,c=R(),d=kn(),y=xt.useRef(null),l=Tn(()=>{if(s&&typeof s!="object")throw new Error("The value passed to the Lexical editor is not an object. This is not supported. Please remove the data from the field and start again. This is the value that was passed in: "+JSON.stringify(s));if(s&&Array.isArray(s)&&!("root"in s))throw new Error("You have tried to pass in data from the old Slate editor to the new Lexical editor. The data structure is different, thus you will have to migrate your data. We offer a one-line migration script which migrates all your rich text fields: https://payloadcms.com/docs/lexical/migration#migration-via-migration-script-recommended");if(s&&"jsonContent"in s)throw new Error("You have tried to pass in data from payload-plugin-lexical. The data structure is different, thus you will have to migrate your data. Migration guide: https://payloadcms.com/docs/lexical/migration#migrating-from-payload-plugin-lexical");return{editable:i!==!0,editorState:s!=null?JSON.stringify(s):void 0,namespace:o.lexical.namespace,nodes:Me({editorConfig:o}),onError:a=>{throw a},theme:o.lexical.theme}},[o]);return l?F(wn,{initialConfig:l,children:F(Re,{editorConfig:o,editorContainerRef:y,fieldProps:r,parentContext:c?.editDepth===d?c:void 0,children:F(Et,{providers:o.features.providers,children:F(yt,{editorConfig:o,editorContainerRef:y,isSmallWidthViewport:n,onChange:u})})})},e+l.editable):F("p",{children:"Loading..."})};var pe="rich-text-lexical",$n=t=>{let{editorConfig:e,field:o,field:{admin:{className:r,description:n,readOnly:u}={},label:i,localized:s,required:c},path:d,readOnly:y,validate:l}=t,a=y||u,h=Mn(),x=Pt((M,Q)=>typeof l=="function"?l(M,{...Q,required:c}):!0,[l,c]),{customComponents:{AfterInput:g,BeforeInput:m,Description:p,Error:f,Label:C}={},disabled:k,initialValue:S,path:b,setValue:w,showError:N,value:v}=An({potentiallyStalePath:d,validate:x}),B=a||k,[T,D]=Rt(!1),[J,he]=Rt(),ye=Nt.useRef(S),I=Nt.useRef(v);St(()=>{let M=()=>{let Q=window.matchMedia("(max-width: 768px)").matches;Q!==T&&D(Q)};return M(),window.addEventListener("resize",M),()=>{window.removeEventListener("resize",M)}},[T]);let Pe=[pe,"field-type",r,N&&"error",B&&`${pe}--read-only`,e?.admin?.hideGutter!==!0&&!T?`${pe}--show-gutter`:null].filter(Boolean).join(" "),oe=`${b}.${h}`,L=ke(),P=Pt(M=>{L(()=>{let Se=M.toJSON();I.current=Se,w(Se)})},[w,L]),wt=On(()=>Bn(o),[o]),kt=_n(M=>{I.current!==v&&!In(I.current!=null?JSON.parse(JSON.stringify(I.current)):I.current,v)&&(ye.current=M,I.current=v,he(new Date))});return St(()=>{Object.is(S,ye.current)||kt(S)},[S]),ge("div",{className:Pe,style:wt,children:[$(bt,{CustomComponent:f,Fallback:$(Ln,{path:b,showError:N})}),C||$(vn,{label:i,localized:s,path:b,required:c}),ge("div",{className:`${pe}__wrap`,children:[ge(Fn,{fallbackRender:Kn,onReset:()=>{},children:[m,$(Ct,{composerKey:oe,editorConfig:e,fieldProps:t,isSmallWidthViewport:T,onChange:P,readOnly:B,value:v},JSON.stringify({path:b,rerenderProviderKey:J})),g]}),$(bt,{CustomComponent:p,Fallback:$(Dn,{description:n,path:b})})]})]},oe)};function Kn({error:t}){return ge("div",{className:"errorBoundary",role:"alert",children:[$("p",{children:"Something went wrong:"}),$("pre",{style:{color:"red"},children:t.message})]})}var _s=$n;export{_s as RichText};
2
- //# sourceMappingURL=Field-43GHEACW.js.map