Skip to main content

React and Angular

@twip/web depends on no framework. An adapter needs four calls: mount, destroy, subscribe and on. These are complete adapters you can copy into your application.

React​

useTwipState reads the editor's state through useSyncExternalStore, so a component re-renders after every change and never tears. useTwipEditor mounts an editor in an element and destroys it on unmount.

useTwip.ts
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
import { Editor, type EditorState, type HeadlessEditor, type MountOptions } from '@twip/web';

/** The editor's latest state. The component re-renders after every change; null until there is an editor. */
export function useTwipState(editor: HeadlessEditor | null): EditorState | null {
const subscribe = useCallback((onChange: () => void) => editor?.subscribe(onChange) ?? (() => {}), [editor]);
return useSyncExternalStore(subscribe, () => editor?.getState() ?? null);
}

/** Mounts an editor in the element `ref` points at, and destroys it on unmount. */
export function useTwipEditor(options?: MountOptions) {
const ref = useRef<HTMLDivElement>(null);
const [editor, setEditor] = useState<Editor | null>(null);
useEffect(() => {
const abort = new AbortController();
const mounting = Editor.mount(ref.current!, { ...options, signal: abort.signal });
mounting.then(setEditor, () => {}); // an aborted mount rejects 'aborted'
return () => {
abort.abort();
void mounting.then((mounted) => mounted.destroy(), () => {});
};
}, []); // mount once: change settings through the editor, not the options
return { ref, editor };
}
DocumentView.tsx
import { useTwipEditor, useTwipState } from './react.js';

export function DocumentView({ document }: { document: Uint8Array }) {
const { ref, editor } = useTwipEditor({ document });
const state = useTwipState(editor);
const bold = state?.commands.setBold;
return (
<div className="document-view">
{/* A press on a button keeps the focus in the document, so typing goes on there. */}
<div role="toolbar" onMouseDown={(e) => e.preventDefault()}>
<button
disabled={!bold?.enabled}
aria-pressed={state?.formatting.bold === true}
onClick={() => editor?.commands.setBold(state?.formatting.bold !== true)}
>
Bold
</button>
<button disabled={!state?.history.canUndo} onClick={() => editor?.commands.undo()}>
Undo
</button>
</div>
<div ref={ref} style={{ height: '80vh' }} />
<footer>{state && `Page ${state.pages.current} of ${state.pages.count}`}</footer>
</div>
);
}

getState() returns the same snapshot until something changes, which is what useSyncExternalStore needs.

The toolbar cancels mousedown, so a click on a button leaves the keyboard focus in the document and typing carries on there. A toolbar that takes the focus (a font-size box, say) calls editor.focus() once its command has run.

Angular​

TwipStateService turns subscribe into a signal and ties listeners to the lifetime of the injector that provides it. Provide it in the component that mounts the editor.

twip-state.service.ts
import { DestroyRef, Injectable, inject, signal } from '@angular/core';
import type { EditorState, HeadlessEditor, TwipEvents } from '@twip/web';

/** One editor's state as a signal, and its events, for the lifetime of the injector that provides it. */
@Injectable()
export class TwipStateService {
private readonly destroyRef = inject(DestroyRef);
private readonly current = signal<EditorState | null>(null);
private editor: HeadlessEditor | null = null;

/** The latest state; null until an editor is attached. */
readonly state = this.current.asReadonly();

/** Follows `editor`: `state` updates after every change. */
attach(editor: HeadlessEditor): void {
this.editor = editor;
this.destroyRef.onDestroy(editor.subscribe((state) => this.current.set(state)));
}

/** Listens to one of the editor's events until the injector is destroyed. */
on<K extends keyof TwipEvents>(type: K, listener: (event: TwipEvents[K]) => void): void {
if (!this.editor) throw new Error('attach an editor first');
this.destroyRef.onDestroy(this.editor.on(type, listener));
}
}
document.component.ts
import { Component, DestroyRef, ElementRef, afterNextRender, computed, inject, viewChild } from '@angular/core';
import { Editor } from '@twip/web';
import { TwipStateService } from './angular.js';

@Component({
selector: 'app-document',
providers: [TwipStateService],
template: `
<!-- A press on a button keeps the focus in the document, so typing goes on there. -->
<div role="toolbar" (mousedown)="$event.preventDefault()">
<button [disabled]="!bold()?.enabled" [attr.aria-pressed]="isBold()" (click)="toggleBold()">Bold</button>
</div>
<div #host style="height: 80vh"></div>
<footer>Page {{ twip.state()?.pages.current }} of {{ twip.state()?.pages.count }}</footer>
`,
})
export class DocumentComponent {
protected readonly twip = inject(TwipStateService);
private readonly host = viewChild.required<ElementRef<HTMLElement>>('host');
private editor: Editor | null = null;

protected readonly bold = computed(() => this.twip.state()?.commands.setBold);
protected readonly isBold = computed(() => this.twip.state()?.formatting.bold === true);

constructor() {
const abort = new AbortController();
inject(DestroyRef).onDestroy(() => {
abort.abort();
void this.editor?.destroy();
});
afterNextRender(async () => {
this.editor = await Editor.mount(this.host().nativeElement, { signal: abort.signal });
this.twip.attach(this.editor);
this.twip.on('hostCommand', ({ command }) => console.log('host command', command));
});
}

protected toggleBold() {
void this.editor?.commands.setBold(!this.isBold());
}
}

Mount in afterNextRender: the editor needs its container in the DOM and sized.