@hacline/ui/rich-text-editorRich Text Editor
Edit structured documents with formatting, tables, block commands, and media previews.
Install
pnpm dlx shadcn@latest add https://hacline.huanan-caoo.workers.dev/r/rich-text-editor.json
With @hacline/ui, use the @hacline/ui/rich-text-editor entry and load @hacline/ui/tokens.css.
Editing and saving media
Select text to format it, type / at the start of a paragraph to insert a block, or drag a block by its handle. Insert an image or video, save the document, and reopen it to see the stored media. This demo saves in your browser.
"use client";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/hacline/components/button";
import type {
JSONContent,
RichTextEditorLocale,
} from "@/components/ui/hacline/components/rich-text-editor";
import { RichTextEditor } from "@/components/ui/hacline/components/rich-text-editor";
const labels = {
en: {
empty: "There is no saved document yet.",
failed: "Could not save the document. Your draft is still open.",
intro: "Edit this paragraph or insert an image or video.",
label: "Editable draft",
opened: "Saved document reopened.",
reopen: "Reopen saved document",
save: "Save document",
saved: "Document and media saved in this browser.",
title: "Project notes",
},
ja: {
empty: "保存済みの文書はありません。",
failed: "文書を保存できませんでした。下書きはそのまま編集できます。",
intro: "この段落を編集するか、画像や動画を挿入してください。",
label: "編集中の下書き",
opened: "保存済みの文書を開きました。",
reopen: "保存済みの文書を開く",
save: "文書を保存",
saved: "文書とメディアをこのブラウザーに保存しました。",
title: "プロジェクトノート",
},
zh: {
empty: "还没有已保存的文档。",
failed: "文档保存失败,草稿仍可继续编辑。",
intro: "编辑这段文字,或插入图片和视频。",
label: "正在编辑的草稿",
opened: "已重新打开保存的文档。",
reopen: "重新打开已保存文档",
save: "保存文档",
saved: "文档与媒体已保存到此浏览器。",
title: "项目笔记",
},
};
const imageTypes = ["image/png", "image/jpeg", "image/webp"];
const videoTypes = ["video/mp4", "video/webm"];
const maxFileBytes = 1024 * 1024;
const storeDemoMedia = (file: File) => {
const { promise, resolve, reject } = Promise.withResolvers<string>();
const reader = new FileReader();
reader.addEventListener(
"load",
() => {
if (typeof reader.result === "string") {
resolve(reader.result);
} else {
reject(new Error("Expected a media URL"));
}
},
{ once: true }
);
reader.addEventListener("error", () => reject(reader.error), { once: true });
reader.readAsDataURL(file);
return promise;
};
const withSavedMedia = async (
value: JSONContent,
files: ReadonlyMap<string, File>
): Promise<JSONContent> => {
const uploads = new Map<string, Promise<string>>();
const replace = async (node: JSONContent): Promise<JSONContent> => {
const source: unknown = node.attrs?.src;
if (
(node.type === "image" || node.type === "video") &&
typeof source === "string"
) {
const file = files.get(source);
if (file) {
const saved = uploads.get(source) ?? storeDemoMedia(file);
uploads.set(source, saved);
return { ...node, attrs: { ...node.attrs, src: await saved } };
}
}
if (node.content) {
return { ...node, content: await Promise.all(node.content.map(replace)) };
}
return node;
};
return await replace(value);
};
const releasePreviews = (previews: Map<string, File>) => {
for (const url of previews.keys()) {
URL.revokeObjectURL(url);
}
previews.clear();
};
export const RichTextEditorMediaDemo = ({
locale = "en",
}: {
locale?: RichTextEditorLocale;
}) => {
const text = labels[locale];
const storageKey = `hacline:rich-text-editor:demo:${locale}`;
const [value, setValue] = useState<JSONContent>(() => ({
type: "doc",
content: [
{
type: "heading",
attrs: { level: 2 },
content: [{ type: "text", text: text.title }],
},
{ type: "paragraph", content: [{ type: "text", text: text.intro }] },
{ type: "paragraph" },
],
}));
const [saving, setSaving] = useState(false);
const [status, setStatus] = useState("");
const [session, setSession] = useState(0);
const files = useRef(new Map<string, File>());
useEffect(() => {
const previews = files.current;
return () => releasePreviews(previews);
}, []);
const preview = (file: File) => {
const url = URL.createObjectURL(file);
files.current.set(url, file);
return url;
};
const openDocument = (document: JSONContent) => {
releasePreviews(files.current);
setValue(document);
// A saved document starts a new session because undo may refer to released URLs.
setSession((current) => current + 1);
};
const save = async () => {
setSaving(true);
try {
// This demo stores media in the browser. An app can upload each File here.
const document = await withSavedMedia(value, files.current);
localStorage.setItem(storageKey, JSON.stringify(document));
openDocument(document);
setStatus(text.saved);
} catch {
setStatus(text.failed);
}
setSaving(false);
};
const reopen = () => {
const saved = localStorage.getItem(storageKey);
if (saved === null) {
setStatus(text.empty);
return;
}
const document: JSONContent = JSON.parse(saved);
openDocument(document);
setStatus(text.opened);
};
return (
<form
className="grid w-full min-w-0 gap-3"
onSubmit={(event) => {
event.preventDefault();
if (!saving) {
void save();
}
}}
>
<RichTextEditor
image={{ accept: imageTypes, maxBytes: maxFileBytes, preview }}
key={session}
label={text.label}
locale={locale}
onChange={setValue}
readOnly={saving}
value={value}
video={{ accept: videoTypes, maxBytes: maxFileBytes, preview }}
/>
<div className="flex flex-wrap items-center gap-2">
<Button aria-busy={saving} disabled={saving} size="sm" type="submit">
{text.save}
</Button>
<Button
disabled={saving}
onClick={reopen}
size="sm"
type="button"
variant="outline"
>
{text.reopen}
</Button>
</div>
<output className="text-hl-fg-muted text-sm">{status}</output>
</form>
);
};Pass image or video with accept, optional maxBytes, and preview(file). Keep the returned preview URLs and their files for the editing session. On save, upload the files referenced in the current document, replace their src attributes with stored URLs, and persist the JSON. Release the preview URLs when the session ends. Keep them when saving fails so the draft can be retried.
Controlled and read-only
Replace the value from the parent, then turn off read-only to edit. Use RichTextEditorRoot with its parts to customize the layout.
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/hacline/components/button";
import type {
JSONContent,
RichTextEditorLocale,
} from "@/components/ui/hacline/components/rich-text-editor";
import {
RichTextEditorContent,
RichTextEditorRoot,
RichTextEditorStatusBar,
RichTextEditorToolbar,
} from "@/components/ui/hacline/components/rich-text-editor";
import { Switch } from "@/components/ui/hacline/components/switch";
const labels = {
en: {
content: ["Draft content", "Content loaded from outside the editor"],
editor: "Controlled document",
readOnly: "Read only",
replace: "Replace document",
},
ja: {
content: ["下書きの内容", "エディターの外部から読み込んだ内容"],
editor: "制御された文書",
readOnly: "読み取り専用",
replace: "文書を差し替える",
},
zh: {
content: ["草稿内容", "由编辑器外部载入的内容"],
editor: "受控文档",
readOnly: "只读",
replace: "替换文档",
},
};
const makeDocument = (text: string): JSONContent => ({
type: "doc",
content: [{ type: "paragraph", content: [{ type: "text", text }] }],
});
export const RichTextEditorControlledDemo = ({
locale = "en",
}: {
locale?: RichTextEditorLocale;
}) => {
const text = labels[locale];
const [initial, replacement] = text.content;
const [document, setDocument] = useState(() => makeDocument(initial));
const [readOnly, setReadOnly] = useState(true);
return (
<div className="grid w-full min-w-0 gap-3">
<div className="flex flex-wrap items-center gap-3">
<Button
onClick={() => setDocument(makeDocument(replacement))}
size="sm"
variant="outline"
>
{text.replace}
</Button>
<label className="text-hl-fg flex items-center gap-2 text-sm">
<Switch checked={readOnly} onCheckedChange={setReadOnly} size="sm" />
{text.readOnly}
</label>
</div>
<RichTextEditorRoot
label={text.editor}
locale={locale}
onChange={setDocument}
readOnly={readOnly}
value={document}
>
<RichTextEditorToolbar />
<RichTextEditorContent />
<RichTextEditorStatusBar />
</RichTextEditorRoot>
</div>
);
};| Prop | Usage |
|---|---|
value, onChange | Read and update a Tiptap JSONContent document. |
readOnly | Show the document with editing controls hidden. Defaults to false. |
label, placeholder, className | Set the accessible name, empty hint, and container class. |
locale | UI language. Use en, zh, or ja. Defaults to en. |
image, video | Enable the corresponding file picker. The image configuration also enables pasting and dropping image files. |