260728_02_ENH: 에디터 툴바 동적 슬롯 사용할 수 있도록 변경

This commit is contained in:
2026-07-28 15:12:22 +09:00
parent d3f94a05b3
commit 59dd2b60c9
6 changed files with 73 additions and 59 deletions

View File

@@ -20,7 +20,7 @@ import TableCell from "@tiptap/extension-table-cell";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import type { KriEditorProps, KriEditorMode, ToolbarState } from "./types";
import type { KriEditorCommand, KriEditorProps, ToolbarState } from "./types";
import { resolveUploadUrl } from "./types";
import { FontSize } from "./extensions/font-size";
import { Div } from "./extensions/div";
@@ -32,10 +32,6 @@ import { useTextareaInsert } from "./hooks/useTextareaInsert";
type ViewMode = "wysiwyg" | "html";
function resolveMode(mode?: KriEditorMode): KriEditorMode {
return mode ?? "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 };
@@ -77,7 +73,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
showPreview = false,
previewClassName,
mode: modeProp,
mode = "wysiwyg",
debounceMs = 350,
onImageUpload,
@@ -93,7 +89,6 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
toolbar = {},
} = props;
const mode = resolveMode(modeProp);
const showHtmlToggle = mode === "both";
const LINK_HTML_ATTRS = {
@@ -106,9 +101,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
const fileRef = useRef<HTMLInputElement | null>(null);
const htmlTextareaRef = useRef<HTMLTextAreaElement | null>(null);
const htmlTi = useTextareaInsert(htmlTextareaRef);
const { insertText: insertTextareaText } = htmlTi;
const [view, setView] = useState<ViewMode>("wysiwyg");
const [wysiwygKey, setWysiwygKey] = useState<number>(0);
const [previewSource, setPreviewSource] = useState(value ?? "");
const viewRef = useRef<ViewMode>("wysiwyg");
@@ -198,7 +193,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
editorProps: {
attributes: {
class: cn(
"min-h-[180px] px-3 py-2 focus:outline-none",
"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",
@@ -257,7 +252,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
},
},
},
},[wysiwygKey]);
}, []);
const restoreSelection = useCallback(() => {
if (!editor) return;
@@ -413,7 +408,6 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
if(onImageUploadError){
onImageUploadError(err);
}else{
toast.error("이미지 업로드에 실패했습니다.");
console.error(err);
}
}
@@ -482,25 +476,26 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
if (viewRef.current === "html") return;
if (value == null) return;
const current = editor.getHTML();
// 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해
// 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정.
const normalizedValue = value || "<p></p>";
const current = editor.getHTML();
if (normalizedValue !== current && normalizedValue !== optimisticHtmlRef.current) {
// 이미지가 포함된 HTML 업데이트면, 아예 editor를 새로 생성
// 외부에서 본문이 변경된 경우에만 기존 editor 문서를 갱신한다.
editor.commands.setContent(normalizedValue, {
emitUpdate: false,
parseOptions: {preserveWhitespace: "full"},
});
// resize가 활성화된 TipTap 이미지 NodeView는 노드의 src 변경을 기존 DOM에 반영하지 않는다.
// editor 전체 대신 NodeView만 다시 생성해 이미지를 갱신하고 편집 포커스는 유지한다.
if (normalizedValue.includes("<img")) {
editor.createNodeViews();
}
}
}, [value, editor, view]);
useEffect(() => {
if (value.includes("<img")) {
setWysiwygKey((k) => k + 1);
return;
}
}, [value]);
useEffect(() => {
if (!editor) return;
@@ -515,6 +510,38 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
};
}, [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(editor.getHTML());
},
}),
[editor, restoreSelection, flushChange, insertTextareaText]
);
useEffect(() => {
if (!props.onCommandReady) return;
@@ -524,43 +551,10 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
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());
},
});
props.onCommandReady(command);
return () => props.onCommandReady?.(null);
}, [editor, props.onCommandReady, restoreSelection, flushChange, htmlTi]);
}, [command, editor, props.onCommandReady]);
const previewHtml = useMemo(() => {
return sanitizeHtmlOpt ? sanitizeHtml(previewSource) : previewSource;
@@ -603,6 +597,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
onAddRow={addRow}
onAddColumn={addColumn}
onDeleteTable={deleteTable}
customContent={props.renderToolbarEnd?.({ editor, command, view })}
/>
</div>
) : null}

View File

@@ -2,12 +2,15 @@ export { KriEditor } from './KriEditor'
export { KriEditorHtmlOnly } from './KriEditorHtmlOnly'
export { KriEditorSms } from './KriEditorSms'
export { KriEditorWysiwyg } from './KriEditorWysiwyg'
export { ToolbarButton as KriEditorToolbarButton } from './toolbar/ToolbarButton'
export type {
KriEditorCommand,
KriEditorMode,
KriEditorProps,
KriEditorToolbarConfig,
KriEditorToolbarContext,
KriEditorToolbarFeature,
KriEditorUploadResult,
ToolbarState,
} from './types'
export type { KriEditorToolbarButtonProps } from './toolbar/ToolbarButton'

View File

@@ -1,6 +1,6 @@
'use client'
import { useEffect, useState } from 'react'
import { useEffect, useState, type ReactNode } from 'react'
import type { Editor } from '@tiptap/react'
import {
AlignCenter,
@@ -50,6 +50,7 @@ interface ToolbarProps {
onAddRow: () => void
onAddColumn: () => void
onDeleteTable: () => void
customContent?: ReactNode
}
const PRESET_COLORS = [
@@ -85,6 +86,7 @@ export function Toolbar({
onAddRow,
onAddColumn,
onDeleteTable,
customContent,
}: ToolbarProps) {
const enabled = (feature: KriEditorToolbarFeature) => config?.[feature] !== false
const showTextStyle = enabled('bold') || enabled('italic') || enabled('underline') || enabled('strike')
@@ -278,6 +280,12 @@ export function Toolbar({
<ToolbarButton active={isHtmlView} title={isHtmlView ? 'WYSIWYG로 전환' : 'HTML 편집'} onClick={onToggleHtmlView}><Code2 className="size-4" /></ToolbarButton>
</>
) : null}
{customContent ? (
<>
<Separator orientation="vertical" className="mx-1 h-6" />
{customContent}
</>
) : null}
</div>
)
}

View File

@@ -4,7 +4,7 @@ import type { ReactNode, MouseEvent } from "react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
type Props = {
export type KriEditorToolbarButtonProps = {
active?: boolean;
disabled?: boolean;
title?: string;
@@ -13,7 +13,7 @@ type Props = {
className?: string;
};
export function ToolbarButton({ active, disabled, title, onClick, children, className }: Props) {
export function ToolbarButton({ active, disabled, title, onClick, children, className }: KriEditorToolbarButtonProps) {
const onMouseDown = (e: MouseEvent) => {
e.preventDefault();
};

View File

@@ -1,4 +1,5 @@
import type { Editor } from '@tiptap/react'
import type { ReactNode } from 'react'
export type KriEditorMode = 'wysiwyg' | 'both' | 'html' | 'sms'
export type KriEditorUploadResult = string | { url: string }
@@ -26,6 +27,12 @@ export type KriEditorCommand = {
insertText: (text: string) => void
}
export type KriEditorToolbarContext = {
editor: Editor
command: KriEditorCommand
view: 'wysiwyg' | 'html'
}
export type KriEditorProps = {
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void
onCommandReady?: (command: KriEditorCommand | null) => void
@@ -55,6 +62,7 @@ export type KriEditorProps = {
smsMaxBytes?: number
lmsMaxBytes?: number
toolbar?: KriEditorToolbarConfig | false
renderToolbarEnd?: (context: KriEditorToolbarContext) => ReactNode
}
export type ToolbarState = {