'use client' // oxlint-disable react/refs -- `latestMarkdownRef` is both the synchronous markdown buffer that // callbacks write and the value rendered as `sourceValue`. Splitting it into state changes when the // buffer is observable and risks the Markdown round-trip, so it needs a verified refactor. import * as React from 'react' import type { ContentEditorMode } from '@admin/utils/editor/content-editor-mode' import type { ContentEditorSelectionRequest } from '@admin/utils/editor/content-editor-selection-request' import type { Editor } from '@tiptap/react' import { appendTrailingParagraph } from '@admin/utils/editor/append-trailing-paragraph' import { docPositionFromPlainTextOffset } from '@admin/utils/editor/doc-position-from-plain-text-offset' import { getContentEditorExtensions } from '@admin/utils/editor/get-content-editor-extensions' import { getPlainTextOffsetBeforeDocPosition } from '@admin/utils/editor/get-plain-text-offset-before-doc-position' import { getPlainTextOffsetBeforeMarkdownOffset } from '@admin/utils/editor/get-plain-text-offset-before-markdown-offset' import { markdownOffsetFromPlainTextOffset } from '@admin/utils/editor/markdown-offset-from-plain-text-offset' import { normalizeEditorMarkdown } from '@admin/utils/editor/normalize-editor-markdown' import { prepareMarkdownForRichMode } from '@admin/utils/editor/prepare-markdown-for-rich-mode' import { removeTrailingEmptyParagraph } from '@admin/utils/editor/remove-trailing-empty-paragraph' import { useEditor } from '@tiptap/react' import { flushSync } from 'react-dom' import { useContentEditorSlashMenu } from './use-content-editor-slash-menu' export interface UseContentEditorOptions { value: string onChange?: (value: string) => void placeholder?: string disabled: boolean defaultMode: ContentEditorMode } export function useContentEditor({ value, onChange, placeholder, disabled, defaultMode }: UseContentEditorOptions) { const [mode, setMode] = React.useState(defaultMode) const [isFocusViewOpen, setIsFocusViewOpen] = React.useState(false) const [sourceSelectionRequest, setSourceSelectionRequest] = React.useState(null) const latestMarkdownRef = React.useRef(value) const lastValuePropRef = React.useRef(value) const pendingRichSelectionOffsetRef = React.useRef(null) const sourceSelectionRef = React.useRef(0) const isInternalChange = React.useRef(false) const isSyncingRichContent = React.useRef(false) const editorRef = React.useRef(null) const isSlashMenuOpenRef = React.useRef(false) const { activeSlashIndex, closeSlashMenu, dismissSlashMenu, filteredSlashCommands, handleSlashKeyDown, selectSlashCommand, setActiveSlashIndex, setSlashSearch, slashMenu, slashSearchQuery, updateSlashMenu } = useContentEditorSlashMenu(editorRef) if (value !== lastValuePropRef.current) { lastValuePropRef.current = value latestMarkdownRef.current = value } const emitChange = React.useCallback( (nextValue: string) => { latestMarkdownRef.current = nextValue onChange?.(nextValue) }, [onChange] ) const editor = useEditor({ immediatelyRender: false, editorProps: { attributes: { autocomplete: 'off', autocorrect: 'off', autocapitalize: 'off', class: 'simple-editor content-editor-prose prose prose-sm max-w-none focus:outline-none p-6' }, handleKeyDown: (_view, event) => handleSlashKeyDown(event) }, extensions: getContentEditorExtensions(placeholder), content: prepareMarkdownForRichMode(value), contentType: 'markdown', editable: !disabled, onUpdate: ({ editor: nextEditor, transaction }) => { if (isSyncingRichContent.current || transaction.getMeta('preventUpdate')) { updateSlashMenu(nextEditor) return } const nextValue = normalizeEditorMarkdown(nextEditor.getMarkdown()) isInternalChange.current = true emitChange(nextValue) updateSlashMenu(nextEditor) }, onSelectionUpdate: ({ editor: nextEditor }) => updateSlashMenu(nextEditor), onBlur: ({ event }) => { const nextFocusTarget = event.relatedTarget if (isSlashMenuOpenRef.current && !nextFocusTarget) return if ( nextFocusTarget instanceof Element && nextFocusTarget.closest('[data-content-editor-slash-menu]') ) { return } closeSlashMenu() } }) React.useEffect(() => { editorRef.current = editor isSlashMenuOpenRef.current = slashMenu !== null }) const syncRichContent = React.useCallback( (nextValue: string = latestMarkdownRef.current, selectionOffset?: number) => { if (!editor) return null const normalizedMarkdown = normalizeEditorMarkdown(editor.getMarkdown()) if (normalizedMarkdown !== nextValue) { isSyncingRichContent.current = true try { editor.commands.setContent(prepareMarkdownForRichMode(nextValue), { contentType: 'markdown', emitUpdate: false }) } finally { queueMicrotask(() => { isSyncingRichContent.current = false }) } } if (selectionOffset !== undefined) { const plainTextOffset = getPlainTextOffsetBeforeMarkdownOffset(nextValue, selectionOffset) const position = docPositionFromPlainTextOffset(editor.state.doc, plainTextOffset) editor.commands.setTextSelection(position) return position } return null }, [editor] ) React.useEffect(() => { if (!editor || mode === 'source') return if (isInternalChange.current) { isInternalChange.current = false return } syncRichContent(latestMarkdownRef.current) }, [editor, mode, syncRichContent]) React.useEffect(() => { editor?.setEditable(!disabled, false) }, [disabled, editor]) React.useEffect(() => { if (!editor || mode !== 'rich') return const selectionOffset = pendingRichSelectionOffsetRef.current if (selectionOffset === null) return pendingRichSelectionOffsetRef.current = null const animationFrame = requestAnimationFrame(() => { const position = syncRichContent(latestMarkdownRef.current, selectionOffset) if (position !== null) { editor.commands.focus(position, { scrollIntoView: true }) return } editor.commands.focus(undefined, { scrollIntoView: true }) }) return () => cancelAnimationFrame(animationFrame) }, [editor, mode, syncRichContent]) const handleSourceSelectionChange = React.useCallback((offset: number) => { sourceSelectionRef.current = offset }, []) const handleSourceChange = React.useCallback( (nextValue: string) => { emitChange(nextValue) }, [emitChange] ) const handleModeChange = React.useCallback(() => { if (mode === 'source') { pendingRichSelectionOffsetRef.current = sourceSelectionRef.current setMode('rich') return } if (editor) { const plainTextOffset = getPlainTextOffsetBeforeDocPosition( editor.state.doc, editor.state.selection.from ) const mappedOffset = markdownOffsetFromPlainTextOffset( latestMarkdownRef.current, plainTextOffset ) sourceSelectionRef.current = mappedOffset setSourceSelectionRequest((current) => ({ id: (current?.id ?? 0) + 1, offset: mappedOffset })) } setMode('source') }, [editor, mode]) // Opening the phone focus view mounts it synchronously (`flushSync`) and then focuses an empty // paragraph at the end, all inside the tap, because iOS only raises the keyboard for a focus // made during the gesture. Closing drops that paragraph again if nothing was typed into it. const openFocusView = React.useCallback(() => { if (!editor) return flushSync(() => setIsFocusViewOpen(true)) if (mode !== 'rich' || !editor.isEditable) return appendTrailingParagraph(editor) editor.view.focus() }, [editor, mode]) const closeFocusView = React.useCallback(() => { if (editor && mode === 'rich') removeTrailingEmptyParagraph(editor) setIsFocusViewOpen(false) }, [editor, mode]) return { activeSlashIndex, closeFocusView, isFocusViewOpen, openFocusView, editor, filteredSlashCommands, handleModeChange, handleSourceChange, handleSourceSelectionChange, mode, closeSlashMenu, dismissSlashMenu, selectSlashCommand, setActiveSlashIndex, setSlashSearch, slashMenu, slashSearchQuery, sourceValue: latestMarkdownRef.current, sourceSelectionRequest, syncRichContent } }