feat(training): captions under lesson images

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>
This commit is contained in:
2026-11-21 00:45:32 +00:00
parent f7a0c8618f
commit 8601a6014f
6 changed files with 130 additions and 11 deletions
+3 -3
View File
@@ -683,9 +683,9 @@ export default function AdminGuidePage() {
</GuideStep>
<GuideStep>
Press the image button to upload a screenshot. Select the image to
align it left, center, or right, choose a width, edit its
description, or move it up and down. You can also drag the image to a
new position in the lesson.
align it left, center, or right, choose a width, add a caption shown
beneath it, edit its description, or move it up and down. You can
also drag the image to a new position in the lesson.
</GuideStep>
<GuideStep>
Set a sort order to control the list position. Lower numbers appear
+16
View File
@@ -245,6 +245,22 @@
margin-left: auto;
}
.training-prose figcaption {
margin-top: 0.4rem;
color: var(--muted-foreground);
font-size: 0.78rem;
line-height: 1.5;
text-align: center;
}
.training-prose figcaption[data-align="left"] {
text-align: left;
}
.training-prose figcaption[data-align="right"] {
text-align: right;
}
.training-prose img.ProseMirror-selectednode {
outline: 3px solid var(--ring);
outline-offset: 2px;
@@ -12,6 +12,7 @@ import {
ArrowDown,
ArrowUp,
Bold,
Captions,
Code,
Heading2,
Heading3,
@@ -31,24 +32,81 @@ import {
} 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 to the stock image extension. Width is already
* a native attribute, so the toolbar can offer percentage presets without any
* inline styles (which the server sanitizer intentionally strips).
* 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 {
...this.parent?.(),
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) => element.getAttribute("data-align") ?? "center",
renderHTML: (attributes) => ({
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;
@@ -192,6 +250,7 @@ export function RichTextEditor({
? String(imageAttributes.width)
: "";
const imageAlt = (imageAttributes.alt as string | undefined) ?? "";
const imageCaption = (imageAttributes.caption as string | undefined) ?? "";
function promptLink() {
if (!editor) return;
@@ -224,6 +283,20 @@ export function RichTextEditor({
.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/")) {
@@ -489,6 +562,13 @@ export function RichTextEditor({
<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)}
@@ -515,7 +595,7 @@ export function RichTextEditor({
<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,
move, or describe it; you can also drag it to a new position.
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">
+11
View File
@@ -30,6 +30,17 @@ describe("sanitizeTrainingHtml", () => {
expect(dataUrl).not.toContain("<img");
});
it("keeps image captions as figure text and strips markup inside them", () => {
const html = sanitizeTrainingHtml(
'<figure data-lesson-image="true"><img src="/api/training/files/abc" alt="Console" data-align="left"><figcaption data-align="left">Console <script>alert(1)</script>ready</figcaption></figure>',
);
expect(html).toContain('<figure data-lesson-image="true">');
expect(html).toContain('<figcaption data-align="left">');
expect(html).toContain("Console ready");
expect(html).not.toContain("<script");
});
it("opens external links safely and keeps internal links local", () => {
const external = sanitizeTrainingHtml(
'<a href="https://example.com/manual">Manual</a>',
+7 -1
View File
@@ -32,12 +32,16 @@ const ALLOWED_TAGS = [
"code",
"a",
"img",
"figure",
"figcaption",
"hr",
];
const ALLOWED_ATTRIBUTES: sanitizeHtml.IOptions["allowedAttributes"] = {
a: ["href", "target", "rel", "title"],
img: ["src", "alt", "title", "width", "height", "data-align"],
figure: ["data-lesson-image"],
figcaption: ["data-align"],
};
function escapeHtml(value: string): string {
@@ -57,7 +61,9 @@ function escapeHtml(value: string): string {
function looksLikeHtml(value: string): boolean {
return (
/<\/[a-z][^>]*>/i.test(value) ||
/<(p|h[1-6]|ul|ol|li|blockquote|pre|img|hr|br|div)\b[^>]*>/i.test(value)
/<(p|h[1-6]|ul|ol|li|blockquote|pre|figure|img|hr|br|div)\b[^>]*>/i.test(
value,
)
);
}