/** * Rich text policy — what the annotation plugin decides about a free-text * annotation's rich document, kept pure so every framework's editor glue * behaves identically (the mechanics live in `@embedpdf/web`'s binding; the * run algebra, an annotation's rich document and a font's face in the core): * * • a flat props patch → the run delta it means for a text range (font, * size, colour, bold/italic/underline) and the keys left for the body * • what a range reads back for those keys (agree → the value, else mixed), * and a caret: the text typed there next * • faces: the DTO font a face names * • the commit rule: a document nothing overrides on a plain annotation * commits as `contents`; anything else as `richText` */ import { faceForFont, type FieldValues, type FontLookup, locateOffset, type ModelAnnotation, richDocOf, type RichTextRange, type RichTextStyleDelta, styleAt, } from '@embedpdf/core-annotation'; import { familyKey, fontNameForFace, type RichTextBody, type RichTextDocument, type RichTextParagraph, type RichTextRunStyle, } from '@embedpdf/engine-core/runtime'; export type TextFormat = 'bold' | 'italic' | 'underline'; /** The editor's selection inside one free-text annotation: flat offsets over * the plain projection (paragraphs joined by `\n`). */ export interface TextSelection extends RichTextRange { id: string; } /** * The editor's selection as the plugin keeps it: at a caret, with the style * chosen there for the text typed next. A selection that moves is a new one, * without it. */ export interface EditorSelection extends TextSelection { readonly typing?: RichTextStyleDelta; } /** The face a run or a body names. */ export interface Face { family: string; weight?: number; italic?: boolean; } /** The fields a text range takes as run deltas: its font, size and colour, and the formats. */ export const RANGE_KEYS: readonly string[] = [ 'fontFamily', 'fontSize', 'fontColor', 'bold', 'italic', 'underline', ]; // ---- Faces --------------------------------------------------------------------- /** The DTO font for a face: the registered key whose identity matches (the * closest weight, italic first), else the standard kebab name, else the * family itself. The inverse of {@link faceForFont}. */ export function fontForFace(face: Face, fonts?: FontLookup): string { const weight = face.weight ?? 400; const italic = face.italic ?? false; return fontNameForFace({ family: face.family, weight, italic }, (family) => { const wanted = familyKey(family); let best: { key: string; score: number } | undefined; for (const handle of fonts?.() ?? []) { if (familyKey(handle.familyName) !== wanted) continue; const score = Math.abs(handle.weight - weight) + (handle.italic === italic ? 0 : 1000); if (!best || score < best.score) best = { key: handle.key, score }; } return best?.key; }); } // ---- Documents ----------------------------------------------------------------- const hex = (css: string): string => css.trim().toUpperCase(); /** * The write a text edit commits: the rich paragraphs, with paragraph * properties equal to the body's stripped (they are inherited, not * overrides) and the body omitted — it stays what the props path last * wrote. One engine, one path: plain and formatted text alike. */ export function textCommitPatch( record: ModelAnnotation, paragraphs: RichTextParagraph[], fonts?: FontLookup, ): { richText: { paragraphs: RichTextParagraph[] } } { return { richText: { paragraphs: stripBodyDefaults(paragraphs, richDocOf(record.annotation, fonts).body), }, }; } /** * Paragraph alignment/direction equal to the body's are not overrides: the * engine echoes them resolved, the editor renders them as inline styles and * serialises them back, and the commit rule must see through that (a plain * `/Contents` annotation must not grow an `/RC` from typing). */ export function stripBodyDefaults( paragraphs: RichTextParagraph[], body: Pick, ): RichTextParagraph[] { return paragraphs.map((paragraph) => { if ( (paragraph.align === undefined || paragraph.align !== body.align) && (paragraph.dir === undefined || paragraph.dir !== body.dir) ) { return paragraph; } const { align, dir, ...rest } = paragraph; return { ...rest, ...(align !== undefined && align !== body.align ? { align } : {}), ...(dir !== undefined && dir !== body.dir ? { dir } : {}), }; }); } // ---- Props ↔ runs -------------------------------------------------------------- /** * Split a patch for an annotation whose editor holds a text range: the run * delta the range takes (font → face, size, colour, and the formats: bold → * weight, italic, underline → decoration) and the fields that still go to the * annotation. */ export function runDeltaForFields( patch: FieldValues, fonts?: FontLookup, ): { delta: RichTextStyleDelta; rest: Record } { const delta: RichTextStyleDelta = {}; const rest: Record = {}; for (const [key, value] of Object.entries(patch)) { if (value === undefined) continue; switch (key) { case 'fontFamily': { const face = faceForFont(value as string, fonts); delta.family = face.family; if (face.weight !== undefined) delta.weight = face.weight; if (face.italic !== undefined) delta.italic = face.italic; break; } case 'fontSize': delta.size = value as number; break; case 'fontColor': delta.color = hex(value as string); break; case 'bold': delta.weight = value ? 700 : 400; break; case 'italic': delta.italic = value as boolean; break; case 'underline': delta.decoration = value ? ['underline'] : []; break; default: rest[key] = value; } } return { delta, rest }; } /** The style deltas of every non-empty run a range overlaps. */ export function runsInRange( doc: { paragraphs: readonly RichTextParagraph[] }, range: RichTextRange, ): RichTextStyleDelta[] { const start = Math.min(range.start, range.end); const end = Math.max(range.start, range.end); if (end <= start) return []; const from = locateOffset(doc, start); const to = locateOffset(doc, end); const out: RichTextStyleDelta[] = []; for (let index = from.paragraph; index <= to.paragraph; index++) { const paragraph = doc.paragraphs[index]!; const localStart = index === from.paragraph ? from.offset : 0; const localEnd = index === to.paragraph ? to.offset : paragraph.runs.reduce((total, run) => total + run.text.length, 0); let pos = 0; for (const run of paragraph.runs) { const runEnd = pos + run.text.length; if (runEnd > localStart && pos < localEnd && run.text.length > 0) out.push(run.style ?? {}); pos = runEnd; } } return out; } /** What text reads back for the range keys: a value each, and the keys its runs disagree on. */ export interface TextProps { values: Record; mixed: string[]; } /** The values a range reads back for the range keys: the runs it covers (`runProps`). */ export function rangeProps( doc: RichTextDocument, range: RichTextRange, fonts?: FontLookup, ): TextProps { return runProps(doc.body, runsInRange(doc, range), fonts); } /** * The values a caret reads back for the range keys: the text typed there * next, in the style of the text before it (`styleAt`) with the style chosen * at the caret over it. */ export function caretProps( doc: RichTextDocument, at: number, typing: RichTextStyleDelta | undefined, fonts?: FontLookup, ): TextProps { return runProps(doc.body, [{ ...styleAt(doc, at), ...typing }], fonts); } /** The values runs read back for the range keys: resolved against the * body, one value where every run agrees, `mixed` where they don't. */ function runProps( body: RichTextBody, runs: readonly RichTextStyleDelta[], fonts?: FontLookup, ): TextProps { const resolve = (delta: RichTextStyleDelta): Partial => ({ family: delta.family ?? body.family, weight: delta.weight ?? body.weight, italic: delta.italic ?? body.italic, size: delta.size ?? body.size, color: delta.color ?? body.color, decoration: delta.decoration ?? body.decoration, }); const styles = (runs.length ? runs : [{}]).map(resolve); const values: Record = {}; const mixed: string[] = []; const read = (key: string, of: (style: Partial) => unknown) => { const first = of(styles[0]!); values[key] = first; if (styles.some((style) => JSON.stringify(of(style)) !== JSON.stringify(first))) mixed.push(key); }; // The family reads back at the body's weight/italic: a run's own weight // and italic are the bold/italic toggles, not a different font ("Helvetica" // stays "helvetica" while bold, never flips to "helvetica-bold"). read('fontFamily', (style) => fontForFace({ family: style.family!, weight: body.weight, italic: body.italic }, fonts), ); read('fontSize', (style) => style.size); read('fontColor', (style) => style.color!.toLowerCase()); read('bold', (style) => (style.weight ?? 400) >= 600); read('italic', (style) => !!style.italic); read('underline', (style) => (style.decoration ?? []).includes('underline')); return { values, mixed }; }