docxkeun 0.1.2 → 0.2.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 (197) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +139 -16
  3. package/dist/api/editor.d.ts +172 -5
  4. package/dist/api/editor.js +814 -24
  5. package/dist/api/headers.d.ts +51 -0
  6. package/dist/api/headers.js +133 -0
  7. package/dist/api/index.d.ts +5 -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 +390 -0
  15. package/dist/api/selection.d.ts +57 -0
  16. package/dist/api/selection.js +91 -0
  17. package/dist/charts/color.d.ts +45 -0
  18. package/dist/charts/color.js +322 -0
  19. package/dist/charts/format.d.ts +12 -0
  20. package/dist/charts/format.js +459 -0
  21. package/dist/charts/index.d.ts +11 -0
  22. package/dist/charts/index.js +8 -0
  23. package/dist/charts/model.d.ts +225 -0
  24. package/dist/charts/model.js +758 -0
  25. package/dist/charts/outline.d.ts +17 -0
  26. package/dist/charts/outline.js +214 -0
  27. package/dist/charts/render.d.ts +20 -0
  28. package/dist/charts/render.js +1772 -0
  29. package/dist/drawing/arrows.d.ts +37 -0
  30. package/dist/drawing/arrows.js +99 -0
  31. package/dist/drawing/formula.d.ts +40 -0
  32. package/dist/drawing/formula.js +159 -0
  33. package/dist/drawing/geometry.d.ts +61 -0
  34. package/dist/drawing/geometry.js +286 -0
  35. package/dist/drawing/index.d.ts +12 -0
  36. package/dist/drawing/index.js +8 -0
  37. package/dist/drawing/presets.d.ts +72 -0
  38. package/dist/drawing/presets.js +2874 -0
  39. package/dist/fonts/shaping/apply.d.ts +94 -0
  40. package/dist/fonts/shaping/apply.js +349 -0
  41. package/dist/fonts/shaping/arabic.d.ts +28 -0
  42. package/dist/fonts/shaping/arabic.js +235 -0
  43. package/dist/fonts/shaping/buffer.d.ts +53 -0
  44. package/dist/fonts/shaping/buffer.js +95 -0
  45. package/dist/fonts/shaping/gdef.d.ts +30 -0
  46. package/dist/fonts/shaping/gdef.js +66 -0
  47. package/dist/fonts/shaping/gpos.d.ts +86 -0
  48. package/dist/fonts/shaping/gpos.js +428 -0
  49. package/dist/fonts/shaping/gsub.d.ts +65 -0
  50. package/dist/fonts/shaping/gsub.js +313 -0
  51. package/dist/fonts/shaping/index.d.ts +32 -0
  52. package/dist/fonts/shaping/index.js +402 -0
  53. package/dist/fonts/shaping/indic.d.ts +6 -0
  54. package/dist/fonts/shaping/indic.js +805 -0
  55. package/dist/fonts/shaping/layout-common.d.ts +124 -0
  56. package/dist/fonts/shaping/layout-common.js +349 -0
  57. package/dist/fonts/shaping/plan.d.ts +87 -0
  58. package/dist/fonts/shaping/plan.js +152 -0
  59. package/dist/fonts/shaping/scripts.d.ts +26 -0
  60. package/dist/fonts/shaping/scripts.js +160 -0
  61. package/dist/fonts/shaping/shaper.d.ts +23 -0
  62. package/dist/fonts/shaping/shaper.js +5 -0
  63. package/dist/fonts/shaping/unicode.d.ts +34 -0
  64. package/dist/fonts/shaping/unicode.js +138 -0
  65. package/dist/images/bmp.d.ts +9 -0
  66. package/dist/images/bmp.js +234 -0
  67. package/dist/images/gif.d.ts +9 -0
  68. package/dist/images/gif.js +215 -0
  69. package/dist/images/index.d.ts +18 -0
  70. package/dist/images/index.js +63 -0
  71. package/dist/images/png-encode.d.ts +4 -0
  72. package/dist/images/png-encode.js +73 -0
  73. package/dist/images/size.d.ts +10 -0
  74. package/dist/images/size.js +83 -0
  75. package/dist/images/tiff.d.ts +14 -0
  76. package/dist/images/tiff.js +407 -0
  77. package/dist/index.d.ts +7 -2
  78. package/dist/index.js +5 -0
  79. package/dist/layout/bidi.d.ts +18 -0
  80. package/dist/layout/bidi.js +71 -0
  81. package/dist/layout/blocks.d.ts +20 -3
  82. package/dist/layout/blocks.js +88 -58
  83. package/dist/layout/cache.d.ts +31 -0
  84. package/dist/layout/cache.js +38 -0
  85. package/dist/layout/drawing.d.ts +30 -0
  86. package/dist/layout/drawing.js +120 -0
  87. package/dist/layout/engine.d.ts +3 -0
  88. package/dist/layout/engine.js +218 -11
  89. package/dist/layout/index.d.ts +1 -0
  90. package/dist/layout/index.js +1 -0
  91. package/dist/layout/lines.d.ts +63 -5
  92. package/dist/layout/lines.js +245 -20
  93. package/dist/layout/paint.d.ts +25 -3
  94. package/dist/layout/paint.js +26 -10
  95. package/dist/layout/shapes.d.ts +7 -0
  96. package/dist/layout/shapes.js +338 -0
  97. package/dist/layout/style.d.ts +4 -0
  98. package/dist/layout/style.js +2 -0
  99. package/dist/layout/types.d.ts +89 -2
  100. package/dist/math/boxes.d.ts +88 -0
  101. package/dist/math/boxes.js +166 -0
  102. package/dist/math/index.d.ts +29 -0
  103. package/dist/math/index.js +44 -0
  104. package/dist/math/layout.d.ts +13 -0
  105. package/dist/math/layout.js +771 -0
  106. package/dist/math/linear.d.ts +3 -0
  107. package/dist/math/linear.js +152 -0
  108. package/dist/math/omml.d.ts +15 -0
  109. package/dist/math/omml.js +57 -0
  110. package/dist/math/paths.d.ts +61 -0
  111. package/dist/math/paths.js +450 -0
  112. package/dist/math/symbols.d.ts +49 -0
  113. package/dist/math/symbols.js +269 -0
  114. package/dist/math/text.d.ts +53 -0
  115. package/dist/math/text.js +316 -0
  116. package/dist/metafile/canvas.d.ts +80 -0
  117. package/dist/metafile/canvas.js +515 -0
  118. package/dist/metafile/dib.d.ts +27 -0
  119. package/dist/metafile/dib.js +300 -0
  120. package/dist/metafile/emf.d.ts +31 -0
  121. package/dist/metafile/emf.js +591 -0
  122. package/dist/metafile/geometry.d.ts +49 -0
  123. package/dist/metafile/geometry.js +85 -0
  124. package/dist/metafile/index.d.ts +27 -0
  125. package/dist/metafile/index.js +34 -0
  126. package/dist/metafile/reader.d.ts +28 -0
  127. package/dist/metafile/reader.js +59 -0
  128. package/dist/metafile/state.d.ts +118 -0
  129. package/dist/metafile/state.js +172 -0
  130. package/dist/metafile/text.d.ts +17 -0
  131. package/dist/metafile/text.js +130 -0
  132. package/dist/metafile/wmf.d.ts +33 -0
  133. package/dist/metafile/wmf.js +395 -0
  134. package/dist/model/content.d.ts +92 -7
  135. package/dist/model/content.js +251 -17
  136. package/dist/model/document.d.ts +34 -1
  137. package/dist/model/document.js +80 -1
  138. package/dist/model/fields.d.ts +4 -0
  139. package/dist/model/fields.js +10 -0
  140. package/dist/model/numbering.d.ts +2 -0
  141. package/dist/model/numbering.js +22 -0
  142. package/dist/model/props.d.ts +2 -0
  143. package/dist/model/props.js +3 -0
  144. package/dist/opc/index.d.ts +1 -1
  145. package/dist/opc/package.d.ts +34 -0
  146. package/dist/opc/package.js +58 -4
  147. package/dist/pdf/export.js +97 -6
  148. package/dist/pdf/images.d.ts +7 -0
  149. package/dist/pdf/images.js +39 -2
  150. package/dist/render/activity.d.ts +138 -0
  151. package/dist/render/activity.js +794 -0
  152. package/dist/render/clipboard.d.ts +29 -0
  153. package/dist/render/clipboard.js +401 -0
  154. package/dist/render/comments.d.ts +166 -0
  155. package/dist/render/comments.js +779 -0
  156. package/dist/render/context-menu.d.ts +124 -0
  157. package/dist/render/context-menu.js +525 -0
  158. package/dist/render/editing.d.ts +146 -5
  159. package/dist/render/editing.js +678 -53
  160. package/dist/render/index.d.ts +12 -0
  161. package/dist/render/index.js +11 -0
  162. package/dist/render/navigation-panel.d.ts +76 -0
  163. package/dist/render/navigation-panel.js +431 -0
  164. package/dist/render/selection.js +5 -0
  165. package/dist/render/svg.d.ts +4 -6
  166. package/dist/render/svg.js +69 -7
  167. package/dist/render/toolbar.d.ts +83 -0
  168. package/dist/render/toolbar.js +505 -0
  169. package/dist/render/ui/comment-layout.d.ts +39 -0
  170. package/dist/render/ui/comment-layout.js +79 -0
  171. package/dist/render/ui/icons.d.ts +6 -0
  172. package/dist/render/ui/icons.js +38 -0
  173. package/dist/render/ui/menu.d.ts +38 -0
  174. package/dist/render/ui/menu.js +274 -0
  175. package/dist/render/ui/nav-model.d.ts +11 -0
  176. package/dist/render/ui/nav-model.js +34 -0
  177. package/dist/render/ui/overflow.d.ts +5 -0
  178. package/dist/render/ui/overflow.js +18 -0
  179. package/dist/render/ui/popover.d.ts +18 -0
  180. package/dist/render/ui/popover.js +109 -0
  181. package/dist/render/ui/theme.d.ts +2 -0
  182. package/dist/render/ui/theme.js +29 -0
  183. package/dist/render/undo.d.ts +76 -0
  184. package/dist/render/undo.js +144 -0
  185. package/dist/render/viewer.d.ts +100 -7
  186. package/dist/render/viewer.js +302 -92
  187. package/dist/security/policy.d.ts +3 -0
  188. package/dist/security/policy.js +6 -2
  189. package/dist/security/protection.d.ts +1 -0
  190. package/dist/security/protection.js +1 -1
  191. package/dist/text/bidi-data.d.ts +53 -0
  192. package/dist/text/bidi-data.js +318 -0
  193. package/dist/text/bidi.d.ts +37 -0
  194. package/dist/text/bidi.js +508 -0
  195. package/dist/xml/ns.d.ts +5 -0
  196. package/dist/xml/ns.js +7 -0
  197. package/package.json +9 -2
@@ -0,0 +1,779 @@
1
+ import { REVISION_COLORS } from '../model/content.js';
2
+ import { icon } from './ui/icons.js';
3
+ import { BUBBLE_SIZE, bubbleGroups, commentMode, layoutCards } from './ui/comment-layout.js';
4
+ import { ensureUiStyle } from './ui/theme.js';
5
+ const STYLE_ID = 'docxkeun-comments-style';
6
+ const COLUMN = 260;
7
+ const STRIP = 36;
8
+ const GAP = 12;
9
+ const CARD_GAP = 8;
10
+ const SWITCH_FLOOR = 32;
11
+ /** Space between a bubble popover and the text, and from the edges of the view. */
12
+ const POP_GAP = 6;
13
+ const EDGE = 4;
14
+ const DRAFT = '__draft';
15
+ const CSS = `
16
+ .docxkeun-comments{position:absolute;top:0;z-index:3;pointer-events:none;font:var(--dk-ui-font);color:var(--dk-ui-fg)}
17
+ .docxkeun-comments button{font:inherit;color:inherit}
18
+ .docxkeun-comments .dk-card{position:absolute;left:0;right:0;box-sizing:border-box;pointer-events:auto;background:var(--dk-ui-bg);border:1px solid var(--dk-ui-line);border-radius:var(--dk-ui-radius);padding:8px 10px;cursor:pointer;box-shadow:0 1px 2px rgba(60,64,67,.25)}
19
+ @media (prefers-reduced-motion:no-preference){.docxkeun-comments .dk-card{transition:top .18s ease}}
20
+ .docxkeun-comments .dk-card:hover{border-color:var(--dk-ui-muted)}
21
+ .docxkeun-comments .dk-card:focus-visible,.docxkeun-comments button:focus-visible,.docxkeun-comments textarea:focus-visible{outline:2px solid var(--dk-ui-accent);outline-offset:1px}
22
+ .docxkeun-comments .dk-card.open,.docxkeun-comments .dk-card.dk-draft{cursor:default;border-color:var(--dk-ui-accent);box-shadow:var(--dk-ui-shadow)}
23
+ .docxkeun-comments .dk-card.resolved{opacity:.6}
24
+ .docxkeun-comments .dk-head{display:flex;align-items:center;gap:6px;min-width:0}
25
+ .docxkeun-comments .dk-avatar{flex:none;width:22px;height:22px;border-radius:50%;color:#fff;font-size:10px;font-weight:600;display:inline-flex;align-items:center;justify-content:center}
26
+ .docxkeun-comments .dk-who{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
27
+ .docxkeun-comments .dk-when{flex:none;margin-left:auto;font-size:12px;color:var(--dk-ui-muted)}
28
+ .docxkeun-comments .dk-text{margin-top:4px;white-space:pre-wrap;overflow-wrap:anywhere}
29
+ .docxkeun-comments .dk-clamp{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;line-clamp:2;overflow:hidden}
30
+ .docxkeun-comments .dk-replies{margin-top:4px;font-size:12px;color:var(--dk-ui-accent)}
31
+ .docxkeun-comments .dk-reply{border-top:1px solid var(--dk-ui-line);margin-top:8px;padding-top:8px}
32
+ .docxkeun-comments .dk-connector{position:absolute;right:100%;height:1px;background:var(--dk-ui-accent);pointer-events:none}
33
+ .docxkeun-comments .dk-actions,.docxkeun-comments .dk-composer-buttons{display:flex;gap:4px;margin-top:8px}
34
+ .docxkeun-comments .dk-actions button,.docxkeun-comments .dk-composer-buttons button,.docxkeun-comments .dk-resolved-switch,.docxkeun-comments .dk-pop-nav button{height:26px;min-width:26px;padding:0 8px;border:1px solid var(--dk-ui-line);border-radius:4px;background:transparent;cursor:pointer;display:inline-flex;align-items:center;justify-content:center}
35
+ .docxkeun-comments button:hover:not(:disabled){background:var(--dk-ui-hover)}
36
+ .docxkeun-comments button:disabled{opacity:.4;cursor:default}
37
+ .docxkeun-comments .dk-composer-buttons .dk-post{background:var(--dk-ui-accent);border-color:var(--dk-ui-accent);color:#fff}
38
+ .docxkeun-comments .dk-composer-buttons .dk-post:hover:not(:disabled){background:var(--dk-ui-accent)}
39
+ .docxkeun-comments textarea{display:block;width:100%;box-sizing:border-box;min-height:56px;margin-top:8px;padding:6px 8px;border:1px solid var(--dk-ui-line);border-radius:4px;background:var(--dk-ui-bg);color:inherit;font:inherit;resize:vertical}
40
+ .docxkeun-comments .dk-resolved-switch{position:absolute;top:4px;right:0;pointer-events:auto;font-size:12px;color:var(--dk-ui-muted);background:var(--dk-ui-bg)}
41
+ .docxkeun-comments .dk-resolved-switch[aria-checked=true]{color:var(--dk-ui-fg);background:var(--dk-ui-accent-soft)}
42
+ .docxkeun-comments .dk-bubble{position:absolute;left:4px;width:${BUBBLE_SIZE}px;height:${BUBBLE_SIZE}px;padding:0;border-radius:50%;border:1px solid var(--dk-ui-line);background:var(--dk-ui-bg);cursor:pointer;pointer-events:auto;box-shadow:0 1px 2px rgba(60,64,67,.25);font-size:12px;font-weight:600;display:inline-flex;align-items:center;justify-content:center;color:var(--dk-ui-accent)}
43
+ .docxkeun-comments .dk-bubble.open{background:var(--dk-ui-accent);border-color:var(--dk-ui-accent);color:#fff}
44
+ .docxkeun-comments .dk-pop{position:absolute;width:${COLUMN}px;pointer-events:auto}
45
+ .docxkeun-comments .dk-pop .dk-card{position:relative;left:auto;right:auto;transition:none}
46
+ .docxkeun-comments .dk-pop-nav{display:flex;align-items:center;justify-content:flex-end;gap:6px;margin-bottom:4px;font-size:12px;color:var(--dk-ui-muted)}
47
+ `;
48
+ function ensureStyle() {
49
+ ensureUiStyle();
50
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID))
51
+ return;
52
+ const style = document.createElement('style');
53
+ style.id = STYLE_ID;
54
+ style.textContent = CSS;
55
+ document.head.appendChild(style);
56
+ }
57
+ /** "just now", "5m ago", "3h ago", "2d ago", else a short date. Empty without a date. */
58
+ export function relativeTime(date, now = Date.now()) {
59
+ if (!date)
60
+ return '';
61
+ const t = Date.parse(date);
62
+ if (Number.isNaN(t))
63
+ return date;
64
+ const s = Math.max(0, (now - t) / 1000);
65
+ if (s < 45)
66
+ return 'just now';
67
+ if (s < 3600)
68
+ return `${Math.max(1, Math.round(s / 60))}m ago`;
69
+ if (s < 86400)
70
+ return `${Math.round(s / 3600)}h ago`;
71
+ if (s < 7 * 86400)
72
+ return `${Math.round(s / 86400)}d ago`;
73
+ const d = new Date(t);
74
+ return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', ...(d.getFullYear() === new Date(now).getFullYear() ? {} : { year: 'numeric' }) });
75
+ }
76
+ function initialsOf(c) {
77
+ const given = c.initials?.trim();
78
+ if (given)
79
+ return given.slice(0, 3).toUpperCase();
80
+ const words = c.author.trim().split(/\s+/).filter(Boolean);
81
+ return (words.length > 1 ? words[0][0] + words[words.length - 1][0] : (words[0]?.slice(0, 2) ?? '?')).toUpperCase();
82
+ }
83
+ function el(tag, className, text) {
84
+ const e = document.createElement(tag);
85
+ if (className)
86
+ e.className = className;
87
+ if (text !== undefined)
88
+ e.textContent = text;
89
+ return e;
90
+ }
91
+ function signature(t, open, replying, actions) {
92
+ const part = (c) => [c.id, c.author, c.initials, c.text, c.date, c.dateUtc, c.resolved];
93
+ return JSON.stringify([part(t.comment), t.replies.map(part), open, replying, actions]);
94
+ }
95
+ function textButton(label, run, className) {
96
+ const b = el('button', className, label);
97
+ b.type = 'button';
98
+ b.addEventListener('click', (e) => {
99
+ e.stopPropagation();
100
+ run();
101
+ });
102
+ return b;
103
+ }
104
+ /** Controls the comment column of a viewer (`viewer.comments`). */
105
+ export class CommentsController {
106
+ host;
107
+ shown;
108
+ pref;
109
+ auto;
110
+ eff = 'cards';
111
+ announced;
112
+ showRes;
113
+ threadList = [];
114
+ openId;
115
+ pendingOpen;
116
+ draft;
117
+ docSeen;
118
+ replying = new Set();
119
+ colWidth = 0;
120
+ builtWidth = 0;
121
+ layer;
122
+ cards = new Map();
123
+ colors = new Map();
124
+ cleanup = [];
125
+ constructor(host, options = {}) {
126
+ this.host = host;
127
+ this.shown = options.visible ?? true;
128
+ this.pref = options.mode ?? 'auto';
129
+ this.showRes = options.showResolved ?? false;
130
+ this.cleanup.push(host.on('layout', () => {
131
+ this.refresh();
132
+ // A new comment that still has no place after a layout is not opened later.
133
+ this.pendingOpen = undefined;
134
+ }));
135
+ if (typeof document !== 'undefined') {
136
+ document.addEventListener('click', this.onDocClick, true);
137
+ document.addEventListener('keydown', this.onKey, true);
138
+ this.cleanup.push(() => {
139
+ document.removeEventListener('click', this.onDocClick, true);
140
+ document.removeEventListener('keydown', this.onKey, true);
141
+ });
142
+ }
143
+ if (typeof ResizeObserver !== 'undefined') {
144
+ let last = host.root.clientWidth;
145
+ const ro = new ResizeObserver(() => {
146
+ if (host.root.clientWidth === last)
147
+ return;
148
+ last = host.root.clientWidth;
149
+ this.refresh();
150
+ });
151
+ ro.observe(host.root);
152
+ this.cleanup.push(() => ro.disconnect());
153
+ }
154
+ }
155
+ get visible() {
156
+ return this.shown;
157
+ }
158
+ show() {
159
+ this.setVisible(true);
160
+ }
161
+ hide() {
162
+ this.setVisible(false);
163
+ }
164
+ setVisible(on) {
165
+ if (on === this.shown)
166
+ return;
167
+ this.shown = on;
168
+ this.refresh();
169
+ this.host.emit('chromechange', { part: 'comments', visible: on, collapsed: this.eff === 'bubbles' });
170
+ }
171
+ get mode() {
172
+ return this.pref;
173
+ }
174
+ set mode(value) {
175
+ if (value === this.pref)
176
+ return;
177
+ this.pref = value;
178
+ this.refresh();
179
+ }
180
+ get effectiveMode() {
181
+ return this.eff;
182
+ }
183
+ get showResolved() {
184
+ return this.showRes;
185
+ }
186
+ set showResolved(value) {
187
+ if (value === this.showRes)
188
+ return;
189
+ this.showRes = value;
190
+ this.refresh();
191
+ }
192
+ /** The space the column takes beside the pages now, in CSS px (0 when hidden or without comments). */
193
+ get width() {
194
+ return this.colWidth;
195
+ }
196
+ /** The column's element, when there is one. */
197
+ get element() {
198
+ return this.layer;
199
+ }
200
+ /** The id of the thread that is open. */
201
+ get openThread() {
202
+ return this.openId;
203
+ }
204
+ /** @internal The viewer rebuilt its rows with the current width. */
205
+ rowsBuilt() {
206
+ this.builtWidth = this.colWidth;
207
+ }
208
+ /** Open a thread (a reply's id opens its thread): line it up with its anchor and draw the connector. */
209
+ open(id) {
210
+ if (!this.shown)
211
+ return;
212
+ this.threadList = this.host.threads();
213
+ if (!this.openThreadById(id))
214
+ return;
215
+ this.refresh();
216
+ }
217
+ /** Open without redrawing. False when there is no such thread or it is already open. */
218
+ openThreadById(id) {
219
+ const t = this.find(id);
220
+ if (!t || this.openId === t.comment.id)
221
+ return false;
222
+ if (this.openId)
223
+ this.replying.delete(this.openId);
224
+ this.openId = t.comment.id;
225
+ this.host.setActive([t.comment.id, ...t.replies.map((r) => r.id)]);
226
+ this.host.emit('commentclick', { comment: t.comment });
227
+ return true;
228
+ }
229
+ /** Open a thread and start its reply box (no-op where the viewer cannot reply). */
230
+ reply(id) {
231
+ if (!this.host.editable() || !this.host.can('reply'))
232
+ return;
233
+ if (!this.shown)
234
+ this.show();
235
+ this.threadList = this.host.threads();
236
+ const t = this.find(id);
237
+ if (!t)
238
+ return;
239
+ this.openThreadById(id);
240
+ this.replying.add(t.comment.id);
241
+ this.refresh();
242
+ }
243
+ close() {
244
+ if (!this.openId)
245
+ return;
246
+ this.replying.delete(this.openId);
247
+ this.openId = undefined;
248
+ this.host.setActive([]);
249
+ this.refresh();
250
+ }
251
+ /** Start a comment on the current selection: a draft card with a text box beside it. */
252
+ compose() {
253
+ if (!this.host.editable() || !this.host.can('comment'))
254
+ return;
255
+ const selection = this.host.selection();
256
+ if (!selection)
257
+ return;
258
+ if (!this.shown)
259
+ this.show();
260
+ this.draft = selection;
261
+ this.refresh();
262
+ }
263
+ /** Recompute what is shown from the host and redraw. Called on layout, resize and state changes. */
264
+ refresh() {
265
+ this.sync();
266
+ if (this.pendingOpen && this.openThreadById(this.pendingOpen))
267
+ this.pendingOpen = undefined;
268
+ if (this.colWidth !== this.builtWidth) {
269
+ this.host.rebuild();
270
+ this.builtWidth = this.colWidth;
271
+ }
272
+ this.place();
273
+ }
274
+ /** Update the threads, the mode and the width, without touching the DOM. */
275
+ sync() {
276
+ const doc = this.host.currentDocument?.();
277
+ if (doc !== this.docSeen) {
278
+ // The draft's range, a reply being typed and a comment waiting to open belong to the old document.
279
+ this.docSeen = doc;
280
+ this.draft = undefined;
281
+ this.replying.clear();
282
+ this.pendingOpen = undefined;
283
+ }
284
+ this.threadList = this.host.threads();
285
+ if (this.openId && !this.find(this.openId)) {
286
+ this.openId = undefined;
287
+ this.host.setActive([]);
288
+ }
289
+ this.eff = this.computeMode();
290
+ const modeChanged = this.announced !== undefined && this.announced !== this.eff;
291
+ this.announced = this.eff;
292
+ this.colWidth = this.shown && this.has() ? (this.eff === 'cards' ? COLUMN : STRIP) + GAP : 0;
293
+ if (modeChanged)
294
+ this.host.emit('chromechange', { part: 'comments', visible: this.shown, collapsed: this.eff === 'bubbles' });
295
+ }
296
+ destroy() {
297
+ for (const fn of this.cleanup)
298
+ fn();
299
+ this.layer?.remove();
300
+ this.layer = undefined;
301
+ }
302
+ // ---- state ---------------------------------------------------------------------------------
303
+ has() {
304
+ return this.threadList.length > 0 || !!this.draft;
305
+ }
306
+ computeMode() {
307
+ if (this.pref !== 'auto')
308
+ return this.pref;
309
+ const width = this.host.root.clientWidth;
310
+ // Without a measured width (not laid out yet) keep what was chosen.
311
+ if (!width)
312
+ return this.auto ?? 'cards';
313
+ return (this.auto = commentMode(width, this.host.widestPage(), this.auto));
314
+ }
315
+ find(id) {
316
+ return this.threadList.find((t) => t.comment.id === id || t.replies.some((r) => r.id === id));
317
+ }
318
+ resolvedCount() {
319
+ return this.threadList.filter((t) => t.comment.resolved).length;
320
+ }
321
+ /** Threads shown now: resolved ones only when switched on (or open), and only those with a place. */
322
+ visibleThreads() {
323
+ const out = [];
324
+ for (const thread of this.threadList) {
325
+ if (thread.comment.resolved && !this.showRes && this.openId !== thread.comment.id)
326
+ continue;
327
+ const at = this.host.anchorOf(thread);
328
+ if (at)
329
+ out.push({ thread, at });
330
+ }
331
+ return out;
332
+ }
333
+ actionsFor(t) {
334
+ if (!this.host.editable())
335
+ return { reply: false, resolve: false, del: false };
336
+ return {
337
+ reply: this.host.can('reply'),
338
+ resolve: this.host.can('resolveComment'),
339
+ del: this.host.can('deleteComment', { commentAuthor: t.comment.author }),
340
+ };
341
+ }
342
+ // ---- events --------------------------------------------------------------------------------
343
+ onDocClick = (e) => {
344
+ const target = e.target;
345
+ if (!target || this.layer?.contains(target))
346
+ return;
347
+ if (this.host.root.contains(target)) {
348
+ const hit = this.highlightAt(e.clientX, e.clientY);
349
+ const thread = hit ? this.find(hit) : undefined;
350
+ if (thread) {
351
+ this.open(thread.comment.id);
352
+ return;
353
+ }
354
+ }
355
+ if (this.openId)
356
+ this.close();
357
+ };
358
+ /** Esc closes the open thread from the page, the editing input or the column (capture: the editor handles Esc itself). */
359
+ onKey = (e) => {
360
+ if (e.key !== 'Escape' || !this.openId)
361
+ return;
362
+ const target = e.target;
363
+ if (!target || !this.host.root.contains(target))
364
+ return;
365
+ // A text box in the column cancels itself.
366
+ if (target.tagName === 'TEXTAREA' && this.layer?.contains(target))
367
+ return;
368
+ this.close();
369
+ };
370
+ highlightAt(x, y) {
371
+ for (const hl of this.host.root.querySelectorAll('.docxkeun-comment-hl')) {
372
+ const r = hl.getBoundingClientRect();
373
+ if (r.width > 0 && x >= r.left && x <= r.right && y >= r.top && y <= r.bottom)
374
+ return hl.dataset.comment;
375
+ }
376
+ return undefined;
377
+ }
378
+ // ---- drawing -------------------------------------------------------------------------------
379
+ place() {
380
+ if (!this.shown || !this.has()) {
381
+ this.layer?.remove();
382
+ this.layer = undefined;
383
+ this.cards.clear();
384
+ return;
385
+ }
386
+ ensureStyle();
387
+ const mode = this.eff;
388
+ if (!this.layer || this.layer.dataset.mode !== mode) {
389
+ this.layer?.remove();
390
+ this.cards.clear();
391
+ const layer = el('div', 'docxkeun-comments docxkeun-ui-root');
392
+ layer.dataset.mode = mode;
393
+ layer.setAttribute('role', 'complementary');
394
+ layer.setAttribute('aria-label', 'Comments');
395
+ this.host.root.appendChild(layer);
396
+ this.layer = layer;
397
+ }
398
+ this.layer.style.left = `${this.host.columnX()}px`;
399
+ this.layer.style.width = `${mode === 'cards' ? COLUMN : STRIP}px`;
400
+ if (mode === 'cards')
401
+ this.placeCards();
402
+ else
403
+ this.placeBubbles();
404
+ }
405
+ placeCards() {
406
+ const layer = this.layer;
407
+ for (const stale of layer.querySelectorAll('.dk-bubble,.dk-pop'))
408
+ stale.remove();
409
+ const visible = this.visibleThreads();
410
+ const wanted = new Set();
411
+ const boxes = [];
412
+ const floor = this.resolvedCount() > 0 ? SWITCH_FLOOR : 0;
413
+ const order = [];
414
+ const fresh = new Set();
415
+ const connectors = new Map();
416
+ const cardFor = (id, create) => {
417
+ wanted.add(id);
418
+ let rec = this.cards.get(id);
419
+ if (!rec) {
420
+ const card = el('div', 'dk-card');
421
+ card.dataset.comment = id;
422
+ create(card);
423
+ rec = { el: card, sig: '' };
424
+ this.cards.set(id, rec);
425
+ layer.appendChild(card);
426
+ fresh.add(card);
427
+ }
428
+ order.push(rec.el);
429
+ return rec;
430
+ };
431
+ for (const { thread, at } of visible) {
432
+ const id = thread.comment.id;
433
+ const open = this.openId === id;
434
+ const actions = this.actionsFor(thread);
435
+ const sig = signature(thread, open, this.replying.has(id), actions);
436
+ const rec = cardFor(id, (c) => this.wireCard(c, id));
437
+ if (rec.sig !== sig) {
438
+ this.fillCard(rec.el, thread, open, actions);
439
+ rec.sig = sig;
440
+ }
441
+ if (open)
442
+ connectors.set(id, at);
443
+ boxes.push({ id, anchorY: Math.max(at.top, floor), height: 0 });
444
+ }
445
+ if (this.draft) {
446
+ const rec = cardFor(DRAFT, (c) => c.classList.add('dk-draft', 'open'));
447
+ if (!rec.sig) {
448
+ this.fillDraft(rec.el);
449
+ rec.sig = 'draft';
450
+ }
451
+ connectors.set(DRAFT, this.draft);
452
+ boxes.push({ id: DRAFT, anchorY: Math.max(this.draft.top, floor), height: 0 });
453
+ }
454
+ for (const [id, rec] of this.cards) {
455
+ if (wanted.has(id))
456
+ continue;
457
+ rec.el.remove();
458
+ this.cards.delete(id);
459
+ }
460
+ this.fillSwitch();
461
+ // Tab order follows the cards' order on the page; moving nodes only when it differs keeps focus.
462
+ const present = [...layer.querySelectorAll('.dk-card')];
463
+ if (present.some((c, i) => c !== order[i]))
464
+ for (const c of order)
465
+ layer.appendChild(c);
466
+ for (const box of boxes)
467
+ box.height = this.cards.get(box.id).el.offsetHeight;
468
+ const tops = layoutCards(boxes, this.draft ? DRAFT : this.openId, CARD_GAP);
469
+ for (const box of boxes) {
470
+ const rec = this.cards.get(box.id);
471
+ const top = tops.get(box.id) ?? box.anchorY;
472
+ // A card that was just created appears in place instead of sliding in from the top.
473
+ if (fresh.has(rec.el))
474
+ rec.el.style.transition = 'none';
475
+ rec.el.style.top = `${top}px`;
476
+ if (fresh.has(rec.el)) {
477
+ void rec.el.offsetHeight;
478
+ rec.el.style.transition = '';
479
+ }
480
+ }
481
+ for (const [id, at] of connectors)
482
+ this.fillConnector(this.cards.get(id).el, at);
483
+ }
484
+ fillSwitch() {
485
+ const layer = this.layer;
486
+ let sw = layer.querySelector('.dk-resolved-switch');
487
+ const n = this.resolvedCount();
488
+ if (!n) {
489
+ sw?.remove();
490
+ return;
491
+ }
492
+ if (!sw) {
493
+ sw = textButton('', () => (this.showResolved = !this.showRes), 'dk-resolved-switch');
494
+ sw.setAttribute('role', 'switch');
495
+ layer.appendChild(sw);
496
+ }
497
+ sw.textContent = `Show resolved (${n})`;
498
+ sw.setAttribute('aria-checked', String(this.showRes));
499
+ }
500
+ placeBubbles() {
501
+ const layer = this.layer;
502
+ const visible = this.visibleThreads();
503
+ const groups = bubbleGroups(visible.map(({ thread, at }) => ({ id: thread.comment.id, y: at.top })), BUBBLE_SIZE + 2);
504
+ const mark = (ids) => ids.includes(this.openId ?? '\0');
505
+ // Bubbles and the popover stay across refreshes, so a reply being typed keeps its text and focus.
506
+ const existing = new Map([...layer.querySelectorAll('.dk-bubble')].map((b) => [b.dataset.key, b]));
507
+ for (const group of groups) {
508
+ const key = group.ids.join(',');
509
+ let b = existing.get(key);
510
+ if (b)
511
+ existing.delete(key);
512
+ else {
513
+ b = textButton('', () => this.open(group.ids[0]), 'dk-bubble');
514
+ b.dataset.key = key;
515
+ if (group.ids.length > 1)
516
+ b.textContent = String(group.ids.length);
517
+ else
518
+ b.innerHTML = icon('comment');
519
+ b.setAttribute('aria-label', group.ids.length > 1 ? `${group.ids.length} comments` : 'Comment');
520
+ layer.appendChild(b);
521
+ }
522
+ b.style.top = `${group.y}px`;
523
+ b.classList.toggle('open', mark(group.ids));
524
+ }
525
+ for (const stale of existing.values())
526
+ stale.remove();
527
+ const pop = layer.querySelector('.dk-pop');
528
+ const drop = () => pop?.remove();
529
+ const group = groups.find((g) => mark(g.ids));
530
+ const thread = this.openId ? this.find(this.openId) : undefined;
531
+ if (this.draft) {
532
+ if (pop?.dataset.sig === 'draft') {
533
+ this.placePopover(pop, this.draft);
534
+ return;
535
+ }
536
+ drop();
537
+ const next = el('div', 'dk-pop docxkeun-ui-root');
538
+ next.dataset.sig = 'draft';
539
+ const card = el('div', 'dk-card dk-draft open');
540
+ card.dataset.comment = DRAFT;
541
+ this.fillDraft(card);
542
+ next.appendChild(card);
543
+ layer.appendChild(next);
544
+ this.placePopover(next, this.draft);
545
+ return;
546
+ }
547
+ if (!group || !thread)
548
+ return drop();
549
+ const at = visible.find((v) => v.thread.comment.id === thread.comment.id)?.at ?? { top: group.y, pageRight: 0, height: 0 };
550
+ const actions = this.actionsFor(thread);
551
+ const sig = signature(thread, true, this.replying.has(thread.comment.id), actions) + group.ids.join(',');
552
+ if (pop?.dataset.sig === sig) {
553
+ this.placePopover(pop, at);
554
+ return;
555
+ }
556
+ drop();
557
+ const next = el('div', 'dk-pop docxkeun-ui-root');
558
+ next.dataset.sig = sig;
559
+ if (group.ids.length > 1) {
560
+ const at = group.ids.indexOf(thread.comment.id);
561
+ const nav = el('div', 'dk-pop-nav');
562
+ const prev = textButton('', () => this.step(group.ids, -1), 'dk-prev');
563
+ prev.innerHTML = icon('back');
564
+ prev.setAttribute('aria-label', 'Previous comment');
565
+ prev.disabled = at <= 0;
566
+ const forward = textButton('', () => this.step(group.ids, 1), 'dk-next');
567
+ forward.innerHTML = icon('forward');
568
+ forward.setAttribute('aria-label', 'Next comment');
569
+ forward.disabled = at >= group.ids.length - 1;
570
+ nav.append(el('span', 'dk-count', `${at + 1} of ${group.ids.length}`), prev, forward);
571
+ next.appendChild(nav);
572
+ }
573
+ const card = el('div', 'dk-card');
574
+ card.dataset.comment = thread.comment.id;
575
+ this.fillCard(card, thread, true, actions);
576
+ card.querySelector('.dk-connector')?.remove();
577
+ next.appendChild(card);
578
+ layer.appendChild(next);
579
+ this.placePopover(next, at);
580
+ }
581
+ /**
582
+ * Put a bubble popover below the last line of its text (so it never covers it), its right edge
583
+ * on the bubble strip's, inside the visible part of the viewer; above the text when there is
584
+ * no room below.
585
+ */
586
+ placePopover(pop, at) {
587
+ const root = this.host.root;
588
+ const x = parseFloat(this.layer.style.left) || 0;
589
+ let left = x + STRIP - COLUMN;
590
+ if (root.clientWidth > 0)
591
+ left = Math.max(root.scrollLeft + EDGE, Math.min(left, root.scrollLeft + root.clientWidth - COLUMN - EDGE));
592
+ pop.style.left = `${left - x}px`;
593
+ const below = (at.bottom ?? at.top + at.height) + POP_GAP;
594
+ let top = below;
595
+ const h = pop.offsetHeight;
596
+ const view = root.clientHeight;
597
+ if (view > 0 && h > 0) {
598
+ const viewTop = root.scrollTop + EDGE;
599
+ const viewBottom = root.scrollTop + view - EDGE;
600
+ const above = at.top - POP_GAP - h;
601
+ if (below + h > viewBottom)
602
+ top = above >= viewTop ? above : Math.max(viewTop, viewBottom - h);
603
+ }
604
+ pop.style.top = `${top}px`;
605
+ }
606
+ step(ids, by) {
607
+ const at = ids.indexOf(this.openId ?? '');
608
+ const id = ids[at + by];
609
+ if (id)
610
+ this.open(id);
611
+ }
612
+ wireCard(card, id) {
613
+ card.tabIndex = 0;
614
+ card.setAttribute('role', 'group');
615
+ card.addEventListener('click', () => {
616
+ if (this.openId !== id)
617
+ this.open(id);
618
+ });
619
+ card.addEventListener('keydown', (e) => {
620
+ if (e.target !== card || (e.key !== 'Enter' && e.key !== ' '))
621
+ return;
622
+ e.preventDefault();
623
+ if (this.openId !== id)
624
+ this.open(id);
625
+ });
626
+ }
627
+ fillConnector(card, at) {
628
+ const line = card.querySelector('.dk-connector');
629
+ if (!line)
630
+ return;
631
+ const cardTop = parseFloat(card.style.top) || at.top;
632
+ const x = parseFloat(this.layer.style.left) || 0;
633
+ line.style.width = `${Math.max(0, x - at.pageRight)}px`;
634
+ line.style.top = `${Math.max(8, Math.min(Math.max(8, card.offsetHeight - 8), at.top + at.height / 2 - cardTop))}px`;
635
+ }
636
+ colorOf(author) {
637
+ let color = this.colors.get(author);
638
+ if (!color) {
639
+ color = `#${REVISION_COLORS[this.colors.size % REVISION_COLORS.length]}`;
640
+ this.colors.set(author, color);
641
+ }
642
+ return color;
643
+ }
644
+ head(c) {
645
+ const head = el('div', 'dk-head');
646
+ const avatar = el('span', 'dk-avatar', initialsOf(c));
647
+ avatar.style.background = this.colorOf(c.author);
648
+ avatar.setAttribute('aria-hidden', 'true');
649
+ const date = c.dateUtc ?? c.date;
650
+ const when = el('span', 'dk-when', relativeTime(date));
651
+ if (date && !Number.isNaN(Date.parse(date)))
652
+ when.title = new Date(date).toLocaleString();
653
+ head.append(avatar, el('span', 'dk-who', c.author || 'Unknown'), when);
654
+ return head;
655
+ }
656
+ fillCard(card, t, open, actions) {
657
+ const c = t.comment;
658
+ card.replaceChildren();
659
+ card.classList.toggle('open', open);
660
+ card.classList.toggle('resolved', c.resolved);
661
+ card.setAttribute('aria-expanded', String(open));
662
+ card.setAttribute('aria-label', `Comment by ${c.author || 'Unknown'}`);
663
+ if (!open) {
664
+ card.append(this.head(c), el('div', 'dk-text dk-clamp', c.text));
665
+ if (t.replies.length)
666
+ card.appendChild(el('div', 'dk-replies', `${t.replies.length} ${t.replies.length === 1 ? 'reply' : 'replies'}`));
667
+ return;
668
+ }
669
+ card.append(el('div', 'dk-connector'), this.head(c), el('div', 'dk-text', c.text));
670
+ for (const r of t.replies) {
671
+ const item = el('div', 'dk-reply');
672
+ item.append(this.head(r), el('div', 'dk-text', r.text));
673
+ card.appendChild(item);
674
+ }
675
+ if (this.replying.has(c.id)) {
676
+ card.appendChild(this.composer('Reply', 'Reply…', (text) => this.postReply(c.id, text), () => {
677
+ this.replying.delete(c.id);
678
+ this.refresh();
679
+ }));
680
+ }
681
+ else if (actions.reply || actions.resolve || actions.del) {
682
+ const row = el('div', 'dk-actions');
683
+ if (actions.reply) {
684
+ row.appendChild(textButton('Reply', () => {
685
+ this.replying.add(c.id);
686
+ this.refresh();
687
+ }));
688
+ }
689
+ if (actions.resolve)
690
+ row.appendChild(textButton(c.resolved ? 'Reopen' : 'Resolve', () => void this.resolve(t)));
691
+ if (actions.del)
692
+ row.appendChild(textButton('Delete', () => void this.remove(t)));
693
+ card.appendChild(row);
694
+ }
695
+ }
696
+ fillDraft(card) {
697
+ const me = { id: DRAFT, author: this.host.author(), text: '', blocks: [], resolved: false, el: {} };
698
+ card.replaceChildren(el('div', 'dk-connector'), this.head(me), this.composer('Comment', 'Add a comment…', (text) => this.postDraft(text), () => {
699
+ this.draft = undefined;
700
+ this.refresh();
701
+ }));
702
+ card.querySelector('.dk-when')?.remove();
703
+ card.setAttribute('aria-label', 'New comment');
704
+ }
705
+ /** A text box with Post and Cancel. `post` rejects to keep the box (the viewer reports the error). */
706
+ composer(label, placeholder, post, cancel) {
707
+ const wrap = el('div', 'dk-composer');
708
+ const box = el('textarea');
709
+ box.placeholder = placeholder;
710
+ box.setAttribute('aria-label', label);
711
+ queueMicrotask(() => box.isConnected && box.focus());
712
+ const send = textButton('Post', () => {
713
+ const text = box.value.trim();
714
+ if (!text)
715
+ return;
716
+ send.disabled = true;
717
+ box.disabled = true;
718
+ post(text).catch(() => {
719
+ send.disabled = !box.value.trim();
720
+ box.disabled = false;
721
+ box.focus();
722
+ });
723
+ }, 'dk-post');
724
+ send.disabled = true;
725
+ box.addEventListener('input', () => (send.disabled = !box.value.trim()));
726
+ box.addEventListener('keydown', (e) => {
727
+ if (e.key === 'Escape') {
728
+ e.stopPropagation();
729
+ cancel();
730
+ }
731
+ else if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
732
+ e.preventDefault();
733
+ if (!send.disabled)
734
+ send.click();
735
+ }
736
+ });
737
+ const buttons = el('div', 'dk-composer-buttons');
738
+ buttons.append(send, textButton('Cancel', cancel));
739
+ wrap.append(box, buttons);
740
+ return wrap;
741
+ }
742
+ // ---- edits ---------------------------------------------------------------------------------
743
+ async postReply(id, text) {
744
+ const author = this.host.author();
745
+ await this.host.transaction('Reply', (editor) => editor.replyToComment(id, { author, text }));
746
+ this.replying.delete(id);
747
+ this.refresh();
748
+ }
749
+ async postDraft(text) {
750
+ const draft = this.draft;
751
+ if (!draft)
752
+ return;
753
+ const author = this.host.author();
754
+ const id = await this.host.transaction('Add comment', (editor) => editor.addComment(draft.range, { author, text }));
755
+ this.draft = undefined;
756
+ this.pendingOpen = id;
757
+ this.refresh();
758
+ }
759
+ async resolve(t) {
760
+ const resolved = !t.comment.resolved;
761
+ try {
762
+ await this.host.transaction(resolved ? 'Resolve comment' : 'Reopen comment', (editor) => editor.resolveComment(t.comment.id, resolved));
763
+ }
764
+ catch {
765
+ return;
766
+ }
767
+ if (resolved)
768
+ this.close();
769
+ }
770
+ async remove(t) {
771
+ try {
772
+ await this.host.transaction('Delete comment', (editor) => editor.deleteComment(t.comment.id));
773
+ }
774
+ catch {
775
+ return;
776
+ }
777
+ this.close();
778
+ }
779
+ }