Files
co-lite/solvway-admin-portal/app/components/pages/RichTextEditor.tsx
T

124 lines
6.9 KiB
TypeScript

"use client";
import { useEffect, useRef, useState, 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";
import { isSafeLink } from "@/app/lib/cmsPages";
// 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.
// Links follow the page rule in cmsPages (isSafeLink), the same one services-counter applies to buttons.
const htmlOf = (editor: Editor) => (editor.isEmpty ? "" : editor.getHTML());
export function RichTextEditor({ id, label, value, onChange, disabled, invalid, bare }: {
id?: string;
label?: string;
value: string;
onChange: (html: string) => void;
disabled?: boolean;
invalid?: boolean;
/** On the page canvas (add-page-visual-editor): the text in the page's own style, the toolbar floating above it while edited. */
bare?: boolean;
}) {
const t = useT();
const [refused, setRefused] = useState(false);
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) => isSafeLink(url) },
}),
TextAlign.configure({ types: ["heading", "paragraph"], alignments: ["left", "center", "right"] }),
],
editorProps: { attributes: { ...(id ? { id } : {}), ...(label ? { "aria-label": label } : {}), ...(invalid ? { "aria-invalid": "true" } : {}), class: bare ? "min-h-[1.5em] outline-none" : "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"));
setRefused(!!url && !isSafeLink(url));
if (!url || !isSafeLink(url)) return;
run((e) => e.chain().focus().extendMarkRange("link").setLink({ href: url }).run());
}
const toolbar = bare
? "absolute bottom-full left-0 z-20 mb-2 hidden flex-wrap items-center gap-1 rounded-md border bg-popover p-1 text-popover-foreground shadow-md group-focus-within/rt:flex"
: "flex flex-wrap items-center gap-1";
return (
<div className={bare ? "group/rt relative rounded-sm hover:outline-dashed hover:outline-1 hover:outline-primary/50 focus-within:outline-2 focus-within:outline-primary" : "space-y-2"}>
<div className={toolbar} 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()))}
{refused ? <p role="alert" className="basis-full px-1 text-sm text-destructive">{t("PagesLinkRefused")}</p> : null}
</div>
{bare ? <EditorContent editor={editor} /> : <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>
);
}