@beyondwork/docx-react-component 1.0.1 → 1.0.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 (172) hide show
  1. package/README.md +44 -104
  2. package/package.json +50 -30
  3. package/src/README.md +85 -0
  4. package/src/api/README.md +22 -0
  5. package/src/api/public-types.ts +525 -0
  6. package/src/compare/diff-engine.ts +530 -0
  7. package/src/compare/export-redlines.ts +162 -0
  8. package/src/compare/snapshot.ts +37 -0
  9. package/src/component-inventory.md +99 -0
  10. package/src/core/README.md +10 -0
  11. package/src/core/commands/README.md +3 -0
  12. package/src/core/commands/formatting-commands.ts +161 -0
  13. package/src/core/commands/image-commands.ts +144 -0
  14. package/src/core/commands/index.ts +1013 -0
  15. package/src/core/commands/list-commands.ts +370 -0
  16. package/src/core/commands/review-commands.ts +108 -0
  17. package/src/core/commands/text-commands.ts +119 -0
  18. package/src/core/schema/README.md +3 -0
  19. package/src/core/schema/text-schema.ts +512 -0
  20. package/src/core/selection/README.md +3 -0
  21. package/src/core/selection/mapping.ts +238 -0
  22. package/src/core/selection/review-anchors.ts +94 -0
  23. package/src/core/state/README.md +3 -0
  24. package/src/core/state/editor-state.ts +580 -0
  25. package/src/core/state/text-transaction.ts +276 -0
  26. package/src/formats/xlsx/io/parse-shared-strings.ts +41 -0
  27. package/src/formats/xlsx/io/parse-sheet.ts +289 -0
  28. package/src/formats/xlsx/io/parse-styles.ts +57 -0
  29. package/src/formats/xlsx/io/parse-workbook.ts +75 -0
  30. package/src/formats/xlsx/io/xlsx-session.ts +306 -0
  31. package/src/formats/xlsx/model/cell.ts +189 -0
  32. package/src/formats/xlsx/model/sheet.ts +244 -0
  33. package/src/formats/xlsx/model/styles.ts +118 -0
  34. package/src/formats/xlsx/model/workbook.ts +449 -0
  35. package/src/index.ts +45 -0
  36. package/src/io/README.md +10 -0
  37. package/src/io/docx-session.ts +1763 -0
  38. package/src/io/export/README.md +3 -0
  39. package/src/io/export/export-session.ts +165 -0
  40. package/src/io/export/minimal-docx.ts +115 -0
  41. package/src/io/export/reattach-preserved-parts.ts +54 -0
  42. package/src/io/export/serialize-comments.ts +876 -0
  43. package/src/io/export/serialize-footnotes.ts +217 -0
  44. package/src/io/export/serialize-headers-footers.ts +200 -0
  45. package/src/io/export/serialize-main-document.ts +982 -0
  46. package/src/io/export/serialize-numbering.ts +97 -0
  47. package/src/io/export/serialize-revisions.ts +389 -0
  48. package/src/io/export/serialize-runtime-revisions.ts +265 -0
  49. package/src/io/export/serialize-tables.ts +147 -0
  50. package/src/io/export/split-review-boundaries.ts +194 -0
  51. package/src/io/normalize/README.md +3 -0
  52. package/src/io/normalize/normalize-text.ts +437 -0
  53. package/src/io/ooxml/README.md +3 -0
  54. package/src/io/ooxml/parse-comments.ts +779 -0
  55. package/src/io/ooxml/parse-complex-content.ts +287 -0
  56. package/src/io/ooxml/parse-fields.ts +438 -0
  57. package/src/io/ooxml/parse-footnotes.ts +403 -0
  58. package/src/io/ooxml/parse-headers-footers.ts +483 -0
  59. package/src/io/ooxml/parse-inline-media.ts +431 -0
  60. package/src/io/ooxml/parse-main-document.ts +1846 -0
  61. package/src/io/ooxml/parse-numbering.ts +425 -0
  62. package/src/io/ooxml/parse-revisions.ts +658 -0
  63. package/src/io/ooxml/parse-shapes.ts +271 -0
  64. package/src/io/ooxml/parse-tables.ts +568 -0
  65. package/src/io/ooxml/parse-theme.ts +314 -0
  66. package/src/io/ooxml/part-manifest.ts +136 -0
  67. package/src/io/ooxml/revision-boundaries.ts +351 -0
  68. package/src/io/opc/README.md +3 -0
  69. package/src/io/opc/corrupt-package.ts +166 -0
  70. package/src/io/opc/docx-package.ts +74 -0
  71. package/src/io/opc/package-reader.ts +325 -0
  72. package/src/io/opc/package-writer.ts +273 -0
  73. package/src/legal/bookmarks.ts +196 -0
  74. package/src/legal/cross-references.ts +356 -0
  75. package/src/legal/defined-terms.ts +203 -0
  76. package/src/model/README.md +3 -0
  77. package/src/model/canonical-document.ts +1911 -0
  78. package/src/model/cds-1.0.0.ts +196 -0
  79. package/src/model/snapshot.ts +393 -0
  80. package/src/preservation/README.md +3 -0
  81. package/src/preservation/markup-compatibility.ts +48 -0
  82. package/src/preservation/opaque-fragment-store.ts +89 -0
  83. package/src/preservation/opaque-region.ts +233 -0
  84. package/src/preservation/package-preservation.ts +120 -0
  85. package/src/preservation/preserved-part-manifest.ts +56 -0
  86. package/src/preservation/relationship-retention.ts +57 -0
  87. package/src/preservation/store.ts +185 -0
  88. package/src/review/README.md +16 -0
  89. package/src/review/store/README.md +3 -0
  90. package/src/review/store/comment-anchors.ts +70 -0
  91. package/src/review/store/comment-remapping.ts +154 -0
  92. package/src/review/store/comment-store.ts +331 -0
  93. package/src/review/store/comment-thread.ts +109 -0
  94. package/src/review/store/revision-actions.ts +394 -0
  95. package/src/review/store/revision-store.ts +303 -0
  96. package/src/review/store/revision-types.ts +168 -0
  97. package/src/review/store/runtime-comment-store.ts +43 -0
  98. package/src/runtime/README.md +3 -0
  99. package/src/runtime/ai-action-policy.ts +764 -0
  100. package/src/runtime/document-runtime.ts +967 -0
  101. package/src/runtime/read-only-diagnostics-runtime.ts +232 -0
  102. package/src/runtime/review-runtime.ts +44 -0
  103. package/src/runtime/revision-runtime.ts +107 -0
  104. package/src/runtime/session-capabilities.ts +138 -0
  105. package/src/runtime/surface-projection.ts +570 -0
  106. package/src/runtime/table-commands.ts +87 -0
  107. package/src/runtime/table-schema.ts +140 -0
  108. package/src/runtime/virtualized-rendering.ts +258 -0
  109. package/src/ui/README.md +30 -0
  110. package/src/ui/WordReviewEditor.tsx +1506 -0
  111. package/src/ui/comments/README.md +3 -0
  112. package/src/ui/compatibility/README.md +3 -0
  113. package/src/ui/editor-surface/README.md +3 -0
  114. package/src/ui/headless/comment-decoration-model.ts +124 -0
  115. package/src/ui/headless/revision-decoration-model.ts +128 -0
  116. package/src/ui/headless/selection-helpers.ts +34 -0
  117. package/src/ui/headless/use-editor-keyboard.ts +98 -0
  118. package/src/ui/review/README.md +3 -0
  119. package/src/ui/shared/revision-filters.ts +31 -0
  120. package/src/ui/status/README.md +3 -0
  121. package/src/ui/theme/README.md +3 -0
  122. package/src/ui/toolbar/README.md +3 -0
  123. package/src/ui-tailwind/chrome/tw-alert-banner.tsx +48 -0
  124. package/src/ui-tailwind/chrome/tw-selection-toolbar.tsx +44 -0
  125. package/src/ui-tailwind/chrome/tw-unsaved-modal.tsx +58 -0
  126. package/src/ui-tailwind/chrome/use-before-unload.ts +20 -0
  127. package/src/ui-tailwind/editor-surface/pm-command-bridge.ts +139 -0
  128. package/src/ui-tailwind/editor-surface/pm-decorations.ts +98 -0
  129. package/src/ui-tailwind/editor-surface/pm-position-map.ts +123 -0
  130. package/src/ui-tailwind/editor-surface/pm-schema.ts +452 -0
  131. package/src/ui-tailwind/editor-surface/pm-state-from-snapshot.ts +327 -0
  132. package/src/ui-tailwind/editor-surface/search-plugin.ts +157 -0
  133. package/src/ui-tailwind/editor-surface/tw-caret.tsx +12 -0
  134. package/src/ui-tailwind/editor-surface/tw-editor-surface.tsx +150 -0
  135. package/src/ui-tailwind/editor-surface/tw-inline-token.tsx +118 -0
  136. package/src/ui-tailwind/editor-surface/tw-opaque-block.tsx +52 -0
  137. package/src/ui-tailwind/editor-surface/tw-paragraph-block.tsx +151 -0
  138. package/src/ui-tailwind/editor-surface/tw-prosemirror-surface.tsx +215 -0
  139. package/src/ui-tailwind/editor-surface/tw-segment-view.tsx +111 -0
  140. package/src/ui-tailwind/editor-surface/tw-table-node-view.tsx +122 -0
  141. package/src/ui-tailwind/index.ts +61 -0
  142. package/src/ui-tailwind/review/tw-comment-sidebar.tsx +276 -0
  143. package/src/ui-tailwind/review/tw-health-panel.tsx +120 -0
  144. package/src/ui-tailwind/review/tw-review-rail.tsx +120 -0
  145. package/src/ui-tailwind/review/tw-revision-sidebar.tsx +164 -0
  146. package/src/ui-tailwind/status/tw-status-bar.tsx +58 -0
  147. package/src/ui-tailwind/theme/editor-theme.css +190 -0
  148. package/src/ui-tailwind/toolbar/tw-toolbar-icon-button.tsx +48 -0
  149. package/src/ui-tailwind/toolbar/tw-toolbar.tsx +231 -0
  150. package/src/ui-tailwind/tw-review-workspace.tsx +140 -0
  151. package/src/validation/README.md +3 -0
  152. package/src/validation/compatibility-engine.ts +317 -0
  153. package/src/validation/compatibility-report.ts +160 -0
  154. package/src/validation/diagnostics.ts +203 -0
  155. package/src/validation/import-diagnostics.ts +128 -0
  156. package/src/validation/low-priority-word-surfaces.ts +373 -0
  157. package/dist/chunk-32W6IVQE.js +0 -7725
  158. package/dist/chunk-32W6IVQE.js.map +0 -1
  159. package/dist/index.cjs +0 -23722
  160. package/dist/index.cjs.map +0 -1
  161. package/dist/index.d.cts +0 -7
  162. package/dist/index.d.ts +0 -7
  163. package/dist/index.js +0 -16011
  164. package/dist/index.js.map +0 -1
  165. package/dist/public-types-DqCURAz8.d.cts +0 -1152
  166. package/dist/public-types-DqCURAz8.d.ts +0 -1152
  167. package/dist/tailwind.cjs +0 -8295
  168. package/dist/tailwind.cjs.map +0 -1
  169. package/dist/tailwind.d.cts +0 -323
  170. package/dist/tailwind.d.ts +0 -323
  171. package/dist/tailwind.js +0 -553
  172. package/dist/tailwind.js.map +0 -1
@@ -0,0 +1,37 @@
1
+ import {
2
+ createCanonicalDocumentSignature,
3
+ projectCanonicalDocument,
4
+ type CanonicalDocument,
5
+ } from "../model/canonical-document.ts";
6
+
7
+ export interface DocumentVersionSnapshot {
8
+ snapshotVersion: "document-version-snapshot/1";
9
+ versionId: string;
10
+ name: string;
11
+ createdAt: string;
12
+ documentId: string;
13
+ documentSignature: string;
14
+ canonicalDocument: CanonicalDocument;
15
+ }
16
+
17
+ export interface CreateDocumentVersionSnapshotOptions {
18
+ versionId?: string;
19
+ name: string;
20
+ createdAt?: string;
21
+ }
22
+
23
+ export function createDocumentVersionSnapshot(
24
+ document: CanonicalDocument,
25
+ options: CreateDocumentVersionSnapshotOptions,
26
+ ): DocumentVersionSnapshot {
27
+ const canonicalDocument = projectCanonicalDocument(document);
28
+ return {
29
+ snapshotVersion: "document-version-snapshot/1",
30
+ versionId: options.versionId ?? `${canonicalDocument.docId}:${options.name}`,
31
+ name: options.name,
32
+ createdAt: options.createdAt ?? canonicalDocument.updatedAt,
33
+ documentId: canonicalDocument.docId,
34
+ documentSignature: createCanonicalDocumentSignature(canonicalDocument),
35
+ canonicalDocument,
36
+ };
37
+ }
@@ -0,0 +1,99 @@
1
+ # Component Inventory
2
+
3
+ This file is the source-owned inventory for the major subsystems in the active docx implementation.
4
+
5
+ Wave 0 established the scaffold and ownership boundaries. Wave 1 froze the contract surface for the editor-side components listed below. That promotion does not claim implementation completeness; it means the subsystem boundaries, contract artifacts, and proof expectations are now explicit enough for later docx waves to build against without reopening the architecture.
6
+
7
+ This inventory does not yet track:
8
+
9
+ - shared OOXML platform extraction as a separate source area
10
+ - a future xlsx runtime inventory
11
+ - future pdf work
12
+
13
+ ## Inventory Table
14
+
15
+ | Component | Current target | Primary paths | Scope in this repo phase | Contract and proof surfaces |
16
+ | --- | --- | --- | --- | --- |
17
+ | `canonical-document-model` | `contract-frozen` | `src/model/`, `src/api/` | Versioned canonical envelope, persisted snapshot shape, migration boundary, document metadata ownership | `docs/plans/waves/specs/wave-1-component-boundaries.md`, `docs/plans/waves/specs/wave-1-runtime-contracts.md`, schema docs, canonical JSON examples, model tests |
18
+ | `command-and-transaction-runtime` | `contract-frozen` | `src/core/`, `src/runtime/` | Deterministic commands, transactions, mapping, selection semantics, runtime mutation boundary | `docs/plans/waves/specs/wave-1-component-boundaries.md`, `docs/plans/waves/specs/wave-1-runtime-contracts.md`, command tests, mapping tests, state-transition proofs |
19
+ | `comments-and-anchor-mapping` | `contract-frozen` | `src/review/`, `src/core/selection/` | Comment threads, anchor remapping, review selectors, edit-safe anchor mapping policy | `docs/plans/waves/specs/wave-1-review-and-ui-contracts.md`, `docs/plans/waves/specs/wave-1-runtime-contracts.md`, anchor remap tests, threaded comment fixtures, review model docs |
20
+ | `tracked-changes-and-review-actions` | `contract-frozen` | `src/review/`, `src/ui/review/` | Revision records, display modes, accept/reject boundaries, review-oriented commands | `docs/plans/waves/specs/wave-1-review-and-ui-contracts.md`, revision fixtures, accept/reject tests, review-state mapping tests |
21
+ | `docx-import-and-normalization` | `contract-frozen` | `src/io/opc/`, `src/io/ooxml/`, `src/io/normalize/` | OPC opening, WordprocessingML parsing, normalization into canonical state, support classification inputs | `docs/plans/waves/specs/wave-1-ooxml-contracts.md`, `.docx` import fixtures, normalization tests, supported-feature mapping docs |
22
+ | `docx-export-and-serialization` | `contract-frozen` | `src/io/export/`, `src/io/opc/` | Regenerated OOXML parts, package writing, relationship integrity, supported-feature serialization | `docs/plans/waves/specs/wave-1-ooxml-contracts.md`, round-trip fixtures, export validation tests, serializer docs |
23
+ | `unsupported-ooxml-preservation` | `contract-frozen` | `src/preservation/`, `src/io/` | Opaque fragment capture, untouched package-part retention, reattachment policy, locked editing regions | `docs/plans/waves/specs/wave-1-ooxml-contracts.md`, preservation fixtures, fragment retention tests, export reattachment tests |
24
+ | `compatibility-and-word-validation` | `contract-frozen` | `src/validation/`, `src/ui/compatibility/`, `services/openxml-validator/` | Editor-side compatibility reporting, support classification, export-risk reporting, validator-service integration boundary | `docs/plans/waves/specs/wave-1-ooxml-contracts.md`, `docs/plans/waves/specs/wave-1-review-and-ui-contracts.md`, feature matrix, compatibility tests, Word reopen evidence |
25
+ | `react-editor-ui` | `contract-frozen` | `src/ui-tailwind/`, `src/ui/headless/`, `src/runtime/`, `src/api/` | Tailwind-based React shell with Radix UI primitives. Headless logic in `src/ui/headless/`. Legacy inline-CSSProperties components removed. | `docs/plans/waves/specs/wave-1-review-and-ui-contracts.md`, component tests, selection behavior checks, review-surface checks, token and theme checks |
26
+
27
+ ## Boundary Notes
28
+
29
+ ### Canonical data stays outside React
30
+
31
+ - `src/model/`, `src/core/`, `src/review/`, `src/io/`, `src/preservation/`, and `src/validation/` should remain framework-light and serializable.
32
+ - The DOM is a rendering target, not canonical state.
33
+
34
+ ### Runtime is the mutation choke point
35
+
36
+ - UI surfaces call into `src/runtime/`.
37
+ - Commands and transactions are owned by `src/core/`.
38
+ - Review actions remain explicit state transitions rather than implicit UI side effects.
39
+
40
+ ### DOCX handling is package-first
41
+
42
+ - `src/io/opc/` owns ZIP/package and relationship handling.
43
+ - `src/io/ooxml/` owns WordprocessingML parsing.
44
+ - `src/preservation/` owns unsupported-content retention and untouched package parts.
45
+
46
+ ### Broader repo work is planned, not landed
47
+
48
+ - The repo now documents a target source layout under `src/platform/` and `src/formats/*`, but this file still inventories the landed docx-first tree.
49
+ - Shared platform and xlsx architecture are currently defined in docs, not in source ownership tables here.
50
+
51
+ ### Review semantics are first-class
52
+
53
+ - Comments and tracked changes are not annotations layered loosely on top of text rendering.
54
+ - Anchors and revisions must stay mappable through edits and export.
55
+
56
+ ## Service-Backed Wave 0 Components
57
+
58
+ The following components have a higher Wave 0 target because they already have repo-landed scaffolds:
59
+
60
+ | Component | Wave 0 target | Primary paths | Landed scaffold evidence |
61
+ | --- | --- | --- | --- |
62
+ | `railway-test-harness` | `repo-landed` | `services/react-word-editor/` | Next.js service package, layout shell, harness dashboard stub, Dockerfile, Railway-oriented README |
63
+ | `openxml-sdk-validator-service` | `repo-landed` | `services/openxml-validator/` | .NET 8 minimal API, `GET /health`, `POST /validate`, Dockerfile, SDK-backed validation README |
64
+
65
+ ## Out Of Scope For Wave 0
66
+
67
+ - No canonical schema implementation yet
68
+ - No command engine implementation yet
69
+ - No comment or revision persistence yet
70
+ - No OOXML transformer or serializer yet
71
+ - No production `WordReviewEditor` React runtime yet
72
+ - No live Railway persistence or private networking integration yet
73
+
74
+ Those surfaces move in later waves. This inventory only establishes where they belong and what proof each promotion will require.
75
+
76
+ ## Contract Freeze References
77
+
78
+ Wave 1 froze the owned architecture in the following durable spec set:
79
+
80
+ - `docs/plans/waves/design/wave-1-a1.md`
81
+ - `docs/plans/waves/specs/wave-1-component-boundaries.md`
82
+ - `docs/plans/waves/specs/wave-1-runtime-contracts.md`
83
+ - `docs/plans/waves/specs/wave-1-ooxml-contracts.md`
84
+ - `docs/plans/waves/specs/wave-1-review-and-ui-contracts.md`
85
+
86
+ ## Future Source Direction
87
+
88
+ Target broader layout:
89
+
90
+ ```text
91
+ src/
92
+ platform/
93
+ formats/
94
+ docx/
95
+ xlsx/
96
+ pdf/
97
+ ```
98
+
99
+ That future layout is a planning direction only. Do not treat it as a landed source move until the actual implementation is reorganized.
@@ -0,0 +1,10 @@
1
+ # Core
2
+
3
+ Commands, transactions, selection, mapping, schema, and deterministic state transitions belong here.
4
+
5
+ Key subdirectories:
6
+
7
+ - `schema/`
8
+ - `state/`
9
+ - `commands/`
10
+ - `selection/`
@@ -0,0 +1,3 @@
1
+ # Core Commands
2
+
3
+ Command handlers, transaction builders, and editor mutation policies belong here.
@@ -0,0 +1,161 @@
1
+ /**
2
+ * ProseMirror formatting commands for the editor surface schema.
3
+ *
4
+ * Each command follows the standard ProseMirror command signature:
5
+ * (state, dispatch?) => boolean
6
+ *
7
+ * Toggle commands use the ProseMirror toggleMark helper.
8
+ * Set commands for value-bearing marks (font, size, color) apply the mark
9
+ * over the current selection, or remove it when the value is null.
10
+ * The setAlignment command sets the `alignment` attr on paragraph nodes
11
+ * that intersect the current selection.
12
+ *
13
+ * These commands operate on the `editorSchema` live surface. In the
14
+ * current architecture the runtime is the canonical document authority;
15
+ * these commands are designed to be used with the PM view's `dispatch`
16
+ * so that mark changes are reflected on the live surface immediately.
17
+ */
18
+
19
+ import { toggleMark } from "prosemirror-commands";
20
+ import type { Command } from "prosemirror-state";
21
+ import type { MarkType, Schema } from "prosemirror-model";
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // Toggle commands (boolean marks – no attrs)
25
+ // ---------------------------------------------------------------------------
26
+
27
+ export function makeToggleBold(schema: Schema): Command {
28
+ return toggleMark(schema.marks.bold);
29
+ }
30
+
31
+ export function makeToggleItalic(schema: Schema): Command {
32
+ return toggleMark(schema.marks.italic);
33
+ }
34
+
35
+ export function makeToggleUnderline(schema: Schema): Command {
36
+ return toggleMark(schema.marks.underline);
37
+ }
38
+
39
+ export function makeToggleStrikethrough(schema: Schema): Command {
40
+ return toggleMark(schema.marks.strikethrough);
41
+ }
42
+
43
+ export function makeToggleSuperscript(schema: Schema): Command {
44
+ return toggleMark(schema.marks.superscript);
45
+ }
46
+
47
+ export function makeToggleSubscript(schema: Schema): Command {
48
+ return toggleMark(schema.marks.subscript);
49
+ }
50
+
51
+ export function makeToggleSmallCaps(schema: Schema): Command {
52
+ return toggleMark(schema.marks.small_caps);
53
+ }
54
+
55
+ export function makeToggleAllCaps(schema: Schema): Command {
56
+ return toggleMark(schema.marks.all_caps);
57
+ }
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // Set commands (value-bearing marks)
61
+ // ---------------------------------------------------------------------------
62
+
63
+ /**
64
+ * Apply or remove a value-bearing mark over the current selection.
65
+ * When `value` is null the mark is removed; otherwise it is added with the
66
+ * given attribute key set to `value`.
67
+ */
68
+ function makeSetValueMark(
69
+ markType: MarkType,
70
+ attrKey: string,
71
+ value: string | number | null,
72
+ ): Command {
73
+ return (state, dispatch) => {
74
+ const { from, to, empty } = state.selection;
75
+ if (empty) return false;
76
+ if (!dispatch) return true;
77
+
78
+ const tr = state.tr;
79
+ if (value === null) {
80
+ tr.removeMark(from, to, markType);
81
+ } else {
82
+ const mark = markType.create({ [attrKey]: value });
83
+ tr.addMark(from, to, mark);
84
+ }
85
+ dispatch(tr);
86
+ return true;
87
+ };
88
+ }
89
+
90
+ export function makeSetFontFamily(schema: Schema, family: string | null): Command {
91
+ return makeSetValueMark(schema.marks.font_family, "family", family);
92
+ }
93
+
94
+ export function makeSetFontSize(schema: Schema, size: number | null): Command {
95
+ return makeSetValueMark(schema.marks.font_size, "size", size);
96
+ }
97
+
98
+ export function makeSetTextColor(schema: Schema, color: string | null): Command {
99
+ return makeSetValueMark(schema.marks.text_color, "color", color);
100
+ }
101
+
102
+ export function makeSetHighlight(schema: Schema, color: string | null): Command {
103
+ return makeSetValueMark(schema.marks.highlight, "color", color);
104
+ }
105
+
106
+ // ---------------------------------------------------------------------------
107
+ // Paragraph alignment
108
+ // ---------------------------------------------------------------------------
109
+
110
+ export type Alignment = "left" | "center" | "right" | "justify";
111
+
112
+ /**
113
+ * Set the `alignment` attribute on every paragraph node that intersects
114
+ * the current selection. Pass `null` to clear the alignment.
115
+ */
116
+ export function makeSetAlignment(schema: Schema, alignment: Alignment | null): Command {
117
+ return (state, dispatch) => {
118
+ const { from, to } = state.selection;
119
+ if (!dispatch) return true;
120
+
121
+ const tr = state.tr;
122
+ let applied = false;
123
+ state.doc.nodesBetween(from, to, (node, pos) => {
124
+ if (node.type === schema.nodes.paragraph) {
125
+ tr.setNodeMarkup(pos, undefined, { ...node.attrs, alignment });
126
+ applied = true;
127
+ }
128
+ });
129
+
130
+ if (!applied) return false;
131
+ dispatch(tr);
132
+ return true;
133
+ };
134
+ }
135
+
136
+ // ---------------------------------------------------------------------------
137
+ // Mark query helpers
138
+ // ---------------------------------------------------------------------------
139
+
140
+ /**
141
+ * Returns true if every character in the selection has the given mark active.
142
+ * When the selection is collapsed, checks the stored marks at the cursor.
143
+ */
144
+ export function isMarkActive(schema: Schema, markName: keyof typeof schema.marks, state: import("prosemirror-state").EditorState): boolean {
145
+ const markType = schema.marks[markName];
146
+ if (!markType) return false;
147
+
148
+ const { from, to, empty } = state.selection;
149
+ if (empty) {
150
+ return Boolean(markType.isInSet(state.storedMarks ?? state.selection.$from.marks()));
151
+ }
152
+
153
+ let active = true;
154
+ state.doc.nodesBetween(from, to, (node) => {
155
+ if (node.isText && !markType.isInSet(node.marks)) {
156
+ active = false;
157
+ return false;
158
+ }
159
+ });
160
+ return active;
161
+ }
@@ -0,0 +1,144 @@
1
+ import {
2
+ cloneParagraphProperties,
3
+ cloneStoryUnit,
4
+ parseTextStory,
5
+ serializeTextStory,
6
+ type TextStory,
7
+ } from "../schema/text-schema.ts";
8
+ import { createSelectionSnapshot, type CanonicalDocumentEnvelope, type SelectionSnapshot } from "../state/editor-state.ts";
9
+ import { TextTransactionError } from "../state/text-transaction.ts";
10
+ import type { TransactionMapping } from "../selection/mapping.ts";
11
+ import type { MediaItem } from "../../model/canonical-document.ts";
12
+
13
+ export interface ImageCommandContext {
14
+ timestamp: string;
15
+ altText?: string;
16
+ }
17
+
18
+ export interface InsertImageResult {
19
+ document: CanonicalDocumentEnvelope;
20
+ selection: SelectionSnapshot;
21
+ mapping: TransactionMapping;
22
+ mediaId: string;
23
+ }
24
+
25
+ /**
26
+ * Insert an image into the document at the current selection.
27
+ *
28
+ * Registers a MediaItem in the catalog with the supplied mimeType and
29
+ * optional dimensions, then inserts an image unit into the text story.
30
+ * Binary data is NOT stored in the canonical document — callers are
31
+ * responsible for persisting it to an external media store.
32
+ */
33
+ export function insertImage(
34
+ document: CanonicalDocumentEnvelope,
35
+ selection: SelectionSnapshot,
36
+ data: Uint8Array | string,
37
+ mimeType: string,
38
+ width?: number,
39
+ height?: number,
40
+ context: ImageCommandContext = { timestamp: new Date().toISOString() },
41
+ ): InsertImageResult {
42
+ const story = parseTextStory(document.content);
43
+ const from = Math.min(selection.anchor, selection.head);
44
+ const to = Math.max(selection.anchor, selection.head);
45
+
46
+ if (from > story.size || to > story.size) {
47
+ throw new TextTransactionError(
48
+ "invalid_selection",
49
+ `Selection ${from}-${to} exceeds story size ${story.size}.`,
50
+ );
51
+ }
52
+
53
+ // Reject insertions whose replacement range crosses protected content.
54
+ const rangeUnits = story.units.slice(from, to);
55
+ const protectedUnit = rangeUnits.find(
56
+ (unit) =>
57
+ unit.kind === "opaque_inline" ||
58
+ unit.kind === "opaque_block" ||
59
+ unit.kind === "image",
60
+ );
61
+ if (protectedUnit) {
62
+ throw new TextTransactionError(
63
+ "unsupported_content",
64
+ `Image insertion range crosses protected ${protectedUnit.kind} content.`,
65
+ );
66
+ }
67
+
68
+ const ext = mimeTypeToExtension(mimeType);
69
+ const timestamp = context.timestamp.replace(/[^0-9]/g, "").slice(0, 14);
70
+ const mediaId = `media:img-${timestamp}`;
71
+ const packagePartName = `/word/media/${mediaId.replace("media:", "")}.${ext}`;
72
+
73
+ const mediaItem: MediaItem = {
74
+ mediaId,
75
+ contentType: mimeType,
76
+ filename: `${mediaId.replace("media:", "")}.${ext}`,
77
+ packagePartName,
78
+ ...(context.altText ? { altText: context.altText } : {}),
79
+ };
80
+
81
+ const existingItems =
82
+ document.media && "items" in document.media
83
+ ? (document.media as { items: Record<string, MediaItem> }).items
84
+ : {};
85
+
86
+ const updatedMedia = {
87
+ items: {
88
+ ...existingItems,
89
+ [mediaId]: mediaItem,
90
+ },
91
+ };
92
+
93
+ const nextUnits = [
94
+ ...story.units.slice(0, from).map(cloneStoryUnit),
95
+ {
96
+ kind: "image" as const,
97
+ mediaId,
98
+ ...(context.altText ? { altText: context.altText } : {}),
99
+ },
100
+ ...story.units.slice(to).map(cloneStoryUnit),
101
+ ];
102
+
103
+ const nextStory: TextStory = {
104
+ firstParagraph: cloneParagraphProperties(story.firstParagraph),
105
+ units: nextUnits,
106
+ size: nextUnits.length,
107
+ };
108
+
109
+ const caret = from + 1;
110
+
111
+ return {
112
+ document: {
113
+ ...document,
114
+ updatedAt: context.timestamp,
115
+ media: updatedMedia,
116
+ content: serializeTextStory(nextStory),
117
+ },
118
+ selection: createSelectionSnapshot(caret, caret),
119
+ mapping: {
120
+ steps: [{ from, to, insertSize: 1 }],
121
+ },
122
+ mediaId,
123
+ };
124
+ }
125
+
126
+ function mimeTypeToExtension(mimeType: string): string {
127
+ switch (mimeType.toLowerCase()) {
128
+ case "image/png":
129
+ return "png";
130
+ case "image/jpeg":
131
+ case "image/jpg":
132
+ return "jpg";
133
+ case "image/gif":
134
+ return "gif";
135
+ case "image/webp":
136
+ return "webp";
137
+ case "image/svg+xml":
138
+ return "svg";
139
+ case "image/bmp":
140
+ return "bmp";
141
+ default:
142
+ return "bin";
143
+ }
144
+ }