RebodocsDocs
Start3
What is Rebodocs
Getting started
Demos to run
Put it in your app8
React component
Headless: your own UI
A complete interface
Without a framework
Only to read: the viewer
Styling and Tailwind
Phones and touch
Accessibility
Documents8
Templates and variables
On a server: DOCX and PDF
Documents in an S3 bucket
Letterheads
Versions
Tracked changes
Fonts
Languages
Together2
Real-time collaboration
AI assistants (MCP)
Reference5
Packages
Components and hooks
Editor API
How it works
Status and roadmap
↑↓ to move↵ to openEsc to close26 pages

Put it in your app Headless: your own UI

Headless: your own UI

When the interface that comes with the editor is not yours, keep the pages and draw everything else yourself. The provider holds the document, the surface is where its pages go, and hooks give you what to show and what to do.

tip: click and type below, and watch the state change
Live

The smallest one

A toolbar of five things and the pages, running, with what state holds beside it. Its whole file is under it.

Opening the editor…

'use client';

import { DocsProvider, DocsSurface, useDocs } from '@rebodocs/react';
import type { ReactNode } from 'react';

function Toolbar() {
  const { state, commands } = useDocs();
  const button = (on: boolean) => `h-8 min-w-8 rounded-md px-2 text-sm font-semibold ${on ? 'bg-blue-100 text-blue-800' : 'hover:bg-neutral-100'}`;
  return (
    <div className="flex items-center gap-1 border-b border-neutral-200 bg-white p-2">
      <button type="button" aria-pressed={state.bold} className={`${button(state.bold)} font-bold`} onClick={() => commands.toggleMark('bold')}>
        B
      </button>
      <button type="button" aria-pressed={state.italic} className={`${button(state.italic)} italic`} onClick={() => commands.toggleMark('italic')}>
        I
      </button>
      <button type="button" aria-pressed={state.list === 'bullet'} className={button(state.list === 'bullet')} onClick={() => commands.toggleList('bullet')}>
        • List
      </button>
      <button type="button" disabled={!state.canUndo} className={`${button(false)} disabled:opacity-40`} onClick={() => commands.undo()}>
        Undo
      </button>
      <span className="ml-auto text-sm text-neutral-600">
        Page {state.page} of {state.pageCount}
      </span>
    </div>
  );
}

export function Editor({ file, children }: { file: Uint8Array; children?: ReactNode }) {
  return (
    <DocsProvider docx={file} onSave={(docx) => console.log('save', docx.length, 'bytes')}>
      <div className="flex min-h-0 min-w-0 flex-1 flex-col">
        <Toolbar />
        <DocsSurface className="min-h-0 flex-1 bg-neutral-100" />
      </div>
      {children}
    </DocsProvider>
  );
}

DocsProvider takes the props of DocsEditor that are about the document (docx, name, author, collab, onSave…), and locale and locales for the texts the library still has (the bar beside the selection, what a screen reader is told); not those of the interface it does not draw (features, className, onReady). It has three of its own: onLinkKey, onFindKey and bubble, below. It puts nothing on the page itself: its children are where they are.

Components and hooks has each piece with what it takes and an example; Styling has six pieces made with Tailwind, running; and A complete interface is a whole application built this way.

Hook

useDocs

What there is to show, what there is to do, and the editor itself.

const { state, commands, editor, docs, ready } = useDocs();

state is a plain snapshot. It is the same object until something in it changes, so a component draws again only when it must.

Text at the selection
bold, italic, underline, strike, fontFamily, fontSize, color, highlight, link
Paragraph
align, lineHeight, styleId, list
What can be done
canUndo, canRedo, collapsed, inTable, canEditTables, canMergeCells, canSplitCell, pictureSelected
Review
trackChanges, changesView, revisionCount, restricted, activeEditable
Where
area (body, header or footer), page, pageCount
View
zoom, view, fit, touch
Document
name, dirty, saves, letterhead, fonts
Search
findCount, findIndex
People
collab, peers, me

commands are the editor’s methods. Each gives the keyboard back to the document afterwards, so a click on your button does not leave the person unable to type.

History
undo, redo
Text
toggleMark, setRunProps, insertText, insertLineBreak, selectAll, copy, cut, paste
Paragraph
setParagraphProps, setParagraphStyle, toggleList, shiftListLevel, setListStyle, restartNumbering, continueNumbering, shiftIndent, insertPageBreak
Tables
insertTable, insertTableRow, insertTableColumn, deleteTableRow, deleteTableColumn, deleteTable, mergeTableCells, splitTableCell, setTableCellProps, setTableBorders, setTableRowHeight, setHeaderRow
Pictures
insertImageFile, insertImageGrid, setPictureWrap, fitSelectedPicture
Templates
insertVariable, fillVariables, insertSignatures
Links and notes
setLink, removeLink, addNote, setNoteText, setNoteColor, removeNote, removeAllNotes, selectNote
Structure
insertToc, updateToc, goToHeading, moveSection, insertFootnote, insertEndnote, insertTextBox, restoreVersion
Review
setTrackChanges, setChangesView, acceptRevision, rejectRevision, acceptAllRevisions, rejectAllRevisions, goToRevision, selectRevision, setRestricted, makeEditable, removeEditable, nextEditable
Columns and sections
setColumns, insertColumnBreak, insertSectionBreak
Page
setPage, setPageNumbering, setFirstPageDifferent, setOwnHeaders, setEndnotesAt, setNoteNumbering, setArea, setLetterhead, setLetterheadFile, fitLetterheadMargins, removeLetterhead
Search
find, findStep, replaceFound, replaceAllFound
View
setZoom, setFit, setView, setShowNotes, print

Before the document is there (on the server, and until the surface is on the page) ready is false, state holds neutral values, and the commands do nothing.

Hooks

Hooks for panels and dialogs

Each gives what there is to show and what there is to do, for a piece of interface you draw, and draws again only when its own value changes.

useDocsFind()
query, setQuery, options, setOptions, count, index, next, previous, replace, replaceAll, close
useDocsLink()
active (address and text), possible, set, remove, open
useDocsNotes()
notes, active, add, setText, setColor, remove, removeAll, select
useDocsOutline()
items, active, goTo, move
useDocsVariables()
names, active, insert, select, blocks, fill; and what each asks of its value: formats, uses, setFormat, preview
useDocsStyles()
styles, active, set
useDocsPage()
page, set, sections, section, ownHeaders, numbering, endnotesAt, noteNumbering, firstPageDifferent, and the letterhead
useDocsSelectionBox()
Where the selection is on the screen, to put something beside it
useDocsCount()
words and characters of the document, and of what is selected
useDocsBubble()
The bar beside the selection, with <DocsProvider bubble>: open, close, toggle, ask
useDocsResponsive()
Fits the pages to a narrow window; narrow, and keyboard in pixels
useDocsValue(select, fallback)
Anything else worked out from the editor, drawing again only when it changes

useDocsValue compares what it selects as JSON at every change, so it is for small values: it warns in the console when given one as large as the document. To know when the document changes, editor.onChange. A find bar, for example:

function Find() {
  const find = useDocsFind();
  return (
    <div className="flex gap-2">
      <input value={find.query} onChange={(e) => find.setQuery(e.target.value)} placeholder="Find" />
      <span>{find.index} / {find.count}</span>
      <button onClick={find.previous}>↑</button>
      <button onClick={find.next}>↓</button>
    </div>
  );
}
Keys

Keys

Most keys are the editor’s own and work with nothing asked of you: ⌘B, ⌘I, ⌘U, ⌘Z and ⇧⌘Z, ⌘A, ⌘↵ for a page break, ⌘S (with an onSave) and ⌘P, ⌘-click on a link, ⌘ and the wheel to zoom. Ctrl takes the place of ⌘ away from a Mac.

Two open something only an interface has, so the editor knows the key and leaves the answer to you. Each is taken from the browser only while you give it someone to call, and only while the keyboard is in the document.

onLinkKey() · ⌘K
Time to ask for the address of a link.
onFindKey(replace) · ⌘F, ⌘H
Time to show the search; replace is true for ⌘H.
function Editor() {
  const [finding, setFinding] = useState(false);
  const [linking, setLinking] = useState(false);
  return (
    <DocsProvider docx={file} onFindKey={() => setFinding(true)} onLinkKey={() => setLinking(true)}>
      {finding && <Find onClose={() => setFinding(false)} />}
      {linking && <LinkDialog onClose={() => setLinking(false)} />}
      <DocsSurface className="h-full" />
    </DocsProvider>
  );
}

Without React they are options of createDocs, and docs.setKeys({ onLinkKey, onFindKey }) changes them later.

Bar

The bar beside the selection

<DocsProvider bubble> gives the document the small bar that comes up beside what is selected, the one the included interface has.

On it: copy, cut and paste on a screen that is touched, a variable made of the words selected, a link, a note, and what can be done to a picture or a table. A tap on ⌘ shows and hides it, and with it ⌘K asks for a link there unless you gave an onLinkKey. It is off unless asked for, and read when the document is made.

It is the one piece here with a look of its own, and it is put in document.body. Give it your colours with the --dx-ui-… variables on body (or on body:has(.your-editor)), not by reaching into its classes. useDocsBubble() gives it to your own buttons:

function InsertMenu() {
  const bubble = useDocsBubble();
  return (
    <>
      <button onClick={() => bubble?.ask('variable')}>Variable</button>
      <button onClick={() => bubble?.ask('note')}>Note</button>
      <button onClick={() => bubble?.ask('link')}>Link</button>
    </>
  );
}

To draw one of your own, useDocsSelectionBox() says where the selection is: there is one running on the page Styling.

Menu

The “/” menu

<DocsProvider slash> gives the document the menu a “/” brings up, the one the included interface has: what can be put where the caret is, or made of its paragraph, without reaching for the toolbar.

<DocsProvider docx={file} bubble slash>
  <DocsSurface className="h-full" />
</DocsProvider>

It comes up when the “/” is typed at the start of a paragraph or after a space, so a date like 12/05, “and/or” or an address is left alone. What is typed after it narrows the list, by name or by what each one does, and without minding accents; h1, h2, h3, ul, ol and toc find their own. ↑ and ↓ choose, Enter or Tab (or a click) does it in place of the “/” and what followed it, and Escape leaves them as text. It goes by itself when the caret leaves the command, or when nothing is found and a space is typed.

Text
Normal, Heading 1 to 3 (those the document has styles for), a bulleted list, a numbered list
Insert
A 3 × 3 table, a picture, a page break, a table of contents, a text box, a footnote
Template
A variable, the signatures, a note on the word before the “/”, and with forms an area to fill in

Only what can be done there is offered: in a table there is no table, no signatures, no page break and no table of contents; in a header or a footer, no page break, table of contents, text box, footnote or note; a table of contents only while there is none. The variable and the note ask for their name and their text in the bar beside the selection, so they are offered only with bubble too. Doing a command is two steps for ⌘Z: the first undoes the command, the second gives back what was typed.

Like the bar, it is put in document.body and takes its colours from the --dx-ui-… variables; it opens under the caret, or over it when there is more room there, the keyboard of a phone counted. It is off unless asked for, and read when the document is made. Without React it is the slash option of createDocs, or createSlashMenu(editor, { ask: bubble.ask }) on a bare editor.

Your own commands

Given settings in place of true, the menu keeps only the commands of its own you name in builtIns (normal, heading1, heading2, heading3, bullets, numbers, table, image, pageBreak, toc, textBox, footnote, variable, signatures, note, field), or none with false, and offers yours after them, those of one group under one heading, “More” when none is given. Each puts in text, a paragraph for each line, or html with its formatting, as pasting it would, or does what its run says once the “/” is gone; when says where it is offered. commands may be a function, asked each time the menu opens.

<DocsProvider
  docx={file}
  slash={{
    builtIns: ['heading1', 'heading2', 'bullets', 'table'],   // false for none
    commands: [
      { label: 'Privacy notice', group: 'Clauses', keywords: 'gdpr', html: '<p><b>Privacy.</b> We keep…</p>' },
      { label: 'Closing', group: 'Clauses', text: 'Yours sincerely,\nThe management' },
      { label: 'Today', run: (editor) => editor.insertText(new Date().toLocaleDateString()) },
      { label: 'Next blank', when: (editor) => editor.restricted, run: (editor) => editor.nextEditable() },
    ],
  }}
>

In DocsEditor the same settings go in features.slash.

Templates

Variables that are dates and amounts

A variable may ask how its value is written: as a date, as an amount, in capitals, in bold.

useDocsVariables() gives what each one asks (formats), changes it for every place the variable is used (setFormat), and says what a value would come out as, or that it cannot be written that way (preview).

function Variable({ name }: { name: string }) {
  const variables = useDocsVariables();
  const [value, setValue] = useState('');
  const has = (id: FormatId) => variables.formats[name]?.some((format) => format.id === id);
  const { text, bad } = variables.preview(name, value);
  return (
    <label>
      {name}
      <input value={value} onChange={(e) => setValue(e.target.value)} />
      <button aria-pressed={has('currency')} onClick={() => variables.setFormat(name, 'currency', !has('currency'))}>$</button>
      <small>{bad ? 'Not a number' : text}</small>
    </label>
  );
}

The formats are date, dateLong, dateFull, number, currency, upper, lower, capital, bold, italic and underline. One way of writing a date or a number takes the place of another, and so does a change of capitals. More on Templates and variables.

Ruler

The ruler

<DocsRuler /> is the ruler of the included interface: the page in centimetres, its margins and the indents of the paragraph, to drag. Put it above the DocsSurface, as wide as it.

<div className="flex h-full flex-col">
  <DocsRuler />
  <DocsSurface className="min-h-0 flex-1" />
</div>

It is drawn on a canvas, so its look is its colours, not classes: the six --dx-ruler… variables. It draws itself again when they change.

Lessons

A whole editor screen

What was learned putting a headless editor inside a CRM: a Next.js application with its own components, saving to its API as the person types, and rooms to work together.

Start from the hooks

Most panels are already one: useDocsVariables for the fields of a template, useDocsPage for sections and page setup, useDocsCount for the status bar, useDocsResponsive for phones, useDocsFind for the search.

Saving as the person types

Listen to the editor, not to React: editor.onChange is called for the selection too, so compare the document itself, which is a new object only when it changed.

const { editor, docs, ready } = useDocs();
useEffect(() => {
  if (!editor || !ready) return;
  let last = editor.doc;
  let timer: ReturnType<typeof setTimeout>;
  return editor.onChange(() => {
    if (editor.doc === last) return;     // the selection moved: nothing to save
    last = editor.doc;
    clearTimeout(timer);
    timer = setTimeout(() => void docs!.save(), 3000);   // calls onSave
  });
}, [editor, ready, docs]);

useDocsValue((e) => e.doc) would compare the whole document as JSON at every key: a long contract then takes a second per keystroke.

Menus give the keyboard back

A menu of a component library gives the focus back to the button that opened it, and the next key goes nowhere. Give it to the document instead: Base UI’s finalFocus, Radix’s onCloseAutoFocus.

const toDocument = () => editor?.element.querySelector<HTMLElement>('.dx-input') ?? true;
<DropdownMenuContent finalFocus={toDocument}>…</DropdownMenuContent>

A loading state

DocsSurface is there before the document is: an empty page shows until ready, and in a room until the room has sent it (state.collab === 'on'). Cover the surface until then, once:

const [loaded, setLoaded] = useState(false);
useEffect(() => {
  if (!loaded && ready && (!collab || state.collab === 'on')) requestAnimationFrame(() => setLoaded(true));
}, [loaded, ready, collab, state.collab]);
// <div className="relative flex-1"><DocsSurface …/>{!loaded && <Skeleton className="absolute inset-0" />}</div>

Read only

editor.readOnly = true for someone who may only look: the commands do nothing and the keys type nothing. In a room, the server’s admit saying readOnly does it for you.

Opening a file without leaving the room

docs.openFile() replaces the document and leaves the room. To put another DOCX in its place as one more change, which the others receive and ⌘Z takes back:

const doc = await loadVersion({ list: async () => [], load: async () => bytes }, file.name);
commands.restoreVersion(doc);

Phones

useDocsResponsive, or commands.setFit('width') on a narrow screen: the whole page across it, zoomed, without setting the text out again. See Phones and touch.

Full screen

The bar beside the selection, menus and toasts are drawn on the page, outside the editor. Put the page in full screen (document.documentElement.requestFullscreen()) and the editor above everything with position: fixed, rather than the editor’s own element. The bar follows an element that holds the editor into full screen; your menus and toasts will not.

A room inside your API

createCollabServer without a port gives a handle to mount at /collab in Express or Nest, with a storage that calls your services straight. The browser must reach it directly: a proxy that reads the whole response first (Next’s route handlers do) never ends a stream of server-sent events. See collaboration.

Lists

setListStyle({ format: 'lowerLetter', text: '#.-' }) writes “a.-”, “b.-”; restartNumbering() and continueNumbering() for the caret’s item. Tab and ⇧Tab change the level wherever the caret is in an item, and Enter on an empty item goes up one.