talnima-editor
v0.3.3
Published
A fast, Medium-style article editor for React, built on Tiptap/ProseMirror, with right-to-left (Dari/Persian/Arabic) support and a server-safe HTML renderer.
Maintainers
Readme
talnima-editor
A fast, Medium-style article editor for React. It has:
- no toolbar;
- a pop-over when you select text;
- a "+" on empty lines;
- images that upload in the background;
- full right-to-left support for Dari, Pashto and Arabic.
It is built on Tiptap v3 (ProseMirror) and ships a server-side renderer, so readers never download the editor.
The design and decisions are in docs/PLAN.md.
npm install talnima-editorReact 18 or 19 is a peer dependency. Tiptap is a regular dependency, and all its packages are kept on one version. If your app also uses Tiptap directly, match that version, because Tiptap's packages require exact matches with each other.
Use it
'use client'
import { ArticleEditor, type ArticleDocument } from 'talnima-editor'
import 'talnima-editor/styles.css'
export function Write({ draft }: { draft: ArticleDocument | null }) {
return (
<ArticleEditor
initialContent={draft}
onChange={(doc, stats) => saveDraft(doc)} // debounced; flushed on blur/unmount
uploadImage={async (file) => ({ url: await uploadToR2(file) })}
showStats
autoFocus
/>
)
}Pure helpers, safe anywhere, even in a client component, with zero dependencies:
import { createEmptyArticle, getArticleTitle, getArticleStats } from 'talnima-editor/document'Render an article on the server, with no editor JavaScript:
// app/articles/[slug]/page.tsx (a server component)
import { renderArticleHTML } from 'talnima-editor/renderer'
import 'talnima-editor/styles.css'
export default async function Article({ params }) {
const doc = await getArticle((await params).slug)
return <article className="te-content" dangerouslySetInnerHTML={{ __html: renderArticleHTML(doc) }} />
}For a Dari interface:
<ArticleEditor dir="rtl" locale="fa-AF" labels={{ editor: 'متن مقاله', titlePlaceholder: 'عنوان', bodyPlaceholder: 'داستان تان را بنویسید…' /* … */ }} />Text direction
Each block reads the way most of its words do, not by its first letter, so
a Dari line that opens with an English word ("IndexedDB یک دیتابیس…") stays
right to left. A block keeps the direction around it until the other
language leads by two words; a list's items all take the list's direction,
so the bullets stay on one side; inline code is not counted. The editor shows
this without storing it, and renderArticleHTML writes it into the HTML.
Pass renderArticleHTML(doc, { dir: 'rtl' }) to set the direction used when
an article's words are evenly split.
Props
| Prop | Default | |
|---|---|---|
| initialContent | empty article | Read once. Change key to load a different article. |
| onChange(doc, stats) | | Debounced. Figures still uploading are never included. |
| changeDebounceMs | 500 | |
| onDirty() | | Called on the first edit before the debounce. Pass autosave.markDirty. |
| uploadImage(file) | | Returns { url, alt? }. Without it, image paste, drop and the image button are off. |
| onUploadError(err, file) | | |
| maxImageBytes | 10 MB | Client-side UX check only. Validate on the server too. |
| labels | English | Every UI string. See EditorLabels. |
| dir | 'ltr' | Direction of the chrome, and of the text while the article has no words. See "Text direction" below. |
| locale | | Number formatting in the stats line. |
| editable, autoFocus, showStats, className | | |
A ref gives you getDocument(), getStats(), focus() and editor.
Autosave
import { ArticleEditor, AutosaveStatus, useAutosave, SaveConflictError } from 'talnima-editor'
const autosave = useAutosave({
// Send `revision` so the server can refuse a stale write; throw SaveConflictError if it does.
save: (doc, { revision }) => api.saveDraft(id, doc, revision), // resolve { revision } if you have them
initialRevision: draft.revision,
backupKey: `article-${id}`, // unsaved changes survive a crash or a closed tab
})
<AutosaveStatus state={autosave} />
<ArticleEditor initialContent={draft.doc} onChange={autosave.onChange} onDirty={autosave.markDirty} />- Saves 1.5 s after typing stops, and at least every 10 s during continuous typing.
- Only one request at a time. An edit made during a save goes out right after it.
- Failures retry after 1, 3, 10 and 30 s. Offline waits for the connection.
- A conflict stops saving until you call
autosave.retry(resolvedRevision). - It saves immediately when the tab is hidden, and warns before closing with unsaved changes.
await autosave.flush()before publishing.readAutosaveBackup(key)returns an unsaved draft from a previous session, so you can offer to restore it.
Code blocks
- Type
```js(or pick from the block's language menu). - 12 languages are supported: JavaScript, TypeScript, HTML, CSS, SCSS, JSON, Shell, Python, SQL, Markdown, YAML and Diff.
- In the editor, lowlight and a language's grammar download only when a block uses it.
renderArticleHTMLhighlights on the server, so readers get coloured code with no JavaScript. Pass{ highlight: false }to turn it off.
Image sizes
- Click an image to choose text width, wide (
--te-wide-measure, 64rem) or full width (--te-full-width). - In the editor, full width is the editor's own width. On a reader page it's the viewport (
100vw). A reader page with a sidebar should set--te-full-widthto its content width. - With an image selected, typing goes into its caption. Backspace or Delete removes the image.
- With classic (non-overlay) scrollbars, put
overflow-x: clipon an ancestor, because100vwincludes the scrollbar.
Security
The output of renderArticleHTML is safe to put into dangerouslySetInnerHTML.
Every input, from the editor, an API or a database row, goes through one
allowlist sanitizer first.
- Allowed: title, paragraph, h2/h3, quote, lists, code, divider, figure/image/caption, line break; bold, italic, inline code, link. All other node types and marks are dropped.
- Links store only
href, and only http(s), mailto:, tel: or relative. Every link renderstarget="_blank" rel="noopener noreferrer nofollow". Pasted or storedclass,rel,targetandstyleare dropped. The editor and the sanitizer use the same URL check. - Images: only
https://,http://, root-relative/pathand base64 PNG/JPEG/GIF/WebP/AVIF. SVG,blob:andjavascript:are dropped. - Attribute values are checked (heading level, list start and type,
dir, code language, image layout), never passed through. - Robustness: depth (48), node count (50,000) and text length are
capped. A corrupted or hostile document renders what it can and never
throws, except for a
schemaVersionnewer than the package. - Tests: a fuzz test renders 2,000 random and hostile documents. It checks every output tag, attribute and class against a fixed list. A schema test fails if the sanitizer and the editor schema ever drift apart.
Sanitize on save too. sanitizeArticle has zero dependencies and works
from CommonJS servers such as Strapi:
import { sanitizeArticle } from 'talnima-editor/document' // or require()
const { value, issues } = sanitizeArticle(body.article)
if (issues.length) return ctx.badRequest('Article rejected', { issues }) // or store `value`Anything written in the editor sanitizes with zero issues. That includes
messy pastes from Word or the web, because the editor normalises pasted
values with the sanitizer's own checks, and both cases are tested. So
rejecting on issues.length won't refuse a legitimate save.
Still your job as the host:
- Cap the request body size on the save endpoint.
- Check the type and size of uploaded images on the server.
- Serve uploads from a domain or bucket that can't run scripts on your site.
- Keep only one copy of this package in your app.
Theming
Override the --te-* variables on .te-root (editor) or .te-content
(reader). Dark mode turns on under .dark or [data-theme="dark"]. Every
rule uses zero-specificity :where(), so your own classes always win.
Develop
npm install
npm run dev # playground at http://localhost:5173 (upload + Dari RTL toggle)
npm test # vitest
npm run typecheck
npm run build # dist/
npm run lint:package # publint + are-the-types-wrong