/** * A free text box's editor on an element: the controller behind the * annotation layer's own text boxes and behind a renderer's element that * draws one itself. The shared rich-text binding ({@link attachRichTextEditor}) * renders the runs as inline-styled spans, turns typing back into runs, maps * the selection to flat offsets and keeps the caret through a restyle; the * browser owns layout, the caret, input methods and the clipboard; the * annotation plugin owns the text, the range routing and the write after a * pause. This module adds what makes the element a text box of the layer: * focus and `contentEditable` follow the plugin's `editing`, never the other * way, and a press inside the box stays inside it. A framework binding keeps * one {@link createTextBoxEditorFollower} per element and hands it what * changed. {@link freeTextBoxOf} is the layer's own editor element and * {@link ownTextBoxOf} one a renderer draws itself, both laid out at a legible * size (`legible-text.ts`). * * The plugin's types are mirrored structurally, so this package stays free of * EmbedPDF imports. */ import { legibleScaleOf, legibleShrinkOf } from './legible-text'; import type { PageToPixels } from './page-pixels'; import { rectInPixels } from './page-pixels'; import { attachRichTextEditor, type RichTextEditorBinding, type RichTextEditorCommand, type RichTextEditorDocument, type RichTextEditorFace, type RichTextEditorHost, type RichTextEditorRange, } from './rich-text-editor'; /** A text box as the annotation plugin lists it (`listTextItems`): the fields the editor reads. */ export interface TextBoxEditorItem { readonly id: string; /** `null` for a box that isn't written yet: nothing to route typing to. */ readonly ref: Ref | null; readonly richText: RichTextEditorDocument; /** The face of its text without one of its own: the box's body. */ readonly face: RichTextEditorFace; /** True while someone types in this box. */ readonly editing: boolean; } /** The annotation plugin's text-editing calls (its host capability satisfies it). */ export interface TextBoxEditorAnnotation { /** Returns the document it keeps (the text typed at the caret in a style chosen there). */ draftRichText(ref: Ref, document: RichTextEditorDocument): RichTextEditorDocument | void; setTextSelection(ref: Ref, range: RichTextEditorRange | null): void; readonly text: { toggleFormat(format: RichTextEditorCommand): unknown }; /** The CSS family list a face is drawn with in the box `id` (`null`: no box yet). */ getCssFontFamily(face: RichTextEditorFace, id: string | null): string; /** The family a CSS family the editor drew with stands for. */ getFamilyOfCss(cssFamily: string): string | undefined; getEditingId(): string | null; } /** An element made a text box's editor. */ export interface TextBoxEditor { /** * The box as the plugin has it now, at `scale` pixels per point (or `null` * while there is none). Call it whenever either changes: the binding * redraws only when the text differs (so the caret never jumps while * typing), and focus follows `editing`. */ update(item: TextBoxEditorItem | null, scale: number): void; /** Remove the listeners and the rich-text binding. */ detach(): void; } /** * Make `element` the editor of a text box. Typing shows at once and reaches * the engine in one write after a pause (or when the edit ends), not one * write per keystroke. */ export function attachTextBoxEditor( element: HTMLElement, annotation: TextBoxEditorAnnotation, ): TextBoxEditor { let item: TextBoxEditorItem | null = null; let binding: RichTextEditorBinding | null = null; // What the element shows: `null` until the first update states it. let shownEditing: boolean | null = null; const host: RichTextEditorHost = { onInput: (document) => (item?.ref ? annotation.draftRichText(item.ref, document) : undefined), onSelectionChange: (range) => { if (item?.ref) annotation.setTextSelection(item.ref, range); }, onCommand: (command) => void annotation.text.toggleFormat(command), cssFontFamily: (face) => annotation.getCssFontFamily(face, item?.id ?? null), familyOfCss: (cssFamily) => annotation.getFamilyOfCss(cssFamily), }; // A press inside the editor stays there: it must not reach the Stage's // listener, which reads it as a click outside (and ends the edit). The // browser then owns the caret and the drag inside the box. const stopPress = (event: Event) => event.stopPropagation(); // The gesture that opens the editor blurs it to right after it // takes focus; while the plugin still edits this box, take focus back. A // real click away ends the edit through the interaction hub first. const refocus = (event: FocusEvent) => { if ( event.relatedTarget == null && element.isConnected && item && annotation.getEditingId() === item.id ) { element.focus(); } }; element.addEventListener('pointerdown', stopPress); element.addEventListener('blur', refocus); return { update(next, scale) { item = next; if (next && !binding) { binding = attachRichTextEditor(element, host, { document: next.richText, scale, body: next.face, }); } else if (!next && binding) { binding.detach(); binding = null; } // Model → DOM: the binding skips its own echo and redraws, caret kept, // for a restyle, a remote edit or a zoom; otherwise it states the line // model for the (maybe restyled) font again. if (next) binding?.update({ document: next.richText, scale, body: next.face }); const editing = next?.editing ?? false; if (editing === shownEditing) return; shownEditing = editing; element.contentEditable = editing ? 'true' : 'false'; if (editing) { element.focus(); // Enter at the top, where the baked appearance anchors the text, so // baked → edit → baked never jumps. element.scrollTop = 0; } }, detach() { binding?.detach(); binding = null; element.removeEventListener('pointerdown', stopPress); element.removeEventListener('blur', refocus); }, }; } /** Keeps an element the editor of a text box while what it edits with changes. */ export interface TextBoxEditorFollower { /** * The element, the plugin, the box and the scale as they are now. Call it * whenever any of them changes: the editor attaches when there are an * element and a plugin, attaches again when either is another one (a * document that opens anew), and gets the box and the scale every time. */ follow( element: HTMLElement | null, annotation: TextBoxEditorAnnotation | null, item: TextBoxEditorItem | null, scale: number, ): void; /** Let go of the element, when the component that drew it goes away. */ detach(): void; } /** * A text box editor that follows its inputs: what each framework's binding * holds between renders. The update runs right after an attach, in the same * call, so the element never shows an editor without its text. */ export function createTextBoxEditorFollower(): TextBoxEditorFollower { let attached: { element: HTMLElement; annotation: TextBoxEditorAnnotation; editor: TextBoxEditor; } | null = null; const detach = () => { attached?.editor.detach(); attached = null; }; return { follow(element, annotation, item, scale) { const same = attached !== null && attached.element === element && attached.annotation === annotation; if (!same) { detach(); if (element && annotation) { attached = { element, annotation, editor: attachTextBoxEditor(element, annotation) }; } } attached?.editor.update(item, scale); }, detach, }; } /** * Pixels per point for an editor element you draw yourself (a renderer's own * text box): the box's width on the page over its width in points, or the * page's view scale while there is no box. Inside a look the layer scales * (`lookScale`, 1 outside one), the element draws at the annotation's 100% * size and the look's scale does the rest. */ export function textBoxEditorScaleOf( item: { box: { x: number; y: number; width: number; height: number } } | null, page: PageToPixels & { viewScale: number }, lookScale: number, ): number { const onPage = item && item.box.width > 0 ? rectInPixels(item.box, page).width / item.box.width : page.viewScale; return onPage / lookScale; } /** A free text body's look, as the plugin hands it (`TextItem.css`). */ export interface TextBoxCss { fontFamily: string; /** In page points. */ fontSize: number; color: string; fontWeight: number; fontStyle: string; textDecoration: string; align: 'left' | 'center' | 'right'; /** The plate's inset from the box, in page points. */ padding: number; } // The style records below are type aliases, not interfaces: an object type alias fits a // framework's style type with an index signature for custom properties (Vue's `CSSProperties`), // which an interface never does. /** A text box's body style as CSS. */ export type TextBoxStyle = { fontFamily: string; /** `none`: the browser never fakes a bold or an italic the engine won't draw. */ fontSynthesis: 'none'; /** In pixels, with its unit. */ fontSize: string; color: string; fontWeight: number; fontStyle: string; textDecoration: string; textAlign: 'left' | 'center' | 'right'; }; /** * A text box's body style at `scale` pixels per point: font, size, color and * alignment. No line height: the editor binding states the engine's line * model per face on the element itself. */ export function textBoxStyleOf(css: TextBoxCss, scale: number): TextBoxStyle { return { fontFamily: css.fontFamily, fontSynthesis: 'none', fontSize: `${css.fontSize * scale}px`, color: css.color, fontWeight: css.fontWeight, fontStyle: css.fontStyle, textDecoration: css.textDecoration, textAlign: css.align, }; } /** The layer's own editor element for a free text box, as CSS. */ export type FreeTextBoxStyle = TextBoxStyle & { position: 'absolute'; left: string; top: string; /** The plate's size times the editor's legible scale, in pixels with their unit. */ width: string; height: string; boxSizing: 'border-box'; /** The box's fill and border are the vector scene's, under this layer. */ background: 'transparent'; whiteSpace: 'pre-wrap'; overflowWrap: 'break-word'; overflowX: 'hidden'; /** It scrolls while someone types, and clips otherwise, where the baked appearance clips. */ overflowY: 'auto' | 'hidden'; outline: string; cursor: 'text' | 'default'; /** Draws the editor, laid out at a legible size, at the plate's size, turned like the box. */ transform: string; transformOrigin: '0 0'; /** Not typing: presses fall through to the shapes (select, move, resize). */ pointerEvents: 'auto' | 'none'; }; /** The layer's own editor element for a free text box, and the scale its text is laid out at. */ export interface FreeTextBox { readonly style: FreeTextBoxStyle; /** Pixels per page point the editor lays its text out at: what its editor takes. */ readonly scale: number; } /** * The layer's own editor element for a free text box: the engine's text * plate (`SetPlateRect` and its `re W n` clip), the box inset by its padding, * with no CSS padding, so its edge is the plate's: CSS padding doesn't clip * overflow, and scrolled lines would paint over the border band. The box * never grows with its text. It is laid out at a legible size and drawn back * at the plate's (`legible-text.ts`), and a turned box turns about its * centre, as the baked appearance does. While someone types it takes the * pointer and shows an `outline` of that color. */ export function freeTextBoxOf( item: { box: { x: number; y: number; width: number; height: number }; css: TextBoxCss; /** Clockwise, in degrees, about the box's centre. */ rot?: number; editing: boolean; }, page: PageToPixels, outline: string, ): FreeTextBox { const box = rectInPixels(item.box, page); const onPage = item.box.width > 0 ? box.width / item.box.width : 1; const inset = item.css.padding * onPage; const width = Math.max(0, box.width - 2 * inset); const height = Math.max(0, box.height - 2 * inset); const legible = legibleScaleOf(item.css.fontSize * onPage); const scale = onPage * legible; // About the plate's centre, once the editor is drawn back at the plate's size from its corner. const turn = item.rot ? `translate(${width / 2}px, ${height / 2}px) rotate(${item.rot}deg) ` + `translate(${-width / 2}px, ${-height / 2}px)` : null; return { scale, style: { position: 'absolute', left: `${box.left + inset}px`, top: `${box.top + inset}px`, width: `${width * legible}px`, height: `${height * legible}px`, ...textBoxStyleOf(item.css, scale), boxSizing: 'border-box', background: 'transparent', whiteSpace: 'pre-wrap', overflowWrap: 'break-word', overflowX: 'hidden', overflowY: item.editing ? 'auto' : 'hidden', outline: item.editing ? `${legible}px solid ${outline}` : 'none', cursor: item.editing ? 'text' : 'default', transform: [turn, legibleShrinkOf(legible)].filter(Boolean).join(' ') || 'none', transformOrigin: '0 0', pointerEvents: item.editing ? 'auto' : 'none', }, }; } /** Your own element as a text box's editor, as CSS: it fills its parent. */ export type OwnTextBoxStyle = TextBoxStyle & { /** The parent's size times the editor's legible scale, in percent with its unit. */ width: string; height: string; boxSizing: 'border-box'; /** Draws the editor, laid out at a legible size, at its parent's size. */ transform: string; transformOrigin: '0 0'; /** While someone types, it takes the pointer (the caret, a drag over words). */ pointerEvents?: 'auto'; }; /** Your own element as a text box's editor, and the scale its text is laid out at. */ export interface OwnTextBox { readonly style: OwnTextBoxStyle; /** Pixels per page point the editor lays its text out at: what its editor takes. */ readonly scale: number; } /** * Your own element as the editor of a text box you draw yourself, at `scale` * pixels per point where it is ({@link textBoxEditorScaleOf}): the box's body * style, filling the element's parent, laid out at a legible size and drawn * back at the parent's (`legible-text.ts`). Draw the box's frame (its fill, * border and padding) on the parent: what's on the element scales with it. */ export function ownTextBoxOf( item: { css: TextBoxCss; editing: boolean }, scale: number, ): OwnTextBox { const legible = legibleScaleOf(item.css.fontSize * scale); return { scale: scale * legible, style: { ...textBoxStyleOf(item.css, scale * legible), width: `${100 * legible}%`, height: `${100 * legible}%`, boxSizing: 'border-box', transform: legibleShrinkOf(legible) ?? 'none', transformOrigin: '0 0', ...(item.editing ? { pointerEvents: 'auto' as const } : {}), }, }; }