"use client"; import { useRef, useState } from "react"; import { EditorContent, useEditor, type Editor } from "@tiptap/react"; import StarterKit from "@tiptap/starter-kit"; import Image from "@tiptap/extension-image"; import { NodeSelection } from "@tiptap/pm/state"; import { AlignCenter, AlignLeft, AlignRight, ArrowDown, ArrowUp, Bold, Captions, Code, Heading2, Heading3, ImagePlus, Italic, Link2, List, ListOrdered, Loader2, Pilcrow, Quote, Redo2, Strikethrough, Trash2, Underline, Undo2, } from "lucide-react"; import { Button } from "@/components/ui/button"; /** The for an image node, whether the node parsed from an or a . */ function imageElement(element: HTMLElement): HTMLElement { return element.tagName === "IMG" ? element : element.querySelector("img") ?? element; } /** * The image node adds alignment and a caption to the stock image extension. * Width is already a native attribute and the caption is emitted as the * figcaption text, so the toolbar needs no inline styles (which the server * sanitizer intentionally strips). */ const TrainingImage = Image.extend({ addAttributes() { return { src: { default: null, parseHTML: (element: HTMLElement) => imageElement(element).getAttribute("src"), }, alt: { default: null, parseHTML: (element: HTMLElement) => imageElement(element).getAttribute("alt"), }, title: { default: null, parseHTML: (element: HTMLElement) => imageElement(element).getAttribute("title"), }, width: { default: null, parseHTML: (element: HTMLElement) => imageElement(element).getAttribute("width"), }, align: { default: "center", parseHTML: (element: HTMLElement) => imageElement(element).getAttribute("data-align") ?? "center", renderHTML: (attributes: Record) => ({ "data-align": attributes.align ?? "center", }), }, caption: { default: null, parseHTML: (element: HTMLElement) => element.tagName === "FIGURE" ? element.querySelector("figcaption")?.textContent?.trim() || null : null, }, }; }, parseHTML() { return [ { tag: "figure[data-lesson-image]" }, { tag: 'img[src]:not([src^="data:"])' }, ]; }, renderHTML({ HTMLAttributes }) { const { caption: captionAttribute, ...attributes } = HTMLAttributes; const caption = typeof captionAttribute === "string" ? captionAttribute.trim() : ""; const align = attributes["data-align"] ?? "center"; if (!caption) { return ["figure", { "data-lesson-image": "true" }, ["img", attributes]]; } return [ "figure", { "data-lesson-image": "true" }, ["img", attributes], ["figcaption", { "data-align": align }, caption], ]; }, }); const IMAGE_WIDTHS = ["25%", "50%", "75%", "100%"] as const; function ToolButton({ label, active, disabled, onClick, children, }: { label: string; active?: boolean; disabled?: boolean; onClick: () => void; children: React.ReactNode; }) { return ( event.preventDefault()} onClick={onClick} > {children} ); } function Separator() { return ; } function selectedImagePosition(editor: Editor): number | null { const { selection } = editor.state; if (selection instanceof NodeSelection && selection.node.type.name === "image") { return selection.from; } const { $from } = selection; for (let depth = $from.depth; depth > 0; depth -= 1) { if ($from.node(depth).type.name === "image") { return $from.before(depth); } } return null; } /** Swap the selected image with its previous/next sibling block. */ function moveImage(editor: Editor, direction: -1 | 1) { const pos = selectedImagePosition(editor); if (pos === null) return; const { state } = editor; const node = state.doc.nodeAt(pos); if (!node) return; const $pos = state.doc.resolve(pos); const parent = $pos.parent; const index = $pos.index(); const tr = state.tr; if (direction < 0) { if (index === 0) return; const previous = parent.child(index - 1); const previousPos = pos - previous.nodeSize; tr.replaceWith(previousPos, pos + node.nodeSize, [node, previous]); tr.setSelection(NodeSelection.create(tr.doc, previousPos)); } else { if (index >= parent.childCount - 1) return; const next = parent.child(index + 1); tr.replaceWith(pos, pos + node.nodeSize + next.nodeSize, [next, node]); tr.setSelection(NodeSelection.create(tr.doc, pos + next.nodeSize)); } editor.view.dispatch(tr); editor.commands.focus(); } export function RichTextEditor({ initialContent, onChange, ensureLessonId, }: { initialContent: string; onChange: (html: string) => void; ensureLessonId: () => Promise; }) { const fileInputRef = useRef(null); const [uploading, setUploading] = useState(false); const [uploadError, setUploadError] = useState(null); const editor = useEditor({ immediatelyRender: false, shouldRerenderOnTransaction: true, extensions: [ StarterKit.configure({ heading: { levels: [2, 3, 4] }, link: { openOnClick: false, autolink: true, defaultProtocol: "https", HTMLAttributes: { rel: "noopener noreferrer nofollow", target: "_blank", }, }, }), TrainingImage.configure({ inline: false, allowBase64: false, }), ], content: initialContent || "", editorProps: { attributes: { id: "lesson-body", class: "training-prose min-h-56 px-3 py-3 focus:outline-none sm:min-h-64", "aria-label": "Content", role: "textbox", "aria-multiline": "true", spellcheck: "true", }, }, onUpdate: ({ editor: current }) => { onChange(current.getHTML()); }, }); const isImage = editor?.isActive("image") ?? false; const imageAttributes = editor?.getAttributes("image") ?? {}; const imageAlign = (imageAttributes.align as string | undefined) ?? "center"; const imageWidth = imageAttributes.width ? String(imageAttributes.width) : ""; const imageAlt = (imageAttributes.alt as string | undefined) ?? ""; const imageCaption = (imageAttributes.caption as string | undefined) ?? ""; function promptLink() { if (!editor) return; const previous = (editor.getAttributes("link").href as string | undefined) ?? ""; const entered = window.prompt("Link URL", previous || "https://"); if (entered === null) return; const value = entered.trim(); if (!value) { editor.chain().focus().extendMarkRange("link").unsetLink().run(); return; } const href = /^(https?:\/\/|mailto:|\/)/i.test(value) ? value : `https://${value}`; editor.chain().focus().extendMarkRange("link").setLink({ href }).run(); } function promptImageAlt() { if (!editor) return; const entered = window.prompt( "Describe the image for screen readers", imageAlt, ); if (entered === null) return; editor .chain() .focus() .updateAttributes("image", { alt: entered.trim() }) .run(); } function promptImageCaption() { if (!editor) return; const entered = window.prompt( "Caption shown under the image (leave empty to remove it)", imageCaption, ); if (entered === null) return; editor .chain() .focus() .updateAttributes("image", { caption: entered.trim() || null }) .run(); } async function uploadImage(file: File) { if (!editor) return; if (!file.type.startsWith("image/")) { setUploadError("Choose an image file."); return; } setUploading(true); setUploadError(null); try { const lessonId = await ensureLessonId(); if (!lessonId) { setUploadError("Add a title before inserting an image."); return; } const form = new FormData(); form.append("lessonId", lessonId); form.append("file", file); const response = await fetch("/api/dev/training/resources", { method: "POST", body: form, }); const data = (await response.json().catch(() => ({}))) as { error?: string; resource?: { id: string; filename: string }; }; if (!response.ok || !data.resource) { throw new Error(data.error ?? "Image upload failed."); } editor .chain() .focus() .insertContent({ type: "image", attrs: { src: `/api/training/files/${data.resource.id}`, alt: data.resource.filename, title: data.resource.filename, align: "center", }, }) .run(); } catch (error) { setUploadError( error instanceof Error ? error.message : "Image upload failed.", ); } finally { setUploading(false); if (fileInputRef.current) fileInputRef.current.value = ""; } } return ( { const file = event.target.files?.[0]; if (file) void uploadImage(file); }} /> editor?.chain().focus().undo().run()} > editor?.chain().focus().redo().run()} > editor?.chain().focus().setParagraph().run()} > editor?.chain().focus().toggleHeading({ level: 2 }).run()} > editor?.chain().focus().toggleHeading({ level: 3 }).run()} > editor?.chain().focus().toggleBold().run()} > editor?.chain().focus().toggleItalic().run()} > editor?.chain().focus().toggleUnderline().run()} > editor?.chain().focus().toggleStrike().run()} > editor?.chain().focus().toggleBulletList().run()} > editor?.chain().focus().toggleOrderedList().run()} > editor?.chain().focus().toggleBlockquote().run()} > editor?.chain().focus().toggleCode().run()} > fileInputRef.current?.click()} > {uploading ? ( ) : ( )} {isImage && ( Image editor?.chain().focus().updateAttributes("image", { align: "left" }).run() } > editor ?.chain() .focus() .updateAttributes("image", { align: "center" }) .run() } > editor ?.chain() .focus() .updateAttributes("image", { align: "right" }) .run() } > {IMAGE_WIDTHS.map((width) => ( editor ?.chain() .focus() .updateAttributes("image", { width }) .run() } > {width} ))} ALT editor && moveImage(editor, -1)} > editor && moveImage(editor, 1)} > editor?.chain().focus().deleteSelection().run()} > )} Insert images with the image button. Select an image to align, resize, caption, move, or describe it; you can also drag it to a new position. {uploading && ( Uploading image⦠)} {uploadError && ( {uploadError} )} ); }
{uploadError}