260714_01_ENH: 테스트 서버에서 기동 후 중간 테스트를 위한 커밋

This commit is contained in:
2026-07-14 10:59:07 +09:00
parent a8ce35f5bf
commit 192d47bdb1
180 changed files with 11942 additions and 6007 deletions

View File

@@ -5,20 +5,20 @@ import { KriEditorHtmlOnly } from "./KriEditorHtmlOnly";
import { KriEditorWysiwyg } from "./KriEditorWysiwyg";
import {KriEditorSms} from "./KriEditorSms";
function resolveMode(mode?: KriEditorMode, editorMode?: KriEditorMode): KriEditorMode {
return mode ?? editorMode ?? "wysiwyg";
function resolveMode(mode?: KriEditorMode): KriEditorMode {
return mode ?? "wysiwyg";
}
export function KriEditor(props: KriEditorProps) {
const mode = resolveMode(props.mode, props.editorMode);
const mode = resolveMode(props.mode);
if (mode === "html") {
return <KriEditorHtmlOnly {...props} mode={mode} editorMode={mode} />;
return <KriEditorHtmlOnly {...props} mode={mode} />;
}
if(mode === "sms") {
return <KriEditorSms {...props} mode={mode} editorMode={mode} />
return <KriEditorSms {...props} mode={mode} />;
}
return <KriEditorWysiwyg {...props} mode={mode} editorMode={mode} />;
return <KriEditorWysiwyg {...props} mode={mode} />;
}

View File

@@ -1,244 +1,158 @@
"use client";
'use client'
import * as React from "react";
import { toast } from "sonner";
import { cn } from "@kri/common/ui";
import * as React from 'react'
import { toast } from 'sonner'
import { cn } from '@/lib/utils'
import type { KriEditorProps } from './types'
import { resolveUploadUrl } from './types'
import { compressImage } from './utils/imageCompression'
import { useDebouncedChange } from './hooks/useDebouncedChange'
import { sanitizeHtmlForPreview } from './utils/sanitizeHtml'
import { useTextareaInsert } from './hooks/useTextareaInsert'
import type { KriEditorProps } from "./types";
import { compressImage } from "./utils/imageCompression";
import { useDebouncedChange } from "./hooks/useDebouncedChange";
import { sanitizeHtmlForPreview } from "./utils/sanitizeHtml";
import {useCallback} from "react";
import { useTextareaInsert } from "./hooks/useTextareaInsert";
type HtmlOnlyProps = Omit<KriEditorProps, 'mode'> & { mode: 'html' }
type HtmlOnlyProps = Omit<KriEditorProps, "mode"> & {
mode: "html";
};
export function KriEditorHtmlOnly({
label,
value,
onChange,
placeholder = 'HTML을 입력하세요...',
className,
showPreview,
previewClassName,
rows = 14,
debounceMs = 350,
onImageUpload,
onImageUploadError,
maxImageBytes = 5 * 1024 * 1024,
imageMaxWidth = 1600,
imageMaxHeight = 1600,
imageQuality = 0.82,
imageMimeType = 'image/webp',
onEditorReady,
onCommandReady,
}: HtmlOnlyProps) {
const [html, setHtml] = React.useState(value || '')
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null)
const fileRef = React.useRef<HTMLInputElement | null>(null)
const latestHtmlRef = React.useRef(html)
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs)
const textareaInsert = useTextareaInsert(textareaRef)
export function KriEditorHtmlOnly(props: HtmlOnlyProps) {
const {
label,
value,
onChange,
placeholder = "HTML을 입력하세요...",
className,
showPreview,
previewClassName,
rows = 14,
debounceMs = 350,
const commitHtml = React.useCallback((next: string, immediate = false) => {
setHtml(next)
latestHtmlRef.current = next
if (immediate) flushChange(next)
else scheduleChange(next)
}, [flushChange, scheduleChange])
onImageUpload,
onImageUploadError,
maxImageBytes = 5 * 1024 * 1024,
imageMaxWidth = 1600,
imageMaxHeight = 1600,
imageQuality = 0.82,
imageMimeType = "image/webp",
} = props;
const [html, setHtml] = React.useState<string>(value || "");
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null);
const fileRef = React.useRef<HTMLInputElement | null>(null);
const latestHtmlRef = React.useRef(html);
const canImageUpload = Boolean(onImageUpload);
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs);
const ti = useTextareaInsert(textareaRef);
const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const next = e.target.value;
setHtml(next);
latestHtmlRef.current = next;
scheduleChange(next);
};
const handleBlur = () => {
flushChange(latestHtmlRef.current);
};
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) 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;
}
setHtml((prev) => {
const current = prev ?? "";
const textarea = textareaRef.current;
const imgTag = `<img src="${url}" alt="" />`;
if (!textarea) {
const next = current + imgTag;
latestHtmlRef.current = next;
scheduleChange(next);
return next;
}
const { selectionStart, selectionEnd } = textarea;
const before = current.slice(0, selectionStart);
const after = current.slice(selectionEnd);
const next = before + imgTag + after;
latestHtmlRef.current = next;
scheduleChange(next);
// 커서 위치를 이미지 태그 뒤로 이동
window.requestAnimationFrame(() => {
const pos = before.length + imgTag.length;
textarea.focus();
textarea.setSelectionRange(pos, pos);
});
return next;
});
} catch (err) {
toast.error("이미지 업로드에 실패했습니다.");
console.error(err);
}
},
[
scheduleChange,
setHtml,
canImageUpload,
onImageUpload,
maxImageBytes,
imageMaxWidth,
imageMaxHeight,
imageMimeType,
imageQuality,
]
);
const sanitizedHtml = React.useMemo(
() => sanitizeHtmlForPreview(html || ""),
[html],
);
// 외부 value 변경 시 동기화
React.useEffect(() => {
if ((value || "") !== latestHtmlRef.current) {
setHtml(value || "");
latestHtmlRef.current = value || "";
if ((value || '') !== latestHtmlRef.current) {
setHtml(value || '')
latestHtmlRef.current = value || ''
}
}, [value]);
}, [value])
React.useEffect(() => {
if (textareaRef.current && props.onEditorReady) {
props.onEditorReady(textareaRef.current);
}
},[props.onEditorReady])
onEditorReady?.(textareaRef.current)
}, [onEditorReady])
React.useEffect(() => {
if (!props.onCommandReady) return;
props.onCommandReady({
if (!onCommandReady) return
onCommandReady({
focus: () => textareaRef.current?.focus(),
insertText: (placeholder: string) => {
const current = latestHtmlRef.current ?? "";
ti.insertText(
placeholder,
current,
(next) => {
setHtml(next);
latestHtmlRef.current = next;
},
(next) => {
// html 모드도 debounce 쓰면 flush 권장
flushChange(next);
},
);
insertText: (text) => {
textareaInsert.insertText(
text,
latestHtmlRef.current,
(next) => commitHtml(next),
(next) => commitHtml(next, true),
)
},
});
})
return () => onCommandReady(null)
}, [commitHtml, onCommandReady, textareaInsert])
return () => props.onCommandReady?.(null);
}, [props.onCommandReady, ti, flushChange]);
const handleFile = async (event: React.ChangeEvent<HTMLInputElement>) => {
try {
const file = event.target.files?.[0]
event.target.value = ''
if (!file || !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('이미지 용량이 제한을 초과합니다.')
return
}
const url = resolveUploadUrl(await onImageUpload(compressed))
if (!url) {
toast.error('이미지 업로드 응답이 올바르지 않습니다.')
return
}
const current = latestHtmlRef.current
const textarea = textareaRef.current
const imageTag = `<img src="${url}" alt="" />`
const start = textarea?.selectionStart ?? current.length
const end = textarea?.selectionEnd ?? current.length
const next = `${current.slice(0, start)}${imageTag}${current.slice(end)}`
commitHtml(next)
requestAnimationFrame(() => {
const position = start + imageTag.length
textarea?.focus()
textarea?.setSelectionRange(position, position)
})
} catch (error) {
if (onImageUploadError) onImageUploadError(error)
else toast.error('이미지 업로드에 실패했습니다.')
}
}
const previewHtml = React.useMemo(() => sanitizeHtmlForPreview(html), [html])
return (
<div className={cn("rounded-md border bg-white", className)}>
{label && (
<div className="border-b px-3 py-2 text-sm font-semibold">
{label}
</div>
)}
<div className={cn('rounded-md border bg-background', className)}>
{label ? <div className="border-b px-3 py-2 text-sm font-semibold">{label}</div> : null}
<div className="flex flex-col gap-2 px-3 py-2">
<div className="flex items-center justify-between text-xs text-gray-500">
<div className="text-muted-foreground flex items-center justify-between text-xs">
<span>HTML 모드</span>
{onImageUpload && (
<button
type="button"
onClick={handlePickImage}
className="rounded border px-2 py-1 text-xs hover:bg-gray-50"
>
{onImageUpload ? (
<button type="button" onClick={() => fileRef.current?.click()} className="rounded border px-2 py-1 hover:bg-muted">
이미지 업로드
</button>
)}
) : null}
</div>
<textarea
ref={textareaRef}
className="min-h-[200px] w-full resize-y border bg-white p-2 text-sm font-mono outline-none"
className="min-h-[200px] w-full resize-y rounded-md border bg-background p-2 font-mono text-sm outline-none"
value={html}
onChange={handleTextChange}
onBlur={handleBlur}
onChange={(event) => commitHtml(event.target.value)}
onBlur={() => flushChange(latestHtmlRef.current)}
placeholder={placeholder}
rows={rows}
{...ti.bindSelectionHandlers}
/>
<input
ref={fileRef}
type="file"
accept="image/*"
className="hidden"
onChange={handleFile}
{...textareaInsert.bindSelectionHandlers}
/>
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} />
</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 text-sm leading-relaxed">
<div dangerouslySetInnerHTML={{ __html: sanitizedHtml }} />
</div>
</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-muted/30 p-3 text-sm leading-relaxed" dangerouslySetInnerHTML={{ __html: previewHtml }} />
</div>
) : null}
</div>
);
)
}

View File

@@ -1,195 +1,119 @@
"use client";
'use client'
import React from "react";
import { cn } from "@kri/common/ui";
import type { KriEditorProps } from "./types";
import { useDebouncedChange } from "./hooks/useDebouncedChange";
import { useTextareaInsert } from "./hooks/useTextareaInsert";
import * as React from 'react'
import { cn } from '@/lib/utils'
import type { KriEditorProps } from './types'
import { useDebouncedChange } from './hooks/useDebouncedChange'
import { useTextareaInsert } from './hooks/useTextareaInsert'
type SmsEditorProps = Omit<KriEditorProps, "mode"> & {
mode: "sms";
};
type SmsEditorProps = Omit<KriEditorProps, 'mode'> & { mode: 'sms' }
export function KriEditorSms(props: SmsEditorProps) {
const {
label,
value,
onChange,
placeholder = "문자 내용을 입력하세요...",
className,
debounceMs = 350,
smsTitle = "",
changeSmsType,
onEditorReady,
} = props;
function calculateBytes(value: string): number {
return Array.from(value).reduce((total, character) => total + (character.charCodeAt(0) > 127 ? 2 : 1), 0)
}
const [text, setText] = React.useState<string>(value || "");
const [byteSize, setByteSize] = React.useState(0);
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null);
const latestTextRef = React.useRef(text);
const lastTypeRef = React.useRef<"SMS" | "LMS" | null>(null);
export function KriEditorSms({
label,
value,
onChange,
placeholder = '문자 내용을 입력하세요...',
className,
debounceMs = 350,
smsTitle = '',
changeSmsType,
onEditorReady,
onCommandReady,
smsMaxBytes = 90,
lmsMaxBytes = 2000,
isSmsReadOnly = false,
}: SmsEditorProps) {
const [text, setText] = React.useState(value || '')
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null)
const latestTextRef = React.useRef(text)
const lastTypeRef = React.useRef<'SMS' | 'LMS' | null>(null)
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs)
const textareaInsert = useTextareaInsert(textareaRef)
const byteSize = React.useMemo(() => calculateBytes(text), [text])
const messageType: 'SMS' | 'LMS' = byteSize > smsMaxBytes || Boolean(smsTitle) ? 'LMS' : 'SMS'
const maxBytes = messageType === 'SMS' ? smsMaxBytes : lmsMaxBytes
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs);
const ti = useTextareaInsert(textareaRef);
const commitText = React.useCallback((next: string, immediate = false) => {
setText(next)
latestTextRef.current = next
if (immediate) flushChange(next)
else scheduleChange(next)
}, [flushChange, scheduleChange])
// 한글은 2byte, 영문/숫자/특수문자는 1byte로 계산
const calculateBytes = React.useCallback((str: string): number => {
let bytes = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charAt(i);
if (escape(char).length > 4) {
bytes += 2;
} else {
bytes += 1;
}
React.useEffect(() => {
if ((value || '') !== latestTextRef.current) {
setText(value || '')
latestTextRef.current = value || ''
}
return bytes;
}, []);
const hasTitle = (smsTitle?.length ?? 0) > 0;
const messageType: "SMS" | "LMS" = (byteSize > 90 || hasTitle) ? "LMS" : "SMS";
const maxBytes = messageType === "LMS" ? 2000 : 90;
const messageTypeColor = messageType === "LMS" ? 'bg-blue-500' : 'bg-red-500';
const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const next = e.target.value;
const bytes = calculateBytes(next);
// 최대 바이트 초과 방지
if (bytes > 2000) {
return;
}
setText(next);
setByteSize(bytes);
latestTextRef.current = next;
scheduleChange(next);
};
const handleBlur = () => {
flushChange(latestTextRef.current);
};
// 외부 value 변경 시 동기화
React.useEffect(() => {
if ((value || "") !== latestTextRef.current) {
const newText = value || "";
setText(newText);
setByteSize(calculateBytes(newText));
latestTextRef.current = newText;
}
}, [value, calculateBytes]);
// 바이트 계산 초기화
React.useEffect(() => {
setByteSize(calculateBytes(text));
}, [text, calculateBytes]);
}, [value])
React.useEffect(() => {
if (!changeSmsType) return;
if (lastTypeRef.current === messageType) return;
lastTypeRef.current = messageType;
changeSmsType(messageType);
}, [messageType, changeSmsType]);
// onEditorReady 콜백
React.useEffect(() => {
if (textareaRef.current && onEditorReady) {
onEditorReady(textareaRef.current);
}
}, [onEditorReady]);
if (lastTypeRef.current === messageType) return
lastTypeRef.current = messageType
changeSmsType?.(messageType)
}, [changeSmsType, messageType])
React.useEffect(() => {
if (!props.onCommandReady) return;
onEditorReady?.(textareaRef.current)
}, [onEditorReady])
props.onCommandReady({
React.useEffect(() => {
if (!onCommandReady) return
onCommandReady({
focus: () => textareaRef.current?.focus(),
insertText: (placeholder: string) => {
const current = latestTextRef.current ?? "";
ti.insertText(
placeholder,
current,
(next) => {
// 로컬 반영
setText(next);
setByteSize(calculateBytes(next));
latestTextRef.current = next;
},
(next) => {
// 부모 반영(즉시) - debounce를 이기기 위해 flush 권장
flushChange(next);
},
);
insertText: (insertedText) => {
textareaInsert.insertText(
insertedText,
latestTextRef.current,
(next) => commitText(next),
(next) => commitText(next, true),
)
},
});
return () => props.onCommandReady?.(null);
}, [props.onCommandReady, ti, calculateBytes, flushChange]);
})
return () => onCommandReady(null)
}, [commitText, onCommandReady, textareaInsert])
return (
<div className={cn("w-full max-w-[320px] mx-auto", className)}>
{label && (
<div className="mb-2 text-sm font-semibold">
{label}
</div>
)}
{/* 휴대전화 디자인 */}
<div className="relative w-full h-[600px] bg-white rounded-[40px] shadow-2xl border-8 border-gray-800 overflow-hidden">
{/* 상단 노치 */}
<div className="absolute top-0 left-1/2 -translate-x-1/2 w-32 h-6 bg-gray-800 rounded-b-2xl z-10" />
{/* 스크린 영역 */}
<div className="h-full bg-gray-50 pt-8 pb-4 px-4 flex flex-col">
{/* 헤더 - 바이트 및 타입 표시 */}
<div className="flex justify-between items-center mb-3 px-2">
<span className="text-xs text-gray-600 font-medium">
{byteSize}/{maxBytes}byte
</span>
<span className={`${messageTypeColor} text-white px-3 py-1 rounded-md text-xs font-bold`}>
<div className={cn('mx-auto w-full max-w-[320px]', className)}>
{label ? <div className="mb-2 text-sm font-semibold">{label}</div> : null}
<div className="relative h-[600px] w-full overflow-hidden rounded-[40px] border-8 border-gray-800 bg-white shadow-2xl">
<div className="absolute top-0 left-1/2 z-10 h-6 w-32 -translate-x-1/2 rounded-b-2xl bg-gray-800" />
<div className="flex h-full flex-col bg-gray-50 px-4 pt-8 pb-4">
<div className="mb-3 flex items-center justify-between px-2">
<span className="text-xs font-medium text-gray-600">{byteSize}/{maxBytes}byte</span>
<span className={cn('rounded-md px-3 py-1 text-xs font-bold text-white', messageType === 'LMS' ? 'bg-blue-500' : 'bg-red-500')}>
{messageType}
</span>
</div>
{/* 메시지 본문 (textarea) */}
<div className="flex-1 bg-white rounded-2xl shadow-sm overflow-hidden flex flex-col">
{/* LMS 제목 */}
{smsTitle && (
<div className="px-4 pt-3 pb-2">
<div className="font-bold text-sm text-gray-800">
{smsTitle}
</div>
</div>
)}
{/* Textarea - 에디터 */}
<textarea
ref={textareaRef}
className="flex-1 w-full p-4 text-sm text-gray-700 outline-none resize-none bg-transparent leading-relaxed"
value={text}
onChange={handleTextChange}
onBlur={handleBlur}
placeholder={placeholder}
style={{ minHeight: smsTitle ? '320px' : '360px' }}
{...ti.bindSelectionHandlers}
/>
</div>
{/* 바이트 초과 경고 */}
{byteSize > maxBytes && (
<div className="mt-2 px-2">
<p className="text-xs text-red-600 font-medium text-center">
⚠️ 최대 용량 초과 ({byteSize - maxBytes}byte)
</p>
</div>
)}
</div>
{/* 하단 홈 버튼 */}
<div className="absolute bottom-2 left-1/2 -translate-x-1/2 w-32 h-1 bg-gray-800 rounded-full" />
<div className="flex flex-1 flex-col overflow-hidden rounded-2xl bg-white shadow-sm">
{smsTitle ? <div className="px-4 pt-3 pb-2 text-sm font-bold text-gray-800">{smsTitle}</div> : null}
<textarea
ref={textareaRef}
className="w-full flex-1 resize-none bg-transparent p-4 text-sm leading-relaxed text-gray-700 outline-none"
value={text}
readOnly={isSmsReadOnly}
onChange={(event) => {
const next = event.target.value
if (calculateBytes(next) <= lmsMaxBytes) commitText(next)
}}
onBlur={() => flushChange(latestTextRef.current)}
placeholder={placeholder}
style={{ minHeight: smsTitle ? '320px' : '360px' }}
{...textareaInsert.bindSelectionHandlers}
/>
</div>
{byteSize > maxBytes ? (
<p className="mt-2 px-2 text-center text-xs font-medium text-red-600">
최대 용량을 {byteSize - maxBytes}byte 초과했습니다.
</p>
) : null}
</div>
<div className="absolute bottom-2 left-1/2 h-1 w-32 -translate-x-1/2 rounded-full bg-gray-800" />
</div>
);
};
</div>
)
}

View File

@@ -18,9 +18,10 @@ import TableHeader from "@tiptap/extension-table-header";
import TableCell from "@tiptap/extension-table-cell";
import { toast } from "sonner";
import { cn } from "@kri/common/ui";
import { cn } from "@/lib/utils";
import type { KriEditorProps, KriEditorMode, ToolbarState } from "./types";
import type { KriEditorProps, ToolbarState } from "./types";
import { resolveUploadUrl } from "./types";
import { FontSize } from "./extensions/font-size";
import { Div } from "./extensions/div";
import { compressImage } from "./utils/imageCompression";
@@ -31,10 +32,6 @@ 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 };
@@ -76,8 +73,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
showPreview = false,
previewClassName,
mode: modeProp,
editorMode,
mode = "wysiwyg",
debounceMs = 350,
onImageUpload,
@@ -90,9 +86,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
allowBase64 = false,
sanitizeHtml: sanitizeHtmlOpt = true,
toolbar = {},
} = props;
const mode = resolveMode(modeProp, editorMode);
const showHtmlToggle = mode === "both";
const LINK_HTML_ATTRS = {
@@ -108,6 +104,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
const [view, setView] = useState<ViewMode>("wysiwyg");
const [wysiwygKey, setWysiwygKey] = useState<number>(0);
const [previewSource, setPreviewSource] = useState(value ?? "");
const viewRef = useRef<ViewMode>("wysiwyg");
useEffect(() => {
@@ -188,7 +185,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
onUpdate: ({ editor }) => {
if (viewRef.current === "html") return;
scheduleChange(editor.getHTML());
const nextHtml = editor.getHTML();
setPreviewSource(nextHtml);
scheduleChange(nextHtml);
},
editorProps: {
@@ -225,8 +224,11 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
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;
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()) ||
@@ -245,7 +247,6 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
// 링크 열기 + 에디터 클릭 처리(커서 이동 등) 막기
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;
},
@@ -300,40 +301,31 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
}, [editor, restoreSelection]);
const normalizeLinkUrl = (raw: string): string => {
const trimmed = raw.trim();
if (!trimmed) return "";
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;
}
if (/^https?:\/\//i.test(trimmed) || /^mailto:/i.test(trimmed) || /^tel:/i.test(trimmed)) {
return trimmed;
}
const url = window.prompt("링크 URL을 입력하세요", prev);
if (url === null) return;
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();
@@ -403,7 +395,7 @@ const normalizeLinkUrl = (raw: string): string => {
return;
}
const { url } = await onImageUpload(compressed);
const url = resolveUploadUrl(await onImageUpload(compressed));
if (!url || typeof url !== "string") {
toast.error("이미지 업로드 응답이 올바르지 않습니다.");
@@ -480,6 +472,7 @@ const normalizeLinkUrl = (raw: string): string => {
}, [editor, view, props.onEditorReady]);
useEffect(() => {
setPreviewSource(value ?? "");
if (!editor) return;
if (viewRef.current === "html") return;
if (value == null) return;
@@ -564,13 +557,12 @@ const normalizeLinkUrl = (raw: string): string => {
}, [editor, props.onCommandReady, restoreSelection, flushChange, htmlTi]);
const previewHtml = useMemo(() => {
const raw = optimisticHtmlRef.current || "";
return sanitizeHtmlOpt ? sanitizeHtml(raw) : raw;
}, [optimisticHtmlRef, sanitizeHtmlOpt]);
return sanitizeHtmlOpt ? sanitizeHtml(previewSource) : previewSource;
}, [previewSource, sanitizeHtmlOpt]);
if (!editor) {
return (
<div className={cn("rounded-lg border bg-white", className)}>
<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>
@@ -578,31 +570,36 @@ const normalizeLinkUrl = (raw: string): string => {
}
return (
<div className={cn("rounded-lg border bg-white", className)}>
<div className={cn("rounded-lg border bg-background", 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>
{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"}
onToggleHtmlView={onToggleHtmlView}
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}
/>
</div>
) : null}
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} disabled={!canImageUpload} />
@@ -617,6 +614,7 @@ const normalizeLinkUrl = (raw: string): string => {
onMouseDown={(e) => e.stopPropagation()}
onChange={(e) => {
htmlDraftRef.current = e.target.value;
setPreviewSource(htmlDraftRef.current);
scheduleChange(htmlDraftRef.current);
}}
onBlur={() => flushChange(htmlDraftRef.current)}
@@ -629,7 +627,7 @@ const normalizeLinkUrl = (raw: string): string => {
{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 className="rounded-md border bg-muted/30 p-3">
<div dangerouslySetInnerHTML={{ __html: previewHtml }} />
</div>
</div>

View File

@@ -1,2 +1,13 @@
export { KriEditor } from "./KriEditor";
export type { KriEditorProps, KriEditorMode, UploadResult, ToolbarState, KriEditorCommand } from "./types";
export { KriEditor } from './KriEditor'
export { KriEditorHtmlOnly } from './KriEditorHtmlOnly'
export { KriEditorSms } from './KriEditorSms'
export { KriEditorWysiwyg } from './KriEditorWysiwyg'
export type {
KriEditorCommand,
KriEditorMode,
KriEditorProps,
KriEditorToolbarConfig,
KriEditorToolbarFeature,
KriEditorUploadResult,
ToolbarState,
} from './types'

View File

@@ -1,21 +1,13 @@
"use client";
'use client'
import type { Editor } from "@tiptap/react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Separator } from "@/components/ui/separator";
import { cn } from "@kri/common/ui";
import { useEffect, useState } from 'react'
import type { Editor } from '@tiptap/react'
import {
AlignCenter,
AlignLeft,
AlignRight,
Bold,
Code2,
Highlighter,
Image as ImageIcon,
Italic,
@@ -23,72 +15,58 @@ import {
List,
ListOrdered,
Palette,
Strikethrough,
Table2,
Underline,
Strikethrough,
Code2,
} from "lucide-react";
import { ToolbarButton } from "./ToolbarButton";
import type { ToolbarState } from "../types";
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Input } from '@/components/ui/input'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { Separator } from '@/components/ui/separator'
import { cn } from '@/lib/utils'
import type { KriEditorToolbarConfig, KriEditorToolbarFeature, ToolbarState } from '../types'
import { ToolbarButton } from './ToolbarButton'
type Props = {
editor: Editor;
state: ToolbarState;
className?: string;
canImageUpload: boolean;
onPickImage: () => void;
showHtmlToggle: boolean;
isHtmlView: boolean;
onToggleHtmlView: () => void;
onSetFontSize: (px: string) => void;
onSetTextColor: (hex: string) => void;
onUnsetTextColor: () => void;
onSetHighlight: (hex: string) => void;
onUnsetHighlight: () => void;
onToggleLink: () => void;
onInsertTable: () => void;
onAddRow: () => void;
onAddColumn: () => void;
onDeleteTable: () => void;
};
interface ToolbarProps {
editor: Editor
state: ToolbarState
config?: KriEditorToolbarConfig
className?: string
canImageUpload: boolean
onPickImage: () => void
showHtmlToggle: boolean
isHtmlView: boolean
onToggleHtmlView: () => void
onSetFontSize: (value: string) => void
onSetTextColor: (value: string) => void
onUnsetTextColor: () => void
onSetHighlight: (value: string) => void
onUnsetHighlight: () => void
linkUrl: string
onSetLink: (url: string) => void
onUnsetLink: () => void
onInsertTable: () => void
onAddRow: () => void
onAddColumn: () => void
onDeleteTable: () => void
}
const PRESET_COLORS = [
"#111827",
"#374151",
"#6B7280",
"#9CA3AF",
"#D1D5DB",
"#EF4444",
"#F97316",
"#F59E0B",
"#84CC16",
"#22C55E",
"#06B6D4",
"#3B82F6",
"#6366F1",
"#A855F7",
"#EC4899",
];
'#111827', '#374151', '#6B7280', '#9CA3AF', '#D1D5DB', '#EF4444', '#F97316', '#F59E0B',
'#84CC16', '#22C55E', '#06B6D4', '#3B82F6', '#6366F1', '#A855F7', '#EC4899',
]
const HIGHLIGHT_COLORS = ['#FEF3C7', '#FDE68A', '#A7F3D0', '#BAE6FD', '#DDD6FE', '#FBCFE8', '#FFE4E6', '#E5E7EB', '#F5F5F4', '#FFFFFF']
function Swatch({ color }: { color: string | null }) {
return (
<span
className="ml-1 inline-block h-2 w-2 rounded-full border align-middle"
style={{ backgroundColor: color ?? "transparent" }}
/>
);
return <span className="ml-1 inline-block size-2 rounded-full border" style={{ backgroundColor: color ?? 'transparent' }} />
}
export function Toolbar({
editor,
state,
config,
className,
canImageUpload,
onPickImage,
@@ -100,230 +78,206 @@ export function Toolbar({
onUnsetTextColor,
onSetHighlight,
onUnsetHighlight,
onToggleLink,
linkUrl,
onSetLink,
onUnsetLink,
onInsertTable,
onAddRow,
onAddColumn,
onDeleteTable,
}: Props) {
}: ToolbarProps) {
const enabled = (feature: KriEditorToolbarFeature) => config?.[feature] !== false
const showTextStyle = enabled('bold') || enabled('italic') || enabled('underline') || enabled('strike')
const showColors = enabled('textColor') || enabled('highlight')
const showLists = enabled('bulletList') || enabled('orderedList')
const [linkOpen, setLinkOpen] = useState(false)
const [linkDraft, setLinkDraft] = useState(linkUrl)
useEffect(() => {
if (linkOpen) setLinkDraft(linkUrl)
}, [linkOpen, linkUrl])
const applyLink = () => {
const next = linkDraft.trim()
if (!next) return
onSetLink(next)
setLinkOpen(false)
}
return (
<div className={cn("flex items-center gap-1 whitespace-nowrap px-2 py-1", className)}>
<select
className="h-8 w-[72px] rounded-md border bg-background px-2 text-sm"
value={state.fontSize}
onChange={(e) => onSetFontSize(e.target.value)}
title="폰트 크기"
>
{["12px","14px","16px","18px","20px","24px","28px","32px"].map((v) => (
<option key={v} value={v}>
{v.replace("px","")}
</option>
))}
</select>
<div className={cn('flex items-center gap-1 overflow-x-auto whitespace-nowrap px-2 py-1', className)}>
{enabled('fontSize') ? (
<select
className="h-8 w-[72px] rounded-md border bg-background px-2 text-sm"
value={state.fontSize}
onChange={(event) => onSetFontSize(event.target.value)}
title="폰트 크기"
>
{['12px', '14px', '16px', '18px', '20px', '24px', '28px', '32px'].map((value) => (
<option key={value} value={value}>{value.replace('px', '')}</option>
))}
</select>
) : null}
<Separator orientation="vertical" className="mx-1 h-6" />
{enabled('fontSize') && showTextStyle ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
<ToolbarButton
active={state.isBold}
disabled={!editor.can().chain().focus().toggleBold().run()}
onClick={() => editor.chain().focus().toggleBold().run()}
title="굵게"
>
<Bold className="h-4 w-4" />
</ToolbarButton>
{enabled('bold') ? (
<ToolbarButton active={state.isBold} disabled={!editor.can().chain().focus().toggleBold().run()} onClick={() => editor.chain().focus().toggleBold().run()} title="굵게">
<Bold className="size-4" />
</ToolbarButton>
) : null}
{enabled('italic') ? (
<ToolbarButton active={state.isItalic} disabled={!editor.can().chain().focus().toggleItalic().run()} onClick={() => editor.chain().focus().toggleItalic().run()} title="기울임">
<Italic className="size-4" />
</ToolbarButton>
) : null}
{enabled('underline') ? (
<ToolbarButton active={state.isUnderline} onClick={() => editor.chain().focus().toggleUnderline().run()} title="밑줄">
<Underline className="size-4" />
</ToolbarButton>
) : null}
{enabled('strike') ? (
<ToolbarButton active={state.isStrike} onClick={() => editor.chain().focus().toggleStrike().run()} title="취소선">
<Strikethrough className="size-4" />
</ToolbarButton>
) : null}
<ToolbarButton
active={state.isItalic}
disabled={!editor.can().chain().focus().toggleItalic().run()}
onClick={() => editor.chain().focus().toggleItalic().run()}
title="기울임"
>
<Italic className="h-4 w-4" />
</ToolbarButton>
{showTextStyle && showColors ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
<ToolbarButton active={state.isUnderline} onClick={() => editor.chain().focus().toggleUnderline().run()} title="밑줄">
<Underline className="h-4 w-4" />
</ToolbarButton>
{enabled('textColor') ? (
<Popover>
<PopoverTrigger asChild>
<span>
<ToolbarButton title="텍스트 색상" active={Boolean(state.textColor)}>
<Palette className="size-4" /><Swatch color={state.textColor} />
</ToolbarButton>
</span>
</PopoverTrigger>
<PopoverContent className="w-56" align="start">
<div className="text-muted-foreground mb-2 text-xs">텍스트 색상</div>
<div className="grid grid-cols-5 gap-2">
{PRESET_COLORS.map((color) => (
<button key={color} type="button" className="size-6 rounded border" style={{ backgroundColor: color }} onMouseDown={(event) => event.preventDefault()} onClick={() => onSetTextColor(color)} aria-label={`색상 ${color}`} />
))}
</div>
<div className="mt-3 flex items-center gap-2">
<input type="color" className="h-8 w-10 cursor-pointer rounded-md border p-1" onMouseDown={(event) => event.preventDefault()} onChange={(event) => onSetTextColor(event.target.value)} aria-label="사용자 지정 텍스트 색상" />
<button type="button" className="text-muted-foreground text-xs underline" onMouseDown={(event) => event.preventDefault()} onClick={onUnsetTextColor}>색상 제거</button>
</div>
</PopoverContent>
</Popover>
) : null}
<ToolbarButton active={state.isStrike} onClick={() => editor.chain().focus().toggleStrike().run()} title="취소선">
<Strikethrough className="h-4 w-4" />
</ToolbarButton>
{enabled('highlight') ? (
<Popover>
<PopoverTrigger asChild>
<span>
<ToolbarButton title="하이라이트" active={Boolean(state.highlightColor)}>
<Highlighter className="size-4" /><Swatch color={state.highlightColor} />
</ToolbarButton>
</span>
</PopoverTrigger>
<PopoverContent className="w-56" align="start">
<div className="text-muted-foreground mb-2 text-xs">하이라이트</div>
<div className="grid grid-cols-5 gap-2">
{HIGHLIGHT_COLORS.map((color) => (
<button key={color} type="button" className="size-6 rounded border" style={{ backgroundColor: color }} onMouseDown={(event) => event.preventDefault()} onClick={() => onSetHighlight(color)} aria-label={`하이라이트 ${color}`} />
))}
</div>
<div className="mt-3 flex items-center gap-2">
<input type="color" className="h-8 w-10 cursor-pointer rounded-md border p-1" onMouseDown={(event) => event.preventDefault()} onChange={(event) => onSetHighlight(event.target.value)} aria-label="사용자 지정 하이라이트" />
<button type="button" className="text-muted-foreground text-xs underline" onMouseDown={(event) => event.preventDefault()} onClick={onUnsetHighlight}>하이라이트 제거</button>
</div>
</PopoverContent>
</Popover>
) : null}
<Popover>
<PopoverTrigger asChild>
<span>
<ToolbarButton title="텍스트 색상" active={Boolean(state.textColor)}>
<Palette className="h-4 w-4" />
<Swatch color={state.textColor} />
</ToolbarButton>
</span>
</PopoverTrigger>
<PopoverContent className="w-56" align="start">
<div className="mb-2 text-xs text-muted-foreground">텍스트 색상</div>
<div className="grid grid-cols-5 gap-2">
{PRESET_COLORS.map((c) => (
<button
key={c}
type="button"
className="h-6 w-6 rounded border"
style={{ backgroundColor: c }}
onMouseDown={(e) => e.preventDefault()}
onClick={() => onSetTextColor(c)}
aria-label={`color ${c}`}
/>
))}
</div>
<div className="mt-3 flex items-center gap-2">
<input
type="color"
className="h-8 w-10 cursor-pointer rounded-md border p-1"
onMouseDown={(e) => e.preventDefault()}
onChange={(e) => onSetTextColor(e.target.value)}
aria-label="custom text color"
/>
<button type="button" className="text-xs text-muted-foreground underline" onMouseDown={(e) => e.preventDefault()} onClick={onUnsetTextColor}>
색상 제거
</button>
</div>
</PopoverContent>
</Popover>
{showColors && enabled('align') ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
<Popover>
<PopoverTrigger asChild>
<span>
<ToolbarButton active={Boolean(state.highlightColor)} title="하이라이트">
<Highlighter className="h-4 w-4" />
<Swatch color={state.highlightColor} />
</ToolbarButton>
</span>
</PopoverTrigger>
<PopoverContent className="w-56" align="start">
<div className="mb-2 text-xs text-muted-foreground">하이라이트</div>
<div className="grid grid-cols-5 gap-2">
{["#FEF3C7", "#FDE68A", "#A7F3D0", "#BAE6FD", "#DDD6FE", "#FBCFE8", "#FFE4E6", "#E5E7EB", "#F5F5F4", "#FFFFFF"].map(
(c) => (
<button
key={c}
type="button"
className="h-6 w-6 rounded border"
style={{ backgroundColor: c }}
onMouseDown={(e) => e.preventDefault()}
onClick={() => onSetHighlight(c)}
aria-label={`highlight ${c}`}
{enabled('align') ? (
<>
<ToolbarButton active={state.align === 'left'} onClick={() => editor.chain().focus().setTextAlign('left').run()} title="왼쪽 정렬"><AlignLeft className="size-4" /></ToolbarButton>
<ToolbarButton active={state.align === 'center'} onClick={() => editor.chain().focus().setTextAlign('center').run()} title="가운데 정렬"><AlignCenter className="size-4" /></ToolbarButton>
<ToolbarButton active={state.align === 'right'} onClick={() => editor.chain().focus().setTextAlign('right').run()} title="오른쪽 정렬"><AlignRight className="size-4" /></ToolbarButton>
</>
) : null}
{enabled('align') && showLists ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
{enabled('bulletList') ? <ToolbarButton active={state.isBulletList} onClick={() => editor.chain().focus().toggleBulletList().run()} title="불릿"><List className="size-4" /></ToolbarButton> : null}
{enabled('orderedList') ? <ToolbarButton active={state.isOrderedList} onClick={() => editor.chain().focus().toggleOrderedList().run()} title="번호"><ListOrdered className="size-4" /></ToolbarButton> : null}
{showLists && (enabled('link') || enabled('image') || enabled('table')) ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
{enabled('link') ? (
<Popover open={linkOpen} onOpenChange={setLinkOpen}>
<PopoverTrigger asChild>
<span>
<ToolbarButton active={state.isLink} title={state.isLink ? '링크 수정' : '링크 삽입'}>
<Link2 className="size-4" />
</ToolbarButton>
</span>
</PopoverTrigger>
<PopoverContent className="w-80" align="start">
<form
className="space-y-3"
onSubmit={(event) => {
event.preventDefault()
applyLink()
}}
>
<div className="space-y-1.5">
<label htmlFor="kri-editor-link-url" className="text-sm font-medium">링크 URL</label>
<Input
id="kri-editor-link-url"
value={linkDraft}
onChange={(event) => setLinkDraft(event.target.value)}
placeholder="https://example.com"
autoFocus
/>
)
)}
</div>
<div className="mt-3 flex items-center gap-2">
<input
type="color"
className="h-8 w-10 cursor-pointer rounded-md border p-1"
onMouseDown={(e) => e.preventDefault()}
onChange={(e) => onSetHighlight(e.target.value)}
aria-label="custom highlight color"
/>
<button type="button" className="text-xs text-muted-foreground underline" onMouseDown={(e) => e.preventDefault()} onClick={onUnsetHighlight}>
하이라이트 제거
</button>
</div>
</PopoverContent>
</Popover>
</div>
<div className="flex justify-end gap-2">
{state.isLink ? (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => {
onUnsetLink()
setLinkOpen(false)
}}
>
링크 해제
</Button>
) : null}
<Button type="submit" size="sm" disabled={!linkDraft.trim()}>적용</Button>
</div>
</form>
</PopoverContent>
</Popover>
) : null}
{enabled('image') ? <ToolbarButton title={canImageUpload ? '이미지 업로드' : 'onImageUpload 미설정'} disabled={!canImageUpload} onClick={onPickImage}><ImageIcon className="size-4" /></ToolbarButton> : null}
<Separator orientation="vertical" className="mx-1 h-6" />
{enabled('table') ? (
<DropdownMenu>
<DropdownMenuTrigger asChild><span><ToolbarButton title="표"><Table2 className="size-4" /></ToolbarButton></span></DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-44">
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onInsertTable() }}>표 삽입</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onAddRow() }} disabled={!state.inTable}>행 추가</DropdownMenuItem>
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onAddColumn() }} disabled={!state.inTable}>열 추가</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onDeleteTable() }} disabled={!state.inTable} className="text-destructive">표 삭제</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : null}
<ToolbarButton active={state.align === "left"} onClick={() => editor.chain().focus().setTextAlign("left").run()} title="왼쪽 정렬">
<AlignLeft className="h-4 w-4" />
</ToolbarButton>
<ToolbarButton active={state.align === "center"} onClick={() => editor.chain().focus().setTextAlign("center").run()} title="가운데 정렬">
<AlignCenter className="h-4 w-4" />
</ToolbarButton>
<ToolbarButton active={state.align === "right"} onClick={() => editor.chain().focus().setTextAlign("right").run()} title="오른쪽 정렬">
<AlignRight className="h-4 w-4" />
</ToolbarButton>
<Separator orientation="vertical" className="mx-1 h-6" />
<ToolbarButton active={state.isBulletList} onClick={() => editor.chain().focus().toggleBulletList().run()} title="불릿">
<List className="h-4 w-4" />
</ToolbarButton>
<ToolbarButton active={state.isOrderedList} onClick={() => editor.chain().focus().toggleOrderedList().run()} title="번호">
<ListOrdered className="h-4 w-4" />
</ToolbarButton>
<Separator orientation="vertical" className="mx-1 h-6" />
<ToolbarButton active={state.isLink} title={state.isLink ? "링크 해제" : "링크 삽입"} onClick={onToggleLink}>
<Link2 className="h-4 w-4" />
</ToolbarButton>
<Separator orientation="vertical" className="mx-1 h-6" />
<ToolbarButton title={canImageUpload ? "이미지 업로드" : "onImageUpload 미설정"} disabled={!canImageUpload} onClick={onPickImage}>
<ImageIcon className="h-4 w-4" />
</ToolbarButton>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<span>
<ToolbarButton title="표">
<Table2 className="h-4 w-4" />
</ToolbarButton>
</span>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-44">
<DropdownMenuItem
onSelect={(e) => {
e.preventDefault();
onInsertTable();
}}
>
표 삽입
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={(e) => {
e.preventDefault();
onAddRow();
}}
disabled={!state.inTable}
>
행 추가
</DropdownMenuItem>
<DropdownMenuItem
onSelect={(e) => {
e.preventDefault();
onAddColumn();
}}
disabled={!state.inTable}
>
열 추가
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={(e) => {
e.preventDefault();
onDeleteTable();
}}
disabled={!state.inTable}
className="text-destructive"
>
표 삭제
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{showHtmlToggle && (
{showHtmlToggle && enabled('html') ? (
<>
<Separator orientation="vertical" className="mx-1 h-6" />
<ToolbarButton active={isHtmlView} title={isHtmlView ? "WYSIWYG로" : "HTML 편집"} onClick={onToggleHtmlView}>
<Code2 className="h-4 w-4" />
</ToolbarButton>
<ToolbarButton active={isHtmlView} title={isHtmlView ? 'WYSIWYG로 전환' : 'HTML 편집'} onClick={onToggleHtmlView}><Code2 className="size-4" /></ToolbarButton>
</>
)}
) : null}
</div>
);
)
}

View File

@@ -1,87 +1,76 @@
import {Editor} from "@tiptap/react";
import type { Editor } from '@tiptap/react'
export type UploadResult = { url: string };
export type KriEditorMode = 'wysiwyg' | 'both' | 'html' | 'sms'
export type KriEditorUploadResult = string | { url: string }
export type KriEditorMode = "wysiwyg" | "both" | "html" | "sms";
export type KriEditorToolbarFeature =
| 'fontSize'
| 'bold'
| 'italic'
| 'underline'
| 'strike'
| 'textColor'
| 'highlight'
| 'align'
| 'bulletList'
| 'orderedList'
| 'link'
| 'image'
| 'table'
| 'html'
export type KriEditorToolbarConfig = Partial<Record<KriEditorToolbarFeature, boolean>>
export type KriEditorCommand = {
focus: () => void;
insertText: (text: string) => void; // placeholder/merge-field 삽입
};
focus: () => void
insertText: (text: string) => void
}
export type KriEditorProps = {
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void;
onCommandReady?: (cmd: KriEditorCommand | null) => void;
label?: string;
value: string;
onChange: (html: string) => void;
placeholder?: string;
className?: string;
showPreview?: boolean;
previewClassName?: string;
/**
* 모드:
* - "wysiwyg": WYSIWYG 전용
* - "html": HTML 전용
* - "both": 툴바에서 WYSIWYG / HTML 전환 가능
* - "sms": SMS 문자 전용 (링크만)
*
* props.mode 가 없으면 editorMode 를 참고하고,
* 둘 다 없으면 "wysiwyg" 으로 동작.
*/
mode?: KriEditorMode;
editorMode?: KriEditorMode;
// 이미지 업로드 (없으면 이미지 버튼 비활성)
onImageUpload?: (file: File) => Promise<UploadResult>;
// 이미지 압축 옵션
maxImageBytes?: number;
imageMaxWidth?: number;
imageMaxHeight?: number;
imageQuality?: number;
imageMimeType?: "image/webp" | "image/jpeg";
// base64 허용 여부 (기본: false)
allowBase64?: boolean;
// HTML을 setHTML 전에 sanitize 할지 여부 (기본: true)
sanitizeHtml?: boolean;
// HTML 전용 모드에서 textarea rows
rows?: number;
// 이미지 업로드 실패 시 콜백
onImageUploadError?: (error: unknown) => void;
// onChange 디바운스 시간 (ms)
debounceMs?: number;
// SMS 모드 전용 props
smsTitle?: string; // LMS 제목용
changeSmsType?: (type: "SMS" | "LMS") => void;
};
isSmsReadOnly?: boolean
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void
onCommandReady?: (command: KriEditorCommand | null) => void
label?: string
value: string
onChange: (html: string) => void
placeholder?: string
className?: string
showPreview?: boolean
previewClassName?: string
mode?: KriEditorMode
onImageUpload?: (file: File) => Promise<KriEditorUploadResult>
maxImageBytes?: number
imageMaxWidth?: number
imageMaxHeight?: number
imageQuality?: number
imageMimeType?: 'image/webp' | 'image/jpeg'
allowBase64?: boolean
sanitizeHtml?: boolean
rows?: number
onImageUploadError?: (error: unknown) => void
debounceMs?: number
smsTitle?: string
changeSmsType?: (type: 'SMS' | 'LMS') => void
smsMaxBytes?: number
lmsMaxBytes?: number
toolbar?: KriEditorToolbarConfig | false
}
export type ToolbarState = {
fontSize: string;
textColor: string | null;
highlightColor: string | null;
fontSize: string
textColor: string | null
highlightColor: string | null
isBold: boolean
isItalic: boolean
isUnderline: boolean
isStrike: boolean
align: 'left' | 'center' | 'right'
isBulletList: boolean
isOrderedList: boolean
isLink: boolean
inTable: boolean
}
isBold: boolean;
isItalic: boolean;
isUnderline: boolean;
isStrike: boolean;
align: "left" | "center" | "right";
isBulletList: boolean;
isOrderedList: boolean;
isLink: boolean;
inTable: boolean;
};
export function resolveUploadUrl(result: KriEditorUploadResult): string {
return typeof result === 'string' ? result : result.url
}

View File

@@ -1,9 +1,9 @@
import type { Editor } from '@tiptap/react';
import type { Editor } from '@tiptap/react'
export function isTipTapEditor(editor: any): editor is Editor {
return editor && typeof editor.chain === 'function';
export function isTipTapEditor(value: unknown): value is Editor {
return Boolean(value && typeof value === 'object' && 'chain' in value && typeof value.chain === 'function')
}
export function isTextAreaElement(element: any): element is HTMLTextAreaElement {
return element instanceof HTMLTextAreaElement;
}
export function isTextAreaElement(value: unknown): value is HTMLTextAreaElement {
return typeof HTMLTextAreaElement !== 'undefined' && value instanceof HTMLTextAreaElement
}