Files
contact-front/src/components/kri-editor/KriEditorWysiwyg.tsx

640 lines
19 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 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 type { KriEditorProps, KriEditorMode, ToolbarState } from "./types";
import { FontSize } from "./extensions/font-size";
import { Div } from "./extensions/div";
import { cn } from "./utils/cn";
import { compressImage } from "./utils/imageCompression";
import { sanitizeHtml } from "./utils/sanitizeHtml";
import { Toolbar } from "./toolbar/Toolbar";
import { useDebouncedChange } from "./hooks/useDebouncedChange";
import { useTextareaInsert } from "./hooks/useTextareaInsert";
type ViewMode = "wysiwyg" | "html";
function resolveMode(mode?: KriEditorMode, editorMode?: KriEditorMode): KriEditorMode {
return mode ?? editorMode ?? "wysiwyg";
}
function getToolbarState(editor: Editor): ToolbarState {
const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; color?: string | null };
const hl = editor.getAttributes("highlight") as { color?: 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 {
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: modeProp,
editorMode,
debounceMs = 350,
onImageUpload,
onImageUploadError,
maxImageBytes = 5 * 1024 * 1024,
imageMaxWidth = 1600,
imageMaxHeight = 1600,
imageQuality = 0.82,
imageMimeType = "image/webp",
allowBase64 = false,
sanitizeHtml: sanitizeHtmlOpt = true,
} = props;
const mode = resolveMode(modeProp, editorMode);
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 htmlTextareaRef = useRef<HTMLTextAreaElement | null>(null);
const htmlTi = useTextareaInsert(htmlTextareaRef);
const [view, setView] = useState<ViewMode>("wysiwyg");
const [wysiwygKey, setWysiwygKey] = useState<number>(0);
const viewRef = useRef<ViewMode>("wysiwyg");
useEffect(() => {
viewRef.current = view;
}, [view]);
const htmlDraftRef = useRef<string>(value ?? "");
const canImageUpload = Boolean(onImageUpload);
const selectionRef = useRef<{ from: number; to: number } | null>(null);
const [tb, setTb] = useState<ToolbarState>({
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,
Color,
Highlight.configure({ multicolor: true }),
Div,
Link.configure({
autolink: true,
openOnClick: false,
linkOnPaste: true,
HTMLAttributes: {
class: "cursor-pointer text-blue-600 underline underline-offset-2",
...LINK_HTML_ATTRS,
},
}),
TextAlign.configure({ types: ["paragraph", "divBlock"] }),
Table.configure({ resizable: true }),
TableRow,
TableHeader,
TableCell,
TiptapImage.configure({
inline: true,
allowBase64,
HTMLAttributes: {
class: "max-w-full h-auto",
"data-kri-image": "true",
},
resize: {
enabled: true,
alwaysPreserveAspectRatio: true,
},
}),
Placeholder.configure({ placeholder }),
],
content: value || "<p></p>",
onUpdate: ({ editor }) => {
if (viewRef.current === "html") return;
scheduleChange(editor.getHTML());
},
editorProps: {
attributes: {
class: cn(
"min-h-[180px] 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 any[] | null | undefined) =>
marks?.find(m => m.type === linkType)?.attrs?.href as string | 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();
console.log(LINK_HTML_ATTRS.rel.replaceAll(" ",","))
window.open(href, LINK_HTML_ATTRS.target, LINK_HTML_ATTRS.rel.replaceAll(" ",","));
return true;
},
},
},
},[wysiwygKey]);
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 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;
}
// 프로토콜이 없으면 https:// 를 기본으로 붙여준다.
return `https://${trimmed}`;
};
const toggleLink = useCallback(() => {
if (!editor) return;
restoreSelection();
const prev = (editor.getAttributes("link").href as string | undefined) ?? "";
if (editor.isActive("link")) {
if(confirm(`링크를 해제 하시겠습니까?\r\nLink: ${prev}`)){
editor.chain().focus().unsetLink().run();
return;
}
}
const url = window.prompt("링크 URL을 입력하세요", prev);
if (url === null) return;
const normalized = normalizeLinkUrl(url);
if (!normalized) return;
editor.chain().focus().extendMarkRange("link").setLink({ href: normalized }).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 } = 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") {
htmlDraftRef.current = editor.getHTML();
setView("html");
return;
}
const raw = htmlDraftRef.current;
const safe = sanitizeHtmlOpt ? sanitizeHtml(raw) : raw;
editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } });
flushChange(editor.getHTML());
setView("wysiwyg");
}, [editor, flushChange, sanitizeHtmlOpt]);
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(() => {
if (!editor) return;
if (viewRef.current === "html") return;
if (value == null) return;
const current = editor.getHTML();
if (value !== current && value !== optimisticHtmlRef.current) {
// 이미지가 포함된 HTML 업데이트면, 아예 editor를 새로 생성
editor.commands.setContent(value, {
emitUpdate: false,
parseOptions: {preserveWhitespace: "full"},
});
}
}, [value, editor, view]);
useEffect(() => {
if (value.includes("<img")) {
setWysiwygKey((k) => k + 1);
return;
}
}, [value]);
useEffect(() => {
if (!editor) return;
const onBlur = () => {
if (viewRef.current === "html") flushChange(htmlDraftRef.current);
else flushChange(editor.getHTML());
};
editor.on("blur", onBlur);
return () => {
editor.off("blur", onBlur);
};
}, [editor, flushChange]);
useEffect(() => {
if (!props.onCommandReady) return;
// editor가 아직 없으면 null 전달
if (!editor) {
props.onCommandReady(null);
return;
}
props.onCommandReady({
focus: () => {
if (viewRef.current === "html") htmlTextareaRef.current?.focus();
else editor.chain().focus().run();
},
insertText: (placeholder: string) => {
// 1) HTML textarea 모드
if (viewRef.current === "html") {
const current = htmlDraftRef.current ?? "";
htmlTi.insertText(
placeholder,
current,
(next) => {
htmlDraftRef.current = next;
// uncontrolled textarea이므로 DOM value를 직접 갱신
if (htmlTextareaRef.current) htmlTextareaRef.current.value = next;
},
(next) => {
// 삽입은 즉시 커밋(저장 버튼 클릭 직후 반영 누락 방지)
flushChange(next);
}
);
return;
}
// 2) WYSIWYG(tiptap) 모드
restoreSelection();
editor.chain().focus().insertContent(placeholder).run();
flushChange(editor.getHTML());
},
});
return () => props.onCommandReady?.(null);
}, [editor, props.onCommandReady, restoreSelection, flushChange, htmlTi]);
const previewHtml = useMemo(() => {
const raw = optimisticHtmlRef.current || "";
return sanitizeHtmlOpt ? sanitizeHtml(raw) : raw;
}, [optimisticHtmlRef, sanitizeHtmlOpt]);
if (!editor) {
return (
<div className={cn("rounded-lg border bg-white", 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-white", className)}>
{label?.trim() ? <div className="border-b p-2 font-semibold">{label}</div> : null}
<div className="border-b">
<Toolbar
editor={editor}
state={tb}
className="flex-nowrap"
canImageUpload={canImageUpload}
onPickImage={handlePickImage}
showHtmlToggle={showHtmlToggle}
isHtmlView={view === "html"}
onToggleHtmlView={onToggleHtmlView}
onSetFontSize={setFontSize}
onSetTextColor={setTextColor}
onUnsetTextColor={unsetTextColor}
onSetHighlight={setHighlight}
onUnsetHighlight={unsetHighlight}
onToggleLink={toggleLink}
onInsertTable={insertTable}
onAddRow={addRow}
onAddColumn={addColumn}
onDeleteTable={deleteTable}
/>
</div>
<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={htmlDraftRef.current}
onMouseDown={(e) => e.stopPropagation()}
onChange={(e) => {
htmlDraftRef.current = e.target.value;
scheduleChange(htmlDraftRef.current);
}}
onBlur={() => flushChange(htmlDraftRef.current)}
placeholder={placeholder}
{...htmlTi.bindSelectionHandlers}
/>
</div>
)}
{showPreview && (
<div className={cn("border-t p-3", previewClassName)}>
<div className="mb-2 text-sm font-semibold">미리보기</div>
<div className="rounded-md border bg-gray-50 p-3">
<div dangerouslySetInnerHTML={{ __html: previewHtml }} />
</div>
</div>
)}
</div>
);
}