Skip to content

About

Open-source ProseMirror alternative and independent TypeScript rich-text editor. Includes Yjs collaboration, comments and tracked changes. Compare with Tiptap and try the live editor.

Topics

Resources

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

1,445 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FountainJS rich-text editor

npm version CI license

FountainJS is an MIT-licensed TypeScript alternative to ProseMirror and Tiptap. Its independent document engine supports tables, comments, tracked changes, Yjs collaboration and version history. Use it from plain JavaScript, React, Vue, Svelte, Angular or a Web Component, and store the document JSON on your own backend.

Try the live editor · Quick start · Compare with ProseMirror and Tiptap · See all three integrations

Install

npm install fountainjs-editor

The plain JavaScript starter mounts an editor, adds a custom block and shows the saved JSON. For other frameworks and server usage, see installation options.

A suggested change and an inline discussion posted through FountainJS in a GitLab merge request

A code review posted in a local GitLab CE 19.5.3 installation using FountainJS. See the stock and replacement editors, recordings and reproduction steps.

Beta status and upgrading

0.5.0-beta.9 is an early beta. Read the versioned release notes for upgrade requirements, verification scope and known limitations. The npm versions and GitHub releases report actual publication state; this repository and the development website can be ahead of the package you installed.

The GitLab CE 19.5.3 replacement passed all six local acceptance gates, including two-node deployment and rollback. Hosted staging and physical devices still need verification. GitLab sign-off

The Directus 12.7.0 Data Studio HTML field passed 57 local desktop Chromium workflows, including editing, permissions, draft recovery, and rollback. Directus qualification

The Outline 1.13.0 document integration passed 11 local journeys on one installed build, including collaboration with the stock editor and reopening saved content after rollback in Chromium, Firefox and WebKit. Outline qualification

Upgrading a persisted collaboration room: the 0.5 default Yjs entry uses retained storage. Existing XML rooms need fountainjs-editor/yjs/legacy or an explicit migration. Changing an import does not migrate data. Read the adoption and recovery guide before upgrading.

Markdown has separate document and source profiles. The default matches 563/652 official CommonMark examples; the complete-file profile matches 635/652. An explicit source-data profile matches all 652 body projections while retaining inactive URI data. Those scores do not establish full GFM support, exact model reopening or safe reader HTML for source-only data. Native DOCX verification covers supported scientific document workflows, with remaining layout and interoperability limits reported.

Try the workflow demos and API walkthroughs. Their bounded issue/task workflows and the professional showcase requirements have separate acceptance criteria. Development builds include a build identity showing their revision, package version and build-time verified npm version. Check the deployed identity when comparing a website demo with an installed package.

What “language agnostic” means

FountainJS is a JavaScript/TypeScript engine. Its browser view uses the DOM; its platform-neutral core also runs on servers without a browser. Other languages can exchange portable document JSON or call a host service.

Its boundaries are language and framework agnostic:

  • Use the DOM API directly from any frontend framework.
  • Register the standards-based <fountain-editor> Web Component in React, Vue, Svelte, Angular, plain HTML, or any Custom-Element-capable environment.
  • Use the first-party React, Vue, Svelte, or Angular binding when framework-specific hooks, stores, signals, actions or components are useful. Each binding is a separate optional entry with its own framework requirements.
  • Persist stable JSON that any backend language can store, validate, index, or transform.
  • Add nodes, marks, plugins, commands, formats, and host services through one extension contract.

React is an adapter, not the architecture. AI is an optional module, not the product identity.

What “open source” means

Every capability counted as shipped has public source, types, tests, and documentation and belongs in this public MIT-licensed package. The MIT license allows commercial use, modification, forks, redistribution, and private application code. FountainJS has no paid editor tier, private feature registry, license-key unlock, or mandatory Fountain-hosted service. Optional entry points keep the surface modular so applications only load what they use.

This does not promise costless infrastructure. Your application may pay its chosen database, file storage, server, conversion service, collaboration host, or model provider. Those systems stay behind replaceable interfaces: you may self-host, use local implementations, or choose a third party without changing the document engine. A practical test is that FountainJS continues to work without a Fountain account and can be maintained from a fork if this project disappears.

Installation options

For a complete project, download the plain JavaScript, React, or Node.js starter from the developer guide. The source is in examples/starters. Choose a starter for the release you install; its package.json pins the editor version and its README provides run instructions. Candidate starters require that version to be published or the locally packed candidate used by the installed-starter audit (pnpm audit:starters:prepare).

React is an optional peer dependency. Install react and react-dom only when importing fountainjs-editor/react. Yjs is also optional. Install yjs only when importing fountainjs-editor/yjs for real-time collaboration.

Server and tooling code can import fountainjs-editor/core. That entry exposes the model, schema, transactions, commands, history, portable extension composition, collaboration lifecycle, and string/JSON/Markdown formats while compiling without lib.dom and running without browser globals or jsdom. Use fountainjs-editor/html/server when a server must parse arbitrary HTML. The platform-neutral core guide defines the exact boundary and its permanent tests.

Compose an editor

Use the supplied rich-document extension, add behavior, and define your own capability:

import {
  CoreExtension,
  EditorView,
  composeExtensions,
  createEditor,
  defineExtension,
  historyPlugin,
  insertNode,
} from 'fountainjs-editor';

const callout = defineExtension({
  name: 'callout',
  nodes: {
    callout: {
      group: 'block',
      content: 'inline*',
      attrs: { tone: { default: 'info' } },
      parseHTML: [{
        tag: 'aside[data-fountain-callout]',
        getAttrs: (element) => ({ tone: element.dataset.tone ?? 'info' }),
      }],
      toDOM: (node) => ['aside', {
        'data-fountain-callout': '',
        'data-tone': node.attrs.tone,
      }, 0],
    },
  },
  commands: {
    insertCallout: (editor, text = 'A useful callout') => {
      const { schema } = editor.state;
      return insertNode(editor, schema.node('callout', { tone: 'info' }, [schema.text(text)]));
    },
  },
  services: {
    analytics: { track: (event) => console.info('editor event', event) },
  },
});

const kit = composeExtensions([
  CoreExtension,
  defineExtension({ name: 'history', plugins: [historyPlugin] }),
  callout,
]);

const editor = createEditor({ schema: kit.schema, plugins: kit.plugins });
const view = new EditorView(document.querySelector('#editor')!, editor, {
  blockHandles: true,
});
const commands = view.commandManager(kit.commands);

commands.commands.insertCallout('This command came from an extension.');
commands.chain().focus('end').insertText('Atomic ').toggleMark('strong').run();
commands.can().insertImage({ src: '/cover.jpg', alt: 'Cover' });

Chains stop and roll back when any command returns false or throws. A successful chain is dispatched once, so subscribers and history see one atomic edit. can() runs the same command logic against temporary state without changing the editor. EditorView.commandManager() adds a view-aware focus('current' | 'start' | 'end') command; use createCommandManager() when there is no DOM view. Use .command(name, ...args) for an extension command named run, command, or chain, since those names are reserved by the fluent API.

Composition rejects duplicate extension names and conflicting node, mark, command, format, or service names by default. Use { onConflict: 'replace' } only for an intentional override.

An extension can contribute:

  • nodes and marks to the schema
  • stateful plugins
  • reusable commands
  • formats with parse/serialize boundaries
  • open-ended services interpreted by the host application

Create and verify an extension

FountainJS ships an extension generator rather than leaving every author to invent package, type, test, and compatibility setup:

npx fountainjs-editor create-extension ./fountain-callout --name callout
cd fountain-callout
npm install
npm run check

The generated framework-neutral package includes versioned manifest metadata, an ordered dependency declaration, a typed example node/command, and fixtures for assertExtensionConformance from fountainjs-editor/testing. The test entry checks schema/JSON round-trips and guarantees command dry-runs do not mutate or notify. Its npm run doctor command checks the complete ordered installation for manifest, dependency, duplicate-name, and contribution conflicts before an editor starts. The generator previews with --dry-run and refuses to overwrite a non-empty directory. Read the complete extension authoring and compatibility policy before publishing or changing stored node data.

Production table editing

Tables use a span-aware TableMap, so logical rows and columns remain correct through rowspan and colspan. The public command set covers row/column insertion and deletion, merge/split, row/column/cell header toggles, whole-row and whole-column selection, exact column widths, repair, and spreadsheet-style TSV paste. Rectangular copy writes both plain TSV and an HTML table. Resizing is available from an accessible pointer/keyboard handle and the React toolbar. Column widths round-trip through JSON and safe HTML.

selectCells(editor, [0, 0, 0], [0, 1, 1])
mergeTableCells(editor)
splitTableCell(editor)
resizeTableColumn(editor, 180)
toggleTableHeaderRow(editor)

TableEditingExtension is part of StarterKit; it repairs non-rectangular geometry after arbitrary host transactions without adding repair steps to local undo history.

StarterKit also includes TrailingEditableBlockExtension. When a configured document root ends with a table, image, divider, widget, or another block that cannot accept text directly, it appends one ordinary paragraph so the user can always place the caret after that content and continue writing. Existing paragraphs, headings, and code blocks already satisfy the invariant, so they are not followed by an extra block. The repair is schema-validated, idempotent, history-neutral, and collaboration-safe. Core-only/custom-schema consumers can omit it or configure the block and root types explicitly; see the trailing editable block guide.

Nested block reordering

moveNode is a framework-neutral, path-based command for same-parent or cross-parent moves. It rejects cycles and validates the whole result before one undoable transaction is dispatched. canMoveNode is its side-effect-free availability check; moveBlock remains the top-level shortcut.

const move = { fromPath: [2, 1], toParentPath: [4], toIndex: 0 }
if (canMoveNode(editor, move)) moveNode(editor, move)

Pass blockHandles: true to EditorView, FountainEditor, FountainComposer, or registerFountainElement. The supplied contextual toolbar follows top-level and nested blocks, adds a native drag handle, shows only schema-valid before/after indicators, and provides labelled move buttons for keyboard and touch users. Hosts can filter candidates and replace every label, or call the same commands from wholly custom UI. See the block-reordering guide.

Every DOM view also gets a general drag target cursor by default: text targets show an inline caret and atomic/block targets show a separate before/after rule. It is transient, never changes the model or browser selection, and yields to the schema-aware block-reordering indicator during a Fountain block move. Pass dropCursor: false to omit it, or provide DropCursorOptions/custom CSS to replace its presentation; the public DropCursorManager is framework-neutral.

Collapsible details

DetailsExtension adds native, editable <details> / <summary> disclosures without changing StarterKit. The summary supports inline formatting and the body accepts any blocks in the composed schema, including lists, tables, media, and nested disclosures.

import { DetailsExtension, insertDetails } from 'fountainjs-editor/details'
import { StarterKit, composeExtensions } from 'fountainjs-editor'

const kit = composeExtensions([...StarterKit.extensions, DetailsExtension])
insertDetails(editor, { summary: 'Deployment notes', open: true })

Clicking the native marker persists the open state. Enter in a summary creates the first body paragraph, Backspace at the start of that paragraph returns to the summary, and Ctrl/Cmd+Enter toggles it. JSON is lossless; safe HTML, Markdown, and text interchange are supported; generic Yjs collaboration carries the structure and state. See the collapsible-details guide.

Ruby pronunciation annotations

The optional fountainjs-editor/ruby entry adds semantic, editable reading guides such as Japanese furigana. It is unrelated to the Ruby programming language. The selected base text and all of its marks stay in the document, while the reading is stored as validated rt metadata.

import { RubyExtension, setRuby } from 'fountainjs-editor/ruby'
import { StarterKit, composeExtensions } from 'fountainjs-editor'

const kit = composeExtensions([...StarterKit.extensions, RubyExtension])
setRuby(editor, { annotation: 'とうきょう' }) // selected 東京

The native NodeView renders <ruby>/<rb>/<rt>/<rp> and supplies an accessible, IME-safe click/keyboard editor that a host may replace. JSON is lossless; semantic HTML and Markdown round-trip; plain text reads 東京 (とうきょう); and generic Yjs collaboration carries both base edits and reading changes. See the ruby-annotation guide.

Complete text styles

CoreExtension and StarterKit include validated foreground/background colour, font-family, font-size, line-height, and signed character-spacing marks. The isolated fountainjs-editor/text-style entry exposes framework-neutral commands and selection inspection for both the supplied UI and custom controls:

import {
  getActiveTextStyle,
  setFontFamily,
  setFontSize,
  setLineHeight,
  setLetterSpacing,
} from 'fountainjs-editor/text-style'

setFontFamily(editor, 'Atkinson Hyperlegible, sans-serif')
setFontSize(editor, '18px')
setLineHeight(editor, 1.7)
setLetterSpacing(editor, '-0.5pt')
console.log(getActiveTextStyle(editor))

Values are normalized and bounded before entering portable JSON. Safe HTML and Fountain Markdown round-trip the complete suite, generic Yjs synchronization carries the marks unchanged, and the React toolbar supplies a responsive Text styles panel. See the text-style guide.

Stable node identities

The opt-in fountainjs-editor/node-ids entry adds portable, document-scoped identities with O(1) lookup and path-aware update/selection commands:

import { CoreExtension, composeExtensions } from 'fountainjs-editor'
import {
  StableNodeIdsExtension,
  getNodeById,
  selectNodeById,
  updateNodeById,
} from 'fountainjs-editor/node-ids'

const kit = composeExtensions([CoreExtension, StableNodeIdsExtension])
updateNodeById(editor, nodeId, { status: 'approved' })
selectNodeById(editor, nodeId)
console.log(getNodeById(editor, nodeId))

Missing, invalid, and copied duplicate IDs are repaired deterministically without adding a repair-only undo entry. Duplicate lookup fails closed, custom eligibility and ID generators are supported, and the generic Yjs adapter writes remote repairs back so peers converge. Pure inspection and JSON normalization run in Node.js without a fake DOM. See the stable identity guide.

Live table of contents

The optional fountainjs-editor/table-of-contents entry derives stable flat and hierarchical heading indexes, current paths/positions, active-section state, view-only DOM anchors, and framework-neutral navigation from the document:

import { CoreExtension, composeExtensions } from 'fountainjs-editor'
import { StableNodeIdsExtension } from 'fountainjs-editor/node-ids'
import {
  TableOfContentsExtension,
  getTableOfContentsState,
  navigateTableOfContents,
} from 'fountainjs-editor/table-of-contents'

const kit = composeExtensions([
  CoreExtension,
  StableNodeIdsExtension,
  TableOfContentsExtension,
])

const first = getTableOfContentsState(editor)?.entries[0]
if (first) navigateTableOfContents(editor, first.id)

The index runs in Node.js without a fake DOM. Titles and paths update while stable anchors survive heading edits and movement. The supplied React Navigator adds hierarchy, aria-current, full-title hover text, and scrolling on top of the same state. See TABLE_OF_CONTENTS.md.

Text integrity and invisible characters

The isolated fountainjs-editor/integrity entry inspects exact Unicode code points, UTF-8 bytes, line endings, normalization, spaces/NBSP, tabs, zero-width characters, BOM, bidi controls, soft hyphens, and invalid surrogates in pure Node.js. It never changes its input. Cleanup requires an explicit per-category policy and returns a before/after preview first.

import { inspectTextIntegrity, previewTextSanitization } from 'fountainjs-editor/integrity'

const report = inspectTextIntegrity('ABC123\u200bxyz')
const preview = previewTextSanitization(report.text, { zeroWidthSpace: 'remove' })

fountainjs-editor/integrity/dom adds optional view-only markers and literal input for eligible code/verbatim blocks. fountainjs-editor/react/integrity adds a replaceable accessible inspector with preview-before-apply cleanup. None of these enter the default React bundle. Byte-for-byte verification still belongs at the original byte import/hash boundary. See TEXT_INTEGRITY.md.

Granular structured attributes

The DOM-free fountainjs-editor/structured-attributes entry updates validated paths inside object or array node attributes as ordinary one-step transactions. The optional Yjs adapter can mirror selected definitions into nested Y.Map and Y.Array values, so two authors changing different fields do not replace the complete object:

import { defineStructuredAttribute, setStructuredAttribute } from 'fountainjs-editor/structured-attributes'
import { createYjsCollaborationExtension } from 'fountainjs-editor/yjs'

const boardConfig = defineStructuredAttribute({
  nodeType: 'board',
  attribute: 'config',
  root: 'object',
})

const collaboration = createYjsCollaborationExtension({
  document: ydoc,
  user,
  structuredAttributes: { definitions: [boardConfig] },
})

setStructuredAttribute(editor, [2], boardConfig, ['layout', 'columns'], 4)

Configured nodes require a valid unique stable ID. Canonical Fountain JSON stays unchanged, incoming nested values pass depth/size/schema validation, concurrent array insertions survive, and local-origin undo preserves remote fields. See the structured-attribute guide and try the controls below the two-editor collaboration demo.

Print-aware page foundation

The isolated fountainjs-editor/pages entry provides a runtime-DOM-independent page-flow algorithm and portable manual page-break, footnote, and canonical header/footer template semantics. Templates support default, first, odd, and even variants plus current-page/page-count fields. Automatic page boundaries are measurements, not JSON, so two collaborators with different fonts or viewports cannot overwrite each other's document.

import { CoreExtension, composeExtensions } from 'fountainjs-editor'
import {
  PagesExtension,
  createPageGeometry,
  insertPageField,
  insertFootnote,
  layoutPages,
  projectPagePresentation,
  selectPageTemplate,
  setPageTemplate,
} from 'fountainjs-editor/pages'
import {
  createDOMEditablePageController,
  createDOMPageLayoutController,
  layoutDOMPages,
} from 'fountainjs-editor/pages/dom'
import { renderDOMPagePreview } from 'fountainjs-editor/pages/preview'

const kit = composeExtensions([CoreExtension, PagesExtension])
insertFootnote(editor, { id: 'source-1', content: 'Source text' })
setPageTemplate(editor, { kind: 'footer', content: 'Page ' })
selectPageTemplate(editor, 'footer')
insertPageField(editor, 'page-number')

const geometry = createPageGeometry({
  size: 'a4',
  margins: 20,
  headerHeight: 32,
  footerHeight: 32,
  unitsPerMillimetre: 96 / 25.4,
})
const result = layoutPages(measuredFlowItems, geometry) // any measurement host
const presentation = projectPagePresentation(editor.state.doc, result)
view.dom.style.boxSizing = 'content-box'
view.dom.style.inlineSize = `${geometry.size.width - geometry.margins.left - geometry.margins.right}px`
const browserResult = layoutDOMPages(view.dom, editor.state.doc, geometry, {
  // Optional: a custom block can declare ordered, legal print bands.
  blockContinuation: ({ node, element }) => node.type.name === 'dashboard'
    ? {
        fragments: [...element.querySelectorAll<HTMLElement>('[data-print-band]')],
        minimumStart: 1,
        minimumEnd: 1,
      }
    : undefined,
})
renderDOMPagePreview(view.dom, previewElement, geometry, browserResult)
const controller = createDOMPageLayoutController(
  view.dom,
  () => editor.state.doc,
  geometry,
  { onLayout: ({ snapshot }) => renderDOMPagePreview(view.dom, previewElement, geometry, snapshot) },
)
// controller.destroy() when the host view is removed

// Or keep one live contenteditable over guarded visual page shells.
const editablePages = createDOMEditablePageController(
  view.dom,
  () => editor.state.doc,
  geometry,
  {
    onFallback: issues => console.warn('Using continuous editing', issues),
  },
)
// editablePages.destroy() before destroying the EditorView

The foundation derives user-facing footnote numbers from first-reference order without storing those numbers in JSON; repeated references share a number and reorder automatically. Standard [^id] Markdown footnotes and semantic HTML doc-noteref / doc-footnote roles round-trip through a pages-enabled schema. The foundation covers legal fragments, keep-with-next, widow/orphan minima, continuation overhead, page-local footnote reservation, canonical editable templates, dynamic page fields, overflow diagnostics, undo, JSON, semantic HTML, and Yjs. Its immutable presentation plan selects first/odd/even/default furniture, resolves page fields, and assigns canonical footnotes to measured pages without cloning the model. The separate pages/dom adapter measures real line boxes, direct blockquote children, list items, rowspan-safe table groups, footnotes, manual breaks, and opt-in host-declared custom-block bands without moving editable DOM. A blockContinuation adapter may return at least two unique, ordered, non-overlapping descendants of one rendered block plus optional start/end minima and repeated continuation height. Fountain validates that contract and rejects foreign, nested, overlapping, or invalid geometry rather than guessing where a NodeView can split. Every measured fragment includes an immutable source map with its model path, structural child paths, clip offset, and height for non-destructive continuation rendering. projectDOMPageContent() joins the neutral layout back to exact validated source slices and separates repeated continuation overhead. Its optional controller coalesces DOM mutations, resize, font, window, and print invalidations into timed snapshots and has explicit teardown. Mutation-only cycles reuse geometry only when both the immutable model node and rendered top-level element are unchanged, even when a structural insertion or removal shifts their top-level path. The view retains those unchanged DOM objects and rebases rendered paths, while the page cache rebases item, fragment, template, warning, and structural source paths without rereading geometry. Changed footnote heights still invalidate their cached references. Resize, font, manual, and print cycles remeasure fully, and { incremental: false } disables reuse for specialized hosts. createDOMEditablePageController() adds a responsive screen-editing surface without cloning, moving, or reordering any editable model node. Whole top-level blocks receive transient visual offsets over fixed page shells. A paragraph can also continue across sheets: the adapter inserts accessibility-hidden, non-model gap widgets at measured line boundaries, marks them as Fountain widgets so selection mapping ignores them, and removes them before every fresh measurement. The paragraph remains one model node inside the same contenteditable; selection, IME, undo/redo, tracked-change decisions, and Yjs convergence are covered across its page boundaries. Carets immediately before or after an injected gap map to the same logical text offset; cross-gap ranges and composition from either DOM side are verified in every desktop engine. Mobile Chrome/Safari emulation also preserves that selection and composition while responsive fallback removes the gaps; physical device testing remains a separate release gate. Lists continue between canonical list items without cloning them. Tables continue only at rowspan-safe row-group boundaries: the one canonical table and every real row stay editable, while transient non-model spacer rows align each continuation and page shells show accessibility-hidden, read-only copies of the canonical column header. Multi-row headers retain their row/column spans when every rowspan stays inside the header band; Fountain omits an unsafe repeated header when a header cell spans into body rows. Transitive body rowspans remain one legal group and are never cut apart. Header edits update every copy on reflow. Selection, IME, undo/redo, tracked-change decisions, and Yjs convergence are covered across both list and table page boundaries. Canonical header templates remain editable once in a rail before the page stack; canonical footer templates and footnote definitions remain editable once after it. Every sheet receives a sanitized, read-only, accessibility-hidden copy with resolved page fields and only the footnotes assigned to that page. Editing a canonical source rebuilds every copy without creating another model path, editable control, or persisted node. Narrow viewports or embedding containers that cannot fit a complete sheet return to a normal continuous editor, and a host resize restores paged mode without remounting the editor. Layout never persists automatic page numbers or continuation widgets into the shared document. Unsupported structural fragments or page intent in an invalid canonical order produce a typed continuous-mode fallback. An individual table row, image, media player, disclosure, code block, or custom NodeView stays one canonical editable node. Unsplittable content moves to the next page when it fits and is marked as explicit overflow rather than clipped or destructively split when it is taller than the body. That guarded boundary is intentional; it is not yet complete Word-style editable pagination. The separate pages/preview entry renders non-destructive read-only page sheets, repeated templates and fields, blockquote/list/table structural continuations, page-local footnotes, and print page breaks. Editing-only selection markers and field-token styling are removed from visual copies, and the continuous accessibility copy is omitted from print. It installs normalized print-only physical @page rules and stable names matching the geometry; pass { includePrintStyles: false } only when the host owns those global rules. For a custom NodeView, canvas, embed, or other atomic surface whose live DOM is not a useful print representation, pass renderPlacement(context). It receives the exact custom source-band range when blockContinuation split the placement. Return a detached element template for the placements your host owns and undefined for Fountain's default sanitized clone/clip. Fountain never moves the template or canonical editor source. Custom continuation is currently a read-only/print contract: if one custom block actually spans pages, the guarded live editable surface returns to continuous mode instead of creating a second editable widget or unsafe DOM split. Browser geometry must use CSS-pixel units (for example, unitsPerMillimetre: 96 / 25.4) for physical A4/Letter output. Visual clipped copies are hidden from assistive technology while one continuous read-only copy preserves document semantics. Chromium, Firefox, and WebKit verify physical A4/Letter sheet geometry, named-page assignment, page-specific headers/numbers, footnotes, print breaks, accessibility isolation, and removal of live editor state. Real Chromium PDFs additionally verify A4/Letter MediaBoxes and page-specific header/field, body, list, table, footnote, and manual-break text without a duplicate hidden document. Whole blocks, measured paragraph lines, canonical list items, and rowspan-safe table row groups are editable across pages. Editable canonical page furniture and page-local footnotes, oversized-row behavior, split-container comments, and top-level block movement now have dedicated browser contracts. A real browser contract also covers canonical image, audio, details, code, and custom NodeView placement, interaction, history, and explicit oversized overflow. Another covers merged two-row headers, rowspan-safe body groups, header-copy sanitization, and history after a table continuation. An imported semantic-HTML contract covers preserved alignment and text styles, ruby, math, nested multi-block quotes/lists, merged tables, forced breaks, and exact once-only body text in generated PDF output. This bounded DOC-14 contract is delivered; further document families remain ongoing hardening under the same explicit browser and accessibility gates in the pagination contract.

Optional clipboard history

ClipboardHistoryExtension adds a bounded, searchable list of text copied inside an editor. Normal Ctrl/Cmd+C, Ctrl/Cmd+X, and Ctrl/Cmd+V keep their native behavior. Ctrl/Cmd+Alt+V (or openClipboardHistory) opens the supplied React picker when it is mounted. Every shortened preview has the complete value in a hover title and can be expanded to read the full text before pasting. In the current preview, Enter in search pastes a single matching entry. Closing the picker or successfully pasting returns focus to the control that had it before the picker opened. Remove and Clear all return focus to search and update the result status.

const kit = composeExtensions([
  ...StarterKit.extensions,
  createClipboardHistoryExtension({ maxEntries: 25 }),
])

History is memory-only by default, belongs to that editor instance, and never uploads anything. Persistence happens only when an application explicitly passes its own synchronous { load, save } adapter. Commands are available for open, close, paste, remove, and clear, so non-React products can render the same immutable state in any interface.

Optional document utilities

Mentions, emoji, typography, and character/word limits are independent modules from fountainjs-editor/document-utilities; none is imposed by StarterKit. Mention and emoji suggestions share an abortable, stale-safe headless controller that any framework can render. The React entry includes an accessible positioned listbox and live count.

import {
  EmojiExtension,
  TypographyExtension,
  createCharacterCountExtension,
  createMentionExtension,
} from 'fountainjs-editor/document-utilities'

const kit = composeExtensions([
  ...StarterKit.extensions,
  createMentionExtension({ suggestions: [{ char: '@', items: findPeople }] }),
  EmojiExtension,
  TypographyExtension,
  createCharacterCountExtension({ limit: 5_000 }),
])

The default emoji module keeps a curated common search catalogue while converting any typed or pasted Unicode emoji. Applications that want the complete searchable RGI catalogue can import UnicodeEmojiExtension or unicodeEmojis from the isolated fountainjs-editor/emoji-data entry. See the document-utilities guide for every option, headless UI contracts, accessibility, persistence, and interchange behavior.

Slash command registry

createSlashCommandExtension() adds a headless / command menu without adding any UI-framework dependency. Its live SlashCommandRegistry combines built-in, product-owned, and asynchronous sources; performs stable multi-term filtering; aborts stale searches; and executes the selected command atomically. A failed command restores the literal query and the complete previous document.

import {
  SlashCommandRegistry,
  createSlashCommandExtension,
} from 'fountainjs-editor/document-utilities'

const registry = new SlashCommandRegistry()
registry.registerItems('product', [myCalloutCommand, myTemplateCommand])
const slash = createSlashCommandExtension({ registry })

Any surface can render kit.services.slashCommands.getController(editor). React applications can use the grouped, viewport-aware FountainSlashCommandMenu. See the complete slash-command guide.

Contextual bubble and floating menus

BubbleMenuExtension and FloatingMenuExtension are separate opt-in modules. Their framework-neutral controllers derive eligibility from semantic selections, support named instances and safe custom shouldShow rules, and never persist UI state. Reusable DOM geometry resolves marked/cross-wrapper text, node, and cell selections and flips/clamps menus within the viewport.

React hosts can render any product controls inside FountainBubbleMenu and FountainFloatingMenu; other frameworks subscribe to the same controller and use getEditorMenuAnchorRect() plus placeEditorMenu(). See the full contextual-menu guide.

Composable React toolbar

The supplied FountainToolbar uses dependency-free SVG icons with complete accessible names. Stable group/action IDs let a product reorder groups and actions, hide controls, replace labels or icons, and wrap or replace any action. FountainComposer accepts the same configuration through toolbarProps.

Unreleased configuration forms have named trigger ownership, keyboard opening focus and composition-safe Escape/Close return focus. Native fields keep their editing keys, and controls wrap inside the editor rather than clipping desktop Link or Find/Replace actions. These are non-modal forms, not focus traps or an accessibility certification; see the toolbar contract.

<FountainComposer editor={editor} toolbarProps={{
  toolbarLabel: 'Article formatting',
  groups: ['marks', 'block-types', 'history'],
  tableControls: 'menu', // default; use 'expanded' for every table icon
  actionOrder: { marks: ['highlight', 'bold', 'italic'] },
  hiddenActions: ['strike', 'subscript', 'superscript'],
  actionLabels: { bold: 'Strong emphasis' },
}} />

Applications can instead assemble FountainToolbarRoot, FountainToolbarGroup, and FountainToolbarButton around any FountainJS or product command. Arrow/Home/End navigation is RTL-aware, mouse activation preserves the model selection, and narrow toolbars scroll by intact groups. See the complete toolbar composition guide.

The default table group appears only while a table is selected and opens a labelled menu for row/column placement, headers, merge/split, width, selection, and deletion. The Quote control transforms the selected block range and changes to Remove quote inside a quotation; it does not insert an unexplained empty block elsewhere. The Highlight control opens its own colour/apply/remove panel.

Native LaTeX mathematics

MathExtension is a first-party but opt-in module. It adds portable inline_math and math_block nodes, $...$ / $$...$$ typing and paste rules, insertion/update commands, accessible source fallback, and portable JSON plus HTML/Markdown/text interchange. A supported imported equation may also retain a typed semantic tree in JSON/HTML; Markdown/text project its TeX.

import katex from 'katex'
import {
  MathExtension, StarterKit, composeExtensions,
  createKaTeXRenderer, createMathExtension,
} from 'fountainjs-editor'

// Source-only fallback with a neutral, unboxed surface:
const portable = composeExtensions([...StarterKit.extensions, MathExtension])

// Or pass a caller-owned renderer:
const math = createMathExtension({
  renderer: createKaTeXRenderer(katex),
  appearance: 'outlined', // optional: 'plain' (default), 'tinted', or 'outlined'
})
const rendered = composeExtensions([...StarterKit.extensions, math])

The editor stores TeX source—not renderer HTML. Supported DOCX imports may also store a validated platform-neutral MathExpression; editing the TeX clears that retained interpretation in the same undoable transaction. KaTeX is deliberately not a runtime dependency: applications choose their renderer/version and may provide another MathRenderer that returns a DOM node. Renderer errors keep the source visible and editable through setMathSource, and selecting a formula reveals an in-place TeX input. The coloured math box is optional presentation, not part of the stored equation.

Lean 4 without mandatory hosting

LeanExtension is also opt-in. With no provider it supplies portable Lean code blocks, insertion/update commands, Unicode backslash shortcuts, highlighting, and an explicit source-only controller; no source leaves the editor and no verification is claimed. Applications may attach a named local, remote, managed, or one-shot provider for diagnostics, goals, hover, and completion. Provider diagnostics render as mapped, transient decorations, and the optional plain-DOM LeanInfoView exposes source-only/provider state plus proof results. There is no built-in endpoint or credential storage.

const kit = composeExtensions([...StarterKit.extensions, LeanExtension])
const editor = createEditor({ schema: kit.schema, plugins: kit.plugins })
kit.commands.insertLeanBlock(editor, 'example : True := by trivial')

const lean = kit.services.lean.createController(editor)
await lean.check() // explicit `not-checked` result in source-only mode

For local checking without hosting a service, launch the packaged fountainjs-lean-bridge against a trusted Lean project and connect with createLeanLoopbackProvider. It exposes fixed, bounded one-shot checking—not a shell or a complete LSP—and is optional; source-only editing remains the default. See Lean integration and trust boundaries for local bridge and provider examples.

Use any UI surface

FountainJS does not impose a visual shell. The supplied React components and styles are optional examples built on public state and commands: an application may restyle them, reorder or replace every control, substitute its own icons, menus, dialogs, outline, block handles, and NodeViews, or omit Fountain CSS and render an entirely product-owned interface. Changing that interface does not fork the document model or alter portable Fountain JSON.

Plain DOM

const editor = createEditor({ schema: kit.schema, plugins: kit.plugins });
const view = new EditorView(document.querySelector('#editor')!, editor, {
  placeholder: 'Start writing…',
  ariaLabel: 'Article body',
  imageUpload: async (file, { signal, reportProgress }) => {
    const body = new FormData();
    body.append('file', file);
    const response = await uploadWithProgress('/api/media', body, {
      signal,
      onProgress: reportProgress,
    });
    return response.json(); // { src, alt?, caption?, width?, srcset?, sizes? }
  },
  assetUpload: async (file, { kind, signal, reportProgress }) => {
    return myAssets.upload(file, { kind, signal, onProgress: reportProgress });
    // Returns a URL or typed audio/video/file attributes.
  },
});

const stopSaving = editor.subscribe((state) => saveDraft(state.doc.toJSON()));

// Cleanup:
stopSaving();
view.destroy();
editor.destroy();

Huge documents

Viewport rendering is opt-in and keeps the complete model, transactions, history, collaboration, and search independent of the DOM window:

const scrollHost = document.querySelector<HTMLElement>('#editor-scroll')!
const view = new EditorView(scrollHost, editor, {
  virtualization: {
    scrollContainer: scrollHost,
    minimumBlockCount: 500,
    estimatedBlockHeight: 48,
    overscanPx: 1_000,
  },
})

Selections pin distant blocks; wide copy/cut and printing temporarily mount the required complete content. Call view.setVirtualizationSuspended(true) when a screen-reader, export, pagination, or host capture mode needs every block in the DOM simultaneously. The current boundary virtualizes top-level blocks, not rows inside one enormous table or another single block. See the huge-document contract for lifecycle, accessibility, measurement, and cross-browser evidence.

Production images

Block images support editable captions, alternative text, titles, left/centre/ right alignment, responsive srcset/sizes, safe load settings, explicit width and height, load-error recovery, and mouse, touch, or keyboard resizing. Use insertInlineImage when the image must live between text fragments. Both forms remain typed, selectable nodes and round-trip through JSON and HTML; standard Markdown image syntax covers their portable subset.

startImageUpload returns an observable task. Its insertion or replacement target maps through edits made while the upload is running, so a slow response cannot silently overwrite the wrong image. The host owns the transport and can report progress; FountainJS supplies cancellation, retry state, validation, and safe insertion:

const task = startImageUpload(editor, file, {
  placement: 'block', // or 'inline'
  upload: async (file, { signal, reportProgress }) =>
    myAssets.upload(file, { signal, onProgress: reportProgress }),
})

const unsubscribe = task.subscribe(snapshot => renderUpload(snapshot))
task.cancel()
await task.retry() // available after a failed attempt

Pass replacePath to replace an existing block or inline image without losing its metadata. Upload state is transient and local; credentials, files, and progress never enter document JSON.

Native audio, video, files, and safe embeds

StarterKit includes the independently composable MediaExtension. It adds typed audio, video, file_attachment, and embed nodes without depending on React. Native playback attributes include controls, autoplay, loop, mute, preload, remote-playback policy, CORS mode, captions/subtitle tracks, video posters, inline mobile playback, dimensions, alignment, titles, and captions. File nodes retain a safe URL, visible name, MIME type, byte size, description, and optional download name. Image MIME types show a lazy thumbnail preview next to the metadata and keep downloading as a separate explicit action; non-image files remain compact attachment cards.

insertAudio(editor, {
  src: 'https://cdn.example.com/episode.mp3',
  title: 'Episode 12',
  controls: true,
  tracks: [{
    src: 'https://cdn.example.com/episode-en.vtt',
    kind: 'captions', srclang: 'en', label: 'English', default: true,
  }],
})

insertVideo(editor, {
  src: 'https://cdn.example.com/launch.mp4',
  poster: 'https://cdn.example.com/launch.webp',
  title: 'Launch film', width: '720px', controls: true, playsInline: true,
})

insertFileAttachment(editor, {
  src: 'https://cdn.example.com/brief.pdf',
  name: 'Project brief.pdf', mimeType: 'application/pdf', size: 125_000,
})

Embeds are fail-closed. The default module canonicalizes approved YouTube URLs to youtube-nocookie.com and Vimeo URLs to player.vimeo.com, then renders a titled, lazy, referrer-limited, sandboxed iframe. An arbitrary iframe URL is rejected at command, JSON-import, attribute-update, and HTML-import boundaries. Replace the entire allowlist when your product trusts another provider:

const media = createMediaExtension({
  embedProviders: [{
    name: 'acme-video',
    sandbox: 'allow-scripts allow-same-origin',
    allow: 'fullscreen; picture-in-picture',
    resolve(url) {
      const match = url.hostname === 'video.acme.test'
        ? url.pathname.match(/^\/(?:watch|embed)\/(\d+)$/)
        : null
      return match ? `https://video.acme.test/embed/${match[1]}` : null
    },
  }],
})

const kit = composeExtensions([
  ...StarterKit.extensions.filter(extension => extension.name !== 'media'),
  media,
])

A provider resolver must recognize both its public input URLs and its own canonical output URL. Persisted allow, sandbox, and fullscreen capabilities may only narrow the provider's declared policy, so imported HTML cannot widen the provider's permissions.

startAssetUpload supplies the same observable, mapped, cancel/retry and fail-closed replacement behavior as image uploads. Audio and video are inferred from MIME type; other files become attachments. Unlike small local images, arbitrary assets are never embedded automatically: the application must pass an assetUpload handler and remains responsible for storage, authorization, malware scanning, quotas, and URL lifetime. Paste/drop emits the composed fountain-asset-upload event for non-React hosts.

Web Component

import { registerFountainElement } from 'fountainjs-editor';

registerFountainElement({
  schema: kit.schema,
  plugins: kit.plugins,
});
<fountain-editor placeholder="Start writing…"></fountain-editor>

<script>
  const element = document.querySelector('fountain-editor');
  element.value = savedDocumentJSON;
  element.addEventListener('fountain-change', (event) => {
    save(event.detail.value);
  });
</script>

React

import { FountainComposer, useFountain } from 'fountainjs-editor/react';
import 'fountainjs-editor/styles.css';

export function WritingRoom() {
  const editor = useFountain({
    schema: kit.schema,
    plugins: kit.plugins,
    onUpdate: (state) => saveDraft(state.doc.toJSON()),
  });

  return <FountainComposer editor={editor} placeholder="Start writing…" />;
}

The React entry is separate, so the framework-neutral root does not load React. A new framework binding only needs to create an editor, subscribe to its immutable state, and mount or replace its view.

Build interactive nodes

Use the first-class widget contract for status fields, date pickers, polls, variables, ratings, form questions, and other application controls. Define portable validated attributes once, then choose a plain-DOM or React renderer:

import { defineWidget } from 'fountainjs-editor/widgets'
import { createDOMWidgetExtension } from 'fountainjs-editor/widgets/dom'

const status = defineWidget({
  name: 'status_field',
  attributes: {
    value: { default: 'open', validate: value => value === 'open' || value === 'done' },
  },
})

const extension = createDOMWidgetExtension(status, context => {
  const button = document.createElement('button')
  button.onclick = () => {
    const current = context.controller.getAttributes()?.value
    context.set('value', current === 'open' ? 'done' : 'open')
  }
  context.controls.append(button)
  const render = next => { button.textContent = String(next.attributes.value) }
  render(context)
  return { update: render }
})

Each accepted update is one validated transaction, so JSON, history, subscriptions, Yjs, read-only state, and mapped focus all observe the same document value. fountainjs-editor/widgets is DOM-free; fountainjs-editor/widgets/dom and fountainjs-editor/react/widgets are separate renderer adapters. See the widget guide and the working plain-DOM demo.

The lower-level NodeView API remains available for unusual rendering contracts. It provides mapped reuse, optional editable contentDOM, semantic selection, event and mutation boundaries, and deterministic teardown. React products can adapt one with createReactNodeView from fountainjs-editor/react; React remains absent from the package root. See the NodeView API.

Included document capabilities

CoreExtension supplies paragraphs, six heading levels, alignment, quotes, bullet/ordered/task lists, code blocks, tables, block/inline images, dividers, semantic hard breaks, links, highlights, text colour, subscript, superscript, and common text marks. Its commands are available both as named imports and through kit.commands. Lists support multi-block wrapping, selected-range type conversion, mixed nesting, multi-item indent/lift, ordered starts, task state, boundary joins, and nested HTML/Markdown interchange; the React controls toggle types and expose lift/indent actions. Tables support span-aware merge/split, structural repair, header scopes, full-row/column selections, column resizing, and TSV/HTML clipboard exchange. StarterKit also adds MediaExtension, safe link behavior, live language-aware code highlighting, automatic table repair, and an ordinary editable block after terminal non-text content. Code tokens and optional line numbers are view-only decorations, language metadata round-trips through JSON/Markdown/HTML, the React toolbar edits language and line-number settings, and createSyntaxHighlightExtension accepts any host tokenizer through validated ranges. Link behavior includes normalization and validation hooks, typed web/email autolinking, link-on-paste, whole-link editing around a caret, host-owned activation, and complete React add/preview/edit/remove controls.

The editing core provides immutable state; mapped text, node, gap, all-document, and rectangular table-cell selections; typed transactions; keyboard and IME input; configurable input/paste rules; exact same-schema Fountain clipboard documents; clean semantic HTML and readable external-editor copy; source-aware Word/Docs/Excel/MathML paste normalization and loss reports; multiline and rich-HTML paste; image and asset paste/drop/upload; schema-safe nested drag/button reordering; find/replace; Markdown shortcuts; and configurable undo/redo that groups adjacent browser input. JSON is the lossless source of truth; Markdown, safe HTML, and plain text are interoperability boundaries.

The optional fountainjs-editor/docx entry imports and exports bounded Word OOXML in browsers and pure Node, with no Word process, fake DOM, or conversion service. It preserves common document structure plus verified embedded raster images and returns explicit issues for tracked revisions, external/unsupported media, custom content, or formatting outside its declared subset. Data-image sources embed directly; hosts can resolve already-authorized URL bytes through an explicit callback, while the converter itself never fetches. Fountain JSON remains the exact source of truth. See the DOCX interchange contract. Measured page preview and print/PDF output remain isolated in the pages entries; ODT and EPUB are not yet claimed.

Copy therefore writes three clipboard flavors: versioned Fountain JSON for an exact compatible Fountain destination, semantic HTML for another rich editor, and readable text for a text-only editor. The receiving Fountain schema still validates the exact payload and falls back to HTML/text when an extension is not installed. Private comments, presence, versions, upload state, credentials, and other host records are never copied as document content.

const schema = new Schema(CoreSchemaSpec);
const document = MarkdownImporter.parse('# Hello\n\nA **bold** beginning.', schema);

const { markdown, losses } = MarkdownExporter.exportWithReport(document, {
  linkStyle: 'reference',
});
HTMLExporter.export(document, { document: false });
JSONExporter.export(document);

HTML export escapes text and attributes, rejects unsafe URL protocols, and restricts generic extension output to non-executable semantic markup. Custom nodes and marks pair toDOM with schema-owned parseDOM selector/attribute rules, or with platform-neutral parseHTML rules when the same conversion must also run on a server. Configured extension content can therefore survive HTML paste and round trips without hard-coding the extension into FountainJS. Every imported document is validated by the receiving schema. JSON remains the exact persistence format; see the format-boundary guide.

Server conversion does not require a fake DOM. The isolated entry bundles its own standards-oriented parser without changing the root/editor bundles:

import { CoreSchemaSpec, Schema } from 'fountainjs-editor'
import { ServerHTMLImporter } from 'fountainjs-editor/html/server'

const schema = new Schema(CoreSchemaSpec)
const document = ServerHTMLImporter.parse('<h1>Hello</h1><p>From Node.</p>', schema)

It includes malformed-input diagnostics, fail-explicit browser-only extension rules, and configurable hard resource limits. See the server HTML contract.

Unreleased: opt-in sourceTokens: true exposes immutable tag-boundary spelling with explicit HTML/Markdown provenance, not file offsets. The separate fountainjs-editor/html/inert factory preserves registered unknown inline tags as bounded data and editable children, never their behavior or layout. See the retention/security contract and Node/Markdown workshop.

Unreleased: fountainjs-editor/html/source can reconstruct registered retained elements as inspected/downloadable unsanitized source data. It validates HTML structure, refuses unrepresentable edits and separately reports native document differences. It is not a reader renderer or an exact-source guarantee. The workshop demonstrates source download, editing, refusal and undo.

The same optional entry offers createInertHTMLRawTextExtension for explicitly registered script/style/textarea source. It shows editable, literal code with a visible inert-source badge—no execution, live CSS or form controls. HTML newline/entity parsing rules still apply; this is preservation, not original document rendering or a CommonMark conformance claim.

createInertHTMLBlockExtension({ tags }) retains explicitly owned unknown wrappers with editable headings, lists, tables and other supported block children. Original tags, handlers and styles stay inert. Imported empty wrappers remain empty until appendInertHTMLBlockParagraph(editor, path) adds an undoable paragraph. Try the structured block sample in the same workshop. Canonical text-leaf shape changes remain reported, not claimed as exact native retention.

Persisted documents can use an explicit, independently versioned envelope. The migration runner accepts historical bare NodeJSON as format version 1, applies only an application-owned sequential chain, rejects unknown future versions, and validates the result with the receiving schema. It has no DOM dependency and is also available from the isolated fountainjs-editor/migrations entry.

const stored = encodeFountainDocument(editor.getJSON(), { validate })
const loaded = migrateFountainDocument(await database.read(id), { validate })
setContent(editor, schema.nodeFromJSON(loaded.envelope.document))

The structural envelope schema is published as fountainjs-editor/schema/document.json. See the document migration contract before changing persisted nodes, marks, attributes, or content invariants.

Markdown import supports titled inline and reference links/images, recursive quotes, loose nested lists, aligned tables with escaped pipes, and variable-delimiter code spans that preserve literal backticks and significant edge spaces. Strict HTML5 character references decode before link safety checks and canonical export protects entity-shaped literal text. Safe relative paths, balanced destinations, strict titles, and code-aware reference definitions are also supported, including multiline definitions. Export can emit deterministic deduplicated references; exportWithReport identifies every unsupported node, mark, or attribute projection by document path so a publishing pipeline never has to guess what Markdown omitted. parseWithSource plus exportWithSource provide an explicit raw/visual boundary: unchanged Markdown returns exactly as supplied, while visual edits retain recognized inert YAML frontmatter and safely aligned unchanged top-level source blocks with an exact preservation result. Unique unchanged blocks can also retain their spelling through insertion, deletion, and movement; ambiguous duplicates or reference ownership fall back instead of guessing that unknown syntax survived.

Optional real-time collaboration

The root package exposes a provider-independent collaboration boundary. The separate fountainjs-editor/yjs entry adds shared editing, relative remote selections, accessible carets, and local-origin undo/redo.

In 0.4.0-beta.2 the default Yjs adapter stores XML. In 0.5.0-beta.1, fountainjs-editor/yjs uses retained character and node identities. To keep editing an existing XML room on 0.5, select fountainjs-editor/yjs/legacy. To adopt retained storage, migrate the room explicitly. Migration and recovery.

npm install fountainjs-editor yjs
// 0.5.0-beta.1 opens the room through the application's authority.
import { CoreExtension, composeExtensions, createEditor } from 'fountainjs-editor'
import { openYjsRoom } from 'fountainjs-editor/yjs/room'

const room = await openYjsRoom({
  schema,
  schemaVersion: 'article-v1',
  expected: { key: articleId },
  open: (protocols, signal) => api.openArticle(articleId, protocols, signal),
  admit: (offer, signal) => api.admitArticle(offer, signal),
})
const collaboration = room.createExtension({
  provider: api.createDisconnectedProvider(room.document, room.lease),
  user: currentUser,
})
const kit = composeExtensions([CoreExtension, collaboration])
const editor = createEditor({
  schema: kit.schema, plugins: kit.plugins, content: room.baseDocument.toJSON(),
})

The application supplies the authorized api, a matching schema and a provider that fences every write against the verified lease. Provision one native room and admit subsequent peers to it. Independently initializing a template on each client is a conflict, even when the templates look identical. The direct createYjsCollaborationExtension factory remains available for already prepared rooms and isolated local experiments.

Switching rooms does not require rebuilding the editor. Open the destination, retain any unsaved source draft, then pass a factory returning next.createAdapter(...) to replaceCollaborationAdapter(editor, factory); late updates from the retired document/provider are ignored and the previous adapter is disconnected and destroyed once. Local cursor awareness is deduplicated and throttled to a 32 ms cadence by default. React's useFountain also creates only one editor across Strict Mode's duplicate development render.

See the collaboration and Yjs guide for lifecycle, provider, security, offline, and replacement examples. For the explicit legacy adapter, preserveConcurrentRoots: true keeps independently initialized shared roots and stops synchronization until the host reviews the drafts and replaces the session. The retained default always preserves these conflicts, including when old code passes preserveConcurrentRoots: false.

The XML compatibility adapter retains the known concurrent typing versus structural/formatting failures. The retained implementation uses a different room format and refuses XML without changing its bytes. Migration must preserve checkpoints, drafts and late updates through the authority. Full default-adoption release checks remain pending. Retained room guide.

The provider is optional. An app may transport Yjs updates itself, add offline persistence to the same Y.Doc, select a managed provider, or leave collaboration out. FountainJS hosts no room service and receives no document or credential. Authentication, authorization, persistence, and provider trust remain explicit application boundaries. See the collaboration and Yjs guide.

Optional threaded comments

fountainjs-editor/comments adds provider-independent review without putting comment records into the document or choosing a hosted service. Inline ranges (including cross-block selections), points, blocks, and the whole document can carry overlapping threads. Anchors map through edits, recover from uniquely matched replacement content, become visibly orphaned when recovery is unsafe, and can be deliberately reattached.

import {
  InMemoryCommentsStore,
  createCommentThread,
  createCommentsExtension,
} from 'fountainjs-editor/comments'

const store = new InMemoryCommentsStore()
const comments = createCommentsExtension({
  adapter: () => store.createAdapter(),
  user: { id: session.user.id, name: session.user.name },
})
const kit = composeExtensions([CoreExtension, comments])
const editor = createEditor({ schema: kit.schema, plugins: kit.plugins })

const thread = await createCommentThread(editor, {
  content: 'Can we verify this statement?',
})

Replies, editable text or rich-JSON bodies, reactions, resolve/reopen, archive/restore, deletion, selection/hover events, and connection lifecycle are available from the framework-neutral entry. The in-memory store is for local use, prototypes, and tests. Production applications replace it with an adapter for their REST, database, CRDT, or other authenticated store. Local permission predicates control UI availability; the backend must independently authenticate and authorize every operation.

React applications may add the optional accessible discussion panel from fountainjs-editor/react/comments. See the threaded-comments guide for anchors, storage operations, idempotency, permissions, security, and the complete public workflow.

Optional tracked changes

fountainjs-editor/tracked-changes turns normal schema-valid transactions into portable review suggestions. It covers text insertion, deletion, exact replacement, formatting, node attributes, atoms, tables, and structural edits; each suggestion carries a stable id, author, timestamps, optional reason, and optional comment-thread link.

import { CoreExtension, composeExtensions } from 'fountainjs-editor'
import {
  createTrackedChangesExtension,
  acceptTrackedSuggestion,
  rejectTrackedSuggestion,
} from 'fountainjs-editor/tracked-changes'

const tracked = createTrackedChangesExtension({
  user: { id: session.user.id, name: session.user.name, color: '#6d4aff' },
})
const kit = composeExtensions([CoreExtension, tracked])

acceptTrackedSuggestion(editor, suggestionId)
rejectTrackedSuggestion(editor, anotherSuggestionId)

Deleted and replaced content remains inspectable until review. Accept/reject can target one suggestion, a range, an author, a filtered set, or everything; decisions are undoable. Metadata lives in FountainJSON and synchronizes through the optional Yjs adapter without a Fountain server. React applications can add the accessible, full-text FountainTrackedChanges panel from fountainjs-editor/react/tracked-changes; every other framework can subscribe to the same headless state and commands. See the tracked-changes guide for representation, comments, collaboration, APIs, and production security.

Optional named versions

fountainjs-editor/versions provides durable named snapshots without choosing a database or cloud. It includes paginated provider contracts, optimistic-head conflicts, idempotent operations, manual and debounced automatic versions, non-destructive preview, exact text/structure/format comparison, and safe restoration. By default restoration first saves unsaved work as a backup, applies one undoable editor transaction, and creates a new head linked to the source version.

import {
  InMemoryVersionProvider,
  VersionController,
} from 'fountainjs-editor/versions'

const versions = new VersionController({
  editor,
  documentId: 'article-42',
  user: { id: session.user.id, name: session.user.name },
  provider: new InMemoryVersionProvider(),
})

const saved = await versions.save({ name: 'Ready for review' })
const comparison = await versions.compare(saved.id) // saved → current
await versions.restore(saved.id) // backup → restore → new linked head

The memory provider is for local use, demos, and tests; production apps replace it with an authenticated provider for their own storage. React apps can import the accessible, confirmation-gated FountainVersions panel from fountainjs-editor/react/versions. Every other framework uses the same controller store and methods. See the named-versions guide for the provider contract, REST adapter, consistency rules, security, failure behavior, and full UI workflow.

Optional AI review module

AI is one example of a host service. FountainJS does not provide a model account or require a Fountain cloud. The optional AIController lets an application inspect exactly what will be sent, request a text proposal from any adapter, show a before/after review, accept or reject, block stale proposals, and undo acceptance.

const adapter = createAIAdapter(async (request, { signal }) => {
  const response = await fetch('/api/rewrite', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(request),
    signal,
  });
  return response.json(); // { replacement, explanation?, model?, metadata? }
});

const ai = new AIController(editor, adapter);
const disclosure = ai.inspectRequest({ action: 'improve' });
const proposal = await ai.suggest({ action: 'improve' });

ai.accept(proposal); // one undoable editor transaction
// or: ai.reject(proposal);

Streaming is the same review contract, not direct model writes into the editor:

const adapter = createStreamingAIAdapter(async function* (request, { signal }) {
  for await (const token of myProvider.stream(request, { signal })) {
    yield { replacementDelta: token }
  }
})

Partial output is transient and cancellable. FountainAIReview shows it live but does not offer Accept until the stream finishes; the completed proposal still passes the ordinary stale-target check and applies as one undoable transaction.

For structured agent work, the isolated DOM-free fountainjs-editor/ai/document-tools entry exposes bounded schema/path reads and five portable tool descriptors: read, insert, replace, format, and structure. Mutation calls create inspectable proposals without editing. The host can read the proposed tree, then accept a fresh schema-valid batch as one undoable transaction or reject it without change. Tool allowlists, total payload/read/ proposal bounds, declared-attribute policy, and stale-document refusal are configurable; no model SDK or Fountain service is required. See the schema-aware document tools guide.

For multi-turn chat, the separate DOM-free fountainjs-editor/ai/conversation entry accepts a host-provided conversation store and model adapter. It supplies bounded context windows, cancellable streaming, optimistic revision checks, inspectable requests, and portable reusable-prompt contracts without providing a Fountain account or cloud. FountainAIConversation is the optional React surface. See the conversation and prompt guide.

Generated images, audio, video, and files use a third optional DOM-free entry: fountainjs-editor/ai/generated-media. The controller builds an inspectable private-by-default request, validates bounded byte-backed candidates, and keeps them outside the document until a person accepts one. In the browser, createAIGeneratedMediaCommitter sends accepted bytes through the existing host-owned image/media upload handler; only its final schema-valid URL and metadata enter the document. The optional FountainAIGeneratedMedia React UI shows local previews, distinct generation/upload progress, provenance, and explicit insert/reject decisions. See the generated-media guide.

Full-document context is off by default. The included MCPAIAdapter connects the same workflow to a compatible MCP Streamable HTTP tool; MCP is a transport option, not the AI itself. Never ship permanent provider credentials in browser code.

React applications can render the optional workflow with <FountainAIReview controller={ai} />.

Honest comparison

FountainJS is not the first framework-neutral or extensible editor.

Project Architecture and maturity Practical reason to choose it
ProseMirror + Tiptap Battle-tested ProseMirror engine plus Tiptap's mature extension, framework, UI, and optional service layer Deep production history, ecosystem breadth, hosted services, and commercial support
Plate Powerful React/Slate framework with a broad plugin catalog A React-first product with many polished capabilities ready now
BlockNote Polished React block editor with an out-of-the-box Notion-like experience Shipping a strong block UI quickly
FountainJS DOM-first editor platform, Web Component, React adapter, and explicit extension composition Owning a modular editor platform and keeping framework/data boundaries open

Choose FountainJS when those boundaries matter and an early API is acceptable. Choose a mature alternative today when you need years of physical-device IME/mobile certification, a large plugin market, hosted collaboration administration, or commercial support.

Tiptap wraps ProseMirror. FountainJS independently implements the responsibilities of both layers: its own engine plus one native extension and product-module contract. The primary comparison is therefore FountainJS versus the combined ProseMirror + Tiptap stack. Read the one-to-one full-stack comparison.

React exports

  • useFountain and useFountainState
  • FountainEditor, FountainToolbar, FountainComposer, and the FountainToolbarRoot / Group / Button / Icon primitives
  • FountainSuggestionMenu, FountainSlashCommandMenu, FountainBubbleMenu, FountainFloatingMenu, and FountainCharacterCount
  • FountainComments from the isolated fountainjs-editor/react/comments entry
  • FountainTrackedChanges from the isolated fountainjs-editor/react/tracked-changes entry
  • FountainVersions from the isolated fountainjs-editor/react/versions entry
  • ClipboardHistoryMenu
  • Navigator, useNavigatorState, and useNavigatorTableOfContentsState
  • FountainAIReview and useAIControllerState
  • FountainAIConversation and useAIConversationState
  • FountainAIGeneratedMedia and useAIGeneratedMediaState
  • createReactNodeView and ReactNodeViewProps

Development

pnpm install
pnpm dev
pnpm check
pnpm test:browser
pnpm audit:ui
pnpm pack:check

Generated bundles and dependencies are not committed. CI runs type checks, behavioural tests, production and package builds, plus Playwright contracts in Chromium, Firefox, WebKit, emulated Pixel Chrome, and emulated iPhone Safari. Failed browser runs retain traces and screenshots. pnpm audit:ui is the recorded human-journey gate: it drives the real public playground and Go-documentation demo through ordinary input, backward selection, quote toggling, sized table creation/deletion, direct and new math, Lean source shortcuts, live outline/integrity/reordering feedback, real browser clipboard exchange from an external rich editor into Fountain and back out, streamed proposal review, formatting-boundary acceptance, multi-turn chat, generated-media preview/upload/insertion, schema-aware structural preview/apply, and undo. Its local WebM, screenshots, and trace are written under artifacts/manual-ui-audit/ for visual inspection and are intentionally not published in the package.

Run build-backed suites sequentially in one checkout: pnpm audit:ui rebuilds the library, and a second suite using the live Vite server can reload mid-action when those files change. Do not run it alongside pnpm check, another audit, or a rebuild of that checkout. For concurrent runs, use separate checkouts and separate server ports. A changed editor after a page restart is not evidence about selection in the original editor. The Markdown recovery journey uses an explicit stable-document guard; forced-reload checks prove the guard fails the run, preserves real errors, and removes its event listener. To record the same journey in Firefox alone, run pnpm exec playwright test -c playwright.audit.config.ts firefox-paragraph-recovery-audit.spec.ts.

The website includes a ten-demo integration gallery with dedicated working pages for React, plain DOM, the Web Component, Vue, Svelte, Angular, headless Node.js, and JSON boundaries with Python, Go, and Java. Framework recipes use the real supported adapter boundary; backend recipes are explicitly presented as portable JSON contracts rather than browser runtimes. Capability-focused labs are paired with matching developer/API explanations so live behavior and its integration contract can be read in either direction.

Project status

The tested release supports multi-paragraph text selection plus mapped node, gap, all-document, and rectangular cell selections; formatting across marked and nested text; block splitting and joining; attributed text and alignment; find/replace; rich content insertion; image URL/upload/paste/drop workflows; exact internal and semantic external clipboard exchange; source-aware external paste normalization; reusable input and paste rules; links, lists, tasks, code, tables, local history, interactive NodeViews, grouped browser input, structured clipboard and selected- nested block drag/button reordering, mentions, emoji, typography, character limits, a live extensible slash-command registry, framework-neutral bubble/floating menus, browser-event plugin hooks, extensible schema composition, safe format serialization, DOM/Web Component/React surfaces, optional AI proposals, MCP transport, and optional provider-independent Yjs collaboration with relative presence and origin-aware undo; plus optional provider-independent threaded comments with mapped inline/block/document anchors and a replaceable storage adapter; plus optional provider-independent tracked insertion, deletion, replacement, formatting, attribute, and structural suggestions with author metadata and individual, range, author, or batch decisions; plus optional named manual/automatic versions with exact comparison, preview, backup-first restoration, and replaceable persistence.

FountainJS is open about integration boundaries: host applications choose their media storage, persistence, authentication, and collaboration provider through adapters and services. No Fountain cloud account is required, and those product-specific systems are not silently bundled into the editor.

License

MIT © Paolo Cappuccini. Optional bundled data attribution is listed in THIRD_PARTY_NOTICES.md.

About

Open-source ProseMirror alternative and independent TypeScript rich-text editor. Includes Yjs collaboration, comments and tracked changes. Compare with Tiptap and try the live editor.

Topics

Resources

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages