251212_01_ENH : kri-editor 1차 완성, 프로젝트 정보 저장 api연동 완료

This commit is contained in:
2025-12-12 17:27:12 +09:00
parent 1080880fba
commit d9775c8a1d
46 changed files with 2124 additions and 1668 deletions

View File

@@ -1,6 +1,6 @@
'use client'
import { useMemo, useState } from 'react'
import {useEffect, useMemo, useState} from 'react'
import {
Dialog,
DialogContent,
@@ -11,104 +11,161 @@ import {
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {Trash2, Plus, Download, Search, XIcon} from 'lucide-react'
export type ResultCode = {
code: string
label: string
}
type Project = {
prjctCd: string
prjctName: string
resultCodes: ResultCode[]
}
import {ProjectInfo, ResultCode} from "@/types/project";
import {nextApi} from "@/lib/http-client";
import {PROJECT_SEARCH_COUNT, RESULT_CODE_TYPE_OPTIONS, ResultCodeType} from "@/const/projectConst";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {SelectedProject} from "@/store/jotai/project";
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
import {useSelectedProject} from "@/hooks/useSelectedProject";
import {useMounted} from "@/hooks/useMounted";
import _ from "lodash";
type ResultCodeDialogProps = {
open?: boolean
onOpenChange?: (open: boolean) => void
onSave?: (codes: ResultCode[]) => void
changeCodeType: ResultCodeType[]
onChangeCodeType: (code: ResultCodeType[]) => void | Promise<void>
sourceArray: ResultCode[]
onSave?: (codes: ResultCode[]) => void | Promise<void>
}
const ResultCodeDialog = ({ open, onOpenChange, onSave }: ResultCodeDialogProps) => {
const ResultCodeDialog = ({
open,
onOpenChange,
changeCodeType,
onChangeCodeType,
sourceArray,
onSave,
}: ResultCodeDialogProps) => {
const mounted = useMounted();
const { selectedProject } = useSelectedProject();
const [importMode, setImportMode] = useState(false)
const [selectedProject, setSelectedProject] = useState<string>('')
const [resultCodeType, setResultCodeType] = useState<ResultCodeType>(ResultCodeType.CONTACT)
const [resultCodeArray, setResultCodeArray] = useState<ResultCode[]>([])
const [importCodeArray, setImportCodeArray] = useState<ResultCode[]>([])
const [resultCodes, setResultCodes] = useState<ResultCode[]>([
{ code: '0', label: '컨택 성공' },
{ code: '1', label: '통화 예약' },
{ code: '2', label: '비수신' },
{ code: '3', label: '부재' },
{ code: '4', label: '휴가' },
{ code: '5', label: '출장' },
{ code: '6', label: '단순 거절' },
{ code: '7', label: '강력 거절' },
{ code: '8', label: '그런 사람 아님' },
{ code: '9', label: '메일 발송' },
{ code: '10', label: '독려' },
{ code: '11', label: '퇴사' },
{ code: '12', label: '기타' },
{ code: '13', label: '조사 대상 아님' },
{ code: '14', label: '수신 거부' },
])
const [searchKeyword, setSearchKeyword] = useState('')
const debouncedKeyword = useDebouncedValue(searchKeyword, 500);
const [projectArray, setProjectArray] = useState<SelectedProject[]>([]);
const [importProject, setImportProject] = useState<SelectedProject|undefined>(undefined)
// 샘플 프로젝트 목록 (실제로는 API에서 가져옴)
const projects: Project[] = [
{
prjctCd: '250701yd',
prjctName: '250701yd',
resultCodes: [
{ code: '0', label: '완료' },
{ code: '1', label: '거절' },
{ code: '2', label: '진행중' },
],
},
{
prjctCd: '1509013',
prjctName: '1509013_J2307KJC_KFB_저기 1차 카카오톡 AUTOAGI_#01250Group',
resultCodes: [
{ code: '0', label: '성공' },
{ code: '1', label: '실패' },
{ code: '2', label: '보류' },
],
},
{
prjctCd: '1503013',
prjctName: '1503013_J2307KJC_KFB_저기 1차 카카오톡 AUTOAGI_그룹01테스트0',
resultCodes: [
{ code: '0', label: '승인' },
{ code: '1', label: '반려' },
],
},
]
const searchTopProject = async (keyword: string) => {
const res = await nextApi.get<ProjectInfo[]>(
`/project/top/${PROJECT_SEARCH_COUNT}`,
{ query: { keyword } }
);
const [projectSearch, setProjectSearch] = useState('')
const filteredProjects = useMemo(() => {
const q = projectSearch.trim().toLowerCase()
if (!q) return projects
return projects.filter(p =>
`${p.prjctCd} ${p.prjctName}`.toLowerCase().includes(q)
)
}, [projectSearch])
setProjectArray(res.filter((prjct) => prjct.prjctCd !== selectedProject?.prjctCd));
};
const selectedProjectData = useMemo(
() => projects.find(p => p.prjctCd === selectedProject),
[selectedProject]
)
const handleSelectProject = (info:SelectedProject|null) => {
if(info === null) return;
setImportProject(info);
}
const handleAddCode = () => {
setResultCodes(prev => [...prev, { code: String(prev.length), label: '' }])
if(resultCodeArray.length === 0) return setResultCodeArray([]);
const lastCode = resultCodeArray[resultCodeArray.length - 1].resultCd;
setResultCodeArray(prev => [
...prev,
{
resultCdUUID: crypto.randomUUID(),
prjctIdx: selectedProject!.prjctIdx,
resultCdTy: resultCodeType,
resultCd: lastCode + 1,
resultCdLbl: '',
}
])
}
const handleDeleteCode = (index: number) => {
setResultCodes(prev => prev.filter((_, i) => i !== index))
const handleDeleteCode = (resultCd: number) => {
setResultCodeArray(prev =>
prev.filter(
rc => !(rc.resultCdTy === resultCodeType && rc.resultCd === resultCd),
),
);
};
const handleCodeChange = (resultCdUUID: string, field: keyof ResultCode, value: string) => {
let replaceValue:string|number = value;
if(field === 'resultCd'){
value = value.replace(/[^0-9]/g, '');
replaceValue = Number(value);
}
setResultCodeArray(prev => {
const idx = prev.findIndex(
rc => rc.resultCdUUID === resultCdUUID,
);
if (idx === -1) return prev; // 못 찾으면 그대로
const next = [...prev];
next[idx] = {
...next[idx],
[field]: replaceValue,
};
return next;
});
if (!changeCodeType.includes(resultCodeType)) {
onChangeCodeType([...changeCodeType, resultCodeType]);
}
}
const handleCodeChange = (index: number, field: keyof ResultCode, value: string) => {
setResultCodes(prev => {
const next = [...prev]
next[index] = { ...next[index], [field]: value }
return next
})
const checkAllDuplicate = (): boolean => {
const map = new Map<string, ResultCode[]>();
for (const row of resultCodeArray) {
if (row.resultCd === undefined || row.resultCd === null) continue;
if (!row.resultCdTy) continue;
const key = `${row.resultCdTy}-${row.resultCd}`;
const list = map.get(key) ?? [];
list.push(row);
map.set(key, list);
}
// 타입별/코드별로 2개 이상 있는 것만 추려내기
const duplicatedList: string[] = [];
for (const [key, list] of map.entries()) {
if (list.length > 1) {
const [ty, cd] = key.split("-");
duplicatedList.push(`(${ty}) ${cd}`);
}
}
if (duplicatedList.length > 0) {
alert(`중복된 코드가 있습니다:\n${duplicatedList.join(", ")}`);
return false;
}
return true;
};
const checkDuplicate = (
resultCdUUID: string,
resultCd: number,
target: HTMLInputElement
) => {
const hasDup = resultCodeArray.some(
(rc) => rc.resultCdTy === resultCodeType && rc.resultCd === resultCd && rc.resultCdUUID !== resultCdUUID
);
if (hasDup) {
alert("코드가 중복됩니다.");
// 바로 focus()를 호출하면 blur 연쇄가 생길 수 있어 살짝 지연
setTimeout(() => {
target.focus();
target.select(); // 선택까지 해주면 바로 수정하기 편함
}, 50);
return false;
}
return true;
}
const handleImportClick = () => {
@@ -116,38 +173,67 @@ const ResultCodeDialog = ({ open, onOpenChange, onSave }: ResultCodeDialogProps)
}
const handleImportApply = () => {
if (selectedProjectData) {
setResultCodes(selectedProjectData.resultCodes)
setImportMode(false)
setSelectedProject('')
setProjectSearch('')
if (importProject) {
setResultCodeArray(_.cloneDeep(importCodeArray.filter(rc => rc.resultCdTy === resultCodeType)));
if (!changeCodeType.includes(resultCodeType)) {
onChangeCodeType([...changeCodeType, resultCodeType]);
}
clearImport();
}
}
const handleImportCancel = () => {
setImportMode(false)
setSelectedProject('')
setProjectSearch('')
clearImport();
}
const handleSave = () => {
onSave?.(resultCodes)
const dupOk = checkAllDuplicate();
if (!dupOk) {
return;
}
onSave?.(resultCodeArray)
onOpenChange?.(false)
setImportMode(false)
setSelectedProject('')
setProjectSearch('')
}
const handleClose = () => {
onOpenChange?.(false)
setImportMode(false)
setSelectedProject('')
setProjectSearch('')
}
const clearImport = () => {
setImportMode(false);
setImportProject(undefined);
setSearchKeyword('');
}
useEffect(() => {
if(open){
setResultCodeType(ResultCodeType.CONTACT);
setResultCodeArray(sourceArray);
}
else{
clearImport();
}
}, [open]);
useEffect(() => {
if(importProject){
nextApi.get<ResultCode[]>(`/project/result-code/${importProject.prjctIdx}`)
.then((res) => setImportCodeArray(res));
}
}, [importProject]);
useEffect(() => {
const keyword = debouncedKeyword.trim();
searchTopProject(keyword);
}, [debouncedKeyword]);
return (
<Dialog open={open} onOpenChange={handleClose}>
{/* ✅ importMode일 때 더 넓게(그리고 애니메이션으로 부드럽게) */}
{/* importMode일 때 더 넓게(그리고 애니메이션으로 부드럽게) */}
<DialogContent
className={[
'p-0 overflow-hidden',
@@ -178,22 +264,47 @@ const ResultCodeDialog = ({ open, onOpenChange, onSave }: ResultCodeDialogProps)
) : (
<div className="flex items-center gap-2 w-130">
<div className="relative flex-1">
<Search className="w-4 h-4 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
<Input
value={projectSearch}
onChange={(e) => setProjectSearch(e.target.value)}
placeholder="프로젝트 코드/이름 검색..."
className="h-9 pl-9"
/>
<KriSingleSelect
<SelectedProject>
items={projectArray}
value={String(importProject?.prjctIdx || "")}
onChange={() => {}}
withInfo
onItemChange={handleSelectProject}
searchMode="inputOnly"
onSearchValueChange={setSearchKeyword}
placeholder="프로젝트 검색..."
widthClassName="w-full"
heightClassName="h-9"
preventDeselect
hideOptionCheck
getLabel={(item) => `${item.prjctCd}_${item.prjctName}`}
getValue={(item) => String(item.prjctIdx)}
/>
</div>
</div>
)}
</div>
<div className="px-6 pt-4 flex flex-wrap items-center gap-2">
{RESULT_CODE_TYPE_OPTIONS
.filter((opt) => opt.value !== ResultCodeType.SURVEY)
.map((opt) => (
<Button
key={opt.value}
type="button"
variant={resultCodeType === opt.value ? "default" : "outline"}
size="sm"
onClick={() => setResultCodeType(opt.value)}
className="px-3"
>
{opt.label}
</Button>
))}
</div>
{/* 본문 */}
<div className={importMode ? 'grid grid-cols-1 lg:grid-cols-2' : 'block'}>
{/* 왼쪽: 결과 코드 */}
<div className="p-6">
<div className="px-6 pb-6">
<div className="rounded-lg border bg-white overflow-hidden">
<div className="px-4 py-3 border-b bg-gray-50 flex items-center justify-between">
<div className="font-semibold text-sm text-gray-900">결과 코드 목록</div>
@@ -205,9 +316,9 @@ const ResultCodeDialog = ({ open, onOpenChange, onSave }: ResultCodeDialogProps)
)}
</div>
<div className="max-h-[420px] overflow-y-auto">
<div className="max-h-[420px] overflow-y-auto relative">
<table className="w-full text-sm">
<thead className="sticky top-0 bg-white border-b">
<thead className="sticky top-0 bg-white border-b z-10">
<tr className="text-gray-600">
<th className="px-4 py-2 text-left w-36">코드</th>
<th className="px-4 py-2 text-left">레이블</th>
@@ -215,20 +326,23 @@ const ResultCodeDialog = ({ open, onOpenChange, onSave }: ResultCodeDialogProps)
</tr>
</thead>
<tbody className="divide-y">
{resultCodes.map((code, index) => (
{resultCodeArray
.filter((rc) => rc.resultCdTy === resultCodeType)
.map((code, index) => (
<tr key={index} className="hover:bg-gray-50">
<td className="px-4 py-2 align-middle">
<Input
value={code.code}
onChange={(e) => handleCodeChange(index, 'code', e.target.value)}
value={code.resultCd}
onChange={(e) => handleCodeChange(code.resultCdUUID, 'resultCd', e.target.value)}
onBlur={(e) => checkDuplicate(code.resultCdUUID, Number(e.target.value), e.target)}
className="h-9"
disabled={importMode}
/>
</td>
<td className="px-4 py-2 align-middle">
<Input
value={code.label}
onChange={(e) => handleCodeChange(index, 'label', e.target.value)}
value={code.resultCdLbl}
onChange={(e) => handleCodeChange(code.resultCdUUID, 'resultCdLbl', e.target.value)}
className="h-9"
disabled={importMode}
/>
@@ -268,20 +382,22 @@ const ResultCodeDialog = ({ open, onOpenChange, onSave }: ResultCodeDialogProps)
<div className="font-semibold text-sm text-gray-900">미리보기</div>
</div>
<div className="max-h-[180px] overflow-y-auto">
{selectedProjectData ? (
<div className="max-h-[420px] overflow-y-auto relative">
{importProject ? (
<table className="w-full text-sm">
<thead className="sticky top-0 bg-white border-b">
<thead className="sticky top-0 bg-white border-b z-10">
<tr className="text-gray-600">
<th className="px-4 py-2 text-left w-32">코드</th>
<th className="px-4 py-2 text-left">레이블</th>
</tr>
</thead>
<tbody className="divide-y">
{selectedProjectData.resultCodes.map((code, idx) => (
{importCodeArray
.filter((rc) => rc.resultCdTy === resultCodeType)
.map((code, idx) => (
<tr key={idx}>
<td className="px-4 py-2">{code.code}</td>
<td className="px-4 py-2">{code.label}</td>
<td className="px-4 py-2">{code.resultCd}</td>
<td className="px-4 py-2">{code.resultCdLbl}</td>
</tr>
))}
</tbody>
@@ -301,7 +417,7 @@ const ResultCodeDialog = ({ open, onOpenChange, onSave }: ResultCodeDialogProps)
<Button variant="outline" onClick={handleImportCancel}>
취소
</Button>
<Button onClick={handleImportApply} disabled={!selectedProject} className="gap-2">
<Button onClick={handleImportApply} disabled={!importProject} className="gap-2">
<Download className="w-4 h-4" />
가져오기 적용
</Button>

View File

@@ -1,196 +1,19 @@
"use client";
import * as React from "react";
import { EditorContent, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Underline from "@tiptap/extension-underline";
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 type { KriEditorProps, KriEditorMode } from "./types";
import { KriEditorHtmlOnly } from "./KriEditorHtmlOnly";
import { KriEditorWysiwyg } from "./KriEditorWysiwyg";
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";
function resolveMode(mode?: KriEditorMode, editorMode?: KriEditorMode): KriEditorMode {
return mode ?? editorMode ?? "wysiwyg";
}
import { toast } from "sonner";
import { cn } from "@/lib/utils";
export function KriEditor(props: KriEditorProps) {
const mode = resolveMode(props.mode, props.editorMode);
import { compressImage } from "./utils/imageCompression";
import { Toolbar } from "./toolbar/Toolbar";
if (mode === "html") {
return <KriEditorHtmlOnly {...props} mode={mode} editorMode={mode} />;
}
export type UploadResult = { url: string };
export type KriEditorProps = {
value: string;
onChange: (html: string) => void;
placeholder?: string;
className?: string;
onImageUpload?: (file: File) => Promise<UploadResult>;
maxImageBytes?: number;
imageMaxWidth?: number;
imageMaxHeight?: number;
imageQuality?: number;
imageMimeType?: "image/webp" | "image/jpeg";
allowBase64?: boolean;
};
export const KriEditor: React.FC<KriEditorProps> = ({
value,
onChange,
placeholder = "내용을 입력하세요…",
className,
onImageUpload,
maxImageBytes = 5 * 1024 * 1024,
imageMaxWidth = 1600,
imageMaxHeight = 1600,
imageQuality = 0.82,
imageMimeType = "image/webp",
allowBase64 = false,
}) => {
const fileRef = React.useRef<HTMLInputElement | null>(null);
const editor = useEditor(
{
immediatelyRender: false,
extensions: [
StarterKit.configure({
blockquote: false,
codeBlock: false,
code: false,
}),
Underline,
Link.configure({
openOnClick: false,
autolink: true,
linkOnPaste: true,
HTMLAttributes: {
class: "text-blue-600 underline underline-offset-2",
},
}),
TextAlign.configure({ types: ["heading", "paragraph"] }),
Table.configure({
resizable: true,
HTMLAttributes: {
class: "w-full table-fixed border-collapse border border-border my-2",
},
}),
TableRow,
TableHeader.configure({
HTMLAttributes: {
class: "border border-border bg-muted px-2 py-1 font-semibold align-top",
},
}),
TableCell.configure({
HTMLAttributes: {
class: "border border-border px-2 py-1 align-top min-w-[80px]",
},
}),
TiptapImage.configure({ allowBase64 }),
Placeholder.configure({ placeholder }),
],
content: value || "<p></p>",
onUpdate: ({ editor }) => onChange(editor.getHTML()),
editorProps: {
attributes: {
class:
"prose prose-sm max-w-none focus:outline-none min-h-[220px] px-0 py-2 " +
"prose-headings:mt-6 prose-headings:mb-3 " +
"prose-p:my-2 prose-ul:my-2 prose-ol:my-2",
},
},
},
[placeholder, allowBase64]
);
React.useEffect(() => {
if (!editor) return;
const current = editor.getHTML();
if (value != null && value != current) {
editor.commands.setContent(value, {
emitUpdate: false,
parseOptions: { preserveWhitespace: "full" },
});
}
}, [value, editor]);
const canImageUpload = Boolean(onImageUpload);
const handlePickImage = () => {
if (!canImageUpload) return;
fileRef.current?.click();
};
const handleFile = 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;
}
editor.chain().focus().setImage({ src: url }).run();
} catch (err) {
toast.error("이미지 업로드에 실패했습니다.");
console.error(err);
}
};
if (!editor) return <div className={cn("text-sm text-muted-foreground", className)}>에디터 로딩 중…</div>;
return (
<div className={cn("w-full", className)}>
<div className="border-b py-2">
<Toolbar editor={editor} canImageUpload={canImageUpload} onPickImage={handlePickImage} />
<input
ref={fileRef}
type="file"
accept="image/*"
className="hidden"
onChange={handleFile}
disabled={!canImageUpload}
/>
</div>
<div className="py-4">
<EditorContent editor={editor} />
</div>
</div>
);
};
return <KriEditorWysiwyg {...props} mode={mode} editorMode={mode} />;
}

View File

@@ -0,0 +1,164 @@
"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
import type { KriEditorProps } from "./types";
import { useDebouncedChange } from "./hooks/useDebouncedChange";
import { sanitizeHtmlForPreview } from "./utils/sanitizeHtml";
type HtmlOnlyProps = Omit<KriEditorProps, "mode"> & {
mode: "html";
};
export function KriEditorHtmlOnly(props: HtmlOnlyProps) {
const {
label,
value,
onChange,
placeholder = "HTML을 입력하세요...",
className,
showPreview,
previewClassName,
rows = 14,
onImageUpload,
onImageUploadError,
debounceMs = 350,
} = props;
const [html, setHtml] = React.useState<string>(value || "");
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null);
const fileInputRef = React.useRef<HTMLInputElement | null>(null);
const latestHtmlRef = React.useRef(html);
latestHtmlRef.current = html;
const flushChange = useDebouncedChange(onChange, debounceMs);
// 외부 value 변경 시 동기화
React.useEffect(() => {
if ((value || "") !== latestHtmlRef.current) {
setHtml(value || "");
latestHtmlRef.current = value || "";
}
}, [value]);
const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const next = e.target.value;
setHtml(next);
latestHtmlRef.current = next;
flushChange(next);
};
const handleBlur = () => {
flushChange(latestHtmlRef.current);
};
const handleClickImageButton = () => {
if (!onImageUpload) return;
fileInputRef.current?.click();
};
const handleFileChange = async (
e: React.ChangeEvent<HTMLInputElement>,
) => {
const file = e.target.files?.[0];
if (!file || !onImageUpload) return;
try {
const url = await onImageUpload(file);
if (!url) 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;
flushChange(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;
flushChange(next);
// 커서 위치를 이미지 태그 뒤로 이동
window.requestAnimationFrame(() => {
const pos = before.length + imgTag.length;
textarea.focus();
textarea.setSelectionRange(pos, pos);
});
return next;
});
} catch (error) {
onImageUploadError?.(error);
} finally {
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
}
};
const sanitizedHtml = 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="flex flex-col gap-2 px-3 py-2">
<div className="flex items-center justify-between text-xs text-gray-500">
<span>HTML 모드</span>
{onImageUpload && (
<button
type="button"
onClick={handleClickImageButton}
className="rounded border px-2 py-1 text-xs hover:bg-gray-50"
>
이미지 업로드
</button>
)}
</div>
<textarea
ref={textareaRef}
className="min-h-[200px] w-full resize-y border bg-white p-2 text-sm font-mono outline-none"
value={html}
onChange={handleTextChange}
onBlur={handleBlur}
placeholder={placeholder}
rows={rows}
/>
<input
ref={fileInputRef}
type="file"
accept="image/*"
className="hidden"
onChange={handleFileChange}
/>
</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">
{/* eslint-disable-next-line react/no-danger */}
<div dangerouslySetInnerHTML={{ __html: sanitizedHtml }} />
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,521 @@
"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 { cn } from "@/lib/utils";
import type { KriEditorProps, KriEditorMode, ToolbarState } from "./types";
import { FontSize } from "./extensions/font-size";
import { Div } from "./extensions/div";
import { compressImage } from "./utils/imageCompression";
import { sanitizeHtml } from "./utils/sanitizeHtml";
import { Toolbar } from "./toolbar/Toolbar";
import { useDebouncedChange } from "./hooks/useDebouncedChange";
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,
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 isLmsMode = mode === "lms";
const showHtmlToggle = mode === "both";
const { scheduleChange, flushChange, optimisticHtmlRef } = useDebouncedChange(onChange, debounceMs);
const fileRef = useRef<HTMLInputElement | null>(null);
const [view, setView] = useState<ViewMode>("wysiwyg");
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: [
isLmsMode
? StarterKit.configure({
heading: false,
bulletList: false,
orderedList: false,
listItem: false,
blockquote: false,
codeBlock: false,
code: false,
strike: false,
bold: false,
italic: false,
horizontalRule: false,
})
: StarterKit.configure({
heading: false,
blockquote: false,
codeBlock: false,
code: false,
}),
Underline,
TextStyle,
FontSize,
Color,
Highlight.configure({ multicolor: true }),
Div,
Link.configure({
openOnClick: false,
autolink: true,
linkOnPaste: true,
HTMLAttributes: {
class: "text-blue-600 underline underline-offset-2",
rel: "noopener noreferrer nofollow",
target: "_blank",
},
}),
TextAlign.configure({ types: ["paragraph", "divBlock"] }),
Table.configure({ resizable: true }),
TableRow,
TableHeader,
TableCell,
TiptapImage.configure({
allowBase64,
HTMLAttributes: {
class: "max-w-full h-auto",
},
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]"
),
},
},
});
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 (!editor) return;
if (viewRef.current === "html") return;
const current = editor.getHTML();
if (value != null && value !== current && value !== optimisticHtmlRef.current) {
editor.commands.setContent(value, {
emitUpdate: false,
parseOptions: { preserveWhitespace: "full" },
});
}
}, [value, editor, optimisticHtmlRef]);
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]);
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();
if (editor.isActive("link")) {
editor.chain().focus().unsetLink().run();
return;
}
const prev = (editor.getAttributes("link").href as string | undefined) ?? "";
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) {
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]);
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}
isLmsMode={isLmsMode}
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
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}
/>
</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>
);
}

View File

@@ -1,86 +0,0 @@
"use client";
import * as React from "react";
import type { Editor } from "@tiptap/react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { validateLinkUrl } from "../utils/link";
import { ToolbarButton } from "./ToolbarButton";
export function LinkPopover({ editor }: { editor: Editor }) {
const [open, setOpen] = React.useState(false);
const isLink = editor.isActive("link");
const previous = editor.getAttributes("link").href as string | undefined;
const onSubmit = React.useCallback(
(e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const raw = String(formData.get("url") ?? "");
const { ok, normalized } = validateLinkUrl(raw);
if (!ok) {
toast.error("유효하지 않은 링크입니다. https 링크만 허용됩니다.");
return;
}
const chain = editor.chain().focus();
if (!normalized) {
chain.extendMarkRange("link").unsetLink().run();
setOpen(false);
return;
}
const { from, to, empty } = editor.state.selection;
chain.extendMarkRange("link").setLink({ href: normalized });
// 선택영역이 없으면 URL 텍스트 삽입
if (empty) chain.insertContentAt({ from, to }, normalized);
chain.run();
setOpen(false);
},
[editor]
);
const onUnlink = React.useCallback(() => {
editor.chain().focus().extendMarkRange("link").unsetLink().run();
}, [editor]);
return (
<div className="flex items-center gap-1">
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<span>
<ToolbarButton active={isLink} onClick={() => setOpen((v) => !v)} title="Link">
Link
</ToolbarButton>
</span>
</PopoverTrigger>
<PopoverContent className="w-80" align="start">
<form onSubmit={onSubmit} className="space-y-2">
<div className="text-sm font-semibold">링크 등록</div>
<Input name="url" placeholder="https://example.com" defaultValue={previous ?? ""} />
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
취소
</Button>
<Button type="submit">등록</Button>
</div>
</form>
</PopoverContent>
</Popover>
<ToolbarButton disabled={!isLink} onClick={onUnlink} title="Unlink">
Unlink
</ToolbarButton>
</div>
);
}

View File

@@ -1,32 +0,0 @@
"use client";
import * as React from "react";
import { Button } from "@/components/ui/button";
export function ToolbarButton({
active,
disabled,
onClick,
children,
title,
}: {
active?: boolean;
disabled?: boolean;
onClick: () => void;
children: React.ReactNode;
title?: string;
}) {
return (
<Button
type="button"
size="sm"
variant={active ? "default" : "outline"}
disabled={disabled}
onClick={onClick}
title={title}
className="h-9 px-2"
>
{children}
</Button>
);
}

View File

@@ -0,0 +1,31 @@
import { Node, mergeAttributes } from "@tiptap/core";
export const Div = Node.create({
name: "divBlock",
group: "block",
content: "block+",
defining: true,
addAttributes() {
return {
class: {
default: null as string | null,
parseHTML: (el) => (el as HTMLElement).getAttribute("class"),
renderHTML: (attrs) => (attrs.class ? { class: attrs.class } : {}),
},
style: {
default: null as string | null,
parseHTML: (el) => (el as HTMLElement).getAttribute("style"),
renderHTML: (attrs) => (attrs.style ? { style: attrs.style } : {}),
},
};
},
parseHTML() {
return [{ tag: "div" }];
},
renderHTML({ HTMLAttributes }) {
return ["div", mergeAttributes(HTMLAttributes), 0];
},
});

View File

@@ -1,5 +1,13 @@
import { Extension } from "@tiptap/core";
declare module "@tiptap/core" {
interface Commands<ReturnType> {
fontSize: {
setFontSize: (fontSize: string | null) => ReturnType;
};
}
}
export const FontSize = Extension.create({
name: "fontSize",
addGlobalAttributes() {
@@ -19,4 +27,17 @@ export const FontSize = Extension.create({
},
];
},
addCommands() {
return {
setFontSize:
(fontSize) =>
({ chain }) => {
if (!fontSize) {
return chain().setMark("textStyle", { fontSize: null }).removeEmptyTextStyle().run();
}
return chain().setMark("textStyle", { fontSize }).run();
},
};
},
});

View File

@@ -1,57 +0,0 @@
import { Node, mergeAttributes } from "@tiptap/core";
import { ReactNodeViewRenderer } from "@tiptap/react";
import type { ImageUploadNodeOptions } from "./types";
import { ImageUploadNodeView } from "./image-upload-nodeview";
declare module "@tiptap/core" {
interface Commands<ReturnType> {
imageUpload: {
setImageUploadNode: () => ReturnType;
};
}
}
export const ImageUploadNode = Node.create({
name: "imageUpload",
group: "block",
atom: true,
draggable: true,
selectable: true,
addOptions() {
return {
accept: "image/*",
maxSize: 0,
upload: undefined,
onError: undefined,
} satisfies Partial<ImageUploadNodeOptions>;
},
addAttributes() {
return {
accept: { default: this.options.accept },
maxSize: { default: this.options.maxSize },
};
},
parseHTML() {
return [{ tag: 'div[data-type="image-upload"]' }];
},
renderHTML({ HTMLAttributes }) {
return ["div", mergeAttributes({ "data-type": "image-upload" }, HTMLAttributes)];
},
addNodeView() {
return ReactNodeViewRenderer(ImageUploadNodeView);
},
addCommands() {
return {
setImageUploadNode:
() =>
({ commands }) =>
commands.insertContent({ type: this.name }),
};
},
});

View File

@@ -1,130 +0,0 @@
"use client";
import * as React from "react";
import { NodeViewWrapper } from "@tiptap/react";
import { toast } from "sonner";
import type { ImageUploadNodeViewProps } from "./types";
import { cn } from "@/lib/utils";
export function ImageUploadNodeView(props: any) {
const { editor, extension, getPos, node } = props as ImageUploadNodeViewProps & {
node: any;
};
const opts = extension.options;
const inputRef = React.useRef<HTMLInputElement | null>(null);
const [status, setStatus] = React.useState<"idle" | "uploading" | "error" | "success">("idle");
const [progress, setProgress] = React.useState<number>(0);
const doUpload = React.useCallback(
async (file: File) => {
if (!file.type.startsWith("image/")) {
opts.onError?.("이미지 파일만 업로드할 수 있습니다.");
toast.error("이미지 파일만 업로드할 수 있습니다.");
return;
}
if (opts.maxSize > 0 && file.size > opts.maxSize) {
const mb = (opts.maxSize / (1024 * 1024)).toFixed(0);
opts.onError?.(`이미지 용량이 제한을 초과합니다. (최대 ${mb}MB)`);
toast.error("이미지 용량이 제한을 초과합니다.", { description: `최대 ${mb}MB` });
return;
}
setStatus("uploading");
setProgress(10);
try {
const url = await opts.upload(file);
if (!url) throw new Error("upload returned empty url");
setProgress(100);
setStatus("success");
const pos = getPos();
const fileName = file.name.replace(/\.[^/.]+$/, "") || "image";
editor
.chain()
.focus()
.deleteRange({ from: pos, to: pos + node.nodeSize })
.insertContentAt(pos, [
{ type: "image", attrs: { src: url, alt: fileName, title: fileName } },
])
.insertContentAt(pos + 1, { type: "paragraph" })
.run();
} catch (e) {
setStatus("error");
setProgress(0);
opts.onError?.("이미지 업로드에 실패했습니다.");
toast.error("이미지 업로드에 실패했습니다.");
// eslint-disable-next-line no-console
console.error(e);
}
},
[editor, getPos, node?.nodeSize, opts]
);
const onPick = React.useCallback(() => {
if (status === "uploading") return;
inputRef.current?.click();
}, [status]);
const onChange = React.useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const f = e.target.files?.[0];
e.target.value = "";
if (!f) return;
void doUpload(f);
},
[doUpload]
);
const onDrop = React.useCallback(
(e: React.DragEvent) => {
e.preventDefault();
if (status === "uploading") return;
const f = e.dataTransfer.files?.[0];
if (!f) return;
void doUpload(f);
},
[doUpload, status]
);
const onDragOver = React.useCallback((e: React.DragEvent) => {
e.preventDefault();
}, []);
return (
<NodeViewWrapper className="not-prose">
<div
className={cn("my-3 rounded-md border border-dashed p-4", status === "uploading" && "opacity-80")}
onClick={onPick}
onDrop={onDrop}
onDragOver={onDragOver}
role="button"
tabIndex={0}
>
<input
ref={inputRef}
type="file"
accept={opts.accept}
className="hidden"
onChange={onChange}
disabled={status === "uploading"}
/>
{status === "uploading" ? (
<div className="text-sm">
업로드 중… {progress}%
<div className="mt-2 h-2 w-full rounded bg-muted">
<div className="h-2 rounded bg-primary" style={{ width: `${progress}%` }} />
</div>
</div>
) : (
<div className="text-sm text-muted-foreground">이미지를 드래그하거나 클릭해 업로드할 수 있습니다.</div>
)}
</div>
</NodeViewWrapper>
);
}

View File

@@ -1,15 +0,0 @@
import type { Editor } from "@tiptap/react";
export type ImageUploadNodeOptions = {
accept: string;
maxSize: number;
upload: (file: File) => Promise<string>; // url 반환
onError?: (message: string) => void;
};
export type ImageUploadNodeViewProps = {
editor: Editor;
extension: { options: ImageUploadNodeOptions };
getPos: () => number;
node: any;
};

View File

@@ -0,0 +1,42 @@
"use client";
import { useCallback, useEffect, useRef } from "react";
export function useDebouncedChange(onChange: (html: string) => void, debounceMs: number) {
const timerRef = useRef<number | null>(null);
const optimisticHtmlRef = useRef<string>("");
const flushChange = useCallback(
(nextHtml: string) => {
optimisticHtmlRef.current = nextHtml;
onChange(nextHtml);
},
[onChange]
);
const scheduleChange = useCallback(
(nextHtml: string) => {
optimisticHtmlRef.current = nextHtml;
if (!debounceMs || debounceMs <= 0) {
onChange(nextHtml);
return;
}
if (timerRef.current) window.clearTimeout(timerRef.current);
timerRef.current = window.setTimeout(() => {
timerRef.current = null;
onChange(optimisticHtmlRef.current);
}, debounceMs);
},
[debounceMs, onChange]
);
useEffect(() => {
return () => {
if (timerRef.current) window.clearTimeout(timerRef.current);
};
}, []);
return { scheduleChange, flushChange, optimisticHtmlRef };
}

View File

@@ -1,199 +0,0 @@
"use client";
import * as React from "react";
import { useEditor, useEditorState } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Underline from "@tiptap/extension-underline";
import TextAlign from "@tiptap/extension-text-align";
import Link from "@tiptap/extension-link";
import Placeholder from "@tiptap/extension-placeholder";
import Image from "@tiptap/extension-image";
import { TextStyle } from "@tiptap/extension-text-style";
import Color from "@tiptap/extension-color";
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 { UploadResult } from "../types";
import { FontSize } from "../extensions/font-size";
import { validateLinkUrl } from "../utils/link";
import { compressImage } from "../utils/image-compress";
import { ImageUploadNode } from "../extensions/image-upload/image-upload-node";
type Params = {
value: string;
onChange: (html: string) => void;
placeholder: string;
allowBase64: boolean;
onImageUpload?: (file: File) => Promise<UploadResult>;
maxImageBytes: number;
imageMaxWidth: number;
imageMaxHeight: number;
imageQuality: number;
imageMimeType: "image/webp" | "image/jpeg";
enableTextStyleTools: boolean;
};
export function useKriEditor({
value,
onChange,
placeholder,
allowBase64,
onImageUpload,
maxImageBytes,
imageMaxWidth,
imageMaxHeight,
imageQuality,
imageMimeType,
enableTextStyleTools,
}: Params) {
const uploadFn = React.useMemo(() => {
if (!onImageUpload) return null;
return async (file: File): Promise<string> => {
if (!file.type.startsWith("image/")) {
throw new Error("not an image");
}
const compressed = await compressImage(file, {
maxBytes: maxImageBytes,
maxWidth: imageMaxWidth,
maxHeight: imageMaxHeight,
mimeType: imageMimeType,
quality: imageQuality,
});
if (compressed.size > maxImageBytes) {
throw new Error("maxImageBytes exceeded");
}
const { url } = await onImageUpload(compressed);
if (!url) throw new Error("upload returned empty url");
return url;
};
}, [onImageUpload, maxImageBytes, imageMaxWidth, imageMaxHeight, imageQuality, imageMimeType]);
const editor = useEditor(
{
immediatelyRender: false,
shouldRerenderOnTransaction: false,
extensions: [
StarterKit,
Underline,
...(enableTextStyleTools ? [TextStyle, FontSize, Color] : []),
Link.configure({
openOnClick: false,
autolink: true,
linkOnPaste: true,
HTMLAttributes: {
rel: "noopener noreferrer",
target: "_blank",
class: "cursor-pointer text-blue-500 hover:text-blue-600",
},
isAllowedUri: (url) => validateLinkUrl(url).ok,
shouldAutoLink: (url) => url.startsWith("https://"),
}).extend({ inclusive: false }),
TextAlign.configure({ types: ["heading", "paragraph"] }),
Table.configure({
resizable: true,
HTMLAttributes: { class: "table-fixed border-collapse w-full" },
}),
TableRow,
TableHeader,
TableCell,
Image.configure({
allowBase64,
HTMLAttributes: { class: "max-w-full h-auto" },
}),
...(uploadFn
? [
ImageUploadNode.configure({
accept: "image/*",
maxSize: maxImageBytes,
upload: uploadFn,
onError: (m: string) => toast.error(m),
}),
]
: []),
Placeholder.configure({ placeholder }),
],
content: value || "<p></p>",
onUpdate: ({ editor }) => onChange(editor.getHTML()),
editorProps: {
attributes: {
class:
"prose prose-sm max-w-none focus:outline-none min-h-[180px] px-3 py-2 " +
"prose-table:border prose-td:border prose-th:border prose-table:table-fixed",
},
},
},
[placeholder, allowBase64, uploadFn, enableTextStyleTools]
);
// 외부 value 동기화
React.useEffect(() => {
if (!editor) return;
const current = editor.getHTML();
if (value != null && value !== current) {
editor.commands.setContent(value, {
emitUpdate: false,
parseOptions: { preserveWhitespace: "full" },
});
}
}, [value, editor]);
const editorState = useEditorState({
editor,
selector: (snapshot) => {
const ed = snapshot.editor;
if (!ed) return null;
return {
isLink: ed.isActive("link"),
};
},
});
const editorRef = React.useCallback(
(node: HTMLDivElement | null) => {
if (!node || !editor) return;
const handleClick = (e: MouseEvent) => {
if (!editor.isFocused && node.contains(e.target as Node)) {
editor.commands.focus("end");
}
};
node.addEventListener("click", handleClick);
return () => node.removeEventListener("click", handleClick);
},
[editor]
);
return {
editor,
editorState,
editorRef,
canImageUpload: Boolean(uploadFn),
enableTextStyleTools,
};
}

View File

@@ -1,2 +1,2 @@
export { KriEditor } from "./KriEditor";
export type { KriEditorProps, UploadResult } from "./types";
export type { KriEditorProps, KriEditorMode, UploadResult, ToolbarState } from "./types";

View File

@@ -1,39 +0,0 @@
"use client";
import * as React from "react";
import type { Editor } from "@tiptap/react";
import { cn } from "@/lib/utils";
type BlockType = "paragraph" | "h1" | "h2" | "h3";
function getCurrent(editor: Editor): BlockType {
if (editor.isActive("heading", { level: 1 })) return "h1";
if (editor.isActive("heading", { level: 2 })) return "h2";
if (editor.isActive("heading", { level: 3 })) return "h3";
return "paragraph";
}
export function HeadingSelect({ editor, className }: { editor: Editor; className?: string }) {
const value = getCurrent(editor);
return (
<select
className={cn("h-9 rounded-md border bg-background px-2 text-sm", className)}
value={value}
onChange={(e) => {
const v = e.target.value as BlockType;
const chain = editor.chain().focus();
if (v === "paragraph") chain.setParagraph().run();
if (v === "h1") chain.toggleHeading({ level: 1 }).run();
if (v === "h2") chain.toggleHeading({ level: 2 }).run();
if (v === "h3") chain.toggleHeading({ level: 3 }).run();
}}
title="Block type"
>
<option value="paragraph">본문</option>
<option value="h1">제목 1</option>
<option value="h2">제목 2</option>
<option value="h3">제목 3</option>
</select>
);
}

View File

@@ -1,47 +0,0 @@
"use client";
import * as React from "react";
import type { Editor } from "@tiptap/react";
import { cn } from "@/lib/utils";
import { ToolbarButton } from "./ToolbarButton";
import { tableMenuItems } from "./toolbarConfig";
export function TableMenu({ editor }: { editor: Editor }) {
const [open, setOpen] = React.useState(false);
const ref = React.useRef<HTMLDivElement | null>(null);
React.useEffect(() => {
const onDoc = (ev: MouseEvent) => {
if (!ref.current) return;
if (!ref.current.contains(ev.target as Node)) setOpen(false);
};
document.addEventListener("mousedown", onDoc);
return () => document.removeEventListener("mousedown", onDoc);
}, []);
return (
<div ref={ref} className="relative">
<ToolbarButton icon={tableMenuItems.icon} title={tableMenuItems.title} onClick={() => setOpen((v) => !v)} />
{open ? (
<div className={cn("absolute right-0 z-50 mt-1 w-52 rounded-md border bg-background p-1 shadow-md")}>
{tableMenuItems.actions.map((item) => (
<button
key={item.key}
type="button"
className={cn("flex w-full items-center gap-2 rounded-sm px-2 py-2 text-left text-sm hover:bg-muted disabled:opacity-50")}
disabled={item.isDisabled ? item.isDisabled(editor) : false}
onClick={() => {
item.onClick(editor);
setOpen(false);
}}
title={item.title}
>
<item.icon className="h-4 w-4" />
<span>{item.title}</span>
</button>
))}
</div>
) : null}
</div>
);
}

View File

@@ -1,99 +1,342 @@
"use client";
import * as React from "react";
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 "@/lib/utils";
import {
AlignCenter,
AlignLeft,
AlignRight,
Bold,
Highlighter,
Image as ImageIcon,
Italic,
Link2,
List,
ListOrdered,
Palette,
Table2,
Underline,
Strikethrough,
Code2,
} from "lucide-react";
import { ToolbarButton } from "./ToolbarButton";
import { ToolbarPipe } from "./ToolbarPipe";
import { TableMenu } from "./TableMenu";
import { alignItems, listItems, markItems, headingItems, linkItem, imageItem } from "./toolbarConfig";
import type { ToolbarState } from "../types";
type Props = {
editor: Editor;
state: ToolbarState;
className?: string;
canImageUpload: boolean;
onPickImage: () => void;
showHtmlToggle: boolean;
isHtmlView: boolean;
onToggleHtmlView: () => void;
isLmsMode: boolean;
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;
};
function promptForUrl(prev?: string) {
return window.prompt("링크 URL을 입력하세요", prev ?? "");
const PRESET_COLORS = [
"#111827",
"#374151",
"#6B7280",
"#9CA3AF",
"#D1D5DB",
"#EF4444",
"#F97316",
"#F59E0B",
"#84CC16",
"#22C55E",
"#06B6D4",
"#3B82F6",
"#6366F1",
"#A855F7",
"#EC4899",
];
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" }}
/>
);
}
export function Toolbar({ editor, canImageUpload, onPickImage }: Props) {
const link = React.useMemo(() => linkItem({ promptForUrl }), []);
const image = React.useMemo(() => imageItem({ onPick: onPickImage, disabled: !canImageUpload }), [
onPickImage,
canImageUpload,
]);
export function Toolbar({
editor,
state,
className,
canImageUpload,
onPickImage,
showHtmlToggle,
isHtmlView,
onToggleHtmlView,
isLmsMode,
onSetFontSize,
onSetTextColor,
onUnsetTextColor,
onSetHighlight,
onUnsetHighlight,
onToggleLink,
onInsertTable,
onAddRow,
onAddColumn,
onDeleteTable,
}: Props) {
if (isLmsMode) {
return (
<div className={cn("flex items-center gap-1 whitespace-nowrap px-2 py-1", className)}>
<ToolbarButton active={state.isLink} title={state.isLink ? "링크 해제" : "링크 삽입"} onClick={onToggleLink}>
<Link2 className="h-4 w-4" />
</ToolbarButton>
</div>
);
}
return (
<div className="flex flex-wrap items-center gap-1 text-foreground">
{/* Headings (H1/H2/H3) */}
{headingItems.map((item) => (
<ToolbarButton
key={item.key}
title={item.title}
active={item.isActive ? item.isActive(editor) : false}
onClick={() => item.onClick(editor)}
>
{item.label}
</ToolbarButton>
))}
<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>
<ToolbarPipe />
<Separator orientation="vertical" className="mx-1 h-6" />
{/* Marks */}
{markItems.map((item) => (
<ToolbarButton
key={item.key}
icon={item.icon}
title={item.title}
active={item.isActive ? item.isActive(editor) : false}
disabled={item.isDisabled ? item.isDisabled(editor) : false}
onClick={() => item.onClick(editor)}
/>
))}
<ToolbarPipe />
{/* Align */}
{alignItems.map((item) => (
<ToolbarButton
key={item.key}
icon={item.icon}
title={item.title}
active={item.isActive ? item.isActive(editor) : false}
onClick={() => item.onClick(editor)}
/>
))}
<ToolbarPipe />
{/* Lists */}
{listItems.map((item) => (
<ToolbarButton
key={item.key}
icon={item.icon}
title={item.title}
active={item.isActive ? item.isActive(editor) : false}
onClick={() => item.onClick(editor)}
/>
))}
<ToolbarPipe />
{/* Media / Link / Table */}
<ToolbarButton
icon={image.icon}
title={image.title}
disabled={image.isDisabled ? image.isDisabled(editor) : false}
onClick={() => image.onClick(editor)}
/>
active={state.isBold}
disabled={!editor.can().chain().focus().toggleBold().run()}
onClick={() => editor.chain().focus().toggleBold().run()}
title="굵게"
>
<Bold className="h-4 w-4" />
</ToolbarButton>
<ToolbarButton
icon={link.icon}
title={link.title}
active={link.isActive ? link.isActive(editor) : false}
onClick={() => link.onClick(editor)}
/>
<TableMenu editor={editor} />
active={state.isItalic}
disabled={!editor.can().chain().focus().toggleItalic().run()}
onClick={() => editor.chain().focus().toggleItalic().run()}
title="기울임"
>
<Italic className="h-4 w-4" />
</ToolbarButton>
<ToolbarButton active={state.isUnderline} onClick={() => editor.chain().focus().toggleUnderline().run()} title="밑줄">
<Underline className="h-4 w-4" />
</ToolbarButton>
<ToolbarButton active={state.isStrike} onClick={() => editor.chain().focus().toggleStrike().run()} title="취소선">
<Strikethrough className="h-4 w-4" />
</ToolbarButton>
<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>
<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}`}
/>
)
)}
</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>
<Separator orientation="vertical" className="mx-1 h-6" />
<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 && (
<>
<Separator orientation="vertical" className="mx-1 h-6" />
<ToolbarButton active={isHtmlView} title={isHtmlView ? "WYSIWYG로" : "HTML 편집"} onClick={onToggleHtmlView}>
<Code2 className="h-4 w-4" />
</ToolbarButton>
</>
)}
</div>
);
}

View File

@@ -1,35 +1,35 @@
"use client";
import * as React from "react";
import type { LucideIcon } from "lucide-react";
import type { ReactNode, MouseEvent } from "react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
type Props = {
icon?: LucideIcon;
title: string;
active?: boolean;
disabled?: boolean;
onClick: () => void;
children?: React.ReactNode; // text buttons (H1/H2/H3)
title?: string;
onClick?: () => void;
children: ReactNode;
className?: string;
};
export function ToolbarButton({ icon: Icon, title, active, disabled, onClick, children, className }: Props) {
export function ToolbarButton({ active, disabled, title, onClick, children, className }: Props) {
const onMouseDown = (e: MouseEvent) => {
e.preventDefault();
};
return (
<button
<Button
type="button"
title={title}
variant={active ? "secondary" : "ghost"}
size="sm"
disabled={disabled}
onMouseDown={onMouseDown}
onClick={onClick}
className={cn(
"inline-flex h-9 min-w-9 items-center justify-center rounded-md px-2 text-sm",
"hover:bg-muted disabled:opacity-50 disabled:hover:bg-transparent",
active ? "bg-muted" : "bg-transparent",
className
)}
title={title}
className={cn("h-8 w-8 p-0", className)}
>
{Icon ? <Icon className="h-4 w-4" /> : null}
{children ? <span className={cn(Icon ? "ml-1" : "")}>{children}</span> : null}
</button>
{children}
</Button>
);
}

View File

@@ -1,8 +0,0 @@
"use client";
import * as React from "react";
import { Separator } from "@/components/ui/separator";
export function ToolbarDivider() {
return <Separator orientation="vertical" className="mx-1 h-7" />;
}

View File

@@ -1,7 +0,0 @@
"use client";
import * as React from "react";
export function ToolbarPipe() {
return <span className="mx-2 inline-block h-6 w-px bg-border align-middle" />;
}

View File

@@ -1,196 +0,0 @@
import type { Editor } from "@tiptap/react";
export type ToolbarItem = {
key: string;
label: string;
title?: string;
isActive?: (editor: Editor) => boolean;
isDisabled?: (editor: Editor) => boolean;
onClick: (editor: Editor) => void;
};
export function makeToolbarGroups() {
const undoRedo: ToolbarItem[] = [
{
key: "undo",
label: "↶",
title: "Undo",
isDisabled: (ed) => !ed.can().chain().focus().undo().run(),
onClick: (ed) => ed.chain().focus().undo().run(),
},
{
key: "redo",
label: "↷",
title: "Redo",
isDisabled: (ed) => !ed.can().chain().focus().redo().run(),
onClick: (ed) => ed.chain().focus().redo().run(),
},
];
const headings: ToolbarItem[] = [
{
key: "h1",
label: "H1",
title: "H1",
isActive: (ed) => ed.isActive("heading", { level: 1 }),
onClick: (ed) => ed.chain().focus().toggleHeading({ level: 1 }).run(),
},
{
key: "h2",
label: "H2",
title: "H2",
isActive: (ed) => ed.isActive("heading", { level: 2 }),
onClick: (ed) => ed.chain().focus().toggleHeading({ level: 2 }).run(),
},
{
key: "h3",
label: "H3",
title: "H3",
isActive: (ed) => ed.isActive("heading", { level: 3 }),
onClick: (ed) => ed.chain().focus().toggleHeading({ level: 3 }).run(),
},
{
key: "p",
label: "P",
title: "본문",
isActive: (ed) => ed.isActive("paragraph"),
onClick: (ed) => ed.chain().focus().setParagraph().run(),
},
];
const marks: ToolbarItem[] = [
{
key: "bold",
label: "B",
title: "Bold",
isActive: (ed) => ed.isActive("bold"),
isDisabled: (ed) => !ed.can().chain().focus().toggleBold().run(),
onClick: (ed) => ed.chain().focus().toggleBold().run(),
},
{
key: "italic",
label: "I",
title: "Italic",
isActive: (ed) => ed.isActive("italic"),
isDisabled: (ed) => !ed.can().chain().focus().toggleItalic().run(),
onClick: (ed) => ed.chain().focus().toggleItalic().run(),
},
{
key: "underline",
label: "U",
title: "Underline",
isActive: (ed) => ed.isActive("underline"),
onClick: (ed) => ed.chain().focus().toggleUnderline().run(),
},
{
key: "strike",
label: "S",
title: "Strike",
isActive: (ed) => ed.isActive("strike"),
onClick: (ed) => ed.chain().focus().toggleStrike().run(),
},
{
key: "code",
label: "</>",
title: "Inline Code",
isActive: (ed) => ed.isActive("code"),
onClick: (ed) => ed.chain().focus().toggleCode().run(),
},
];
const blocks: ToolbarItem[] = [
{
key: "bulletList",
label: "• List",
title: "Bullet List",
isActive: (ed) => ed.isActive("bulletList"),
onClick: (ed) => ed.chain().focus().toggleBulletList().run(),
},
{
key: "orderedList",
label: "1. List",
title: "Ordered List",
isActive: (ed) => ed.isActive("orderedList"),
onClick: (ed) => ed.chain().focus().toggleOrderedList().run(),
},
{
key: "blockquote",
label: "“ ”",
title: "Blockquote",
isActive: (ed) => ed.isActive("blockquote"),
onClick: (ed) => ed.chain().focus().toggleBlockquote().run(),
},
{
key: "codeBlock",
label: "Code",
title: "Code Block",
isActive: (ed) => ed.isActive("codeBlock"),
onClick: (ed) => ed.chain().focus().toggleCodeBlock().run(),
},
];
const align: ToolbarItem[] = [
{
key: "alignLeft",
label: "⬅",
title: "Align Left",
isActive: (ed) => ed.isActive({ textAlign: "left" }),
onClick: (ed) => ed.chain().focus().setTextAlign("left").run(),
},
{
key: "alignCenter",
label: "↔",
title: "Align Center",
isActive: (ed) => ed.isActive({ textAlign: "center" }),
onClick: (ed) => ed.chain().focus().setTextAlign("center").run(),
},
{
key: "alignRight",
label: "➡",
title: "Align Right",
isActive: (ed) => ed.isActive({ textAlign: "right" }),
onClick: (ed) => ed.chain().focus().setTextAlign("right").run(),
},
];
const hr: ToolbarItem[] = [
{
key: "hr",
label: "―",
title: "Horizontal Rule",
onClick: (ed) => ed.chain().focus().setHorizontalRule().run(),
},
];
const table: ToolbarItem[] = [
{
key: "insertTable",
label: "표",
title: "Insert Table",
onClick: (ed) => ed.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(),
},
{
key: "addRowAfter",
label: "행+",
title: "Add Row",
isDisabled: (ed) => !ed.can().chain().focus().addRowAfter().run(),
onClick: (ed) => ed.chain().focus().addRowAfter().run(),
},
{
key: "addColumnAfter",
label: "열+",
title: "Add Column",
isDisabled: (ed) => !ed.can().chain().focus().addColumnAfter().run(),
onClick: (ed) => ed.chain().focus().addColumnAfter().run(),
},
{
key: "deleteTable",
label: "표삭제",
title: "Delete Table",
isDisabled: (ed) => !ed.can().chain().focus().deleteTable().run(),
onClick: (ed) => ed.chain().focus().deleteTable().run(),
},
];
return { undoRedo, headings, marks, blocks, align, hr, table };
}

View File

@@ -1,200 +0,0 @@
import type { Editor } from "@tiptap/react";
import type { LucideIcon } from "lucide-react";
import {
Bold,
Italic,
Underline,
Strikethrough,
AlignLeft,
AlignCenter,
AlignRight,
AlignJustify,
List,
ListOrdered,
Link2,
Image as ImageIcon,
Table2,
Rows3,
Columns3,
Trash2,
} from "lucide-react";
export type ToolbarItem = {
key: string;
icon?: LucideIcon;
label?: string; // text buttons (H1/H2/H3)
title: string;
isActive?: (editor: Editor) => boolean;
isDisabled?: (editor: Editor) => boolean;
onClick: (editor: Editor) => void;
};
export const headingItems: ToolbarItem[] = [
{
key: "h1",
label: "H1",
title: "Heading 1",
isActive: (e) => e.isActive("heading", { level: 1 }),
onClick: (e) => e.chain().focus().toggleHeading({ level: 1 }).run(),
},
{
key: "h2",
label: "H2",
title: "Heading 2",
isActive: (e) => e.isActive("heading", { level: 2 }),
onClick: (e) => e.chain().focus().toggleHeading({ level: 2 }).run(),
},
{
key: "h3",
label: "H3",
title: "Heading 3",
isActive: (e) => e.isActive("heading", { level: 3 }),
onClick: (e) => e.chain().focus().toggleHeading({ level: 3 }).run(),
},
];
export const markItems: ToolbarItem[] = [
{
key: "bold",
icon: Bold,
title: "Bold",
isActive: (e) => e.isActive("bold"),
isDisabled: (e) => !e.can().chain().focus().toggleBold().run(),
onClick: (e) => e.chain().focus().toggleBold().run(),
},
{
key: "italic",
icon: Italic,
title: "Italic",
isActive: (e) => e.isActive("italic"),
isDisabled: (e) => !e.can().chain().focus().toggleItalic().run(),
onClick: (e) => e.chain().focus().toggleItalic().run(),
},
{
key: "underline",
icon: Underline,
title: "Underline",
isActive: (e) => e.isActive("underline"),
onClick: (e) => e.chain().focus().toggleUnderline().run(),
},
{
key: "strike",
icon: Strikethrough,
title: "Strikethrough",
isActive: (e) => e.isActive("strike"),
onClick: (e) => e.chain().focus().toggleStrike().run(),
},
];
export const alignItems: ToolbarItem[] = [
{
key: "alignLeft",
icon: AlignLeft,
title: "Align Left",
isActive: (e) => e.isActive({ textAlign: "left" }),
onClick: (e) => e.chain().focus().setTextAlign("left").run(),
},
{
key: "alignCenter",
icon: AlignCenter,
title: "Align Center",
isActive: (e) => e.isActive({ textAlign: "center" }),
onClick: (e) => e.chain().focus().setTextAlign("center").run(),
},
{
key: "alignRight",
icon: AlignRight,
title: "Align Right",
isActive: (e) => e.isActive({ textAlign: "right" }),
onClick: (e) => e.chain().focus().setTextAlign("right").run(),
},
{
key: "alignJustify",
icon: AlignJustify,
title: "Justify",
isActive: (e) => e.isActive({ textAlign: "justify" }),
onClick: (e) => e.chain().focus().setTextAlign("justify").run(),
},
];
export const listItems: ToolbarItem[] = [
{
key: "bulletList",
icon: List,
title: "Bullet List",
isActive: (e) => e.isActive("bulletList"),
onClick: (e) => e.chain().focus().toggleBulletList().run(),
},
{
key: "orderedList",
icon: ListOrdered,
title: "Ordered List",
isActive: (e) => e.isActive("orderedList"),
onClick: (e) => e.chain().focus().toggleOrderedList().run(),
},
];
export const linkItem = (opts: { promptForUrl: (prev?: string) => string | null }): ToolbarItem => ({
key: "link",
icon: Link2,
title: "Link / Unlink",
isActive: (e) => e.isActive("link"),
onClick: (e) => {
const isLinked = e.isActive("link");
if (isLinked) {
e.chain().focus().extendMarkRange("link").unsetLink().run();
return;
}
const prev = e.getAttributes("link")?.href as string | undefined;
const url = opts.promptForUrl(prev);
if (url == null) return;
const trimmed = url.trim();
if (!trimmed) return;
e.chain().focus().extendMarkRange("link").setLink({ href: trimmed }).run();
},
});
export const imageItem = (opts: { onPick: () => void; disabled: boolean }): ToolbarItem => ({
key: "image",
icon: ImageIcon,
title: opts.disabled ? "onImageUpload 미설정으로 비활성" : "Image Upload",
isDisabled: () => opts.disabled,
onClick: () => opts.onPick(),
});
export const tableMenuItems = {
icon: Table2,
title: "Table",
actions: [
{
key: "insertTable",
icon: Table2,
title: "Insert Table",
isDisabled: (e: Editor) =>
!e.can().chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(),
onClick: (e: Editor) =>
e.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(),
},
{
key: "addRowAfter",
icon: Rows3,
title: "Add Row",
isDisabled: (e: Editor) => !e.can().chain().focus().addRowAfter().run(),
onClick: (e: Editor) => e.chain().focus().addRowAfter().run(),
},
{
key: "addColumnAfter",
icon: Columns3,
title: "Add Column",
isDisabled: (e: Editor) => !e.can().chain().focus().addColumnAfter().run(),
onClick: (e: Editor) => e.chain().focus().addColumnAfter().run(),
},
{
key: "deleteTable",
icon: Trash2,
title: "Delete Table",
isDisabled: (e: Editor) => !e.can().chain().focus().deleteTable().run(),
onClick: (e: Editor) => e.chain().focus().deleteTable().run(),
},
] as ToolbarItem[],
};

View File

@@ -1,7 +1,10 @@
export type UploadResult = { url: string };
export type KriEditorMode = "wysiwyg" | "both" | "html" | "lms";
export type KriEditorProps = {
label?: string;
value: string;
onChange: (html: string) => void;
@@ -11,19 +14,59 @@ export type KriEditorProps = {
showPreview?: boolean;
previewClassName?: string;
// 이미지 업로드 (없으면 기능 OFF)
/**
* 모드:
* - "wysiwyg": WYSIWYG 전용
* - "html": HTML 전용
* - "both": 툴바에서 WYSIWYG / HTML 전환 가능
* - "lms": LMS 문자 전용 (링크만)
*
* props.mode 가 없으면 editorMode 를 참고하고,
* 둘 다 없으면 "wysiwyg" 으로 동작.
*/
mode?: KriEditorMode;
editorMode?: KriEditorMode;
// 이미지 업로드 (없으면 이미지 버튼 비활성)
onImageUpload?: (file: File) => Promise<UploadResult>;
// 업로드 전 압축/리사이즈/용량 제한
maxImageBytes?: number; // 기본 5MB
imageMaxWidth?: number; // 기본 1600
imageMaxHeight?: number; // 기본 1600
imageQuality?: number; // 기본 0.82
imageMimeType?: "image/webp" | "image/jpeg"; // 기본 webp
// 이미지 압축 옵션
maxImageBytes?: number;
imageMaxWidth?: number;
imageMaxHeight?: number;
imageQuality?: number;
imageMimeType?: "image/webp" | "image/jpeg";
// base64 허용 옵션 (기본 false)
// base64 허용 여부 (기본: false)
allowBase64?: boolean;
// 폰트/컬러 툴바 표시 (기본 true)
enableTextStyleTools?: boolean;
// HTML을 setHTML 전에 sanitize 할지 여부 (기본: true)
sanitizeHtml?: boolean;
// HTML 전용 모드에서 textarea rows
rows?: number;
// 이미지 업로드 실패 시 콜백
onImageUploadError?: (error: unknown) => void;
// onChange 디바운스 시간 (ms)
debounceMs?: number;
};
export type ToolbarState = {
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;
};

View File

@@ -1,93 +0,0 @@
export type CompressOptions = {
maxBytes: number;
maxWidth: number;
maxHeight: number;
mimeType: "image/webp" | "image/jpeg";
quality: number; // 0~1
};
async function canvasToBlob(
canvas: HTMLCanvasElement,
mimeType: string,
quality: number
): Promise<Blob> {
return new Promise((resolve, reject) => {
canvas.toBlob(
(b) => (b ? resolve(b) : reject(new Error("canvas.toBlob returned null"))),
mimeType,
quality
);
});
}
async function loadImageFromBlob(blob: Blob): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const url = URL.createObjectURL(blob);
const img = document.createElement("img"); // new Image() 충돌 방지
img.onload = () => {
URL.revokeObjectURL(url);
resolve(img);
};
img.onerror = (e) => {
URL.revokeObjectURL(url);
reject(e);
};
img.src = url;
});
}
export async function compressImage(file: File, opts: CompressOptions): Promise<File> {
const img = await loadImageFromBlob(file);
const srcW = img.naturalWidth || img.width;
const srcH = img.naturalHeight || img.height;
const ratio = Math.min(1, opts.maxWidth / srcW, opts.maxHeight / srcH);
const targetW = Math.max(1, Math.round(srcW * ratio));
const targetH = Math.max(1, Math.round(srcH * ratio));
if (ratio === 1 && file.size <= opts.maxBytes) return file;
const canvas = document.createElement("canvas");
canvas.width = targetW;
canvas.height = targetH;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("canvas 2d context is null");
ctx.drawImage(img, 0, 0, targetW, targetH);
// 1차 시도
let q = opts.quality;
let blob = await canvasToBlob(canvas, opts.mimeType, q);
// 용량 초과 시 품질 낮추며 재시도
while (blob.size > opts.maxBytes && q > 0.5) {
q = Math.max(0.5, q - 0.1);
blob = await canvasToBlob(canvas, opts.mimeType, q);
}
// 그래도 크면 1회 다운스케일 후 재시도
if (blob.size > opts.maxBytes && (targetW > 900 || targetH > 900)) {
const w2 = Math.round(targetW * 0.85);
const h2 = Math.round(targetH * 0.85);
canvas.width = Math.max(1, w2);
canvas.height = Math.max(1, h2);
const ctx2 = canvas.getContext("2d");
if (!ctx2) throw new Error("canvas 2d context is null (2)");
ctx2.drawImage(img, 0, 0, canvas.width, canvas.height);
q = opts.quality;
blob = await canvasToBlob(canvas, opts.mimeType, q);
while (blob.size > opts.maxBytes && q > 0.5) {
q = Math.max(0.5, q - 0.1);
blob = await canvasToBlob(canvas, opts.mimeType, q);
}
}
const ext = opts.mimeType === "image/webp" ? "webp" : "jpg";
const safeName = file.name.replace(/\.[^.]+$/, `.${ext}`);
return new File([blob], safeName, { type: blob.type });
}

View File

@@ -8,7 +8,11 @@ export type CompressOptions = {
async function canvasToBlob(canvas: HTMLCanvasElement, mimeType: string, quality: number): Promise<Blob> {
return new Promise((resolve, reject) => {
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("canvas.toBlob returned null"))), mimeType, quality);
canvas.toBlob(
(b) => (b ? resolve(b) : reject(new Error("canvas.toBlob returned null"))),
mimeType,
quality
);
});
}
@@ -57,6 +61,23 @@ export async function compressImage(file: File, opts: CompressOptions): Promise<
blob = await canvasToBlob(canvas, opts.mimeType, q);
}
if (blob.size > opts.maxBytes && (targetW > 900 || targetH > 900)) {
const w2 = Math.round(targetW * 0.85);
const h2 = Math.round(targetH * 0.85);
canvas.width = Math.max(1, w2);
canvas.height = Math.max(1, h2);
const ctx2 = canvas.getContext("2d");
if (!ctx2) throw new Error("canvas 2d context is null (2)");
ctx2.drawImage(img, 0, 0, canvas.width, canvas.height);
q = opts.quality;
blob = await canvasToBlob(canvas, opts.mimeType, q);
while (blob.size > opts.maxBytes && q > 0.5) {
q = Math.max(0.5, q - 0.1);
blob = await canvasToBlob(canvas, opts.mimeType, q);
}
}
const ext = opts.mimeType === "image/webp" ? "webp" : "jpg";
const safeName = file.name.replace(/\.[^.]+$/, `.${ext}`);

View File

@@ -1,18 +0,0 @@
export function validateLinkUrl(url: string): { ok: boolean; normalized?: string } {
try {
const trimmed = url.trim();
if (!trimmed) return { ok: true, normalized: "" };
const parsed = trimmed.includes(":") ? new URL(trimmed) : new URL(`https://${trimmed}`);
// 보안: https만 허용
if (parsed.protocol !== "https:") return { ok: false };
// 상대경로/로컬 링크 방지
if (trimmed.startsWith("./") || trimmed.startsWith("../")) return { ok: false };
return { ok: true, normalized: parsed.href };
} catch {
return { ok: false };
}
}

View File

@@ -0,0 +1,15 @@
export function sanitizeHtml(input: string): string {
if (!input) return "";
let s = input.replace(/<\s*script[^>]*>[\s\S]*?<\s*\/\s*script\s*>/gi, "");
s = s.replace(/<\s*style[^>]*>[\s\S]*?<\s*\/\s*style\s*>/gi, "");
s = s.replace(/\son\w+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, "");
s = s.replace(/\s(href|src)\s*=\s*("|')\s*javascript:[^"']*("|')/gi, ' $1="#"');
return s;
}
// 기존 코드 호환용
export function sanitizeHtmlForPreview(input: string): string {
return sanitizeHtml(input);
}

View File

@@ -37,7 +37,8 @@ export const Header = ({
setUserInfo(auth.user);
}
else{
onNavigate("/logout")
alert("Fix Me!!!! components/layout/Header.tsx")
//window.location.replace("/logout");
}
}, [auth])

View File

@@ -0,0 +1,257 @@
"use client"
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
)
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
)
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className
)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}