import React, { useCallback, useEffect, useRef } from 'react'; import { sanitizeInlineHtml, inlineHtmlToText, isPlainInlineHtml, textToInlineHtml, resolveInlineHtml, markExternalLinks, } from '../../utils/inline-html'; interface InlineTextProps { text?: string; html?: string; } const SHORTCUTS: Record = { b: 'bold', i: 'italic', u: 'underline' }; /** * contentEditable wiring shared by Heading and TextBlock (#46). * * - The DOM is written imperatively (innerHTML) only while the node is NOT * selected and has no pending edit, so the caret is never reset mid-typing. * - An edit is committed ONCE -- on blur, or on deselect if no blur came * first -- as a single `setProp` (= one undo step) that stores BOTH the * sanitised `html` and its plain `text` mirror. Unmarked content stores * `html: ''` so legacy nodes keep their legacy shape. * - mod+b/i/u is handled locally: the global shortcut dispatcher skips * contentEditable targets. */ export function useInlineEditable( text: string, html: string, selected: boolean, setProp: (cb: (p: InlineTextProps) => void) => void, ) { const elRef = useRef(null); const pendingRef = useRef(false); const commit = useCallback(() => { if (!pendingRef.current) return; pendingRef.current = false; const el = elRef.current; if (!el) return; markExternalLinks(el); const clean = sanitizeInlineHtml(el.innerHTML); const nextText = inlineHtmlToText(clean); const nextHtml = isPlainInlineHtml(clean) ? '' : clean; setProp((p) => { p.html = nextHtml; p.text = nextText; }); }, [setProp]); // Deselect without a blur (e.g. Escape, programmatic selection change). useEffect(() => { if (!selected) commit(); }, [selected, commit]); useEffect(() => { if (elRef.current && !selected && !pendingRef.current) { elRef.current.innerHTML = resolveInlineHtml(text, html) ?? textToInlineHtml(text || ''); } }, [text, html, selected]); const onInput = useCallback(() => { pendingRef.current = true; }, []); const onKeyDown = useCallback((e: React.KeyboardEvent) => { if (!(e.metaKey || e.ctrlKey) || e.shiftKey || e.altKey) return; const cmd = SHORTCUTS[e.key.toLowerCase()]; if (!cmd) return; if (typeof document.execCommand !== 'function') return; e.preventDefault(); document.execCommand(cmd); pendingRef.current = true; }, []); return { elRef, onBlur: commit, onInput, onKeyDown }; }