'use client' import * as React from 'react' import type { ContentEditorFocusBlock } from '@admin/utils/editor/content-editor-focus-block' import type { Editor } from '@tiptap/react' import { getContentEditorFocusBlock } from '@admin/utils/editor/get-content-editor-focus-block' // Tracks the block that holds the cursor in the phone focus view: its position inside the editor // frame (re-measured as the content scrolls or resizes) and whether the editor still has focus. // Block actions prevent the pointer default, but iOS Safari still blurs the editor on a tap, which // unmounted the toolbar before its click landed. A blur that follows a press inside // `[data-content-editor-chrome]` is ignored, so the chrome only hides when the person taps outside. export function useContentEditorFocusBlock(editor: Editor | null) { const containerRef = React.useRef(null) const [block, setBlock] = React.useState(null) const [isFocused, setIsFocused] = React.useState(false) const isChromePressRef = React.useRef(false) React.useEffect(() => { if (!editor) return const measure = () => { const container = containerRef.current setBlock(container ? getContentEditorFocusBlock(editor, container) : null) } const handleFocus = () => { setIsFocused(true) measure() } const handleBlur = () => { if (!isChromePressRef.current) setIsFocused(false) } const handlePointerDown = (event: PointerEvent) => { isChromePressRef.current = event.target instanceof Element && event.target.closest('[data-content-editor-chrome]') !== null } const scrollElement = editor.view.dom.parentElement document.addEventListener('pointerdown', handlePointerDown, { capture: true }) const resizeObserver = new ResizeObserver(measure) resizeObserver.observe(editor.view.dom) scrollElement?.addEventListener('scroll', measure, { passive: true }) editor.on('selectionUpdate', measure) editor.on('update', measure) editor.on('focus', handleFocus) editor.on('blur', handleBlur) setIsFocused(editor.isFocused) measure() return () => { resizeObserver.disconnect() document.removeEventListener('pointerdown', handlePointerDown, { capture: true }) scrollElement?.removeEventListener('scroll', measure) editor.off('selectionUpdate', measure) editor.off('update', measure) editor.off('focus', handleFocus) editor.off('blur', handleBlur) } }, [editor]) return { block, containerRef, isFocused } }