Getting started in the browser
@twip/web is a complete editor for a page: you mount it in an element, and it owns input, rendering, scrolling,
the clipboard and the accessibility DOM (Accessibility) inside that element. Your application draws everything around it (toolbar,
menus, dialogs, panes) from the editor's state and services. Install it first (see Installation).
Mount an editor
import { Editor } from '@twip/web';
// The container needs a size: the editor fills it and scrolls inside it.
const container = document.querySelector<HTMLElement>('#editor')!;
const response = await fetch('/report.docx');
const editor = await Editor.mount(container, {
document: new Uint8Array(await response.arrayBuffer()),
author: { name: 'Ada Lovelace', initials: 'AL' },
rulers: true,
zoom: 'pageWidth',
});
editor.focus();
await editor.commands.selectAll();
await editor.commands.setBold(true);
console.log(editor.getState().formatting.bold); // true: the state is already at the command's revision
const { bytes } = await editor.export({ format: 'docx' });
const download = document.createElement('a');
download.href = URL.createObjectURL(new Blob([bytes.slice()]));
download.download = 'report.docx';
download.click(); // or send the bytes to your server
await editor.destroy(); // releases the session and everything the editor added to the container
Editor.mount resolves once the editor accepts commands. The container must have a size; the editor fills it.
MountOptions also sets the read-only flag, the mode ('editing' or 'design'), the language, spelling
dictionaries, track changes, the rulers and their unit, the markup pane width, the zoom and the background around
the pages. Mounting never takes focus: call focus() when the editor should have it.
Without a document, the editor starts with a blank one. open(bytes) replaces the document later, only once the
new one has been read, and newDocument() starts a blank one. Both take an AbortSignal.
Commands
Every edit is a command, one method each on editor.commands. They act on the selection, like their buttons in a
word processor, and resolve after the change commits.
import { type HeadlessEditor, inches, type Op } from '@twip/web';
export async function format(editor: HeadlessEditor) {
// One method per command. Each resolves after its change commits.
await editor.commands.setFontSize(14);
await editor.commands.setIndents({ left: inches(0.5), firstLine: inches(0.25) });
await editor.commands.insertTable({ rows: 3, columns: 2 });
// A batch is atomic: one transaction and one undo step, or nothing when an op fails.
const ops: Op[] = [
{ type: 'insertText', value: 'Total' },
{ type: 'setBold', value: true },
{ type: 'setAlignment', value: 'right' },
];
await editor.batch(ops, { label: 'Add total' });
await editor.commands.undo(); // undoes the whole batch
// The catalog describes every command, for a command palette or a shortcut list.
for (const command of editor.catalog.filter((c) => c.group === 'table')) {
console.log(command.id, command.label, command.shortcuts.windows.join(', '));
}
}
Setters take a value: there are no toggles. To make a Bold button, read formatting.bold and pass the opposite.
Lengths are points; inches(), cm(), mm() and pt() convert. A command that can't run now rejects with an
EditorError: 'unavailable' (its availability rule is false), 'read-only', or 'invalid-argument'.
editor.catalog lists every command with its English label, group, shortcuts and undo grouping, for a command
palette, menus or a shortcut sheet. The API reference lists every command with its arguments.
State
getState() returns the latest state: one immutable snapshot, read synchronously. subscribe calls your listener
with it now and after every change. A toolbar and status bar need nothing else.
import type { EditorState, HeadlessEditor } from '@twip/web';
export function bindToolbar(editor: HeadlessEditor, bold: HTMLButtonElement, undo: HTMLButtonElement, status: HTMLElement) {
// Called now with the current state, then after every change. One immutable snapshot each time.
const render = (state: EditorState) => {
const command = state.commands.setBold;
bold.disabled = !command.enabled;
bold.ariaPressed = state.formatting.bold === 'mixed' ? 'mixed' : String(state.formatting.bold === true);
undo.disabled = !state.history.canUndo;
undo.title = state.history.undoLabel ? `Undo ${state.history.undoLabel}` : 'Undo';
status.textContent = `Page ${state.pages.current} of ${state.pages.count}${state.modified ? ' (modified)' : ''}`;
};
const unsubscribe = editor.subscribe(render);
// Setters take a value: the toolbar passes the opposite of what the state shows.
bold.onclick = () => editor.commands.setBold(editor.getState().formatting.bold !== true);
undo.onclick = () => editor.commands.undo();
return unsubscribe;
}
The state holds the selection, character, paragraph and page formatting, each command's enabled, checked and
value, the undo history, page counts, view settings, review counts, spelling, fonts and the ruler model. Values that
differ across the selection are 'mixed', and values that don't apply (no table selected) are null.
revision counts committed transactions and sequence counts every change, selection moves included. When a
command resolves, getState() is already at its revision.
pages.count counts the pages laid out so far. The engine lays out the rest in the background, a few milliseconds
at a time on timers it arms, mounted or headless; each slice that adds pages, and the last one, which sets
pages.complete, is a new state with the same revision. Show the count as provisional until complete.
dialogs says which dialogs dialogs.open opens now (Table properties needs a table, Picture size and Alt text an
object), and selection.text is the selection as plain text, or null past 10,000 characters.
Events
on(type, listener) listens to things that happen, such as a commit, a link click, a key your application owns or
a context menu request. See Events.
Headless
HeadlessEditor.create() gives the same API with no DOM, in Node, a worker, a test or a server: documents,
commands, batches, state, events and services. The mounted extras (the view, gestures, rulers, balloons, hit
testing) are on Editor only.
import { EditorError, HeadlessEditor } from '@twip/web';
// No DOM: Node, a worker, a test or a server.
const editor = await HeadlessEditor.create({ author: { name: 'Report bot' } });
try {
const { warnings } = await editor.open(new Uint8Array(await (await fetch('/template.docx')).arrayBuffer()));
for (const warning of warnings) console.warn(warning.code, warning.message);
await editor.commands.moveSelection({ by: 'document', direction: 'forward' });
await editor.commands.insertText('Generated on the server.');
const pdf = await editor.export({ format: 'pdf' });
console.log(`${pdf.bytes.length} bytes at revision ${pdf.revision}`);
} catch (e) {
if (e instanceof EditorError && e.code === 'import-failed') console.error('not a document Twip can read');
else throw e;
} finally {
await editor.destroy();
}
export({ format: 'pdf' }) also takes openPassword (the PDF is encrypted with AES-256) and keywords (written to
its metadata); see PDF conversion.
Worker mode
By default (execution: 'auto'), a mounted editor runs the engine in a worker where the browser supports module
workers and OffscreenCanvas, and on the page's thread otherwise. Every editor on the page shares one worker, with
one font library and one clipboard. The API doesn't change: operations are promises in both modes, and getState()
stays synchronous because the SDK keeps the latest snapshot on the page. 'main' and 'worker' force a mode.
import { Editor } from '@twip/web';
// 'auto' (the default) runs the engine in a worker where the browser supports it, so layout never blocks input.
const editor = await Editor.mount(document.querySelector<HTMLElement>('#editor')!, { execution: 'auto' });
console.log(editor.executionMode); // 'worker' or 'main'
// The API is the same in both modes: operations are promises, and getState() is synchronous.
await editor.commands.insertText('Same code, either thread.');
console.log(editor.getState().revision);
The worker is @twip/web/worker.js, beside the package's other files. Bundlers that copy assets referenced with
new URL(..., import.meta.url) (Vite, webpack 5, esbuild with the file loader) need no setup.
Where the bundler leaves those URLs as they are (Angular's esbuild builder), copy the package's dist/ unchanged to a
folder you serve and call configure({ assets: '<that folder>/' }) before the first FontLibrary call or editor. The folder may be on a
CDN: it must then send CORS headers for every file, and serve twip_wasm.wasm as application/wasm (the package
README has the details).
Start early
The first editor on a page downloads and compiles the engine, and in worker mode starts the worker, before it can show
anything. preload() does that work ahead of time, with no document and no container, so the first editor appears
without the wait. Call it as soon as the page knows it will show an editor. Calls share one load per execution mode
(execution, as for Editor.mount), editors and the font library use the engine it loaded, and a failed load is tried
again by the next call or editor. A preloaded worker stays until the first editor's session has started and closed.
Call configure first if the package's files are served from another folder.
import { Editor, preload } from '@twip/web';
// On a page shown before the editor (a sign-in screen, a document list): start the engine now, in the background.
void preload();
// Later, when the user opens a document, the editor doesn't wait for the download or the compile.
const editor = await Editor.mount(document.querySelector<HTMLElement>('#editor')!);
await editor.open(await (await fetch('/documents/letter.docx')).bytes());
Destroy
destroy() releases the session, the worker's share of it and everything the editor added to the container. It is
idempotent. After it, operations reject with 'destroyed'.
Errors
Operations reject with EditorError, whose code is one of 'destroyed', 'invalid-argument', 'unavailable',
'read-only', 'import-failed', 'export-failed', 'aborted', 'not-allowed', 'unsupported' or
'internal'. A failed open keeps the current document. An error with fatal: true is a fault: the editor
rejects new operations, and destroy() still works.