Files
co-lite/solvway-admin-portal/app/components/pages/RichTextEditor.tsx
T
ngqileandClaude Opus 5.5 0ee9c217c2 fix(pages): hero grows with its text on phones; name the rich text box
The live check at 360 px clipped the hero heading because the image set a
fixed height. The text now sets the height and the image fills behind it.
The rich text box now carries its field label as an accessible name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 16:54:05 +08:00

115 lines
6.0 KiB
TypeScript

"use client";
import { useEffect, useRef, type ReactNode } from "react";
import { EditorContent, useEditor, useEditorState, type Editor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import TextAlign from "@tiptap/extension-text-align";
import { AlignCenter, AlignLeft, AlignRight, Bold, Eraser, Italic, Link as LinkIcon, List, ListOrdered, Minus, Quote, Strikethrough, Underline } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { useT } from "@/app/lib/i18n/MessagesProvider";
// Ported from babyboo's RichTextEditor, trimmed for landing pages: no YouTube, tables, inline images, emoji,
// colour or HTML source view. The public page sanitises the HTML again with an allow-list.
const SAFE_LINK = /^(https:\/\/|mailto:|tel:|\/(?!\/))/i;
const htmlOf = (editor: Editor) => (editor.isEmpty ? "" : editor.getHTML());
export function RichTextEditor({ id, label, value, onChange, disabled, invalid }: {
id?: string;
label?: string;
value: string;
onChange: (html: string) => void;
disabled?: boolean;
invalid?: boolean;
}) {
const t = useT();
const emitted = useRef(value);
const editor = useEditor({
immediatelyRender: false,
editable: !disabled,
content: value,
extensions: [
StarterKit.configure({
heading: { levels: [2, 3] },
trailingNode: false,
link: { openOnClick: false, protocols: ["https", "mailto", "tel"], isAllowedUri: (url) => SAFE_LINK.test(url) },
}),
TextAlign.configure({ types: ["heading", "paragraph"], alignments: ["left", "center", "right"] }),
],
editorProps: { attributes: { ...(id ? { id } : {}), ...(label ? { "aria-label": label } : {}), ...(invalid ? { "aria-invalid": "true" } : {}), class: "min-h-[140px] px-3 py-2 text-sm outline-none" } },
onUpdate: ({ editor }) => {
const html = htmlOf(editor);
emitted.current = html;
onChange(html);
},
});
useEffect(() => {
if (editor && value !== emitted.current) {
emitted.current = value;
editor.commands.setContent(value, { emitUpdate: false });
}
}, [editor, value]);
useEffect(() => {
editor?.setEditable(!disabled, false);
}, [editor, disabled]);
const state = useEditorState({
editor,
selector: ({ editor }) => ({
level: editor?.isActive("heading") ? String(editor.getAttributes("heading").level) : "0",
active: Object.fromEntries(
["bold", "italic", "underline", "strike", "bulletList", "orderedList", "blockquote", "link"].map((n) => [n, editor?.isActive(n) ?? false]),
) as Record<string, boolean>,
}),
});
const run = (fn: (e: Editor) => void) => { if (editor) fn(editor); };
const off = disabled || !editor;
const btn = (label: string, icon: ReactNode, onClick: () => void, active?: boolean) => (
<Button type="button" variant={active ? "secondary" : "outline"} size="icon" aria-label={label} title={label} aria-pressed={active} disabled={off} onClick={onClick}>
{icon}
</Button>
);
function addLink() {
const url = window.prompt(t("PagesLinkPrompt"));
if (!url || !SAFE_LINK.test(url)) return;
run((e) => e.chain().focus().extendMarkRange("link").setLink({ href: url }).run());
}
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-1" role="toolbar" aria-label={t("PagesToolbar")}>
<select aria-label={t("PagesTextStyle")} title={t("PagesTextStyle")} disabled={off} value={state?.level ?? "0"}
className="h-9 rounded-md border border-input bg-transparent px-2 text-sm"
onChange={(ev) => {
const level = Number(ev.target.value) as 0 | 2 | 3;
run((e) => (level === 0 ? e.chain().focus().setParagraph().run() : e.chain().focus().setHeading({ level }).run()));
}}>
<option value="0">{t("PagesParagraph")}</option>
<option value="2">{t("PagesHeadingLevel", { level: 2 })}</option>
<option value="3">{t("PagesHeadingLevel", { level: 3 })}</option>
</select>
{btn(t("PagesBold"), <Bold />, () => run((e) => e.chain().focus().toggleBold().run()), state?.active.bold)}
{btn(t("PagesItalic"), <Italic />, () => run((e) => e.chain().focus().toggleItalic().run()), state?.active.italic)}
{btn(t("PagesUnderline"), <Underline />, () => run((e) => e.chain().focus().toggleUnderline().run()), state?.active.underline)}
{btn(t("PagesStrike"), <Strikethrough />, () => run((e) => e.chain().focus().toggleStrike().run()), state?.active.strike)}
{btn(t("PagesAlignLeft"), <AlignLeft />, () => run((e) => e.chain().focus().setTextAlign("left").run()))}
{btn(t("PagesAlignCentre"), <AlignCenter />, () => run((e) => e.chain().focus().setTextAlign("center").run()))}
{btn(t("PagesAlignRight"), <AlignRight />, () => run((e) => e.chain().focus().setTextAlign("right").run()))}
{btn(t("PagesBulletList"), <List />, () => run((e) => e.chain().focus().toggleBulletList().run()), state?.active.bulletList)}
{btn(t("PagesNumberedList"), <ListOrdered />, () => run((e) => e.chain().focus().toggleOrderedList().run()), state?.active.orderedList)}
{btn(t("PagesQuote"), <Quote />, () => run((e) => e.chain().focus().toggleBlockquote().run()), state?.active.blockquote)}
{btn(t("PagesDivider"), <Minus />, () => run((e) => e.chain().focus().setHorizontalRule().run()))}
{btn(t("PagesLink"), <LinkIcon />, addLink, state?.active.link)}
{btn(t("PagesClearFormatting"), <Eraser />, () => run((e) => e.chain().focus().unsetAllMarks().clearNodes().run()))}
</div>
<div className="rounded-md border border-input [&_.ProseMirror_a]:underline [&_.ProseMirror_blockquote]:border-l-2 [&_.ProseMirror_blockquote]:pl-3 [&_.ProseMirror_h2]:text-xl [&_.ProseMirror_h2]:font-semibold [&_.ProseMirror_h3]:text-lg [&_.ProseMirror_h3]:font-semibold [&_.ProseMirror_ol]:list-decimal [&_.ProseMirror_ol]:pl-5 [&_.ProseMirror_ul]:list-disc [&_.ProseMirror_ul]:pl-5">
<EditorContent editor={editor} />
</div>
</div>
);
}