@forevka/wordcanvas 0.7.2 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist-lib/assets/{worker-4HYrkNrG.js → worker-CqU4Popa.js} +399 -375
  2. package/dist-lib/assets/{worker-CJpwUzKh.js → worker-Cw5cYW5z.js} +359 -344
  3. package/dist-lib/{blockFactory-B_CLnkUh.js → blockFactory-DDCRWDnA.js} +16 -31
  4. package/dist-lib/browser-BUrsjziD.js +612 -0
  5. package/dist-lib/builder.js +16 -17
  6. package/dist-lib/editorApp-CB_ZArIF.js +9566 -0
  7. package/dist-lib/export.js +28 -28
  8. package/dist-lib/generate-toc.js +6 -6
  9. package/dist-lib/import.js +2 -2
  10. package/dist-lib/lists-DpmgbDyt.js +110 -0
  11. package/dist-lib/measure.js +2 -2
  12. package/dist-lib/{measureHost-B2aKX7lF.js → measureHost-BlukHGwx.js} +1 -1
  13. package/dist-lib/metrics-bvGO8KDK.js +96 -0
  14. package/dist-lib/paintStyle-vT6jtWbH.js +74 -0
  15. package/dist-lib/{pipeline-DD0nxAYM.js → pipeline-UryP-u7Z.js} +80 -80
  16. package/dist-lib/recalc-docx.js +2 -2
  17. package/dist-lib/{recalcToc-CFCGCgij.js → recalcToc-BfXlXZik.js} +3 -3
  18. package/dist-lib/{stylesheet-B6oczA-L.js → stylesheet-LTBEGkvG.js} +32 -27
  19. package/dist-lib/toc-D09f4PrI.js +939 -0
  20. package/dist-lib/{webmcp-CXghUon_.js → webmcp-K6UZgQJ0.js} +60 -68
  21. package/dist-lib/wordcanvas-DBx2ana_.js +734 -0
  22. package/dist-lib/wordcanvas.js +4 -2
  23. package/dist-node/{chunk-PIMVQULL.js → chunk-373K2XRY.js} +34 -22
  24. package/dist-node/chunk-373K2XRY.js.map +7 -0
  25. package/dist-node/{chunk-57L5XMCL.js → chunk-3PUV3BG6.js} +2 -2
  26. package/dist-node/{chunk-U27EBKBG.js → chunk-5RX3IHWE.js} +3 -3
  27. package/dist-node/chunk-5RX3IHWE.js.map +7 -0
  28. package/dist-node/{chunk-SA26UVIJ.js → chunk-HWQKGDS2.js} +2 -2
  29. package/dist-node/{chunk-T3253N22.js → chunk-ZLLSXOO2.js} +3 -3
  30. package/dist-node/{engine-5F7DUU4W.js → engine-LLA6PCS5.js} +4 -4
  31. package/dist-node/export.js +5 -5
  32. package/dist-node/generate-toc.js +4 -4
  33. package/dist-node/import.js +2 -2
  34. package/dist-node/measure.js +2 -2
  35. package/dist-node/recalc-docx.js +3 -3
  36. package/package.json +1 -1
  37. package/types/wordcanvas.d.ts +649 -212
  38. package/dist-lib/browser-p_rkUcqE.js +0 -1339
  39. package/dist-lib/editorApp-mTD0YNv-.js +0 -9863
  40. package/dist-lib/lists-Sc5I40JO.js +0 -110
  41. package/dist-lib/metrics-BUMIC9Mv.js +0 -164
  42. package/dist-lib/toc-Dj57zdz-.js +0 -213
  43. package/dist-lib/wordcanvas-D5DI9ZR1.js +0 -151
  44. package/dist-node/chunk-PIMVQULL.js.map +0 -7
  45. package/dist-node/chunk-U27EBKBG.js.map +0 -7
  46. /package/dist-node/{chunk-57L5XMCL.js.map → chunk-3PUV3BG6.js.map} +0 -0
  47. /package/dist-node/{chunk-SA26UVIJ.js.map → chunk-HWQKGDS2.js.map} +0 -0
  48. /package/dist-node/{chunk-T3253N22.js.map → chunk-ZLLSXOO2.js.map} +0 -0
  49. /package/dist-node/{engine-5F7DUU4W.js.map → engine-LLA6PCS5.js.map} +0 -0
@@ -1,212 +1,649 @@
1
- // Public type surface for the @forevka/wordcanvas (WordCanvas) package.
2
- // Hand-written so the published types stay small, self-contained, and stable
3
- // regardless of internal refactors — no dependency on internal workspace types.
4
-
5
- import type { Block, Document, ParaStyle, Run } from "./model";
6
-
7
- export type { Document } from "./model";
8
-
9
- /** Caller-supplied identity, used for change attribution and presence. */
10
- export interface UserInfo {
11
- id: string;
12
- firstName: string;
13
- lastName: string;
14
- }
15
-
16
- /** One other collaborator currently in the document (online mode). */
17
- export interface Participant {
18
- siteId: string;
19
- user?: UserInfo;
20
- }
21
-
22
- export interface WordCanvasOptions {
23
- /** Element to mount the editor into. */
24
- container: HTMLElement;
25
- /** Backend base URL (e.g. "https://api.example.com"). Online iff provided;
26
- * omit for a fully offline editor (no sync, publish, or share). */
27
- backendUrl?: string;
28
- /** Open this document on load (online only) — e.g. the id returned by an
29
- * upload. Canonical name; `collabId` is the deprecated alias. */
30
- docId?: string;
31
- /** @deprecated Use `docId`. Join an existing collaboration session on load. */
32
- collabId?: string;
33
- /** Caller-supplied identity (attribution + presence). The embedder owns auth. */
34
- user?: UserInfo;
35
- /** Override how a share link is surfaced (default: a built-in dialog). */
36
- onShareLink?: (url: string, docId: string) => void;
37
- /** Resolve a custom (developer-defined) field's content from your backend. When
38
- * set, right-clicking a custom field offers "Update Field (<name>)"; the
39
- * callback receives the field's name + verbatim instruction and returns the new
40
- * result to splice in (see FieldResult). */
41
- resolveField?: FieldResolver;
42
- /** Expose this editor to AI agents over WebMCP (https://webmcp.dev), the standard
43
- * `navigator.modelContext` API. `true` registers the full tool set read &
44
- * inspect (including a layout-geometry dump for debugging rendering / text-
45
- * placement issues), plus suggestions, comments, and direct edits. Pass an
46
- * object to restrict capabilities or namespace the tool names. The WebMCP
47
- * polyfill is lazy-loaded only when this is set, so it adds nothing for
48
- * embedders that don't opt in. Connect an agent via the WebMCP browser
49
- * extension / Chrome DevTools MCP. */
50
- agentTools?: boolean | AgentToolsOptions;
51
- /** Track first-load progress so you can show a loader while the big chunks
52
- * stream. Fires for the editor JS chunk download (`phase: "bundle"`,
53
- * indeterminate) and the bundled font fetch (`phase: "fonts"`, the dominant
54
- * ~9 MB cost — a smooth, size-weighted bar), then once at `phase: "ready"`
55
- * with `percent: 1`. Read `percent` (0..1, monotonic) to drive a progress bar. */
56
- onLoadProgress?: (progress: LoadProgress) => void;
57
- }
58
-
59
- /** First-load progress (see WordCanvasOptions.onLoadProgress). */
60
- export interface LoadProgress {
61
- /** Coarse stage: "bundle" = downloading the editor JS chunk (indeterminate
62
- * a dynamic import can't be byte-measured); "fonts" = fetching the bundled
63
- * fonts (measurable); "ready" = mount complete. */
64
- phase: "bundle" | "fonts" | "ready";
65
- /** Overall startup progress, 0..1, monotonic. Drive a progress bar with this. */
66
- percent: number;
67
- /** Bytes fetched / total for the current measurable phase (fonts). Both 0 when
68
- * the phase is indeterminate (bundle). Informational. */
69
- loaded: number;
70
- total: number;
71
- }
72
-
73
- /** Opt-in WebMCP agent tooling (see WordCanvasOptions.agentTools). */
74
- export interface AgentToolsOptions {
75
- /** Which tool buckets to register. Default: all three.
76
- * - `read` — read & inspect (get_document, get_selection, search_document,
77
- * inspect_layout, get_document_stats);
78
- * - `suggest` — set_mode, comments, tracked-change suggestions, accept/reject;
79
- * - `edit` — replace_text, insert_text, format_text, set_alignment,
80
- * select_range, undo/redo, set_document. */
81
- capabilities?: ("read" | "suggest" | "edit")[];
82
- /** Optional prefix so several editors on one page don't collide
83
- * (e.g. "doc1" → "doc1_get_document"). */
84
- name?: string;
85
- }
86
-
87
- /** Request passed to a custom-field resolver (see WordCanvasOptions.resolveField). */
88
- export interface FieldResolveRequest {
89
- /** The field's id within the document. */
90
- fieldId: string;
91
- /** Field keyword, uppercased (e.g. "MYCHART"). */
92
- name: string;
93
- /** The verbatim field instruction (e.g. ` MYCHART "sales-2026" `). */
94
- instruction: string;
95
- /** The collaboration doc id, when the session has one. */
96
- docId?: string;
97
- }
98
-
99
- /** What a field resolver returns:
100
- * - a full **.docx** (ArrayBuffer / Uint8Array / Blob) — RECOMMENDED: imported
101
- * through the same pipeline as opening a document, so images, tables, lists and
102
- * styles come through (media survives export);
103
- * - or an **OOXML fragment string** (w:p / w:tbl, or a w:document) for simple,
104
- * text-only results (no embedded media). */
105
- export type FieldResult = string | ArrayBuffer | Uint8Array | Blob;
106
-
107
- /** Host hook producing a field's result for a resolve request. */
108
- export type FieldResolver = (req: FieldResolveRequest) => Promise<FieldResult>;
109
-
110
- /** What to render into a child-document surface (see WordCanvas.createChild). */
111
- export type ChildContent =
112
- | { kind: "blocks"; blocks: Block[] }
113
- | { kind: "fragment"; fragment: { blocks: { runs: Run[]; style: ParaStyle }[]; inline?: boolean } }
114
- | { kind: "runs"; runs: Run[]; paraStyle?: ParaStyle }
115
- /** Body OOXML (w:p / w:tbl, or a w:document). Media-free (no images by r:id). */
116
- | { kind: "ooxml"; ooxml: string }
117
- /** A real sample of a named style ("AaBbCc" in the style's resolved formatting). */
118
- | { kind: "styleSample"; styleId: string; sampleText?: string };
119
-
120
- export interface ChildRenderOptions {
121
- /** Layout/wrap width in CSS px. Default: target.clientWidth. */
122
- widthPx?: number;
123
- /** Child section margins (all sides), CSS px. Default 0. */
124
- padding?: number;
125
- /** Cap the displayed height; content beyond it is clipped. */
126
- maxHeightPx?: number;
127
- /** Fixed presentational scale (1 = 100%). Ignored when `fit` is set. */
128
- zoom?: number;
129
- /** Auto-scale the content to fit `widthPx` × `maxHeightPx` (compact swatches). */
130
- fit?: boolean;
131
- }
132
-
133
- /** A live interactive editor over a child slice (canvas-native editing). */
134
- export interface ChildEditorHandle {
135
- /** The edited content as model blocks (hand back to splice into the parent). */
136
- getBlocks(): Block[];
137
- getDocument(): Document;
138
- /** Insert an image at the caret. The bytes are registered in the parent
139
- * document's shared media store (content-addressed), so the image renders here,
140
- * survives serialize/export, and resolves after commit-back. Dimensions default
141
- * to the image's natural size. */
142
- insertImage(bytes: Uint8Array, mime: string, opts?: { widthPx?: number; heightPx?: number }): Promise<void>;
143
- destroy(): void;
144
- }
145
-
146
- /** A lightweight sibling document that shares the parent editor's live styles,
147
- * fonts and theme and renders/edits a content slice on canvas. */
148
- export interface ChildDocument {
149
- /** Paint a static preview of `content` into `target`. Safe to call repeatedly. */
150
- render(target: HTMLElement, content: ChildContent, opts?: ChildRenderOptions): void;
151
- /** Mount an interactive editor over `content` inside `target`. */
152
- mountEditor(target: HTMLElement, content: ChildContent, opts?: ChildRenderOptions): ChildEditorHandle;
153
- /** Tear down every surface/editor this child created. */
154
- destroy(): void;
155
- }
156
-
157
- /** Event name → payload, for `on(...)`/`off(...)`. */
158
- export interface WordCanvasEventMap {
159
- ready: Record<string, never>;
160
- shared: { docId: string; url: string };
161
- userEntered: { siteId: string; user?: UserInfo };
162
- userLeave: { siteId: string; user?: UserInfo };
163
- presence: { participants: Participant[] };
164
- }
165
-
166
- /** Handle resolved once the editor is mounted (via `whenReady()`). */
167
- export interface EditorHandle {
168
- /** Snapshot of the current document (plain data). */
169
- getDocument(): Document;
170
- /** Create a child document sharing this editor's live styles/fonts/theme. */
171
- createChild(): ChildDocument;
172
- /** Replace the open document with a programmatically-built one (e.g. a
173
- * DocumentBuilder result). Cloned; drops undo history and any live collab
174
- * session; preserves zoom + scroll. */
175
- setDocument(doc: Document): void;
176
- /** Open a .docx (auto-publishes when online); resolves when loaded. */
177
- openDocx(file: File | ArrayBuffer): Promise<void>;
178
- /** Publish the current document and resolve its shareable link (online only). */
179
- share(): Promise<string>;
180
- getDocId(): string | null;
181
- getShareLink(): string | null;
182
- destroy(): void;
183
- }
184
-
185
- export declare class WordCanvas {
186
- constructor(opts: WordCanvasOptions);
187
- /** Subscribe to a collaboration event. Returns an unsubscribe function. */
188
- on<E extends keyof WordCanvasEventMap>(event: E, handler: (data: WordCanvasEventMap[E]) => void): () => void;
189
- /** Unsubscribe a handler previously passed to `on()`. */
190
- off<E extends keyof WordCanvasEventMap>(event: E, handler: (data: WordCanvasEventMap[E]) => void): void;
191
- /** Resolves once the editor is mounted and ready. */
192
- whenReady(): Promise<EditorHandle>;
193
- /** Create a child document that shares this editor's live styles, fonts and
194
- * theme render a real, document-styled preview of a content slice onto a
195
- * canvas (instead of an HTML approximation), or mount a canvas-native editor
196
- * over a slice. Returned synchronously; render() before ready is buffered.
197
- * (mountEditor() requires the editor to be ready — await whenReady() first.) */
198
- createChild(): ChildDocument;
199
- /** Open a .docx. When online, auto-publishes it and surfaces a share link. */
200
- openDocx(file: File | ArrayBuffer): Promise<void>;
201
- /** Replace the open document with a programmatically-built one (e.g. a
202
- * DocumentBuilder result). The input is cloned. Like openDocx, this starts a
203
- * NEW document: undo history and any live collab session are dropped (the
204
- * next share() forks). Zoom and scroll are preserved, so calling this on
205
- * every data change gives a stable live preview. */
206
- setDocument(doc: Document): Promise<void>;
207
- /** Publish the current document and resolve its shareable link (online only). */
208
- share(): Promise<string>;
209
- getDocId(): string | null;
210
- getShareLink(): string | null;
211
- destroy(): void;
212
- }
1
+ // Public type surface for the @forevka/wordcanvas (WordCanvas) package.
2
+ // Hand-written so the published types stay small, self-contained, and stable
3
+ // regardless of internal refactors — no dependency on internal workspace types.
4
+
5
+ import type { Block, CharStyle, DocPosition, Document, ParaStyle, Run } from "./model";
6
+
7
+ export type { Document } from "./model";
8
+
9
+ /** Caller-supplied identity, used for change attribution and presence. */
10
+ export interface UserInfo {
11
+ id: string;
12
+ firstName: string;
13
+ lastName: string;
14
+ }
15
+
16
+ /** One other collaborator currently in the document (online mode). */
17
+ export interface Participant {
18
+ siteId: string;
19
+ user?: UserInfo;
20
+ }
21
+
22
+ /** Editor mode: "edit" (raw editing), "suggest" (edits become tracked changes),
23
+ * or "view" (read-only). The three are mutually exclusive. */
24
+ export type EditMode = "edit" | "suggest" | "view";
25
+
26
+ /** A selection/caret in the document (offsets are UTF-16 code units into a
27
+ * block's concatenated run text). `anchor === focus` is a collapsed caret. */
28
+ export interface DocSelection {
29
+ anchor: DocPosition;
30
+ focus: DocPosition;
31
+ /** Preserved X column for Up/Down caret movement; usually ignorable. */
32
+ goalX?: number;
33
+ }
34
+
35
+ // ===== Review layer (track changes + comments) =============================
36
+ // An attributed, anchored overlay on top of the core document. `getReview()`
37
+ // returns a snapshot; the `reviewChanged` event carries the full layer.
38
+
39
+ /** Rich-text comment body the same style-homogeneous run list the document
40
+ * uses (so a comment composes/renders like any other content). */
41
+ export type Fragment = Run[];
42
+
43
+ /** A range into the live document; `start === end` is a point (caret) anchor. */
44
+ export interface ReviewAnchor {
45
+ start: DocPosition;
46
+ end: DocPosition;
47
+ }
48
+
49
+ export type SuggestionKind = "insert" | "delete" | "format" | "structural";
50
+
51
+ /** A tracked structural edit (split/merge/block/table op). `op`/`inverse` are the
52
+ * internal core ops captured at intercept time opaque on the public surface
53
+ * (not part of the stable contract); `blockId` is the block the record hangs on. */
54
+ export interface StructuralChange {
55
+ op: unknown;
56
+ inverse: unknown;
57
+ blockId: string;
58
+ }
59
+
60
+ /** One tracked change. Text-bearing kinds (insert/delete/format) cover live text;
61
+ * `structural` records carry a degenerate point anchor + the applied op. */
62
+ export interface Suggestion {
63
+ /** Globally unique id. */
64
+ id: string;
65
+ kind: SuggestionKind;
66
+ /** Covers text present in the live document. */
67
+ anchor: ReviewAnchor;
68
+ /** Attribution (the embedder owns identity; the layer just presents it). */
69
+ author: UserInfo;
70
+ /** Wall-clock ms; display/sort only. */
71
+ createdAt: number;
72
+ /** format only: the applied char-style patch + its inverse (for reject). */
73
+ patch?: Partial<CharStyle>;
74
+ inverse?: Partial<CharStyle>;
75
+ /** structural only: the applied core op, its inverse, and the host block. */
76
+ structural?: StructuralChange;
77
+ /** Optional grouping so related records accept/reject as a unit. */
78
+ groupId?: string;
79
+ }
80
+
81
+ export interface Comment {
82
+ id: string;
83
+ author: UserInfo;
84
+ body: Fragment;
85
+ createdAt: number;
86
+ editedAt?: number;
87
+ /** Resolved identities of users @-mentioned in this comment. */
88
+ mentions?: UserInfo[];
89
+ }
90
+
91
+ export type ThreadStatus = "open" | "resolved";
92
+
93
+ export interface CommentThread {
94
+ id: string;
95
+ /** Highlighted span; `start === end` point comment. */
96
+ anchor: ReviewAnchor;
97
+ status: ThreadStatus;
98
+ /** Ordered; `comments[0]` is the root, the rest are replies. */
99
+ comments: Comment[];
100
+ }
101
+
102
+ /** Snapshot of the review overlay (suggestions + comment threads). */
103
+ export interface ReviewLayer {
104
+ docId: string;
105
+ /** Core document version these anchors were last rebased to. */
106
+ baseVersion: number;
107
+ suggestions: Suggestion[];
108
+ threads: CommentThread[];
109
+ }
110
+
111
+ // ===== Theming & behavior (see WordCanvasOptions.theme / .behavior) =========
112
+
113
+ /** Ruler band styling (the strip the horizontal + vertical rulers paint). */
114
+ export interface RulerTheme {
115
+ /** Band fill behind the ticks. */
116
+ bg?: string;
117
+ /** The lighter "content area" portion of the band (within the margins). */
118
+ content?: string;
119
+ /** Tick + boundary line color. */
120
+ line?: string;
121
+ /** Number label color. */
122
+ label?: string;
123
+ /** CSS font for the number labels. */
124
+ font?: string;
125
+ }
126
+
127
+ /** Editor color theme every field optional; omit to keep the built-in value.
128
+ * Affects the on-screen editor only (exported PDFs keep the built-in look). */
129
+ export interface EditorTheme {
130
+ /** Gray gutter behind the pages (the scroll area + ruler troughs). */
131
+ canvasBackground?: string;
132
+ /** Native table gridlines when a cell carries no explicit border. */
133
+ grid?: string;
134
+ /** Drawing-grid overlay mesh (the dotted snap grid). */
135
+ gridMesh?: string;
136
+ /** External hyperlink color. */
137
+ externalLink?: string;
138
+ /** UI accent (band-edit boundary and similar chrome affordances). */
139
+ accent?: string;
140
+ /** Footnote separator rule. */
141
+ footnoteRule?: string;
142
+ /** Non-printing formatting marks (space dots, tab arrows, pilcrows). */
143
+ formattingMark?: string;
144
+ /** TOC dot-leader color. */
145
+ tocLeader?: string;
146
+ /** Placeholder fill for an image whose bitmap hasn't loaded. */
147
+ imagePlaceholder?: string;
148
+ /** Rule between newspaper columns. */
149
+ columnSeparator?: string;
150
+ /** Blinking text caret color. */
151
+ caret?: string;
152
+ /** Find-highlight color. */
153
+ searchHighlight?: string;
154
+ /** Comment pin fill once its thread is resolved. */
155
+ reviewPinResolved?: string;
156
+ /** Comment pin stroke. */
157
+ reviewPinStroke?: string;
158
+ /** Gap (px) between stacked pages. */
159
+ pageGapPx?: number;
160
+ /** Ruler band styling. */
161
+ ruler?: RulerTheme;
162
+ }
163
+
164
+ /** Editor behavior tuning — every field optional. */
165
+ export interface EditorBehavior {
166
+ /** Multiplicative zoom step for +/- and Ctrl+wheel. Default 1.1. */
167
+ zoomStep?: number;
168
+ /** Absolute minimum zoom. Default 0.25. */
169
+ zoomMin?: number;
170
+ /** Absolute maximum zoom. Default 5. */
171
+ zoomMax?: number;
172
+ /** Indent / outdent step in px per toolbar press. Default 36. */
173
+ indentStepPx?: number;
174
+ /** Default drawing-grid spacing in px (view.gridSpacingPx still overrides). Default 24. */
175
+ gridSpacingPx?: number;
176
+ }
177
+
178
+ /** Overrides the LIBRARY's built-in default run/paragraph styles for NEW/blank
179
+ * documents and the fallback stylesheet — NOT a loaded .docx's own defaults. */
180
+ export interface DefaultStyleOverrides {
181
+ /** Body (Normal) font family, e.g. "Times New Roman, serif". */
182
+ fontFamily?: string;
183
+ /** Body font size in px (96 dpi). */
184
+ fontSizePx?: number;
185
+ /** Body text color (any CSS color string). */
186
+ color?: string;
187
+ /** Default paragraph line height (multiplier). */
188
+ lineHeight?: number;
189
+ /** Heading font family (Title/Heading1/Heading2). Omit to keep the built-in. */
190
+ headingFontFamily?: string;
191
+ }
192
+
193
+ /** A ready-made dark-canvas theme (darkens the chrome/gutter; pages stay white
194
+ * for print fidelity). Spread + tweak it for your own theme. */
195
+ export declare const darkCanvasTheme: EditorTheme;
196
+
197
+ // ===== Ribbon customization (see WordCanvasOptions.customizeRibbon) =========
198
+
199
+ /** Where to place a tab/group/button relative to an existing one (by id). When
200
+ * the anchor id is absent/omitted, the item is appended at the end. */
201
+ export interface RibbonAnchor {
202
+ before?: string;
203
+ after?: string;
204
+ }
205
+
206
+ /** The editor handle handed to a custom ribbon button's `onClick`, plus macro
207
+ * helpers read/edit the document at the caret, emit events, open popups. */
208
+ export interface RibbonActionContext extends EditorHandle {
209
+ getSelection(): DocSelection | null;
210
+ insertText(text: string): void;
211
+ /** Emit a custom event to the embedder (`wc.on("custom", …)`). */
212
+ emit(name: string, payload?: unknown): void;
213
+ /** Tie a DOM node (removed) or callback (run) to the editor's teardown so an
214
+ * embedder's popup is cleaned up on destroy(). */
215
+ registerCleanup(target: HTMLElement | (() => void)): void;
216
+ }
217
+
218
+ /** A custom ribbon button. */
219
+ export interface RibbonButtonSpec {
220
+ /** Stable id (namespace it, e.g. "myco.macros.upper"). */
221
+ id: string;
222
+ /** Raw innerHTML for the button face — an SVG string, emoji, or text. */
223
+ icon?: string;
224
+ /** Text label (used when `icon` is omitted). */
225
+ label?: string;
226
+ tooltip?: string;
227
+ onClick: (ctx: RibbonActionContext) => void;
228
+ /** Optional pressed-state predicate, re-evaluated on every selection change. */
229
+ active?: (fmt: unknown) => boolean;
230
+ /** Optional enabled predicate; the button greys out when it returns false. */
231
+ enabled?: (fmt: unknown) => boolean;
232
+ }
233
+
234
+ export interface RibbonTabSpec extends RibbonAnchor {
235
+ id: string;
236
+ label: string;
237
+ }
238
+ export interface RibbonGroupSpec extends RibbonAnchor {
239
+ id: string;
240
+ label: string;
241
+ }
242
+
243
+ /** Ribbon mutation API. Ordering is by id; an unknown id is a no-op with a
244
+ * console warning. Discover built-in ids with `tabs()`/`groups()`/`items()`. */
245
+ export interface RibbonApi {
246
+ tabs(): string[];
247
+ groups(tabId: string): string[];
248
+ items(groupId: string): string[];
249
+ addTab(spec: RibbonTabSpec): void;
250
+ removeTab(id: string): void;
251
+ moveTab(id: string, pos: RibbonAnchor): void;
252
+ addGroup(tabId: string, spec: RibbonGroupSpec): void;
253
+ removeGroup(id: string): void;
254
+ moveGroup(id: string, pos: RibbonAnchor): void;
255
+ addButton(groupId: string, spec: RibbonButtonSpec & RibbonAnchor): void;
256
+ removeItem(id: string): void;
257
+ moveItem(id: string, pos: RibbonAnchor & { toGroup?: string }): void;
258
+ }
259
+
260
+ /** Hook for the `customizeRibbon` option — called once at mount. */
261
+ export type CustomizeRibbon = (api: RibbonApi) => void;
262
+
263
+ /** Options for `makeFloatingDialog` (a draggable, non-blocking panel). */
264
+ export interface FloatingDialogOptions {
265
+ backdrop: HTMLElement;
266
+ modal: HTMLElement;
267
+ handle: HTMLElement;
268
+ signal: AbortSignal;
269
+ noDrag?: string;
270
+ }
271
+
272
+ /** Turn a backdrop+modal pair into a draggable, non-blocking floating panel —
273
+ * a convenience for building config/informational popups from a custom button. */
274
+ export declare function makeFloatingDialog(o: FloatingDialogOptions): void;
275
+
276
+ // ===========================================================================
277
+
278
+ export interface WordCanvasOptions {
279
+ /** Element to mount the editor into. */
280
+ container: HTMLElement;
281
+ /** Backend base URL (e.g. "https://api.example.com"). Online iff provided;
282
+ * omit for a fully offline editor (no sync, publish, or share). */
283
+ backendUrl?: string;
284
+ /** Open this document on load (online only) — e.g. the id returned by an
285
+ * upload. Canonical name; `collabId` is the deprecated alias. */
286
+ docId?: string;
287
+ /** @deprecated Use `docId`. Join an existing collaboration session on load. */
288
+ collabId?: string;
289
+ /** Caller-supplied identity (attribution + presence). The embedder owns auth. */
290
+ user?: UserInfo;
291
+ /** Override how a share link is surfaced (default: a built-in dialog). */
292
+ onShareLink?: (url: string, docId: string) => void;
293
+ /** Route exports to your own pipeline. When set, the toolbar's Export (PDF /
294
+ * DOCX) buttons hand the produced file to this callback — a Blob plus raw
295
+ * bytes, the format, and any export warnings (see SaveEvent) — instead of
296
+ * triggering a browser download. Return a promise to keep the UI responsive
297
+ * while you upload. Omit to keep the default download behaviour. (For a fully
298
+ * custom button, call `exportDocx()` / `exportPdf()` on the instance.) */
299
+ onSave?: SaveHandler;
300
+ /** Mount as a view-only viewer: the document renders and stays selectable and
301
+ * copyable, but the editing chrome is hidden and every mutation is a no-op.
302
+ * In an online session a read-only client still receives live remote edits.
303
+ * Equivalent to `mode: "view"`. */
304
+ readonly?: boolean;
305
+ /** Initial editor mode: "edit" (default), "suggest" (edits become tracked
306
+ * changes), or "view" (read-only). Defaults to "view" when `readonly`. */
307
+ mode?: EditMode;
308
+ /** Restrict which modes the user can switch to (constrains the mode picker and
309
+ * setMode). Omit ⇒ all three. e.g. ["suggest","view"] locks out raw editing. */
310
+ allowedModes?: EditMode[];
311
+ /** Users that can be @-mentioned in comments. The embedder owns this roster;
312
+ * update it later with `setKnownUsers`. */
313
+ knownUsers?: UserInfo[];
314
+ /** Resolve a custom (developer-defined) field's content from your backend. When
315
+ * set, right-clicking a custom field offers "Update Field (<name>)"; the
316
+ * callback receives the field's name + verbatim instruction and returns the new
317
+ * result to splice in (see FieldResult). */
318
+ resolveField?: FieldResolver;
319
+ /** Expose this editor to AI agents over WebMCP (https://webmcp.dev), the standard
320
+ * `navigator.modelContext` API. `true` registers the full tool set — read &
321
+ * inspect (including a layout-geometry dump for debugging rendering / text-
322
+ * placement issues), plus suggestions, comments, and direct edits. Pass an
323
+ * object to restrict capabilities or namespace the tool names. The WebMCP
324
+ * polyfill is lazy-loaded only when this is set, so it adds nothing for
325
+ * embedders that don't opt in. Connect an agent via the WebMCP browser
326
+ * extension / Chrome DevTools MCP. */
327
+ agentTools?: boolean | AgentToolsOptions;
328
+ /** Initial view-chrome state — what the reader sees on open (rulers, grid,
329
+ * panels, ribbon, status bar, the Export buttons, zoom). Omit any field to keep
330
+ * its default. See WordCanvasViewOptions. */
331
+ view?: WordCanvasViewOptions;
332
+ /** Color theme — pass a (partial) `EditorTheme` to recolor the editor chrome:
333
+ * the gray canvas/gutter, gridlines, hyperlink/accent colors, formatting marks,
334
+ * TOC leaders, rulers, caret, etc. Omit any field to keep its built-in value.
335
+ * A ready-made `darkCanvasTheme` is exported to spread + tweak. Affects the
336
+ * on-screen editor only (exported PDFs keep the built-in look). */
337
+ theme?: EditorTheme;
338
+ /** Override the LIBRARY's built-in default run/paragraph styles (body font,
339
+ * size, color, line height, heading font) for NEW/blank documents and the
340
+ * fallback stylesheet. IMPORTANT: a loaded .docx keeps its OWN defaults
341
+ * (w:docDefaults / Normal) — set defaults there, or here, not both. */
342
+ overrideDefaultStyles?: DefaultStyleOverrides;
343
+ /** Behavior tuning: zoom step (default 1.1), zoom clamp (0.25–5), indent step
344
+ * (36px), and default drawing-grid spacing (24px; `view.gridSpacingPx` wins). */
345
+ behavior?: EditorBehavior;
346
+ /** Customize the ribbon toolbar. Called once at mount with a `RibbonApi` to
347
+ * reorder/remove built-in tabs/groups/buttons (by id — discover them with
348
+ * `api.tabs()/groups()/items()`) and add your own tabs, groups, and buttons.
349
+ * A custom button's `onClick` gets a `RibbonActionContext` (the editor handle +
350
+ * `getSelection`/`insertText`/`emit`/`registerCleanup`) — for macros, config
351
+ * popups, and informational popups. */
352
+ customizeRibbon?: CustomizeRibbon;
353
+ /** Track first-load progress so you can show a loader while the big chunks
354
+ * stream. Fires for the editor JS chunk download (`phase: "bundle"`,
355
+ * indeterminate) and the bundled font fetch (`phase: "fonts"`, the dominant
356
+ * ~9 MB cost — a smooth, size-weighted bar), then once at `phase: "ready"`
357
+ * with `percent: 1`. Read `percent` (0..1, monotonic) to drive a progress bar. */
358
+ onLoadProgress?: (progress: LoadProgress) => void;
359
+ }
360
+
361
+ /** Initial view-chrome state (see WordCanvasOptions.view). Every field is
362
+ * optional; omit one to keep its built-in default. */
363
+ export interface WordCanvasViewOptions {
364
+ /** Show the horizontal ruler. Default true (always hidden in readonly). */
365
+ ruler?: boolean;
366
+ /** Show the vertical ruler. Default true (always hidden in readonly). */
367
+ verticalRuler?: boolean;
368
+ /** Show the drawing-grid overlay on every page. Default false. */
369
+ grid?: boolean;
370
+ /** Snap dragged anchored objects to the grid. Default false. */
371
+ snapToGrid?: boolean;
372
+ /** Grid step in document px (96dpi). Default 24 (1/4 inch). */
373
+ gridSpacingPx?: number;
374
+ /** Show non-printing formatting marks (spaces, tabs, paragraph ends, line
375
+ * breaks) on open. Default false. */
376
+ formattingMarks?: boolean;
377
+ /** Open the Outline / navigation pane (left drawer). Default true. */
378
+ outline?: boolean;
379
+ /** Open the Bookmarks panel. Default false. */
380
+ bookmarks?: boolean;
381
+ /** Open the Review pane (track changes + comments). Default false. */
382
+ reviewPane?: boolean;
383
+ /** Open the Activity panel (online only — who edited & when). Default false. */
384
+ activity?: boolean;
385
+ /** Show the ribbon toolbar. Default true (always hidden in readonly). When
386
+ * false the editor stays fully editable but chromeless. */
387
+ toolbar?: boolean;
388
+ /** Start with the ribbon body collapsed (tab strip stays). Default false. */
389
+ ribbonCollapsed?: boolean;
390
+ /** Show the status bar (page/word count + zoom). Default true. */
391
+ statusBar?: boolean;
392
+ /** Show the File ▸ Export **PDF** button. Default true. Set false when the
393
+ * embedder ships its own export/save pipeline (e.g. via `onSave` or the
394
+ * `exportPdf()` method) and doesn't want the built-in button. */
395
+ exportPdf?: boolean;
396
+ /** Show the File ▸ Export **DOCX** button. Default true. Set false when the
397
+ * embedder ships its own export/save pipeline (e.g. via `onSave` or the
398
+ * `exportDocx()` method) and doesn't want the built-in button. */
399
+ exportDocx?: boolean;
400
+ /** Initial presentational zoom (1 = 100%, clamped to [0.25, 5]). Default 1. */
401
+ zoom?: number;
402
+ }
403
+
404
+ /** First-load progress (see WordCanvasOptions.onLoadProgress). */
405
+ export interface LoadProgress {
406
+ /** Coarse stage: "bundle" = downloading the editor JS chunk (indeterminate —
407
+ * a dynamic import can't be byte-measured); "fonts" = fetching the bundled
408
+ * fonts (measurable); "ready" = mount complete. */
409
+ phase: "bundle" | "fonts" | "ready";
410
+ /** Overall startup progress, 0..1, monotonic. Drive a progress bar with this. */
411
+ percent: number;
412
+ /** Bytes fetched / total for the current measurable phase (fonts). Both 0 when
413
+ * the phase is indeterminate (bundle). Informational. */
414
+ loaded: number;
415
+ total: number;
416
+ }
417
+
418
+ /** Opt-in WebMCP agent tooling (see WordCanvasOptions.agentTools). */
419
+ export interface AgentToolsOptions {
420
+ /** Which tool buckets to register. Default: all three.
421
+ * - `read` — read & inspect (get_document, get_selection, search_document,
422
+ * inspect_layout, get_document_stats);
423
+ * - `suggest` — set_mode, comments, tracked-change suggestions, accept/reject;
424
+ * - `edit` — replace_text, insert_text, format_text, set_alignment,
425
+ * select_range, undo/redo, set_document. */
426
+ capabilities?: ("read" | "suggest" | "edit")[];
427
+ /** Optional prefix so several editors on one page don't collide
428
+ * (e.g. "doc1" → "doc1_get_document"). */
429
+ name?: string;
430
+ }
431
+
432
+ /** Request passed to a custom-field resolver (see WordCanvasOptions.resolveField). */
433
+ export interface FieldResolveRequest {
434
+ /** The field's id within the document. */
435
+ fieldId: string;
436
+ /** Field keyword, uppercased (e.g. "MYCHART"). */
437
+ name: string;
438
+ /** The verbatim field instruction (e.g. ` MYCHART "sales-2026" `). */
439
+ instruction: string;
440
+ /** The collaboration doc id, when the session has one. */
441
+ docId?: string;
442
+ }
443
+
444
+ /** What a field resolver returns:
445
+ * - a full **.docx** (ArrayBuffer / Uint8Array / Blob) — RECOMMENDED: imported
446
+ * through the same pipeline as opening a document, so images, tables, lists and
447
+ * styles come through (media survives export);
448
+ * - or an **OOXML fragment string** (w:p / w:tbl, or a w:document) for simple,
449
+ * text-only results (no embedded media). */
450
+ export type FieldResult = string | ArrayBuffer | Uint8Array | Blob;
451
+
452
+ /** Host hook producing a field's result for a resolve request. */
453
+ export type FieldResolver = (req: FieldResolveRequest) => Promise<FieldResult>;
454
+
455
+ /** The file format an export/save produces. */
456
+ export type SaveFormat = "docx" | "pdf";
457
+
458
+ /** A deduplicated lossy-mapping note from an export. `count` = times it fired. */
459
+ export interface ExportWarning {
460
+ code: string;
461
+ detail?: string;
462
+ count: number;
463
+ }
464
+
465
+ /** Payload handed to a host `onSave` handler when the user triggers an export
466
+ * while `onSave` is configured (see WordCanvasOptions.onSave). */
467
+ export interface SaveEvent {
468
+ /** The exported file as a Blob with the correct MIME type set. */
469
+ blob: Blob;
470
+ /** The same file content as raw bytes (handy for FormData / a Node Buffer). */
471
+ bytes: Uint8Array;
472
+ /** Which format the user exported. */
473
+ format: SaveFormat;
474
+ /** Deduplicated lossy-mapping notes from the export (usually empty). */
475
+ warnings: ExportWarning[];
476
+ }
477
+
478
+ /** Host hook invoked instead of the built-in download when the user exports. */
479
+ export type SaveHandler = (event: SaveEvent) => void | Promise<void>;
480
+
481
+ /** What to render into a child-document surface (see WordCanvas.createChild). */
482
+ export type ChildContent =
483
+ | { kind: "blocks"; blocks: Block[] }
484
+ | { kind: "fragment"; fragment: { blocks: { runs: Run[]; style: ParaStyle }[]; inline?: boolean } }
485
+ | { kind: "runs"; runs: Run[]; paraStyle?: ParaStyle }
486
+ /** Body OOXML (w:p / w:tbl, or a w:document). Media-free (no images by r:id). */
487
+ | { kind: "ooxml"; ooxml: string }
488
+ /** A real sample of a named style ("AaBbCc" in the style's resolved formatting). */
489
+ | { kind: "styleSample"; styleId: string; sampleText?: string };
490
+
491
+ export interface ChildRenderOptions {
492
+ /** Layout/wrap width in CSS px. Default: target.clientWidth. */
493
+ widthPx?: number;
494
+ /** Child section margins (all sides), CSS px. Default 0. */
495
+ padding?: number;
496
+ /** Cap the displayed height; content beyond it is clipped. */
497
+ maxHeightPx?: number;
498
+ /** Fixed presentational scale (1 = 100%). Ignored when `fit` is set. */
499
+ zoom?: number;
500
+ /** Auto-scale the content to fit `widthPx` × `maxHeightPx` (compact swatches). */
501
+ fit?: boolean;
502
+ }
503
+
504
+ /** A live interactive editor over a child slice (canvas-native editing). */
505
+ export interface ChildEditorHandle {
506
+ /** The edited content as model blocks (hand back to splice into the parent). */
507
+ getBlocks(): Block[];
508
+ getDocument(): Document;
509
+ /** Insert an image at the caret. The bytes are registered in the parent
510
+ * document's shared media store (content-addressed), so the image renders here,
511
+ * survives serialize/export, and resolves after commit-back. Dimensions default
512
+ * to the image's natural size. */
513
+ insertImage(bytes: Uint8Array, mime: string, opts?: { widthPx?: number; heightPx?: number }): Promise<void>;
514
+ destroy(): void;
515
+ }
516
+
517
+ /** A lightweight sibling document that shares the parent editor's live styles,
518
+ * fonts and theme and renders/edits a content slice on canvas. */
519
+ export interface ChildDocument {
520
+ /** Paint a static preview of `content` into `target`. Safe to call repeatedly. */
521
+ render(target: HTMLElement, content: ChildContent, opts?: ChildRenderOptions): void;
522
+ /** Mount an interactive editor over `content` inside `target`. */
523
+ mountEditor(target: HTMLElement, content: ChildContent, opts?: ChildRenderOptions): ChildEditorHandle;
524
+ /** Tear down every surface/editor this child created. */
525
+ destroy(): void;
526
+ }
527
+
528
+ /** Event name → payload, for `on(...)`/`off(...)`. */
529
+ export interface WordCanvasEventMap {
530
+ ready: Record<string, never>;
531
+ shared: { docId: string; url: string };
532
+ userEntered: { siteId: string; user?: UserInfo };
533
+ userLeave: { siteId: string; user?: UserInfo };
534
+ presence: { participants: Participant[] };
535
+ /** The editor mode changed (picker or setMode). */
536
+ modeChanged: { mode: EditMode };
537
+ /** The review overlay changed (suggestion/comment added, resolved, rebased).
538
+ * Carries the full layer so panels can re-render. */
539
+ reviewChanged: { review: ReviewLayer };
540
+ /** A custom ribbon button emitted an event via `ctx.emit(name, payload)`. */
541
+ custom: { name: string; payload?: unknown };
542
+ }
543
+
544
+ /** Handle resolved once the editor is mounted (via `whenReady()`). */
545
+ export interface EditorHandle {
546
+ /** Snapshot of the current document (plain data). */
547
+ getDocument(): Document;
548
+ /** Create a child document sharing this editor's live styles/fonts/theme. */
549
+ createChild(): ChildDocument;
550
+ /** Replace the open document with a programmatically-built one (e.g. a
551
+ * DocumentBuilder result). Cloned; drops undo history and any live collab
552
+ * session; preserves zoom + scroll. */
553
+ setDocument(doc: Document): void;
554
+ /** Open a .docx (auto-publishes when online); resolves when loaded. */
555
+ openDocx(file: File | ArrayBuffer): Promise<void>;
556
+ /** Export the current document to a .docx Blob (track changes baked to the
557
+ * original baseline, matching the toolbar's Export). For a custom Save button. */
558
+ exportDocx(): Promise<Blob>;
559
+ /** Export the current document to a PDF Blob (see `exportDocx`). */
560
+ exportPdf(): Promise<Blob>;
561
+ /** Publish the current document and resolve its shareable link (online only). */
562
+ share(): Promise<string>;
563
+ getDocId(): string | null;
564
+ getShareLink(): string | null;
565
+ /** The current selection/caret, or null when the editor isn't focused. */
566
+ getSelection(): DocSelection | null;
567
+ /** Insert plain text at the caret, replacing any selection. */
568
+ insertText(text: string): void;
569
+ // ---- review layer (track changes + comments) ----------------------------
570
+ /** The current editor mode. */
571
+ getMode(): EditMode;
572
+ /** Switch mode; returns false if the mode isn't allowed. */
573
+ setMode(mode: EditMode): boolean;
574
+ /** Snapshot of the review overlay (suggestions + comment threads). */
575
+ getReview(): ReviewLayer;
576
+ /** The effective @-mentionable roster (configured base + live editors). */
577
+ getKnownUsers(): UserInfo[];
578
+ /** Replace the configured base roster (live editors stay merged on top). */
579
+ setKnownUsers(users: UserInfo[]): void;
580
+ acceptSuggestion(id: string): void;
581
+ rejectSuggestion(id: string): void;
582
+ acceptAllSuggestions(): void;
583
+ rejectAllSuggestions(): void;
584
+ /** Add a comment thread anchored to the current selection. Returns the thread
585
+ * id, or null if there's no selection. */
586
+ addComment(body: Fragment, mentions?: UserInfo[]): string | null;
587
+ replyToComment(threadId: string, body: Fragment, mentions?: UserInfo[]): void;
588
+ resolveThread(threadId: string, resolved?: boolean): void;
589
+ destroy(): void;
590
+ }
591
+
592
+ export declare class WordCanvas {
593
+ constructor(opts: WordCanvasOptions);
594
+ /** Subscribe to a collaboration event. Returns an unsubscribe function. */
595
+ on<E extends keyof WordCanvasEventMap>(event: E, handler: (data: WordCanvasEventMap[E]) => void): () => void;
596
+ /** Unsubscribe a handler previously passed to `on()`. */
597
+ off<E extends keyof WordCanvasEventMap>(event: E, handler: (data: WordCanvasEventMap[E]) => void): void;
598
+ /** Resolves once the editor is mounted and ready. */
599
+ whenReady(): Promise<EditorHandle>;
600
+ /** Create a child document that shares this editor's live styles, fonts and
601
+ * theme — render a real, document-styled preview of a content slice onto a
602
+ * canvas (instead of an HTML approximation), or mount a canvas-native editor
603
+ * over a slice. Returned synchronously; render() before ready is buffered.
604
+ * (mountEditor() requires the editor to be ready — await whenReady() first.) */
605
+ createChild(): ChildDocument;
606
+ /** Open a .docx. When online, auto-publishes it and surfaces a share link. */
607
+ openDocx(file: File | ArrayBuffer): Promise<void>;
608
+ /** Export the current document to a .docx Blob — track changes baked to the
609
+ * original baseline, exactly like the toolbar's Export. Wire it to your own
610
+ * Save button and POST it anywhere. Resolves once the editor is ready. */
611
+ exportDocx(): Promise<Blob>;
612
+ /** Export the current document to a PDF Blob (see `exportDocx`). */
613
+ exportPdf(): Promise<Blob>;
614
+ /** Replace the open document with a programmatically-built one (e.g. a
615
+ * DocumentBuilder result). The input is cloned. Like openDocx, this starts a
616
+ * NEW document: undo history and any live collab session are dropped (the
617
+ * next share() forks). Zoom and scroll are preserved, so calling this on
618
+ * every data change gives a stable live preview. */
619
+ setDocument(doc: Document): Promise<void>;
620
+ /** Publish the current document and resolve its shareable link (online only). */
621
+ share(): Promise<string>;
622
+ // ---- review layer (track changes + comments) ----------------------------
623
+ /** Current editor mode. Returns null before the editor is ready. */
624
+ getMode(): EditMode | null;
625
+ /** Switch mode. Resolves to false if the mode isn't allowed (or not ready). */
626
+ setMode(mode: EditMode): Promise<boolean>;
627
+ /** Snapshot of the review overlay (suggestions + comment threads). */
628
+ getReview(): Promise<ReviewLayer>;
629
+ /** The effective @-mentionable roster (configured base + live editors). */
630
+ getKnownUsers(): Promise<UserInfo[]>;
631
+ /** Replace the configured base roster (live editors stay merged on top). */
632
+ setKnownUsers(users: UserInfo[]): Promise<void>;
633
+ acceptSuggestion(id: string): Promise<void>;
634
+ rejectSuggestion(id: string): Promise<void>;
635
+ acceptAllSuggestions(): Promise<void>;
636
+ rejectAllSuggestions(): Promise<void>;
637
+ /** Add a comment thread anchored to the current selection. Resolves to the
638
+ * thread id, or null if there's no selection. */
639
+ addComment(body: Fragment, mentions?: UserInfo[]): Promise<string | null>;
640
+ replyToComment(threadId: string, body: Fragment, mentions?: UserInfo[]): Promise<void>;
641
+ resolveThread(threadId: string, resolved?: boolean): Promise<void>;
642
+ /** Current selection/caret. Returns null before ready or when unfocused. */
643
+ getSelection(): DocSelection | null;
644
+ /** Insert plain text at the caret (replacing any selection). */
645
+ insertText(text: string): Promise<void>;
646
+ getDocId(): string | null;
647
+ getShareLink(): string | null;
648
+ destroy(): void;
649
+ }