801 lines
26 KiB
TypeScript
801 lines
26 KiB
TypeScript
"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";
|
|
import { useImageMapOverlay } from "./hooks/useImageMapOverlay";
|
|
|
|
type ViewMode = "wysiwyg" | "html";
|
|
|
|
type ToolbarEndSlotProps = Pick<KriEditorProps, "renderToolbarEnd"> & {
|
|
editor: Editor;
|
|
command: KriEditorCommand;
|
|
view: ViewMode;
|
|
};
|
|
|
|
// command는 ref를 사용하는 함수 묶음이라, 렌더 중 외부 함수에 직접 넘기면 React Compiler가
|
|
// ref 접근으로 판단한다. 별도 컴포넌트의 props로 전달해 렌더 범위를 분리한다(동작 동일).
|
|
function ToolbarEndSlot({ renderToolbarEnd, editor, command, view }: Readonly<ToolbarEndSlotProps>) {
|
|
return <>{renderToolbarEnd?.({ editor, command, view })}</>;
|
|
}
|
|
|
|
// 주입된 정제 함수가 우선이고, 없으면 sanitizeHtml 옵션에 따라 기본 정제기를 사용한다.
|
|
function sanitizeEditorHtml(
|
|
html: string,
|
|
htmlSanitizer: KriEditorProps["htmlSanitizer"],
|
|
sanitizeEnabled: boolean,
|
|
allowedCustomHtml: KriEditorProps["allowedCustomHtml"],
|
|
): string {
|
|
if (htmlSanitizer) return htmlSanitizer(html);
|
|
if (sanitizeEnabled) return sanitizeHtml(html, allowedCustomHtml);
|
|
return html;
|
|
}
|
|
|
|
function writeHtmlDraft(
|
|
draftRef: { current: string },
|
|
textareaRef: { current: HTMLTextAreaElement | null },
|
|
html: string,
|
|
): void {
|
|
draftRef.current = html;
|
|
if (textareaRef.current) textareaRef.current.value = html;
|
|
}
|
|
|
|
// 외부에서 본문이 변경된 경우에만 기존 editor 문서를 갱신한다.
|
|
function syncEditorContent(editor: Editor, value: string, optimisticHtml: string): void {
|
|
// 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해
|
|
// 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정.
|
|
const normalizedValue = value || "<p></p>";
|
|
if (normalizedValue === editor.getHTML() || normalizedValue === optimisticHtml) return;
|
|
|
|
editor.commands.setContent(normalizedValue, {
|
|
emitUpdate: false,
|
|
parseOptions: { preserveWhitespace: "full" },
|
|
});
|
|
|
|
// resize가 활성화된 TipTap 이미지 NodeView는 노드의 src 변경을 기존 DOM에 반영하지 않는다.
|
|
// editor 전체 대신 NodeView만 다시 생성해 이미지를 갱신하고 편집 포커스는 유지한다.
|
|
if (normalizedValue.includes("<img")) {
|
|
editor.createNodeViews();
|
|
}
|
|
}
|
|
|
|
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: Readonly<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<HTMLInputElement | null>(null);
|
|
const previewContainerRef = useRef<HTMLDivElement | null>(null);
|
|
const htmlTextareaRef = useRef<HTMLTextAreaElement | null>(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<ViewMode>(initialView);
|
|
const [previewSource, setPreviewSource] = useState(value ?? "");
|
|
const viewRef = useRef<ViewMode>(initialView);
|
|
|
|
useEffect(() => {
|
|
viewRef.current = view;
|
|
}, [view]);
|
|
|
|
const htmlDraftRef = useRef<string>(value ?? "");
|
|
// HTML textarea는 비제어 컴포넌트다. 렌더 중 ref를 읽지 않도록, HTML 보기로 전환하는 시점의
|
|
// 초안을 state로 보관해 textarea가 마운트될 때의 초기값(defaultValue)으로만 사용한다.
|
|
const [htmlTextareaSeed, setHtmlTextareaSeed] = useState<string>(value ?? "");
|
|
const canImageUpload = Boolean(onImageUpload);
|
|
|
|
const selectionRef = useRef<{ from: number; to: number } | null>(null);
|
|
|
|
const [tb, setTb] = useState<ToolbarState>({
|
|
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 || "<p></p>",
|
|
|
|
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<string, unknown> }[] | 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 (실제 <a>가 있는 경우)
|
|
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<HTMLInputElement>) => {
|
|
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;
|
|
setHtmlTextareaSeed(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 = sanitizeEditorHtml(raw, htmlSanitizer, sanitizeHtmlOpt, allowedCustomHtml);
|
|
|
|
editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } });
|
|
flushChange(preserveEmptyParagraphs(editor.getHTML()));
|
|
setView("wysiwyg");
|
|
}, [allowedCustomHtml, editor, flushChange, getCompatibility, htmlSanitizer, sanitizeHtmlOpt, setView, setPreviewSource, setHtmlTextareaSeed]);
|
|
|
|
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, setPreviewSource]);
|
|
|
|
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 || value == null) return;
|
|
|
|
// WYSIWYG로 손실 없이 편집할 수 없는 값은 HTML 보기로 전환해 원문을 유지한다.
|
|
if (showHtmlToggle && !getCompatibility(value).compatible) {
|
|
writeHtmlDraft(htmlDraftRef, htmlTextareaRef, value);
|
|
if (viewRef.current !== "html") {
|
|
viewRef.current = "html";
|
|
setHtmlTextareaSeed(value);
|
|
setView("html");
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (viewRef.current === "html") {
|
|
const isExternalChange = value !== optimisticHtmlRef.current && value !== htmlDraftRef.current;
|
|
if (getWysiwygCompatibility && isExternalChange) {
|
|
writeHtmlDraft(htmlDraftRef, htmlTextareaRef, value);
|
|
}
|
|
return;
|
|
}
|
|
|
|
syncEditorContent(editor, value, optimisticHtmlRef.current);
|
|
}, [value, editor, view, getCompatibility, getWysiwygCompatibility, showHtmlToggle]);
|
|
|
|
useEffect(() => {
|
|
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<KriEditorCommand>(
|
|
() => ({
|
|
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 = sanitizeEditorHtml(preserved, htmlSanitizer, sanitizeHtmlOpt, allowedCustomHtml);
|
|
const withLinkStyle = applyLinkPreviewClass(sanitized);
|
|
return transformPreviewHtml ? transformPreviewHtml(withLinkStyle) : withLinkStyle;
|
|
}, [allowedCustomHtml, htmlSanitizer, previewSource, sanitizeHtmlOpt, transformPreviewHtml]);
|
|
|
|
// 이미지맵을 사용할 때만 미리보기에 <area> 영역을 표시한다.
|
|
const imageMapOverlayBoxes = useImageMapOverlay(previewContainerRef, previewHtml, enableImageMap && showPreview);
|
|
|
|
const wysiwygCompatibility = useMemo(
|
|
() => getCompatibility(view === "html" ? previewSource : (editor?.getHTML() ?? previewSource)),
|
|
[editor, getCompatibility, previewSource, view],
|
|
);
|
|
|
|
if (!editor) {
|
|
return (
|
|
<div className={cn("rounded-lg border bg-background", className)}>
|
|
{label?.trim() ? <div className="border-b p-2 font-semibold">{label}</div> : null}
|
|
<div className="p-3 text-sm text-muted-foreground">에디터 로딩 중…</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className={cn("rounded-lg border bg-background", className)}>
|
|
{label?.trim() ? <div className="border-b p-2 font-semibold">{label}</div> : null}
|
|
|
|
{toolbar !== false ? (
|
|
<div className="border-b">
|
|
<Toolbar
|
|
editor={editor}
|
|
state={tb}
|
|
config={toolbar}
|
|
className="flex-nowrap"
|
|
canImageUpload={canImageUpload}
|
|
onPickImage={handlePickImage}
|
|
showHtmlToggle={showHtmlToggle}
|
|
isHtmlView={view === "html"}
|
|
htmlToWysiwygDisabled={!wysiwygCompatibility.compatible}
|
|
htmlToWysiwygDisabledReason={wysiwygCompatibility.reason}
|
|
onToggleHtmlView={onToggleHtmlView}
|
|
onFormatHtml={formatHtmlView}
|
|
fontFamilyOptions={fontFamilyOptions}
|
|
onSetFontFamily={setFontFamily}
|
|
onSetFontSize={setFontSize}
|
|
onSetTextColor={setTextColor}
|
|
onUnsetTextColor={unsetTextColor}
|
|
onSetHighlight={setHighlight}
|
|
onUnsetHighlight={unsetHighlight}
|
|
linkUrl={(editor.getAttributes("link").href as string | undefined) ?? ""}
|
|
onSetLink={setLink}
|
|
onUnsetLink={unsetLink}
|
|
onInsertTable={insertTable}
|
|
onAddRow={addRow}
|
|
onAddColumn={addColumn}
|
|
onDeleteTable={deleteTable}
|
|
customContent={
|
|
props.renderToolbarEnd ? (
|
|
<ToolbarEndSlot renderToolbarEnd={props.renderToolbarEnd} editor={editor} command={command} view={view} />
|
|
) : undefined
|
|
}
|
|
/>
|
|
</div>
|
|
) : null}
|
|
|
|
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} disabled={!canImageUpload} />
|
|
|
|
{view === "wysiwyg" ? (
|
|
<EditorContent editor={editor} />
|
|
) : (
|
|
<div className="p-2">
|
|
<textarea
|
|
ref={htmlTextareaRef}
|
|
className="h-[220px] w-full resize-y rounded-md border bg-background p-3 font-mono text-sm outline-none"
|
|
defaultValue={htmlTextareaSeed}
|
|
onMouseDown={(e) => e.stopPropagation()}
|
|
onChange={(e) => {
|
|
htmlDraftRef.current = e.target.value;
|
|
setPreviewSource(htmlDraftRef.current);
|
|
scheduleChange(htmlDraftRef.current);
|
|
}}
|
|
onBlur={() => flushChange(htmlDraftRef.current)}
|
|
placeholder={placeholder}
|
|
{...htmlTi.bindSelectionHandlers}
|
|
/>
|
|
{!wysiwygCompatibility.compatible ? (
|
|
<output className="mt-2 block text-xs text-amber-700">
|
|
{wysiwygCompatibility.reason ?? "현재 HTML은 WYSIWYG에서 손실 없이 편집할 수 없습니다."}
|
|
</output>
|
|
) : null}
|
|
</div>
|
|
)}
|
|
|
|
{showPreview && (
|
|
<div className={cn("border-t p-3", previewClassName)}>
|
|
<div className="mb-2 text-sm font-semibold">미리보기</div>
|
|
<div ref={previewContainerRef} className="relative rounded-md border bg-muted/30 p-3">
|
|
<div dangerouslySetInnerHTML={{ __html: previewHtml }} />
|
|
{imageMapOverlayBoxes.length > 0 && (
|
|
<div className="pointer-events-none absolute inset-0" aria-hidden="true">
|
|
{imageMapOverlayBoxes.map((box) => (
|
|
<div
|
|
key={box.key}
|
|
className="absolute border-2 border-sky-500 bg-sky-500/30"
|
|
style={box.style}
|
|
/>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|