docxkeun 0.1.3 → 0.3.0

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 (199) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +166 -16
  3. package/dist/api/editor.d.ts +231 -7
  4. package/dist/api/editor.js +1125 -26
  5. package/dist/api/headers.d.ts +51 -0
  6. package/dist/api/headers.js +133 -0
  7. package/dist/api/index.d.ts +6 -1
  8. package/dist/api/index.js +4 -1
  9. package/dist/api/lists.d.ts +37 -0
  10. package/dist/api/lists.js +132 -0
  11. package/dist/api/parts.js +1 -0
  12. package/dist/api/positions.js +1 -0
  13. package/dist/api/revisions.d.ts +61 -0
  14. package/dist/api/revisions.js +401 -0
  15. package/dist/api/selection.d.ts +57 -0
  16. package/dist/api/selection.js +91 -0
  17. package/dist/api/tables.d.ts +60 -0
  18. package/dist/api/tables.js +138 -0
  19. package/dist/charts/color.d.ts +45 -0
  20. package/dist/charts/color.js +322 -0
  21. package/dist/charts/format.d.ts +12 -0
  22. package/dist/charts/format.js +459 -0
  23. package/dist/charts/index.d.ts +11 -0
  24. package/dist/charts/index.js +8 -0
  25. package/dist/charts/model.d.ts +225 -0
  26. package/dist/charts/model.js +758 -0
  27. package/dist/charts/outline.d.ts +17 -0
  28. package/dist/charts/outline.js +214 -0
  29. package/dist/charts/render.d.ts +20 -0
  30. package/dist/charts/render.js +1772 -0
  31. package/dist/drawing/arrows.d.ts +37 -0
  32. package/dist/drawing/arrows.js +99 -0
  33. package/dist/drawing/formula.d.ts +40 -0
  34. package/dist/drawing/formula.js +159 -0
  35. package/dist/drawing/geometry.d.ts +61 -0
  36. package/dist/drawing/geometry.js +286 -0
  37. package/dist/drawing/index.d.ts +12 -0
  38. package/dist/drawing/index.js +8 -0
  39. package/dist/drawing/presets.d.ts +72 -0
  40. package/dist/drawing/presets.js +2874 -0
  41. package/dist/fonts/shaping/apply.d.ts +94 -0
  42. package/dist/fonts/shaping/apply.js +349 -0
  43. package/dist/fonts/shaping/arabic.d.ts +28 -0
  44. package/dist/fonts/shaping/arabic.js +235 -0
  45. package/dist/fonts/shaping/buffer.d.ts +53 -0
  46. package/dist/fonts/shaping/buffer.js +95 -0
  47. package/dist/fonts/shaping/gdef.d.ts +30 -0
  48. package/dist/fonts/shaping/gdef.js +66 -0
  49. package/dist/fonts/shaping/gpos.d.ts +86 -0
  50. package/dist/fonts/shaping/gpos.js +428 -0
  51. package/dist/fonts/shaping/gsub.d.ts +65 -0
  52. package/dist/fonts/shaping/gsub.js +313 -0
  53. package/dist/fonts/shaping/index.d.ts +32 -0
  54. package/dist/fonts/shaping/index.js +402 -0
  55. package/dist/fonts/shaping/indic.d.ts +6 -0
  56. package/dist/fonts/shaping/indic.js +805 -0
  57. package/dist/fonts/shaping/layout-common.d.ts +124 -0
  58. package/dist/fonts/shaping/layout-common.js +349 -0
  59. package/dist/fonts/shaping/plan.d.ts +87 -0
  60. package/dist/fonts/shaping/plan.js +152 -0
  61. package/dist/fonts/shaping/scripts.d.ts +26 -0
  62. package/dist/fonts/shaping/scripts.js +160 -0
  63. package/dist/fonts/shaping/shaper.d.ts +23 -0
  64. package/dist/fonts/shaping/shaper.js +5 -0
  65. package/dist/fonts/shaping/unicode.d.ts +34 -0
  66. package/dist/fonts/shaping/unicode.js +138 -0
  67. package/dist/images/bmp.d.ts +9 -0
  68. package/dist/images/bmp.js +234 -0
  69. package/dist/images/gif.d.ts +9 -0
  70. package/dist/images/gif.js +215 -0
  71. package/dist/images/index.d.ts +18 -0
  72. package/dist/images/index.js +63 -0
  73. package/dist/images/png-encode.d.ts +4 -0
  74. package/dist/images/png-encode.js +73 -0
  75. package/dist/images/size.d.ts +10 -0
  76. package/dist/images/size.js +83 -0
  77. package/dist/images/tiff.d.ts +14 -0
  78. package/dist/images/tiff.js +407 -0
  79. package/dist/index.d.ts +7 -2
  80. package/dist/index.js +5 -0
  81. package/dist/layout/bidi.d.ts +18 -0
  82. package/dist/layout/bidi.js +71 -0
  83. package/dist/layout/blocks.d.ts +20 -3
  84. package/dist/layout/blocks.js +88 -58
  85. package/dist/layout/cache.d.ts +31 -0
  86. package/dist/layout/cache.js +38 -0
  87. package/dist/layout/drawing.d.ts +30 -0
  88. package/dist/layout/drawing.js +120 -0
  89. package/dist/layout/engine.d.ts +3 -0
  90. package/dist/layout/engine.js +218 -11
  91. package/dist/layout/index.d.ts +1 -0
  92. package/dist/layout/index.js +1 -0
  93. package/dist/layout/lines.d.ts +63 -5
  94. package/dist/layout/lines.js +245 -20
  95. package/dist/layout/paint.d.ts +25 -3
  96. package/dist/layout/paint.js +26 -10
  97. package/dist/layout/shapes.d.ts +7 -0
  98. package/dist/layout/shapes.js +338 -0
  99. package/dist/layout/style.d.ts +4 -0
  100. package/dist/layout/style.js +2 -0
  101. package/dist/layout/types.d.ts +89 -2
  102. package/dist/math/boxes.d.ts +88 -0
  103. package/dist/math/boxes.js +166 -0
  104. package/dist/math/index.d.ts +29 -0
  105. package/dist/math/index.js +44 -0
  106. package/dist/math/layout.d.ts +13 -0
  107. package/dist/math/layout.js +771 -0
  108. package/dist/math/linear.d.ts +3 -0
  109. package/dist/math/linear.js +152 -0
  110. package/dist/math/omml.d.ts +15 -0
  111. package/dist/math/omml.js +57 -0
  112. package/dist/math/paths.d.ts +61 -0
  113. package/dist/math/paths.js +450 -0
  114. package/dist/math/symbols.d.ts +49 -0
  115. package/dist/math/symbols.js +269 -0
  116. package/dist/math/text.d.ts +53 -0
  117. package/dist/math/text.js +316 -0
  118. package/dist/metafile/canvas.d.ts +80 -0
  119. package/dist/metafile/canvas.js +515 -0
  120. package/dist/metafile/dib.d.ts +27 -0
  121. package/dist/metafile/dib.js +300 -0
  122. package/dist/metafile/emf.d.ts +31 -0
  123. package/dist/metafile/emf.js +591 -0
  124. package/dist/metafile/geometry.d.ts +49 -0
  125. package/dist/metafile/geometry.js +85 -0
  126. package/dist/metafile/index.d.ts +27 -0
  127. package/dist/metafile/index.js +34 -0
  128. package/dist/metafile/reader.d.ts +28 -0
  129. package/dist/metafile/reader.js +59 -0
  130. package/dist/metafile/state.d.ts +118 -0
  131. package/dist/metafile/state.js +172 -0
  132. package/dist/metafile/text.d.ts +17 -0
  133. package/dist/metafile/text.js +130 -0
  134. package/dist/metafile/wmf.d.ts +33 -0
  135. package/dist/metafile/wmf.js +395 -0
  136. package/dist/model/content.d.ts +92 -7
  137. package/dist/model/content.js +251 -17
  138. package/dist/model/document.d.ts +34 -1
  139. package/dist/model/document.js +80 -1
  140. package/dist/model/fields.d.ts +4 -0
  141. package/dist/model/fields.js +10 -0
  142. package/dist/model/numbering.d.ts +2 -0
  143. package/dist/model/numbering.js +22 -0
  144. package/dist/model/props.d.ts +2 -0
  145. package/dist/model/props.js +3 -0
  146. package/dist/opc/index.d.ts +1 -1
  147. package/dist/opc/package.d.ts +34 -0
  148. package/dist/opc/package.js +58 -4
  149. package/dist/pdf/export.js +97 -6
  150. package/dist/pdf/images.d.ts +7 -0
  151. package/dist/pdf/images.js +39 -2
  152. package/dist/render/activity.d.ts +179 -0
  153. package/dist/render/activity.js +1003 -0
  154. package/dist/render/clipboard.d.ts +29 -0
  155. package/dist/render/clipboard.js +401 -0
  156. package/dist/render/comments.d.ts +166 -0
  157. package/dist/render/comments.js +779 -0
  158. package/dist/render/context-menu.d.ts +124 -0
  159. package/dist/render/context-menu.js +525 -0
  160. package/dist/render/editing.d.ts +146 -5
  161. package/dist/render/editing.js +678 -53
  162. package/dist/render/index.d.ts +12 -0
  163. package/dist/render/index.js +11 -0
  164. package/dist/render/navigation-panel.d.ts +76 -0
  165. package/dist/render/navigation-panel.js +431 -0
  166. package/dist/render/selection.js +5 -0
  167. package/dist/render/svg.d.ts +4 -6
  168. package/dist/render/svg.js +69 -7
  169. package/dist/render/toolbar.d.ts +83 -0
  170. package/dist/render/toolbar.js +505 -0
  171. package/dist/render/ui/comment-layout.d.ts +39 -0
  172. package/dist/render/ui/comment-layout.js +79 -0
  173. package/dist/render/ui/icons.d.ts +6 -0
  174. package/dist/render/ui/icons.js +38 -0
  175. package/dist/render/ui/menu.d.ts +38 -0
  176. package/dist/render/ui/menu.js +274 -0
  177. package/dist/render/ui/nav-model.d.ts +11 -0
  178. package/dist/render/ui/nav-model.js +34 -0
  179. package/dist/render/ui/overflow.d.ts +5 -0
  180. package/dist/render/ui/overflow.js +18 -0
  181. package/dist/render/ui/popover.d.ts +18 -0
  182. package/dist/render/ui/popover.js +109 -0
  183. package/dist/render/ui/theme.d.ts +2 -0
  184. package/dist/render/ui/theme.js +29 -0
  185. package/dist/render/undo.d.ts +76 -0
  186. package/dist/render/undo.js +144 -0
  187. package/dist/render/viewer.d.ts +100 -7
  188. package/dist/render/viewer.js +304 -92
  189. package/dist/security/policy.d.ts +3 -0
  190. package/dist/security/policy.js +6 -2
  191. package/dist/security/protection.d.ts +1 -0
  192. package/dist/security/protection.js +1 -1
  193. package/dist/text/bidi-data.d.ts +53 -0
  194. package/dist/text/bidi-data.js +318 -0
  195. package/dist/text/bidi.d.ts +37 -0
  196. package/dist/text/bidi.js +508 -0
  197. package/dist/xml/ns.d.ts +5 -0
  198. package/dist/xml/ns.js +7 -0
  199. package/package.json +9 -2
@@ -0,0 +1,124 @@
1
+ import type { SelectionInfo } from '../api/selection.js';
2
+ import type { ImageInline } from '../model/content.js';
3
+ import { type LinkTarget } from '../model/fields.js';
4
+ import type { Page } from '../layout/types.js';
5
+ import type { MenuItem } from './ui/menu.js';
6
+ import type { DocxViewer } from './viewer.js';
7
+ export type MenuTargetKind = 'text' | 'link' | 'comment' | 'image' | 'header' | 'footer';
8
+ export interface MenuTarget {
9
+ kind: MenuTargetKind;
10
+ link?: LinkTarget;
11
+ commentId?: string;
12
+ image?: ImageInline;
13
+ /** The header or footer part. */
14
+ part?: string;
15
+ }
16
+ /** What was clicked. `x` and `y` are viewport coordinates (the pointer), `page` is 0-based. */
17
+ export interface MenuContext {
18
+ x: number;
19
+ y: number;
20
+ page: number;
21
+ selection: SelectionInfo | undefined;
22
+ target: MenuTarget;
23
+ }
24
+ export type FormatChoice = 'bold' | 'italic' | 'underline' | 'strike' | 'superscript' | 'subscript' | 'clear';
25
+ export type ParagraphChoice = {
26
+ align: 'left' | 'center' | 'right' | 'justify';
27
+ } | {
28
+ list: 'bullet' | 'decimal';
29
+ } | {
30
+ indent: 1 | -1;
31
+ } | {
32
+ direction: 'ltr' | 'rtl';
33
+ } | {
34
+ style: string;
35
+ };
36
+ type Run = () => void | Promise<void>;
37
+ /** What the menu items do when chosen. */
38
+ export interface MenuActions {
39
+ copy: Run;
40
+ cut: Run;
41
+ paste: Run;
42
+ pastePlain: Run;
43
+ comment: Run;
44
+ link: Run;
45
+ format(f: FormatChoice): void | Promise<void>;
46
+ paragraph(f: ParagraphChoice): void | Promise<void>;
47
+ openLink: Run;
48
+ copyLink: Run;
49
+ editLink: Run;
50
+ removeLink: Run;
51
+ reply: Run;
52
+ resolve: Run;
53
+ deleteComment: Run;
54
+ altText: Run;
55
+ copyImage: Run;
56
+ deleteImage: Run;
57
+ editStory: Run;
58
+ removeStory: Run;
59
+ }
60
+ export interface MenuEnv {
61
+ editable: boolean;
62
+ /** The refusal reason for an action, or `undefined` when it is allowed. */
63
+ can(action: 'edit' | 'format' | 'comment' | 'link' | 'reply' | 'resolveComment' | 'deleteComment', detail?: {
64
+ commentAuthor?: string;
65
+ }): string | undefined;
66
+ /** Whether the async clipboard can be read (otherwise Paste just focuses the page for ⌘V). */
67
+ clipboardRead: boolean;
68
+ act: MenuActions;
69
+ /** Author and state of a comment, for the comment group's header and Resolve/Reopen. */
70
+ commentInfo?(id: string): {
71
+ author: string;
72
+ resolved: boolean;
73
+ } | undefined;
74
+ /** Paragraph styles offered (id and name). */
75
+ styles?: Array<{
76
+ id: string;
77
+ name: string;
78
+ }>;
79
+ }
80
+ /** What lies at a point of a laid-out page (points): link, comment, picture, header/footer, else text. */
81
+ export declare function hitTarget(page: Page, x: number, y: number): MenuTarget;
82
+ /** The default menu for what was clicked (see the spec's list); the app's items come last. */
83
+ export declare function defaultItems(at: MenuContext, env: MenuEnv): MenuItem[];
84
+ /** A link field's text as a hyperlink target: `#name` is a bookmark, anything else an address. */
85
+ export declare function parseLinkTarget(value: string): {
86
+ url: string;
87
+ } | {
88
+ bookmark: string;
89
+ } | undefined;
90
+ export interface ContextMenuOptions {
91
+ /** Change the menu: receives what was clicked and the default items, returns the items to show. */
92
+ items?: (at: MenuContext, defaults: MenuItem[]) => MenuItem[];
93
+ }
94
+ /** What the controller needs from the viewer. */
95
+ export type ContextMenuHost = Pick<DocxViewer, 'root' | 'container' | 'emit' | 'editing' | 'comments' | 'scale' | 'layout' | 'document' | 'followLink' | 'imageBlob'>;
96
+ /** Controls the right-click menu of a viewer (`viewer.contextMenu`). Off until `enable()`. */
97
+ export declare class ContextMenuController {
98
+ private readonly host;
99
+ private readonly options;
100
+ private on;
101
+ private dead;
102
+ private handle;
103
+ /** Closes the link and alt-text prompts the menu opened (on destroy). */
104
+ private readonly prompts;
105
+ constructor(host: ContextMenuHost, options?: ContextMenuOptions);
106
+ get enabled(): boolean;
107
+ enable(): void;
108
+ disable(): void;
109
+ /** Open the menu at a viewport point (from a "⋯" button, a long-press or code). */
110
+ open(x: number, y: number): void;
111
+ close(): void;
112
+ destroy(): void;
113
+ private readonly onContextMenu;
114
+ private openOn;
115
+ /** Build and show the menu for a point on a page (points), with the menu itself at a viewport point. False when there was nothing to show. */
116
+ private openAt;
117
+ private env;
118
+ private styles;
119
+ /** Run an edit as one undo step; a failure has already been reported through `editerror`. */
120
+ private edit;
121
+ private write;
122
+ private actions;
123
+ }
124
+ export {};
@@ -0,0 +1,525 @@
1
+ /**
2
+ * The right-click menu (`viewer.contextMenu`, off by default). `hitTarget` says what was clicked,
3
+ * `defaultItems` builds the menu for it (guard refusals show as disabled items with the reason),
4
+ * and `ContextMenuController` wires the `contextmenu` event, moves the caret, and runs the
5
+ * actions, each of them one undo step through `viewer.editing.transaction`.
6
+ */
7
+ import { DocxEditor, objectNode } from '../api/editor.js';
8
+ import { readComments } from '../comments/read.js';
9
+ import { linkSource } from '../model/fields.js';
10
+ import { openMenu } from './ui/menu.js';
11
+ import { promptPopover } from './ui/popover.js';
12
+ const hasRect = (r, x, y) => x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h;
13
+ /** What lies at a point of a laid-out page (points): link, comment, picture, header/footer, else text. */
14
+ export function hitTarget(page, x, y) {
15
+ const link = page.links.find((l) => hasRect(l, x, y));
16
+ if (link)
17
+ return { kind: 'link', link: link.target };
18
+ const comment = page.comments.find((c) => c.w > 0 && hasRect(c, x, y));
19
+ if (comment)
20
+ return { kind: 'comment', commentId: comment.id };
21
+ for (let i = page.items.length - 1; i >= 0; i--) {
22
+ const item = page.items[i];
23
+ if (item.type === 'image' && item.inline && !item.frameOnly && hasRect(item, x, y))
24
+ return { kind: 'image', image: item.inline };
25
+ }
26
+ const line = page.storyLines.find((l) => (l.story === 'header' || l.story === 'footer') && hasRect({ x: l.x - 2, y: l.y - 2, w: l.w + 4, h: l.h + 4 }, x, y));
27
+ if (line && (line.story === 'header' || line.story === 'footer'))
28
+ return { kind: line.story, ...(line.part ? { part: line.part } : {}) };
29
+ return { kind: 'text' };
30
+ }
31
+ const DEFAULT_STYLES = [
32
+ { id: 'Normal', name: 'Normal' },
33
+ { id: 'Title', name: 'Title' },
34
+ { id: 'Heading1', name: 'Heading 1' },
35
+ { id: 'Heading2', name: 'Heading 2' },
36
+ { id: 'Heading3', name: 'Heading 3' },
37
+ ];
38
+ const FIELD_LINK = 'This link cannot be edited here';
39
+ /** The default menu for what was clicked (see the spec's list); the app's items come last. */
40
+ export function defaultItems(at, env) {
41
+ const { act } = env;
42
+ const refuse = (action, detail) => env.can(action, detail) ?? (env.editable ? undefined : 'The document is read-only');
43
+ const off = (reason, hint) => reason ?? hint ?? false;
44
+ const nothingSelected = !at.selection || at.selection.collapsed;
45
+ const groups = [];
46
+ const clipboard = [];
47
+ if (env.editable)
48
+ clipboard.push({ id: 'cut', label: 'Cut', icon: 'cut', shortcut: '⌘X', disabled: off(refuse('edit'), at.selection?.collapsed ? 'Nothing selected' : undefined), run: act.cut });
49
+ clipboard.push({ id: 'copy', label: 'Copy', icon: 'copy', shortcut: '⌘C', disabled: at.selection?.collapsed ? 'Nothing selected' : false, run: act.copy });
50
+ if (env.editable) {
51
+ clipboard.push({ id: 'paste', label: env.clipboardRead ? 'Paste' : 'Paste (⌘V)', icon: 'paste', ...(env.clipboardRead ? { shortcut: '⌘V' } : {}), disabled: off(refuse('edit')), run: act.paste });
52
+ if (env.clipboardRead)
53
+ clipboard.push({ id: 'paste-plain', label: 'Paste as plain text', shortcut: '⇧⌘V', disabled: off(refuse('edit')), run: act.pastePlain });
54
+ }
55
+ groups.push(clipboard);
56
+ const kind = at.target.kind;
57
+ if (kind === 'text' || kind === 'link' || kind === 'comment') {
58
+ const formatReason = refuse('format');
59
+ const choice = (id, label, shortcut) => ({ id: `format-${id}`, label, ...(shortcut ? { shortcut } : {}), disabled: off(formatReason), run: () => act.format(id) });
60
+ const para = (id, label, p) => ({ id: `paragraph-${id}`, label, disabled: off(formatReason), run: () => act.paragraph(p) });
61
+ const styles = env.styles ?? DEFAULT_STYLES;
62
+ groups.push([
63
+ { id: 'comment', label: 'Comment', icon: 'comment', disabled: off(refuse('comment'), nothingSelected ? 'Select some text to comment on' : undefined), run: act.comment },
64
+ { id: 'link', label: 'Link…', icon: 'link', disabled: off(refuse('link'), nothingSelected && kind !== 'link' ? 'Select some text to link' : undefined), run: act.link },
65
+ {
66
+ id: 'format',
67
+ label: 'Format',
68
+ disabled: off(formatReason),
69
+ items: [
70
+ choice('bold', 'Bold', '⌘B'),
71
+ choice('italic', 'Italic', '⌘I'),
72
+ choice('underline', 'Underline', '⌘U'),
73
+ choice('strike', 'Strikethrough'),
74
+ choice('superscript', 'Superscript'),
75
+ choice('subscript', 'Subscript'),
76
+ choice('clear', 'Clear formatting'),
77
+ ],
78
+ },
79
+ {
80
+ id: 'paragraph',
81
+ label: 'Paragraph',
82
+ disabled: off(formatReason),
83
+ items: [
84
+ para('left', 'Align left', { align: 'left' }),
85
+ para('center', 'Align center', { align: 'center' }),
86
+ para('right', 'Align right', { align: 'right' }),
87
+ para('justify', 'Justify', { align: 'justify' }),
88
+ '-',
89
+ para('bullets', 'Bullets', { list: 'bullet' }),
90
+ para('numbering', 'Numbering', { list: 'decimal' }),
91
+ para('indent', 'Increase indent', { indent: 1 }),
92
+ para('outdent', 'Decrease indent', { indent: -1 }),
93
+ '-',
94
+ para('ltr', 'Left to right', { direction: 'ltr' }),
95
+ para('rtl', 'Right to left', { direction: 'rtl' }),
96
+ '-',
97
+ { id: 'styles', label: 'Styles', disabled: off(formatReason), items: styles.map((s) => para(`style-${s.id}`, s.name, { style: s.id })) },
98
+ ],
99
+ },
100
+ ]);
101
+ }
102
+ if (kind === 'link' && at.target.link) {
103
+ const link = at.target.link;
104
+ // A link made by a HYPERLINK field has no w:hyperlink to change.
105
+ const linkReason = refuse('link') ?? (linkSource(link) ? undefined : FIELD_LINK);
106
+ groups.push([
107
+ { id: 'link-address', label: link.url ?? `#${link.anchor ?? ''}`, icon: 'link', disabled: true },
108
+ { id: 'open-link', label: 'Open link', run: act.openLink },
109
+ { id: 'copy-link', label: 'Copy link address', run: act.copyLink },
110
+ { id: 'edit-link', label: 'Edit link…', disabled: off(linkReason), run: act.editLink },
111
+ { id: 'remove-link', label: 'Remove link', disabled: off(linkReason), run: act.removeLink },
112
+ ]);
113
+ }
114
+ if (kind === 'comment' && at.target.commentId !== undefined) {
115
+ const info = env.commentInfo?.(at.target.commentId);
116
+ groups.push([
117
+ { id: 'comment-header', label: info ? `Comment by ${info.author}` : 'Comment', icon: 'comment', disabled: true },
118
+ { id: 'reply', label: 'Reply', disabled: off(refuse('reply')), run: act.reply },
119
+ { id: 'resolve', label: info?.resolved ? 'Reopen' : 'Resolve', disabled: off(refuse('resolveComment')), run: act.resolve },
120
+ { id: 'delete-comment', label: 'Delete comment', disabled: off(refuse('deleteComment', info ? { commentAuthor: info.author } : undefined)), run: act.deleteComment },
121
+ ]);
122
+ }
123
+ if (kind === 'image') {
124
+ const reason = refuse('edit');
125
+ groups.push([
126
+ { id: 'alt-text', label: 'Alt text…', disabled: off(reason), run: act.altText },
127
+ { id: 'copy-picture', label: 'Copy picture', icon: 'copy', run: act.copyImage },
128
+ { id: 'delete-picture', label: 'Delete', disabled: off(reason), run: act.deleteImage },
129
+ ]);
130
+ }
131
+ if (kind === 'header' || kind === 'footer') {
132
+ const reason = refuse('edit');
133
+ groups.push([
134
+ { id: 'edit-story', label: 'Edit header/footer', disabled: off(reason), run: act.editStory },
135
+ { id: 'remove-story', label: 'Remove header/footer', disabled: off(reason), run: act.removeStory },
136
+ ]);
137
+ }
138
+ const out = [];
139
+ for (const group of groups) {
140
+ if (out.length)
141
+ out.push('-');
142
+ out.push(...group);
143
+ }
144
+ return out;
145
+ }
146
+ /** A link field's text as a hyperlink target: `#name` is a bookmark, anything else an address. */
147
+ export function parseLinkTarget(value) {
148
+ const v = value.trim();
149
+ if (!v)
150
+ return undefined;
151
+ if (v.startsWith('#'))
152
+ return v.length > 1 ? { bookmark: v.slice(1) } : undefined;
153
+ return { url: /^[a-z][a-z0-9+.-]*:/i.test(v) ? v : `https://${v}` };
154
+ }
155
+ const STYLE_WANTED = ['Normal', 'Title', 'Heading1', 'Heading2', 'Heading3'];
156
+ /** Controls the right-click menu of a viewer (`viewer.contextMenu`). Off until `enable()`. */
157
+ export class ContextMenuController {
158
+ host;
159
+ options;
160
+ on = false;
161
+ dead = false;
162
+ handle;
163
+ /** Closes the link and alt-text prompts the menu opened (on destroy). */
164
+ prompts = new AbortController();
165
+ constructor(host, options = {}) {
166
+ this.host = host;
167
+ this.options = options;
168
+ }
169
+ get enabled() {
170
+ return this.on;
171
+ }
172
+ enable() {
173
+ if (this.on)
174
+ return;
175
+ this.on = true;
176
+ this.host.root.addEventListener('contextmenu', this.onContextMenu);
177
+ this.host.emit('chromechange', { part: 'contextMenu', visible: true });
178
+ }
179
+ disable() {
180
+ if (!this.on)
181
+ return;
182
+ this.on = false;
183
+ this.host.root.removeEventListener('contextmenu', this.onContextMenu);
184
+ this.close();
185
+ this.host.emit('chromechange', { part: 'contextMenu', visible: false });
186
+ }
187
+ /** Open the menu at a viewport point (from a "⋯" button, a long-press or code). */
188
+ open(x, y) {
189
+ const under = typeof document.elementFromPoint === 'function' ? document.elementFromPoint(x, y) : null;
190
+ let pageEl = under?.closest?.('.docxkeun-page');
191
+ if (pageEl && !this.host.root.contains(pageEl))
192
+ pageEl = undefined;
193
+ if (pageEl) {
194
+ this.openOn(pageEl, x, y);
195
+ return;
196
+ }
197
+ // Not over a page (a button, say): use the selection's page and line, else the first page.
198
+ const spot = this.host.editing?.isEnabled ? this.host.editing.selectionSpot() : undefined;
199
+ if (spot)
200
+ this.openAt(spot.page, spot.x, spot.y + spot.h / 2, x, y, true);
201
+ else
202
+ this.openAt(0, 0, 0, x, y, false);
203
+ }
204
+ close() {
205
+ this.handle?.close();
206
+ this.handle = undefined;
207
+ }
208
+ destroy() {
209
+ this.on = false;
210
+ this.dead = true;
211
+ this.host.root.removeEventListener('contextmenu', this.onContextMenu);
212
+ this.close();
213
+ // An open prompt resolves as cancelled, and anything still queued does nothing (see edit()).
214
+ this.prompts.abort();
215
+ }
216
+ onContextMenu = (e) => {
217
+ if (e.shiftKey)
218
+ return;
219
+ const pageEl = e.target?.closest?.('.docxkeun-page');
220
+ if (!pageEl || !this.host.root.contains(pageEl))
221
+ return;
222
+ // No items (the app's `items` returned none): the browser's own menu shows.
223
+ if (this.openOn(pageEl, e.clientX, e.clientY))
224
+ e.preventDefault();
225
+ };
226
+ openOn(pageEl, clientX, clientY) {
227
+ const rect = pageEl.getBoundingClientRect();
228
+ const s = this.host.scale;
229
+ return this.openAt(Number(pageEl.dataset.page ?? 0), (clientX - rect.left) / s, (clientY - rect.top) / s, clientX, clientY, true);
230
+ }
231
+ /** Build and show the menu for a point on a page (points), with the menu itself at a viewport point. False when there was nothing to show. */
232
+ openAt(page, px, py, clientX, clientY, hasPoint) {
233
+ const editing = this.host.editing;
234
+ const layoutPage = this.host.layout?.pages[page];
235
+ const target = layoutPage && hasPoint ? hitTarget(layoutPage, px, py) : { kind: 'text' };
236
+ const live = !!editing?.isEnabled;
237
+ // As in Word, a right-click outside the selection first moves the caret there (not into a header).
238
+ if (live && hasPoint && target.kind !== 'header' && target.kind !== 'footer' && !editing.selectionContains(page, px, py))
239
+ editing.placeCaretAt(page, px, py);
240
+ const at = { x: clientX, y: clientY, page, selection: live ? editing.selectionInfo() : undefined, target };
241
+ const defaults = defaultItems(at, this.env(at));
242
+ const items = this.options.items ? this.options.items(at, defaults) : defaults;
243
+ if (!items.length)
244
+ return false;
245
+ this.close();
246
+ this.handle = openMenu(items, { x: clientX, y: clientY }, { label: 'Document menu', ...(this.host.container ? { container: this.host.container } : {}), onClose: () => (this.handle = undefined) });
247
+ return true;
248
+ }
249
+ // ---- what the items need -----------------------------------------------------------------
250
+ env(at) {
251
+ const editing = this.host.editing;
252
+ const editable = !!editing?.isEnabled;
253
+ const clipboard = typeof navigator === 'undefined' ? undefined : navigator.clipboard;
254
+ return {
255
+ editable,
256
+ can: (action, detail) => {
257
+ if (!editing?.isEnabled)
258
+ return 'The document is read-only';
259
+ const guard = editing.guard;
260
+ if (!guard)
261
+ return undefined;
262
+ try {
263
+ guard.assert(action, undefined, detail);
264
+ return undefined;
265
+ }
266
+ catch (error) {
267
+ return (error instanceof Error && error.message) || 'Not allowed';
268
+ }
269
+ },
270
+ clipboardRead: !!(clipboard && (clipboard.read || clipboard.readText)),
271
+ commentInfo: (id) => {
272
+ const doc = this.host.document;
273
+ const c = doc ? readComments(doc).find((x) => x.id === id) : undefined;
274
+ return c ? { author: c.author, resolved: c.resolved } : undefined;
275
+ },
276
+ styles: this.styles(),
277
+ act: this.actions(at),
278
+ };
279
+ }
280
+ styles() {
281
+ const doc = this.host.document;
282
+ return STYLE_WANTED.filter((id) => !doc || id === 'Normal' || doc.styles.get(id)).map((id) => ({ id, name: doc?.styles.get(id)?.name?.replace(/^heading ?/i, 'Heading ') ?? DEFAULT_STYLES.find((s) => s.id === id)?.name ?? id }));
283
+ }
284
+ /** Run an edit as one undo step; a failure has already been reported through `editerror`. */
285
+ edit(label, fn) {
286
+ const editing = this.host.editing;
287
+ if (this.dead || !editing?.isEnabled)
288
+ return Promise.resolve();
289
+ return editing.transaction(label, fn).then(() => undefined, () => undefined);
290
+ }
291
+ async write(text) {
292
+ try {
293
+ await navigator.clipboard?.writeText(text);
294
+ }
295
+ catch {
296
+ // Refused by the browser: nothing to copy to.
297
+ }
298
+ }
299
+ actions(at) {
300
+ const host = this.host;
301
+ const target = at.target;
302
+ const point = { x: at.x, y: at.y };
303
+ const container = host.container;
304
+ const signal = this.prompts.signal;
305
+ const ask = (title, value, placeholder, validate) => promptPopover({ title, value, ...(placeholder ? { placeholder } : {}), at: point, ...(validate ? { validate } : {}), ...(container ? { container } : {}), signal });
306
+ const linkValidate = (v) => (parseLinkTarget(v) ? undefined : 'Enter a web address, or #bookmark');
307
+ const withEditing = () => (host.editing?.isEnabled ? host.editing : undefined);
308
+ const selectedRange = (editing) => {
309
+ const sel = editing.selection;
310
+ return editing.rangeOf(sel.anchor, sel.focus);
311
+ };
312
+ /** The w:hyperlink that was right-clicked (not whatever the selection touches). */
313
+ const clickedHyperlink = () => {
314
+ const source = target.link && linkSource(target.link);
315
+ if (!source)
316
+ throw new Error(FIELD_LINK);
317
+ return source;
318
+ };
319
+ /**
320
+ * The editor for the part holding `node`: a link or picture in a header, footer or note is
321
+ * changed through that part (its relationships, its dirty flag), with the editing layer's
322
+ * guard, Track Changes and author. The transaction's own editor when it is that part.
323
+ */
324
+ const ownerEditor = (editor, node) => {
325
+ const doc = host.document;
326
+ const editing = host.editing;
327
+ const part = doc ? partHolding(doc, node) : undefined;
328
+ if (!doc || !editing || !part || part === editor.part)
329
+ return editor;
330
+ return new DocxEditor(doc, editing.guard, { part, trackChanges: editing.trackChanges, author: editing.author });
331
+ };
332
+ const copyFromPage = async () => {
333
+ const text = window.getSelection?.()?.toString() ?? '';
334
+ if (text)
335
+ await this.write(text);
336
+ };
337
+ const paste = async (plain) => {
338
+ const editing = withEditing();
339
+ if (!editing)
340
+ return;
341
+ editing.focus();
342
+ const clipboard = navigator.clipboard;
343
+ if (!clipboard || (!clipboard.read && !clipboard.readText))
344
+ return; // ⌘V works from the focused page
345
+ try {
346
+ if (!plain && clipboard.read) {
347
+ let text;
348
+ for (const item of await clipboard.read()) {
349
+ if (item.types.includes('text/html') && editing.pasteHtml(await (await item.getType('text/html')).text()))
350
+ return;
351
+ if (text === undefined && item.types.includes('text/plain'))
352
+ text = await (await item.getType('text/plain')).text();
353
+ }
354
+ if (text !== undefined)
355
+ return editing.pasteText(text);
356
+ }
357
+ if (clipboard.readText)
358
+ return editing.pasteText(await clipboard.readText());
359
+ }
360
+ catch {
361
+ editing.focus();
362
+ }
363
+ };
364
+ return {
365
+ copy: () => (withEditing()?.selection ? withEditing().copySelection(false) : copyFromPage()),
366
+ cut: () => withEditing()?.copySelection(true),
367
+ paste: () => paste(false),
368
+ pastePlain: () => paste(true),
369
+ comment: () => host.comments.compose(),
370
+ link: async () => {
371
+ const value = await ask('Link', '', 'https://… or #bookmark', linkValidate);
372
+ const parsed = value === undefined ? undefined : parseLinkTarget(value);
373
+ const editing = withEditing();
374
+ if (!parsed || !editing?.selection)
375
+ return;
376
+ await this.edit('Add link', (editor) => editor.addHyperlink(selectedRange(editing), parsed));
377
+ },
378
+ format: (f) => {
379
+ const editing = withEditing();
380
+ if (!editing)
381
+ return;
382
+ switch (f) {
383
+ case 'bold':
384
+ case 'italic':
385
+ case 'underline':
386
+ case 'strike':
387
+ return editing.toggle(f);
388
+ case 'superscript':
389
+ case 'subscript':
390
+ return editing.format({ vertAlign: f });
391
+ case 'clear': {
392
+ if (!editing.selection)
393
+ return;
394
+ return this.edit('Clear formatting', (editor) => editor.clearFormatting(selectedRange(editing)));
395
+ }
396
+ }
397
+ },
398
+ paragraph: (f) => {
399
+ const editing = withEditing();
400
+ if (!editing)
401
+ return;
402
+ if ('align' in f)
403
+ return editing.formatParagraphs({ align: f.align });
404
+ if ('direction' in f)
405
+ return editing.formatParagraphs({ direction: f.direction });
406
+ if ('list' in f)
407
+ return editing.setList(f.list);
408
+ if ('indent' in f)
409
+ return editing.indent(f.indent);
410
+ return editing.setStyle(f.style);
411
+ },
412
+ openLink: () => {
413
+ if (target.link)
414
+ host.followLink(target.link);
415
+ },
416
+ copyLink: () => {
417
+ const l = target.link;
418
+ return l ? this.write(l.url ?? `#${l.anchor ?? ''}`) : undefined;
419
+ },
420
+ editLink: async () => {
421
+ const link = target.link;
422
+ const value = await ask('Edit link', link?.url ?? (link?.anchor ? `#${link.anchor}` : ''), 'https://… or #bookmark', linkValidate);
423
+ const parsed = value === undefined ? undefined : parseLinkTarget(value);
424
+ const editing = withEditing();
425
+ if (!parsed || !editing)
426
+ return;
427
+ await this.edit('Edit link', (editor) => {
428
+ const link = clickedHyperlink();
429
+ return ownerEditor(editor, link).setHyperlinkTarget(link, parsed);
430
+ });
431
+ },
432
+ removeLink: async () => {
433
+ const editing = withEditing();
434
+ if (!editing)
435
+ return;
436
+ await this.edit('Remove link', (editor) => {
437
+ const link = clickedHyperlink();
438
+ return ownerEditor(editor, link).removeHyperlink(link);
439
+ });
440
+ },
441
+ reply: () => {
442
+ if (target.commentId !== undefined)
443
+ host.comments.reply(target.commentId);
444
+ },
445
+ resolve: async () => {
446
+ const id = target.commentId;
447
+ if (id === undefined)
448
+ return;
449
+ const resolved = !readComments(host.document).find((c) => c.id === id)?.resolved;
450
+ await this.edit(resolved ? 'Resolve comment' : 'Reopen comment', (editor) => editor.resolveComment(id, resolved));
451
+ if (resolved)
452
+ host.comments.close();
453
+ },
454
+ deleteComment: async () => {
455
+ const id = target.commentId;
456
+ if (id === undefined)
457
+ return;
458
+ await this.edit('Delete comment', (editor) => editor.deleteComment(id));
459
+ host.comments.close();
460
+ },
461
+ altText: async () => {
462
+ const image = target.image;
463
+ if (!image)
464
+ return;
465
+ const text = await ask('Alt text', image.alt ?? '', 'Describe the picture');
466
+ if (text === undefined)
467
+ return;
468
+ await this.edit('Alt text', (editor) => ownerEditor(editor, image.drawing).setImageAlt(image.drawing, text));
469
+ },
470
+ copyImage: async () => {
471
+ const blob = target.image ? await host.imageBlob(target.image) : undefined;
472
+ if (!blob || typeof ClipboardItem === 'undefined')
473
+ return;
474
+ try {
475
+ await navigator.clipboard.write([new ClipboardItem({ [blob.type]: blob })]);
476
+ }
477
+ catch {
478
+ // Refused: the browser does not take pictures on the clipboard.
479
+ }
480
+ },
481
+ deleteImage: async () => {
482
+ const image = target.image;
483
+ const node = image && objectNode(image);
484
+ if (!node)
485
+ return;
486
+ // A picture in a header, footer or note is deleted through that part's editor (still one undo step).
487
+ await this.edit('Delete picture', (editor) => ownerEditor(editor, node).deleteRange({ start: { node, offset: 0 }, end: { node, offset: 1 } }));
488
+ },
489
+ editStory: () => {
490
+ const editing = withEditing();
491
+ if (editing && target.part && (target.kind === 'header' || target.kind === 'footer'))
492
+ editing.enterStory({ kind: target.kind, part: target.part });
493
+ },
494
+ removeStory: async () => {
495
+ const part = target.part;
496
+ if (!part || (target.kind !== 'header' && target.kind !== 'footer'))
497
+ return;
498
+ const section = (host.layout?.pages[at.page]?.sectionIndex ?? 0) + 1;
499
+ await this.edit('Remove header/footer', async (editor) => {
500
+ const info = editor.headersAndFooters().find((h) => h.part === part);
501
+ if (!info)
502
+ throw new Error('This header or footer was not found');
503
+ // Its own section when it has a reference there; otherwise the sections it is declared in.
504
+ for (const s of info.sections.includes(section) ? [section] : info.sections)
505
+ await editor.removeHeaderFooter(info.kind, { type: info.type, section: s });
506
+ });
507
+ },
508
+ };
509
+ }
510
+ }
511
+ function nodeIn(root, node) {
512
+ for (const c of root.children)
513
+ if (c.type === 'element' && (c === node || nodeIn(c, node)))
514
+ return true;
515
+ return false;
516
+ }
517
+ /** The part whose XML holds `node`: the main document, a header, a footer or a notes part. */
518
+ function partHolding(doc, node) {
519
+ if (nodeIn(doc.documentXml.root, node))
520
+ return doc.mainPart;
521
+ return doc.storyParts().find((sp) => {
522
+ const root = doc.xmlSync(sp.part)?.root;
523
+ return !!root && nodeIn(root, node);
524
+ })?.part;
525
+ }