8601a6014f
Authors can now attach a caption to an image in the lesson editor; it is sanitized as figure text and follows the image's alignment in the reader. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
616 lines
18 KiB
TypeScript
616 lines
18 KiB
TypeScript
"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 <img> for an image node, whether the node parsed from an <img> or a <figure>. */
|
|
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<string, unknown>) => ({
|
|
"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 (
|
|
<Button
|
|
type="button"
|
|
size="sm"
|
|
variant={active ? "secondary" : "ghost"}
|
|
className="h-8 min-w-8 gap-1 px-2"
|
|
aria-label={label}
|
|
aria-pressed={active}
|
|
title={label}
|
|
disabled={disabled}
|
|
onMouseDown={(event) => event.preventDefault()}
|
|
onClick={onClick}
|
|
>
|
|
{children}
|
|
</Button>
|
|
);
|
|
}
|
|
|
|
function Separator() {
|
|
return <span className="mx-1 h-5 w-px bg-border" aria-hidden="true" />;
|
|
}
|
|
|
|
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<string | null>;
|
|
}) {
|
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
|
const [uploading, setUploading] = useState(false);
|
|
const [uploadError, setUploadError] = useState<string | null>(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 || "<p></p>",
|
|
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 (
|
|
<div className="overflow-hidden rounded-md border border-input bg-background">
|
|
<input
|
|
ref={fileInputRef}
|
|
type="file"
|
|
accept="image/png,image/jpeg,image/gif,image/webp,image/avif"
|
|
className="sr-only"
|
|
aria-label="Upload an image for the lesson"
|
|
onChange={(event) => {
|
|
const file = event.target.files?.[0];
|
|
if (file) void uploadImage(file);
|
|
}}
|
|
/>
|
|
|
|
<div
|
|
className="flex flex-wrap items-center gap-0.5 border-b border-border bg-muted/30 p-1"
|
|
role="toolbar"
|
|
aria-label="Lesson formatting"
|
|
>
|
|
<ToolButton
|
|
label="Undo"
|
|
disabled={!editor?.can().undo()}
|
|
onClick={() => editor?.chain().focus().undo().run()}
|
|
>
|
|
<Undo2 aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Redo"
|
|
disabled={!editor?.can().redo()}
|
|
onClick={() => editor?.chain().focus().redo().run()}
|
|
>
|
|
<Redo2 aria-hidden="true" />
|
|
</ToolButton>
|
|
|
|
<Separator />
|
|
|
|
<ToolButton
|
|
label="Paragraph"
|
|
active={editor?.isActive("paragraph")}
|
|
onClick={() => editor?.chain().focus().setParagraph().run()}
|
|
>
|
|
<Pilcrow aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Heading 2"
|
|
active={editor?.isActive("heading", { level: 2 })}
|
|
onClick={() => editor?.chain().focus().toggleHeading({ level: 2 }).run()}
|
|
>
|
|
<Heading2 aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Heading 3"
|
|
active={editor?.isActive("heading", { level: 3 })}
|
|
onClick={() => editor?.chain().focus().toggleHeading({ level: 3 }).run()}
|
|
>
|
|
<Heading3 aria-hidden="true" />
|
|
</ToolButton>
|
|
|
|
<Separator />
|
|
|
|
<ToolButton
|
|
label="Bold"
|
|
active={editor?.isActive("bold")}
|
|
onClick={() => editor?.chain().focus().toggleBold().run()}
|
|
>
|
|
<Bold aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Italic"
|
|
active={editor?.isActive("italic")}
|
|
onClick={() => editor?.chain().focus().toggleItalic().run()}
|
|
>
|
|
<Italic aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Underline"
|
|
active={editor?.isActive("underline")}
|
|
onClick={() => editor?.chain().focus().toggleUnderline().run()}
|
|
>
|
|
<Underline aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Strikethrough"
|
|
active={editor?.isActive("strike")}
|
|
onClick={() => editor?.chain().focus().toggleStrike().run()}
|
|
>
|
|
<Strikethrough aria-hidden="true" />
|
|
</ToolButton>
|
|
|
|
<Separator />
|
|
|
|
<ToolButton
|
|
label="Bulleted list"
|
|
active={editor?.isActive("bulletList")}
|
|
onClick={() => editor?.chain().focus().toggleBulletList().run()}
|
|
>
|
|
<List aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Numbered list"
|
|
active={editor?.isActive("orderedList")}
|
|
onClick={() => editor?.chain().focus().toggleOrderedList().run()}
|
|
>
|
|
<ListOrdered aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Quote"
|
|
active={editor?.isActive("blockquote")}
|
|
onClick={() => editor?.chain().focus().toggleBlockquote().run()}
|
|
>
|
|
<Quote aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Inline code"
|
|
active={editor?.isActive("code")}
|
|
onClick={() => editor?.chain().focus().toggleCode().run()}
|
|
>
|
|
<Code aria-hidden="true" />
|
|
</ToolButton>
|
|
|
|
<Separator />
|
|
|
|
<ToolButton
|
|
label={editor?.isActive("link") ? "Remove link" : "Add link"}
|
|
active={editor?.isActive("link")}
|
|
onClick={promptLink}
|
|
>
|
|
<Link2 aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Insert image"
|
|
disabled={!editor || uploading}
|
|
onClick={() => fileInputRef.current?.click()}
|
|
>
|
|
{uploading ? (
|
|
<Loader2 className="animate-spin" aria-hidden="true" />
|
|
) : (
|
|
<ImagePlus aria-hidden="true" />
|
|
)}
|
|
</ToolButton>
|
|
</div>
|
|
|
|
{isImage && (
|
|
<div
|
|
className="flex flex-wrap items-center gap-0.5 border-b border-border bg-background px-1 py-1"
|
|
role="toolbar"
|
|
aria-label="Selected image"
|
|
>
|
|
<span className="px-1 text-xs font-medium text-muted-foreground">
|
|
Image
|
|
</span>
|
|
<ToolButton
|
|
label="Align image left"
|
|
active={imageAlign === "left"}
|
|
onClick={() =>
|
|
editor?.chain().focus().updateAttributes("image", { align: "left" }).run()
|
|
}
|
|
>
|
|
<AlignLeft aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Center image"
|
|
active={imageAlign === "center"}
|
|
onClick={() =>
|
|
editor
|
|
?.chain()
|
|
.focus()
|
|
.updateAttributes("image", { align: "center" })
|
|
.run()
|
|
}
|
|
>
|
|
<AlignCenter aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Align image right"
|
|
active={imageAlign === "right"}
|
|
onClick={() =>
|
|
editor
|
|
?.chain()
|
|
.focus()
|
|
.updateAttributes("image", { align: "right" })
|
|
.run()
|
|
}
|
|
>
|
|
<AlignRight aria-hidden="true" />
|
|
</ToolButton>
|
|
|
|
<Separator />
|
|
|
|
{IMAGE_WIDTHS.map((width) => (
|
|
<ToolButton
|
|
key={width}
|
|
label={`Set image width to ${width}`}
|
|
active={imageWidth === width}
|
|
onClick={() =>
|
|
editor
|
|
?.chain()
|
|
.focus()
|
|
.updateAttributes("image", { width })
|
|
.run()
|
|
}
|
|
>
|
|
<span className="text-[11px] font-medium">{width}</span>
|
|
</ToolButton>
|
|
))}
|
|
|
|
<Separator />
|
|
|
|
<ToolButton label="Edit image description" onClick={promptImageAlt}>
|
|
<span className="text-[11px] font-semibold">ALT</span>
|
|
</ToolButton>
|
|
<ToolButton
|
|
label={imageCaption ? "Edit image caption" : "Add image caption"}
|
|
active={Boolean(imageCaption)}
|
|
onClick={promptImageCaption}
|
|
>
|
|
<Captions aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Move image up"
|
|
onClick={() => editor && moveImage(editor, -1)}
|
|
>
|
|
<ArrowUp aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Move image down"
|
|
onClick={() => editor && moveImage(editor, 1)}
|
|
>
|
|
<ArrowDown aria-hidden="true" />
|
|
</ToolButton>
|
|
<ToolButton
|
|
label="Remove image"
|
|
onClick={() => editor?.chain().focus().deleteSelection().run()}
|
|
>
|
|
<Trash2 aria-hidden="true" />
|
|
</ToolButton>
|
|
</div>
|
|
)}
|
|
|
|
<EditorContent editor={editor} />
|
|
|
|
<div className="flex flex-wrap items-center justify-between gap-2 border-t border-border px-2 py-1.5 text-xs text-muted-foreground">
|
|
<span>
|
|
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.
|
|
</span>
|
|
{uploading && (
|
|
<span role="status" className="inline-flex items-center gap-1">
|
|
<Loader2 className="h-3 w-3 animate-spin" aria-hidden="true" />
|
|
Uploading image…
|
|
</span>
|
|
)}
|
|
</div>
|
|
|
|
{uploadError && (
|
|
<p role="alert" className="border-t border-border px-2 py-1.5 text-xs text-destructive">
|
|
{uploadError}
|
|
</p>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|