# Writeon > A framework-agnostic, headless, accessible rich text editor built on ProseMirror. --- Source: /guide/getting-started.md # Getting started **Early development:** Writeon is in early development (0.x). The API may still change before 1.0. ## Install ```sh [npm] npm install @writeon/core # and the adapter for your framework, if you use one npm install @writeon/react # React 18+ npm install @writeon/vue # Vue 3.3+ ``` ```sh [pnpm] pnpm add @writeon/core # and the adapter for your framework, if you use one pnpm add @writeon/react # React 18+ pnpm add @writeon/vue # Vue 3.3+ ``` ```sh [yarn] # Yarn does not install peer dependencies: list them yarn add @writeon/core prosemirror-commands prosemirror-history prosemirror-inputrules \ prosemirror-keymap prosemirror-model prosemirror-schema-list \ prosemirror-state prosemirror-transform prosemirror-view # and the adapter for your framework, if you use one yarn add @writeon/react # React 18+ yarn add @writeon/vue # Vue 3.3+ ``` ```sh [bun] bun add @writeon/core # and the adapter for your framework, if you use one bun add @writeon/react # React 18+ bun add @writeon/vue # Vue 3.3+ ``` ProseMirror packages are peer dependencies, so your app has one copy of each. npm (7+), pnpm and bun install them for you; with Yarn, add them yourself as shown. ## Your first editor An editor is made of **extensions**. `basic()` gives paragraphs, headings, bold, italic, underline, strike, inline code, links, lists, blockquotes, line breaks and undo/redo. Every editor needs a **label**: the accessible name screen readers announce for the editable area. **Vanilla** ```ts import { createEditor } from '@writeon/core' import { toggleBold } from '@writeon/core/commands' import { basic } from '@writeon/core/presets' //
and const element = document.querySelector('#editor') if (!element) throw new Error('No #editor element') const editor = createEditor({ element, extensions: basic(), // Required: screen readers announce the editor by this name. label: 'Article text', placeholder: 'Start writing…', onChange: (editor) => console.log(editor.getJSON()), }) // Commands are factories: call toggleBold(), then run the result. document.querySelector('#bold')?.addEventListener('click', () => { editor.run(toggleBold()) }) ``` **React** ```tsx import type { DocJSON } from '@writeon/core' import { toggleBold } from '@writeon/core/commands' import { basic } from '@writeon/core/presets' import { EditorContent, useEditor, useEditorState, } from '@writeon/react' // Create the extensions once, outside components. const extensions = basic() interface Props { initial: DocJSON onSave: (doc: DocJSON) => void } export function ArticleEditor({ initial, onSave }: Props) { const editor = useEditor({ extensions, content: initial, label: 'Article text', onChange: (editor) => onSave(editor.getJSON()), }) // Re-renders only when this value changes. const isBold = useEditorState(editor, (s) => s.marks.has('bold')) return ( <> ) } ``` **Vue** ```vue ``` ## Styles The core ships no styles. ProseMirror needs this one rule so spaces and line breaks show correctly: ```css .ProseMirror { white-space: pre-wrap; word-wrap: break-word; } ``` Or use the [default kit](/guide/kit.md): a themeable toolbar and content styles in one CSS file. ## Next - [Core concepts](/guide/concepts.md): documents, extensions, commands and state. - [Saving and loading](/guide/saving.md): store JSON, convert to HTML or Markdown. - [Security](/guide/security.md): validate on the server before you store or render. --- Source: /guide/concepts.md # Core concepts ## The document is JSON The editor's content is a `DocJSON` value: a tree of nodes (paragraphs, headings, list items…) with text and marks (bold, link…). ```json { "type": "doc", "schemaVersion": 1, "content": [ { "type": "paragraph", "content": [{ "type": "text", "text": "Hello", "marks": [{ "type": "bold" }] }] } ] } ``` - **Store this JSON.** It is lossless and does not depend on the browser. HTML and Markdown are derived from it (see [Saving and loading](/guide/saving.md)). - `schemaVersion` is the version of the format itself. When it changes, `migrateDoc()` (run automatically on load) brings old documents up to date. ## Extensions define what a document may contain An extension adds node or mark types to the schema, plus behaviour: keyboard shortcuts, input rules (Markdown-style shortcuts such as `## `), and ProseMirror plugins. Presets are just arrays of extensions: ```ts import { basic } from '@writeon/core/presets' basic() // everything basic({ strike: false }) // without strikethrough basic({ heading: { levels: [2, 3] } }) // only H2 and H3 basic({ link: { protocols: ['https'] } }) // https links only ``` Content the schema does not allow is dropped when a document is loaded or pasted. Use **the same extensions** on the server (see [Security](/guide/security.md)). To write your own, see [Your own extension](/recipes/custom-extension.md). ## Commands change the document Commands are **factories**: `toggleBold()` returns a command, which you pass to `editor.run()`. Commands live in `@writeon/core/commands` and in the packages that add features. ```ts import type { Editor } from '@writeon/core' import { setHeading, setLink, toggleBold, toggleBulletList, } from '@writeon/core/commands' export function examples(editor: Editor) { // Commands are factories: call them, then run the result. editor.run(toggleBold()) // can() asks without changing anything. // Use it to disable buttons. const canList = editor.can(toggleBulletList()) // Several commands, one undo step. // Nothing is applied if one of them fails. editor.transaction((tx) => { tx.run(setHeading(2)) tx.run(setLink({ href: 'https://example.com' })) }) // What is active at the selection. const inHeading = editor.isActive('heading', { level: 2 }) // A snapshot for your UI; subscribe() says when it changed. const off = editor.subscribe(() => { const { marks, canUndo, block } = editor.getSnapshot() console.log([...marks], canUndo, block.type) }) return { canList, inHeading, off } } ``` ## State for your UI `editor.getSnapshot()` returns an immutable object with what UI usually needs: active marks, the current block, selection, `canUndo`, `focused`, `editable`, `empty`. `editor.subscribe()` calls you when it changes (batched per microtask). In React, `useEditorState(editor, selector)` re-renders only when the selected value changes; in Vue, it returns a ref. ## Lifecycle - `createEditor({ element })` mounts at once; without `element`, call `editor.mount(el)` later. Document and history survive `unmount()` and `mount()`. - `editor.destroy()` releases everything. The React and Vue adapters do this for you. - `editor.pm` gives direct access to ProseMirror. It is **not a stable API**: it may change in any minor release. --- Source: /guide/basic-and-advanced.md # Basic and advanced Most editors need only the basics. Task lists, code blocks, images, tables and mentions are **advanced** and live in `@writeon/advanced`. Advanced is split in two so it costs nothing until it is used: | Part | Package | Loaded | | --------------------------------------------- | --------------------------- | -------------------- | | Node types (schema) | `@writeon/advanced/schema` | Up front, about 2 KB | | Behaviour (shortcuts, table editing, uploads) | `@writeon/advanced` | On demand | Because the schema is always there, every document opens and displays correctly, even one with tables, before the behaviour is loaded. ```ts import { advancedSchema } from '@writeon/advanced/schema' import { createEditor } from '@writeon/core' import { basic } from '@writeon/core/presets' // The node types are small and loaded up front, so every document // opens and renders before the advanced behaviour arrives. export const extensions = [...basic(), advancedSchema()] const editor = createEditor({ extensions, label: 'Notes' }) // Later, when the user needs it. Shortcuts, input rules, table editing // and the rest come in a separate chunk. // The document, undo history and selection are kept. export async function turnOnAdvanced(): Promise { await editor.enable(() => import('@writeon/advanced')) } ``` `editor.enable()` adds behaviour to the running editor and keeps the document, undo history and selection. Extensions already added are skipped, so calling it twice is harmless. If you do not need lazy loading, pass everything up front: ```ts import { advanced, advancedSchema } from '@writeon/advanced' createEditor({ extensions: [...basic(), advancedSchema(), ...advanced()], label: 'Notes' }) ``` ## What advanced adds | Feature | Commands | Notes | | ----------- | -------------------------------------------------- | ---------------------------------------------- | | Task lists | `toggleTaskList()`, `toggleTaskChecked()` | `Mod-Shift-9`, `[ ] ` input rule | | Code blocks | `toggleCodeBlock()`, `setCodeBlockLanguage()` | `Mod-Alt-c`, ` ``` ` input rule | | Images | `insertImage()`, `updateImage()`, `uploadImages()` | `imageUpload()` for drop, paste and progress | | Tables | `insertTable()`, `addRowAfter()`, `mergeCells()`… | Header row by default; Tab moves between cells | | Mentions | `insertMention({ id, label })` | Use with a suggestion menu | ## Fonts, colours and alignment `@writeon/advanced/formatting` (about 2 KB, loaded up front like the schema) adds three extensions configured with what your design allows: | Extension | Stores | Renders | | --- | --- | --- | | `fontFamily({ fonts })` | `{ font: 'inter' }` mark, so one paragraph can mix fonts | `` | | `textColor({ colors })` | `{ color: 'brand' }` mark | `` | | `textAlign()` | `align` on paragraphs and headings (`null` is left) | `style="text-align: …"`; `Mod-Shift-l/e/r` | ```ts import { fontFamily, setFontFamily, setTextAlign, setTextColor, textAlign, textColor, } from '@writeon/advanced/formatting' import { createEditor } from '@writeon/core' import { basic } from '@writeon/core/presets' // The values your design allows. Documents store only the ids. export const extensions = [ ...basic(), fontFamily({ fonts: [ { id: 'inter', label: 'Inter', css: 'Inter, sans-serif' }, { id: 'serif', label: 'Serif', css: 'Georgia, serif' }, ], }), textColor({ colors: [ { id: 'brand', label: 'Red', value: '#C00414' }, { id: 'muted', label: 'Gray', value: '#475467' }, ], }), textAlign(), ] const editor = createEditor({ extensions, label: 'Post' }) // On the selection, or on what is typed next. editor.run(setFontFamily('serif')) editor.run(setTextColor('brand')) // On the selected paragraphs and headings. editor.run(setTextAlign('center')) // null removes the font or the colour. editor.run(setFontFamily(null)) ``` - **Only ids are stored.** An id that is not configured does not fit the schema, so `validate()` drops it, and `toHTML()` writes nothing but `text-align`, `font-family` and `color` with strict values. - **Pasted text keeps** a font when its `font-family` starts with one of yours, a colour when it is exactly one of yours, and alignment. - **Contrast:** `textColor()` warns while you develop when a colour is under 4.5:1 on the background (`background`, default white). - **Markdown** has no fonts or colours: `toMarkdown()` keeps the text without them. - For menus, `activeFontFamily(state)` and `activeTextColor(state)` give the current id, and `textAlignmentAt(state)` the alignment. ### Image addresses Image `src` is checked by the schema: `http(s)` or relative URLs only. `data:` URLs are refused unless you allow raster ones with `advancedSchema({ image: { dataUrls: true } })`. SVG is never allowed, because an SVG served from your domain can run scripts. ### Alt text An image's `alt` is `null` until someone describes it (the element gets `data-alt-missing`, so you can show a hint), or `""` when it is marked decorative. The kit's image dialog requires one of the two. --- Source: /guide/saving.md # Saving and loading ```ts import { advancedSchema } from '@writeon/advanced/schema' import { createEditor, type DocJSON, debounce, type Editor, } from '@writeon/core' import { basic } from '@writeon/core/presets' import { fromHTML, toHTML } from '@writeon/html' import { fromMarkdown, toMarkdown } from '@writeon/markdown' const extensions = [...basic(), advancedSchema()] declare function saveDraft(doc: DocJSON): Promise declare const stored: DocJSON // Save at most twice a second. const save = debounce((editor: Editor) => { return saveDraft(editor.getJSON()) }, 500) const editor = createEditor({ extensions, content: stored, label: 'Draft', onChange: save, }) // And once more before the page goes away. window.addEventListener('pagehide', () => save.flush()) // Replace the whole document (not added to the undo history). editor.setContent(stored) // Other formats, always with the same extensions. const doc = editor.getJSON() const html = toHTML(doc, { extensions }) const markdown = toMarkdown(doc, { extensions }) const fromOldHtml = fromHTML('

Hello world

', { extensions, }) const fromReadme = fromMarkdown('# Title\n\n- one\n- two', { extensions, }) export { fromOldHtml, fromReadme, html, markdown } ``` ## onChange `onChange` runs after **every** change. Serializing the document on each keystroke is cheap for small documents, but for saving use `debounce()` from `@writeon/core`: it has `flush()` for the last pending call (before navigating away) and `cancel()`. ## HTML `@writeon/html` converts both ways: - `toHTML(doc, { extensions })` renders semantic HTML. It runs on the server too (no DOM needed). - `fromHTML(html, { extensions })` parses HTML inside an inert `