251210_02_ENH : 이전파일 누락 내용 추가

This commit is contained in:
2025-12-10 16:30:11 +09:00
parent ef949a6242
commit 1080880fba
21 changed files with 1574 additions and 0 deletions

View File

@@ -0,0 +1,196 @@
"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 { 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 { compressImage } from "./utils/imageCompression";
import { Toolbar } from "./toolbar/Toolbar";
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>
);
};

View File

@@ -0,0 +1,86 @@
"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

@@ -0,0 +1,32 @@
"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,22 @@
import { Extension } from "@tiptap/core";
export const FontSize = Extension.create({
name: "fontSize",
addGlobalAttributes() {
return [
{
types: ["textStyle"],
attributes: {
fontSize: {
default: null as string | null,
parseHTML: (element) => (element as HTMLElement).style.fontSize || null,
renderHTML: (attributes) => {
if (!attributes.fontSize) return {};
return { style: `font-size:${attributes.fontSize}` };
},
},
},
},
];
},
});

View File

@@ -0,0 +1,57 @@
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

@@ -0,0 +1,130 @@
"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

@@ -0,0 +1,15 @@
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,199 @@
"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

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

View File

@@ -0,0 +1,39 @@
"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

@@ -0,0 +1,47 @@
"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

@@ -0,0 +1,99 @@
"use client";
import * as React from "react";
import type { Editor } from "@tiptap/react";
import { ToolbarButton } from "./ToolbarButton";
import { ToolbarPipe } from "./ToolbarPipe";
import { TableMenu } from "./TableMenu";
import { alignItems, listItems, markItems, headingItems, linkItem, imageItem } from "./toolbarConfig";
type Props = {
editor: Editor;
canImageUpload: boolean;
onPickImage: () => void;
};
function promptForUrl(prev?: string) {
return window.prompt("링크 URL을 입력하세요", prev ?? "");
}
export function Toolbar({ editor, canImageUpload, onPickImage }: Props) {
const link = React.useMemo(() => linkItem({ promptForUrl }), []);
const image = React.useMemo(() => imageItem({ onPick: onPickImage, disabled: !canImageUpload }), [
onPickImage,
canImageUpload,
]);
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>
))}
<ToolbarPipe />
{/* 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)}
/>
<ToolbarButton
icon={link.icon}
title={link.title}
active={link.isActive ? link.isActive(editor) : false}
onClick={() => link.onClick(editor)}
/>
<TableMenu editor={editor} />
</div>
);
}

View File

@@ -0,0 +1,35 @@
"use client";
import * as React from "react";
import type { LucideIcon } from "lucide-react";
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)
className?: string;
};
export function ToolbarButton({ icon: Icon, title, active, disabled, onClick, children, className }: Props) {
return (
<button
type="button"
title={title}
disabled={disabled}
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
)}
>
{Icon ? <Icon className="h-4 w-4" /> : null}
{children ? <span className={cn(Icon ? "ml-1" : "")}>{children}</span> : null}
</button>
);
}

View File

@@ -0,0 +1,8 @@
"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

@@ -0,0 +1,7 @@
"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

@@ -0,0 +1,196 @@
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

@@ -0,0 +1,200 @@
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

@@ -0,0 +1,29 @@
export type UploadResult = { url: string };
export type KriEditorProps = {
label?: string;
value: string;
onChange: (html: string) => void;
placeholder?: string;
className?: string;
showPreview?: boolean;
previewClassName?: string;
// 이미지 업로드 (없으면 기능 OFF)
onImageUpload?: (file: File) => Promise<UploadResult>;
// 업로드 전 압축/리사이즈/용량 제한
maxImageBytes?: number; // 기본 5MB
imageMaxWidth?: number; // 기본 1600
imageMaxHeight?: number; // 기본 1600
imageQuality?: number; // 기본 0.82
imageMimeType?: "image/webp" | "image/jpeg"; // 기본 webp
// base64 허용 옵션 (기본 false)
allowBase64?: boolean;
// 폰트/컬러 툴바 표시 (기본 true)
enableTextStyleTools?: boolean;
};

View File

@@ -0,0 +1,93 @@
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

@@ -0,0 +1,64 @@
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");
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);
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);
}
const ext = opts.mimeType === "image/webp" ? "webp" : "jpg";
const safeName = file.name.replace(/\.[^.]+$/, `.${ext}`);
return new File([blob], safeName, { type: blob.type });
}

View File

@@ -0,0 +1,18 @@
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 };
}
}