"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { EditorContent, useEditor, type Editor } from "@tiptap/react"; import StarterKit from "@tiptap/starter-kit"; import Underline from "@tiptap/extension-underline"; import { TextStyle } from "@tiptap/extension-text-style"; import FontFamily from "@tiptap/extension-font-family"; import Color from "@tiptap/extension-color"; import Highlight from "@tiptap/extension-highlight"; import TiptapImage from "@tiptap/extension-image"; import Placeholder from "@tiptap/extension-placeholder"; import Link from "@tiptap/extension-link"; import TextAlign from "@tiptap/extension-text-align"; import { Table } from "@tiptap/extension-table"; import TableRow from "@tiptap/extension-table-row"; import TableHeader from "@tiptap/extension-table-header"; import TableCell from "@tiptap/extension-table-cell"; import { toast } from "sonner"; import { cn } from "@/lib/utils"; import type { KriEditorCommand, KriEditorProps, ToolbarState } from "./types"; import { resolveUploadUrl } from "./types"; import { FontSize } from "./extensions/font-size"; import { Div } from "./extensions/div"; import { ImageMap, ImageWithMap } from "./extensions/image-map"; import { compressImage } from "./utils/imageCompression"; import { sanitizeHtml } from "./utils/sanitizeHtml"; import { preserveEmptyParagraphs } from "./utils/emptyParagraph"; import { DEFAULT_FONT_FAMILY_OPTIONS } from "./utils/fontFamilyOptions"; import { formatHtmlSource } from "./utils/formatHtml"; import { applyLinkPreviewClass, KRI_EDITOR_LINK_CLASS } from "./utils/linkPreview"; import { Toolbar } from "./toolbar/Toolbar"; import { useDebouncedChange } from "./hooks/useDebouncedChange"; import { useTextareaInsert } from "./hooks/useTextareaInsert"; type ViewMode = "wysiwyg" | "html"; function getToolbarState(editor: Editor): ToolbarState { const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; fontFamily?: string | null; color?: string | null }; const hl = editor.getAttributes("highlight") as { color?: string | null }; const fontFamily = (ts?.fontFamily ?? null) as string | null; const fontSize = (ts?.fontSize ?? "16px") as string; const textColor = (ts?.color ?? null) as string | null; const highlightColor = (hl?.color ?? null) as string | null; const align = (editor.isActive({ textAlign: "center" }) && "center") || (editor.isActive({ textAlign: "right" }) && "right") || "left"; return { fontFamily, fontSize, textColor, highlightColor, isBold: editor.isActive("bold"), isItalic: editor.isActive("italic"), isUnderline: editor.isActive("underline"), isStrike: editor.isActive("strike"), align, isBulletList: editor.isActive("bulletList"), isOrderedList: editor.isActive("orderedList"), isLink: editor.isActive("link"), inTable: editor.isActive("table"), }; } export function KriEditorWysiwyg(props: KriEditorProps) { const { label, value, onChange, placeholder = "내용을 입력하세요…", className, showPreview = false, previewClassName, mode = "wysiwyg", debounceMs = 350, onImageUpload, onImageUploadError, maxImageBytes = 5 * 1024 * 1024, imageMaxWidth = 1600, imageMaxHeight = 1600, imageQuality = 0.82, imageMimeType = "image/webp", allowBase64 = false, sanitizeHtml: sanitizeHtmlOpt = true, toolbar = {}, fontFamilyOptions = DEFAULT_FONT_FAMILY_OPTIONS, editorExtensions = [], allowedCustomHtml, enableImageMap = false, htmlSanitizer, getWysiwygCompatibility, transformPreviewHtml, } = props; const showHtmlToggle = mode === "both"; const LINK_HTML_ATTRS = { rel: "noopener noreferrer", target: "_blank", } as const; const { scheduleChange, flushChange, optimisticHtmlRef } = useDebouncedChange(onChange, debounceMs); const fileRef = useRef(null); const htmlTextareaRef = useRef(null); const htmlTi = useTextareaInsert(htmlTextareaRef); const { insertText: insertTextareaText } = htmlTi; const getCompatibility = useCallback( (html: string) => getWysiwygCompatibility?.(html) ?? { compatible: true }, [getWysiwygCompatibility], ); const initialView: ViewMode = showHtmlToggle && !getCompatibility(value ?? "").compatible ? "html" : "wysiwyg"; const [view, setView] = useState(initialView); const [previewSource, setPreviewSource] = useState(value ?? ""); const viewRef = useRef(initialView); useEffect(() => { viewRef.current = view; }, [view]); const htmlDraftRef = useRef(value ?? ""); const canImageUpload = Boolean(onImageUpload); const selectionRef = useRef<{ from: number; to: number } | null>(null); const [tb, setTb] = useState({ fontFamily: null, fontSize: "16px", textColor: null, highlightColor: null, isBold: false, isItalic: false, isUnderline: false, isStrike: false, align: "left", isBulletList: false, isOrderedList: false, isLink: false, inTable: false, }); const editor = useEditor({ immediatelyRender: false, extensions: [ StarterKit.configure({ heading: false, blockquote: false, codeBlock: false, code: false, }), Underline, TextStyle, FontSize, FontFamily, Color, Highlight.configure({ multicolor: true }), Div, Link.configure({ autolink: true, openOnClick: false, linkOnPaste: true, HTMLAttributes: { class: KRI_EDITOR_LINK_CLASS, ...LINK_HTML_ATTRS, }, }), TextAlign.configure({ types: ["paragraph", "divBlock"] }), Table.configure({ resizable: true }), TableRow, TableHeader, TableCell, (enableImageMap ? ImageWithMap : TiptapImage).configure({ inline: true, allowBase64, HTMLAttributes: { class: "max-w-full h-auto", "data-kri-image": "true", }, resize: { enabled: true, alwaysPreserveAspectRatio: true, }, }), ...(enableImageMap ? [ImageMap] : []), Placeholder.configure({ placeholder }), ...editorExtensions, ], content: value || "

", onUpdate: ({ editor }) => { if (viewRef.current === "html") return; const nextHtml = editor.getHTML(); setPreviewSource(nextHtml); scheduleChange(preserveEmptyParagraphs(nextHtml)); }, editorProps: { attributes: { class: cn( "min-h-[180px] max-h-[420px] overflow-y-auto px-3 py-2 focus:outline-none", "[&_p]:my-2 [&_p:first-child]:mt-0 [&_p:last-child]:mb-0", "[&_ul]:list-disc [&_ul]:pl-6 [&_ol]:list-decimal [&_ol]:pl-6", "[&_li]:my-1", "[&_a]:text-blue-600 [&_a]:underline [&_a]:underline-offset-2", "[&_table]:w-full [&_table]:border-collapse [&_table]:table-fixed", "[&_th]:border [&_th]:bg-muted [&_th]:p-2 [&_th]:text-left", "[&_td]:border [&_td]:p-2 [&_td]:align-top [&_td]:min-w-[90px]" ), }, handleDOMEvents: { click: (view, event) => { const e = event as MouseEvent; // Alt + 좌클릭만 if (!e.altKey || e.button !== 0) return false; // 이미지(또는 리사이즈 컨테이너) 클릭일 때만 const target = e.target as HTMLElement | null; const isImageClick = !!target?.closest?.("img, [data-resize-container]"); if (!isImageClick) return false; // 1) 문서 상태에서 link mark의 href 찾기 (NodeView/리사이즈 DOM에서도 안전) const pos = view.posAtCoords({ left: e.clientX, top: e.clientY }); const linkType = view.state.schema.marks.link; let href: string | undefined; if (pos && linkType) { const $pos = view.state.doc.resolve(pos.pos); const pickHref = (marks: readonly { type: unknown; attrs?: Record }[] | null | undefined) => { const mark = marks?.find((candidate) => candidate.type === linkType); const value = mark?.attrs?.href; return typeof value === "string" ? value : undefined; }; href = pickHref($pos.marks()) || pickHref($pos.nodeAfter?.marks) || pickHref($pos.nodeBefore?.marks); } // 2) DOM fallback (실제 가 있는 경우) if (!href) { const a = target?.closest?.("a") as HTMLAnchorElement | null; if (a?.href) href = a.href; } if (!href) return false; // 링크 열기 + 에디터 클릭 처리(커서 이동 등) 막기 e.preventDefault(); e.stopPropagation(); window.open(href, LINK_HTML_ATTRS.target, LINK_HTML_ATTRS.rel.replaceAll(" ",",")); return true; }, }, }, }, []); const restoreSelection = useCallback(() => { if (!editor) return; const s = selectionRef.current; if (!s) return; editor.commands.setTextSelection(s); }, [editor]); const setFontSize = useCallback( (px: string) => { if (!editor) return; restoreSelection(); editor.chain().focus().setFontSize(px).run(); }, [editor, restoreSelection] ); const setFontFamily = useCallback( (value: string) => { if (!editor) return; restoreSelection(); if (!value) { editor.chain().focus().unsetFontFamily().run(); return; } editor.chain().focus().setFontFamily(value).run(); }, [editor, restoreSelection] ); const setTextColor = useCallback( (hex: string) => { if (!editor) return; restoreSelection(); editor.chain().focus().setColor(hex).run(); }, [editor, restoreSelection] ); const unsetTextColor = useCallback(() => { if (!editor) return; restoreSelection(); editor.chain().focus().unsetColor().run(); }, [editor, restoreSelection]); const setHighlight = useCallback( (hex: string) => { if (!editor) return; restoreSelection(); editor.chain().focus().setHighlight({ color: hex }).run(); }, [editor, restoreSelection] ); const unsetHighlight = useCallback(() => { if (!editor) return; restoreSelection(); editor.chain().focus().unsetHighlight().run(); }, [editor, restoreSelection]); const normalizeLinkUrl = (raw: string): string => { const trimmed = raw.trim(); if (!trimmed) return ""; if (/^https?:\/\//i.test(trimmed) || /^mailto:/i.test(trimmed) || /^tel:/i.test(trimmed)) { return trimmed; } return `https://${trimmed}`; }; const setLink = useCallback((url: string) => { if (!editor) return; restoreSelection(); const normalized = normalizeLinkUrl(url); if (!normalized) return; editor.chain().focus().extendMarkRange("link").setLink({ href: normalized }).run(); }, [editor, restoreSelection]); const unsetLink = useCallback(() => { if (!editor) return; restoreSelection(); editor.chain().focus().extendMarkRange("link").unsetLink().run(); }, [editor, restoreSelection]); const insertTable = useCallback(() => { if (!editor) return; restoreSelection(); editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(); }, [editor, restoreSelection]); const addRow = useCallback(() => { if (!editor) return; restoreSelection(); if (!editor.isActive("table")) { toast.message("표 안에서 셀을 클릭한 뒤 사용해 주세요."); return; } const ok = editor.chain().focus().addRowAfter().run(); if (!ok) toast.error("행 추가에 실패했습니다."); }, [editor, restoreSelection]); const addColumn = useCallback(() => { if (!editor) return; restoreSelection(); if (!editor.isActive("table")) { toast.message("표 안에서 셀을 클릭한 뒤 사용해 주세요."); return; } const ok = editor.chain().focus().addColumnAfter().run(); if (!ok) toast.error("열 추가에 실패했습니다."); }, [editor, restoreSelection]); const deleteTable = useCallback(() => { if (!editor) return; restoreSelection(); if (!editor.isActive("table")) return; editor.chain().focus().deleteTable().run(); }, [editor, restoreSelection]); const handlePickImage = useCallback(() => { if (!canImageUpload) return; fileRef.current?.click(); }, [canImageUpload]); const handleFile = useCallback( async (e: React.ChangeEvent) => { try { const file = e.target.files?.[0]; e.target.value = ""; if (!file || !editor) return; if (!canImageUpload || !onImageUpload) return; if (!file.type.startsWith("image/")) { toast.error("이미지 파일만 업로드할 수 있습니다."); return; } const compressed = await compressImage(file, { maxBytes: maxImageBytes, maxWidth: imageMaxWidth, maxHeight: imageMaxHeight, mimeType: imageMimeType, quality: imageQuality, }); if (compressed.size > maxImageBytes) { toast.error("이미지 용량이 제한을 초과합니다.", { description: `최대 ${(maxImageBytes / (1024 * 1024)).toFixed(0)}MB`, }); return; } const url = resolveUploadUrl(await onImageUpload(compressed)); if (!url || typeof url !== "string") { toast.error("이미지 업로드 응답이 올바르지 않습니다."); return; } restoreSelection(); editor.chain().focus().setImage({ src: url }).run(); } catch (err) { if(onImageUploadError){ onImageUploadError(err); }else{ toast.error("이미지 업로드에 실패했습니다."); console.error(err); } } }, [ editor, canImageUpload, onImageUpload, maxImageBytes, imageMaxWidth, imageMaxHeight, imageMimeType, imageQuality, restoreSelection, ] ); const onToggleHtmlView = useCallback(() => { if (!editor) return; if (viewRef.current === "wysiwyg") { const raw = editor.getHTML(); htmlDraftRef.current = raw; setView("html"); // WYSIWYG에서 막 넘어온, 사용자가 직접 타이핑하지 않은 HTML이므로 // 화면 표시용으로만 정렬한다(onChange는 호출하지 않음 — 저장값은 그대로 유지). formatHtmlSource(raw) .then((formatted) => { if (viewRef.current !== "html" || htmlDraftRef.current !== raw) return; htmlDraftRef.current = formatted; if (htmlTextareaRef.current) htmlTextareaRef.current.value = formatted; setPreviewSource(formatted); }) .catch(() => {}); return; } const raw = htmlDraftRef.current; const compatibility = getCompatibility(raw); if (!compatibility.compatible) { toast.message(compatibility.reason ?? "현재 HTML은 WYSIWYG로 전환할 수 없습니다."); return; } const safe = htmlSanitizer ? htmlSanitizer(raw) : sanitizeHtmlOpt ? sanitizeHtml(raw, allowedCustomHtml) : raw; editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } }); flushChange(preserveEmptyParagraphs(editor.getHTML())); setView("wysiwyg"); }, [allowedCustomHtml, editor, flushChange, getCompatibility, htmlSanitizer, sanitizeHtmlOpt]); const formatHtmlView = useCallback(async () => { try { const formatted = await formatHtmlSource(htmlDraftRef.current); htmlDraftRef.current = formatted; if (htmlTextareaRef.current) htmlTextareaRef.current.value = formatted; setPreviewSource(formatted); scheduleChange(preserveEmptyParagraphs(formatted)); } catch (err) { toast.error("HTML 정렬에 실패했습니다."); console.error(err); } }, [scheduleChange]); useEffect(() => { if (!editor) return; const sync = () => { selectionRef.current = { from: editor.state.selection.from, to: editor.state.selection.to }; setTb(getToolbarState(editor)); }; sync(); editor.on("selectionUpdate", sync); editor.on("transaction", sync); return () => { editor.off("selectionUpdate", sync); editor.off("transaction", sync); }; }, [editor]); useEffect(() => { if (!props.onEditorReady || !editor) return; if (viewRef.current === "html") { props.onEditorReady(htmlTextareaRef.current); } else { props.onEditorReady(editor); } }, [editor, view, props.onEditorReady]); useEffect(() => { setPreviewSource(value ?? ""); if (!editor) return; if (value == null) return; const compatibility = getCompatibility(value); if (showHtmlToggle && !compatibility.compatible) { htmlDraftRef.current = value; if (htmlTextareaRef.current) htmlTextareaRef.current.value = value; if (viewRef.current !== "html") { viewRef.current = "html"; setView("html"); } return; } if (viewRef.current === "html") { if (getWysiwygCompatibility && value !== optimisticHtmlRef.current && value !== htmlDraftRef.current) { htmlDraftRef.current = value; if (htmlTextareaRef.current) htmlTextareaRef.current.value = value; } return; } // 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해 // 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정. const normalizedValue = value || "

"; const current = editor.getHTML(); if (normalizedValue !== current && normalizedValue !== optimisticHtmlRef.current) { // 외부에서 본문이 변경된 경우에만 기존 editor 문서를 갱신한다. editor.commands.setContent(normalizedValue, { emitUpdate: false, parseOptions: {preserveWhitespace: "full"}, }); // resize가 활성화된 TipTap 이미지 NodeView는 노드의 src 변경을 기존 DOM에 반영하지 않는다. // editor 전체 대신 NodeView만 다시 생성해 이미지를 갱신하고 편집 포커스는 유지한다. if (normalizedValue.includes(" { if (!editor) return; const onBlur = () => { if (viewRef.current === "html") flushChange(preserveEmptyParagraphs(htmlDraftRef.current)); else flushChange(preserveEmptyParagraphs(editor.getHTML())); }; editor.on("blur", onBlur); return () => { editor.off("blur", onBlur); }; }, [editor, flushChange]); const command = useMemo( () => ({ focus: () => { if (viewRef.current === "html") htmlTextareaRef.current?.focus(); else editor?.chain().focus().run(); }, insertText: (text: string) => { if (viewRef.current === "html") { const current = htmlDraftRef.current ?? ""; insertTextareaText( text, current, (next) => { htmlDraftRef.current = next; if (htmlTextareaRef.current) htmlTextareaRef.current.value = next; }, (next) => { flushChange(next); } ); return; } if (!editor) return; restoreSelection(); editor.chain().focus().insertContent(text).run(); flushChange(preserveEmptyParagraphs(editor.getHTML())); }, }), [editor, restoreSelection, flushChange, insertTextareaText] ); useEffect(() => { if (!props.onCommandReady) return; // editor가 아직 없으면 null 전달 if (!editor) { props.onCommandReady(null); return; } props.onCommandReady(command); return () => props.onCommandReady?.(null); }, [command, editor, props.onCommandReady]); const previewHtml = useMemo(() => { const preserved = preserveEmptyParagraphs(previewSource); const sanitized = htmlSanitizer ? htmlSanitizer(preserved) : sanitizeHtmlOpt ? sanitizeHtml(preserved, allowedCustomHtml) : preserved; const withLinkStyle = applyLinkPreviewClass(sanitized); return transformPreviewHtml ? transformPreviewHtml(withLinkStyle) : withLinkStyle; }, [allowedCustomHtml, htmlSanitizer, previewSource, sanitizeHtmlOpt, transformPreviewHtml]); const wysiwygCompatibility = useMemo( () => getCompatibility(view === "html" ? previewSource : (editor?.getHTML() ?? previewSource)), [editor, getCompatibility, previewSource, view], ); if (!editor) { return (
{label?.trim() ?
{label}
: null}
에디터 로딩 중…
); } return (
{label?.trim() ?
{label}
: null} {toolbar !== false ? (
) : null} {view === "wysiwyg" ? ( ) : (