diff --git a/src/components/kri-editor/KriEditor.tsx b/src/components/kri-editor/KriEditor.tsx new file mode 100644 index 0000000..c01fe88 --- /dev/null +++ b/src/components/kri-editor/KriEditor.tsx @@ -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; + + maxImageBytes?: number; + imageMaxWidth?: number; + imageMaxHeight?: number; + imageQuality?: number; + imageMimeType?: "image/webp" | "image/jpeg"; + + allowBase64?: boolean; +}; + +export const KriEditor: React.FC = ({ + 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(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 || "

", + 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) => { + 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
에디터 로딩 중…
; + + return ( +
+
+ + +
+ +
+ +
+
+ ); +}; diff --git a/src/components/kri-editor/components/LinkPopover.tsx b/src/components/kri-editor/components/LinkPopover.tsx new file mode 100644 index 0000000..62ca2e9 --- /dev/null +++ b/src/components/kri-editor/components/LinkPopover.tsx @@ -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) => { + 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 ( +
+ + + + setOpen((v) => !v)} title="Link"> + Link + + + + + +
+
링크 등록
+ +
+ + +
+
+
+
+ + + Unlink + +
+ ); +} diff --git a/src/components/kri-editor/components/ToolbarButton.tsx b/src/components/kri-editor/components/ToolbarButton.tsx new file mode 100644 index 0000000..614dbf7 --- /dev/null +++ b/src/components/kri-editor/components/ToolbarButton.tsx @@ -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 ( + + ); +} diff --git a/src/components/kri-editor/extensions/font-size.ts b/src/components/kri-editor/extensions/font-size.ts new file mode 100644 index 0000000..467d7a3 --- /dev/null +++ b/src/components/kri-editor/extensions/font-size.ts @@ -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}` }; + }, + }, + }, + }, + ]; + }, +}); diff --git a/src/components/kri-editor/extensions/image-upload/image-upload-node.ts b/src/components/kri-editor/extensions/image-upload/image-upload-node.ts new file mode 100644 index 0000000..9ccf635 --- /dev/null +++ b/src/components/kri-editor/extensions/image-upload/image-upload-node.ts @@ -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 { + 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; + }, + + 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 }), + }; + }, +}); diff --git a/src/components/kri-editor/extensions/image-upload/image-upload-nodeview.tsx b/src/components/kri-editor/extensions/image-upload/image-upload-nodeview.tsx new file mode 100644 index 0000000..2b7f668 --- /dev/null +++ b/src/components/kri-editor/extensions/image-upload/image-upload-nodeview.tsx @@ -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(null); + + const [status, setStatus] = React.useState<"idle" | "uploading" | "error" | "success">("idle"); + const [progress, setProgress] = React.useState(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) => { + 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 ( + +
+ + + {status === "uploading" ? ( +
+ 업로드 중… {progress}% +
+
+
+
+ ) : ( +
이미지를 드래그하거나 클릭해 업로드할 수 있습니다.
+ )} +
+ + ); +} diff --git a/src/components/kri-editor/extensions/image-upload/types.ts b/src/components/kri-editor/extensions/image-upload/types.ts new file mode 100644 index 0000000..d5a91af --- /dev/null +++ b/src/components/kri-editor/extensions/image-upload/types.ts @@ -0,0 +1,15 @@ +import type { Editor } from "@tiptap/react"; + +export type ImageUploadNodeOptions = { + accept: string; + maxSize: number; + upload: (file: File) => Promise; // url 반환 + onError?: (message: string) => void; +}; + +export type ImageUploadNodeViewProps = { + editor: Editor; + extension: { options: ImageUploadNodeOptions }; + getPos: () => number; + node: any; +}; diff --git a/src/components/kri-editor/hooks/useKriEditor.ts b/src/components/kri-editor/hooks/useKriEditor.ts new file mode 100644 index 0000000..55247fd --- /dev/null +++ b/src/components/kri-editor/hooks/useKriEditor.ts @@ -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; + 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 => { + 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 || "

", + 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, + }; +} diff --git a/src/components/kri-editor/index.ts b/src/components/kri-editor/index.ts new file mode 100644 index 0000000..4ee0889 --- /dev/null +++ b/src/components/kri-editor/index.ts @@ -0,0 +1,2 @@ +export { KriEditor } from "./KriEditor"; +export type { KriEditorProps, UploadResult } from "./types"; diff --git a/src/components/kri-editor/toolbar/HeadingSelect.tsx b/src/components/kri-editor/toolbar/HeadingSelect.tsx new file mode 100644 index 0000000..0fc0c94 --- /dev/null +++ b/src/components/kri-editor/toolbar/HeadingSelect.tsx @@ -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 ( + + ); +} diff --git a/src/components/kri-editor/toolbar/TableMenu.tsx b/src/components/kri-editor/toolbar/TableMenu.tsx new file mode 100644 index 0000000..5455079 --- /dev/null +++ b/src/components/kri-editor/toolbar/TableMenu.tsx @@ -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(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 ( +
+ setOpen((v) => !v)} /> + {open ? ( +
+ {tableMenuItems.actions.map((item) => ( + + ))} +
+ ) : null} +
+ ); +} diff --git a/src/components/kri-editor/toolbar/Toolbar.tsx b/src/components/kri-editor/toolbar/Toolbar.tsx new file mode 100644 index 0000000..56f5025 --- /dev/null +++ b/src/components/kri-editor/toolbar/Toolbar.tsx @@ -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 ( +
+ {/* Headings (H1/H2/H3) */} + {headingItems.map((item) => ( + item.onClick(editor)} + > + {item.label} + + ))} + + + + {/* Marks */} + {markItems.map((item) => ( + item.onClick(editor)} + /> + ))} + + + + {/* Align */} + {alignItems.map((item) => ( + item.onClick(editor)} + /> + ))} + + + + {/* Lists */} + {listItems.map((item) => ( + item.onClick(editor)} + /> + ))} + + + + {/* Media / Link / Table */} + image.onClick(editor)} + /> + link.onClick(editor)} + /> + +
+ ); +} diff --git a/src/components/kri-editor/toolbar/ToolbarButton.tsx b/src/components/kri-editor/toolbar/ToolbarButton.tsx new file mode 100644 index 0000000..d62edb6 --- /dev/null +++ b/src/components/kri-editor/toolbar/ToolbarButton.tsx @@ -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 ( + + ); +} diff --git a/src/components/kri-editor/toolbar/ToolbarDivider.tsx b/src/components/kri-editor/toolbar/ToolbarDivider.tsx new file mode 100644 index 0000000..d729348 --- /dev/null +++ b/src/components/kri-editor/toolbar/ToolbarDivider.tsx @@ -0,0 +1,8 @@ +"use client"; + +import * as React from "react"; +import { Separator } from "@/components/ui/separator"; + +export function ToolbarDivider() { + return ; +} diff --git a/src/components/kri-editor/toolbar/ToolbarPipe.tsx b/src/components/kri-editor/toolbar/ToolbarPipe.tsx new file mode 100644 index 0000000..433b4b7 --- /dev/null +++ b/src/components/kri-editor/toolbar/ToolbarPipe.tsx @@ -0,0 +1,7 @@ +"use client"; + +import * as React from "react"; + +export function ToolbarPipe() { + return ; +} diff --git a/src/components/kri-editor/toolbar/toolbar-config.ts b/src/components/kri-editor/toolbar/toolbar-config.ts new file mode 100644 index 0000000..24e105e --- /dev/null +++ b/src/components/kri-editor/toolbar/toolbar-config.ts @@ -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 }; +} diff --git a/src/components/kri-editor/toolbar/toolbarConfig.ts b/src/components/kri-editor/toolbar/toolbarConfig.ts new file mode 100644 index 0000000..4e7ec47 --- /dev/null +++ b/src/components/kri-editor/toolbar/toolbarConfig.ts @@ -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[], +}; diff --git a/src/components/kri-editor/types.ts b/src/components/kri-editor/types.ts new file mode 100644 index 0000000..5b45305 --- /dev/null +++ b/src/components/kri-editor/types.ts @@ -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; + + // 업로드 전 압축/리사이즈/용량 제한 + 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; +}; diff --git a/src/components/kri-editor/utils/image-compress.ts b/src/components/kri-editor/utils/image-compress.ts new file mode 100644 index 0000000..240b7c3 --- /dev/null +++ b/src/components/kri-editor/utils/image-compress.ts @@ -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 { + 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 { + 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 { + 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 }); +} diff --git a/src/components/kri-editor/utils/imageCompression.ts b/src/components/kri-editor/utils/imageCompression.ts new file mode 100644 index 0000000..1494b59 --- /dev/null +++ b/src/components/kri-editor/utils/imageCompression.ts @@ -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 { + 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 { + 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 { + 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 }); +} diff --git a/src/components/kri-editor/utils/link.ts b/src/components/kri-editor/utils/link.ts new file mode 100644 index 0000000..b4fff97 --- /dev/null +++ b/src/components/kri-editor/utils/link.ts @@ -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 }; + } +}