@folijs/view 0.4.0 → 0.6.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 (71) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/dist/clipboard.d.ts +3 -1
  3. package/dist/clipboard.d.ts.map +1 -1
  4. package/dist/clipboard.js.map +1 -1
  5. package/dist/index.d.ts +2 -1
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +2 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/layout/flow.d.ts +195 -20
  10. package/dist/layout/flow.d.ts.map +1 -1
  11. package/dist/layout/flow.js +790 -102
  12. package/dist/layout/flow.js.map +1 -1
  13. package/dist/print.d.ts +22 -0
  14. package/dist/print.d.ts.map +1 -0
  15. package/dist/print.js +31 -0
  16. package/dist/print.js.map +1 -0
  17. package/dist/view.d.ts +407 -8
  18. package/dist/view.d.ts.map +1 -1
  19. package/dist/view.js +2956 -263
  20. package/dist/view.js.map +1 -1
  21. package/dist/word/blocks.d.ts +99 -2
  22. package/dist/word/blocks.d.ts.map +1 -1
  23. package/dist/word/blocks.js +535 -31
  24. package/dist/word/blocks.js.map +1 -1
  25. package/dist/word/columns.d.ts +23 -0
  26. package/dist/word/columns.d.ts.map +1 -0
  27. package/dist/word/columns.js +51 -0
  28. package/dist/word/columns.js.map +1 -0
  29. package/dist/word/controls.d.ts +63 -0
  30. package/dist/word/controls.d.ts.map +1 -0
  31. package/dist/word/controls.js +411 -0
  32. package/dist/word/controls.js.map +1 -0
  33. package/dist/word/edit.d.ts +32 -11
  34. package/dist/word/edit.d.ts.map +1 -1
  35. package/dist/word/edit.js +215 -33
  36. package/dist/word/edit.js.map +1 -1
  37. package/dist/word/matches.d.ts +23 -0
  38. package/dist/word/matches.d.ts.map +1 -0
  39. package/dist/word/matches.js +97 -0
  40. package/dist/word/matches.js.map +1 -0
  41. package/dist/word/notes.d.ts +105 -0
  42. package/dist/word/notes.d.ts.map +1 -0
  43. package/dist/word/notes.js +392 -0
  44. package/dist/word/notes.js.map +1 -0
  45. package/dist/word/pages.d.ts +26 -13
  46. package/dist/word/pages.d.ts.map +1 -1
  47. package/dist/word/pages.js +439 -203
  48. package/dist/word/pages.js.map +1 -1
  49. package/dist/word/regions.d.ts +113 -0
  50. package/dist/word/regions.d.ts.map +1 -0
  51. package/dist/word/regions.js +374 -0
  52. package/dist/word/regions.js.map +1 -0
  53. package/dist/word/table.d.ts +79 -0
  54. package/dist/word/table.d.ts.map +1 -0
  55. package/dist/word/table.js +210 -0
  56. package/dist/word/table.js.map +1 -0
  57. package/package.json +2 -2
  58. package/src/clipboard.ts +3 -0
  59. package/src/index.ts +8 -1
  60. package/src/layout/flow.ts +948 -111
  61. package/src/print.ts +48 -0
  62. package/src/view.ts +3291 -273
  63. package/src/word/blocks.ts +611 -28
  64. package/src/word/columns.ts +66 -0
  65. package/src/word/controls.ts +447 -0
  66. package/src/word/edit.ts +253 -30
  67. package/src/word/matches.ts +99 -0
  68. package/src/word/notes.ts +451 -0
  69. package/src/word/pages.ts +524 -192
  70. package/src/word/regions.ts +469 -0
  71. package/src/word/table.ts +267 -0
package/src/view.ts CHANGED
@@ -2,41 +2,86 @@ import {
2
2
  AllSelection,
3
3
  arrowAcrossLeaf,
4
4
  autolinkHref,
5
+ CellSelection,
5
6
  type Command,
7
+ type ControlRange,
8
+ caretStop,
9
+ cellsAsTable,
6
10
  closeHistory,
11
+ controlAt,
12
+ controlProperties,
13
+ controlSpot,
7
14
  type DocumentSettings,
15
+ type DocumentTarget,
8
16
  deleteBackward,
9
17
  deleteForward,
10
18
  deleteSelection,
19
+ deleteSelectionKeepingTables,
11
20
  type Editor,
12
21
  type EditorState,
22
+ ensureStory,
23
+ extendCellSelection,
24
+ type Field,
25
+ type FieldLayout,
26
+ type FieldsReport,
27
+ type FindMatch,
28
+ type FoundMatches,
29
+ fieldCodesShown,
30
+ fieldsIn,
13
31
  fitPaste,
14
32
  fitPastedV2,
33
+ goToCellVertically,
34
+ insertControlText,
15
35
  insertHardBreak,
16
36
  insertLink,
37
+ insertNote,
38
+ insertPicture,
17
39
  insertText,
18
40
  isSafeHref,
41
+ keepTablesApart,
19
42
  type Node as ModelNode,
20
43
  marksAt,
44
+ type NavigationRequest,
21
45
  NodeSelection,
46
+ type NoteNumber,
47
+ noteAtSelection,
48
+ noteNumbers,
49
+ noteProperties,
50
+ noteTexts,
51
+ type OpenStory,
52
+ pageVariant,
22
53
  parseContentV2,
54
+ pasteCells,
55
+ type ResourceJSON,
23
56
  type ReviewView,
24
57
  redo,
58
+ referencesIn,
25
59
  type SectionJSON,
26
60
  Selection,
27
61
  Slice,
62
+ type StorySide,
63
+ StoryStep,
64
+ type StoryView,
65
+ sameSpot,
28
66
  sectionSettings,
67
+ setColumnWidth,
29
68
  setComments,
30
69
  setLink,
70
+ setPictureSize,
31
71
  splitBlock,
72
+ storyOfSection,
32
73
  TextSelection,
33
74
  type Transaction,
34
75
  TransformError,
76
+ toggleFieldCodes,
35
77
  toggleMark,
36
78
  trackState,
37
79
  typedMarks,
80
+ type UpdateFieldsOptions,
38
81
  undo,
82
+ updateFields,
39
83
  type WordContext,
84
+ type WordSettingsJSON,
40
85
  withEnvelope,
41
86
  wordContext,
42
87
  } from "@folijs/core";
@@ -45,22 +90,110 @@ import {
45
90
  type BlockBox,
46
91
  contentHeight,
47
92
  DEFAULT_RULES,
93
+ type FlowNote,
94
+ type FlowPage,
48
95
  type FlowResult,
49
96
  type FlowRules,
97
+ type FlowSection,
98
+ type Fragment,
50
99
  flowFrom,
100
+ notePieces,
101
+ type PageFacts,
51
102
  PX_PER_MM,
103
+ pagesOf,
52
104
  type Reuse,
105
+ spaceAfterText,
53
106
  } from "./layout/flow.js";
54
- import { type BlockDesc, PAGE_BREAK_ATTR } from "./render.js";
55
-
56
- import { spacing, type WordBlockDesc, WordRenderer } from "./word/edit.js";
107
+ import { printStyles, SHEET_ATTR } from "./print.js";
108
+ import { type BlockDesc, type LeafDesc, PAGE_BREAK_ATTR } from "./render.js";
109
+ import {
110
+ EMU_PER_PX,
111
+ imageSource,
112
+ NOTE_NUMBER_ATTR,
113
+ NOTE_REF_ATTR,
114
+ PICTURE_ATTR,
115
+ WORD_COLUMN_BREAK_ATTR,
116
+ } from "./word/blocks.js";
117
+ import {
118
+ BAND_CLASS,
119
+ bandElement,
120
+ COLUMN_CLASS,
121
+ type ColumnsPx,
122
+ columnsKey,
123
+ columnsPx,
124
+ } from "./word/columns.js";
125
+ import {
126
+ type Box,
127
+ boxOf,
128
+ CONTROL_STYLES,
129
+ CONTROL_UI_ATTR,
130
+ ControlChrome,
131
+ } from "./word/controls.js";
132
+ import {
133
+ FLOAT_ANCHORS,
134
+ spacing,
135
+ type WordBlockDesc,
136
+ type WordInfo,
137
+ WordRenderer,
138
+ } from "./word/edit.js";
139
+ import { MATCH_STYLES, MatchMarks, rangesInText } from "./word/matches.js";
140
+ import { NOTE_ATTR, type NoteGroup, PageNotes } from "./word/notes.js";
57
141
  import { measureLineRatio } from "./word/pages.js";
142
+ import { PageRegions, REGION_CONTENT_CLASS } from "./word/regions.js";
143
+ import {
144
+ collect,
145
+ type FlowItem,
146
+ FRAME_ATTR,
147
+ type Frame,
148
+ frameElement,
149
+ REPEATED_ATTR,
150
+ type Unit,
151
+ } from "./word/table.js";
152
+
153
+ /** What the flow needs of a table: no paragraph spacing or keep rules of its own. */
154
+ const TABLE_WORD: WordInfo = {
155
+ before: 0,
156
+ after: 0,
157
+ keepNext: false,
158
+ keepLines: false,
159
+ pageBreakBefore: false,
160
+ style: null,
161
+ contextual: false,
162
+ empty: false,
163
+ };
164
+
165
+ /** Where a table's fragment is: the rows it shows, the header rows drawn again above them. */
166
+ interface TablePart {
167
+ rows: number[];
168
+ headers: number[];
169
+ }
170
+
171
+ /** A table as last rendered: its wrappers (one per page it is on), their pages, how it was cut. */
172
+ interface FrameState {
173
+ wrappers: HTMLElement[];
174
+ pages: number[];
175
+ /** The parts and the units' fragments in each, as a string: equal means the same DOM. */
176
+ key: string;
177
+ }
178
+
179
+ /** A table's measurement, in layout px from the table's top (drawn whole). */
180
+ export interface TableMeasure {
181
+ rows: { top: number; bottom: number }[];
182
+ /** The top of each of its units (by index into the units), null for one not shown (covered). */
183
+ tops: Map<number, number | null>;
184
+ /** Where the table may break: inside rows that may split, and between rows (sorted). */
185
+ breaks?: number[];
186
+ }
58
187
 
59
188
  /** Word's paragraph spacing for a schema v3 document (`flow`'s `word` spacing). */
60
189
  const WORD_RULES: FlowRules = { ...DEFAULT_RULES, spacing: "word" };
61
190
 
62
191
  /** Class of the element of a node-selected block (a rule). */
63
192
  const SELECTED_CLASS = "foli-selected-node";
193
+ /** Marks a cell of a cell selection. */
194
+ const CELL_CLASS = "foli-selected-cell";
195
+ /** On the host while cells are selected: the browser's own highlight (in DOM order) is hidden. */
196
+ const CELLS_ATTR = "data-foli-cells";
64
197
 
65
198
  interface DomPoint {
66
199
  node: Node;
@@ -72,12 +205,42 @@ export interface EditorViewOptions {
72
205
  editable?: boolean;
73
206
  /** Shown while the document is one empty block (default: none). */
74
207
  placeholder?: string;
208
+ /**
209
+ * The URL to show a picture's image from (`key` in the document's `resources`): an image in
210
+ * the .docx package it came from has none of its own (`packageImages` in `@folijs/docx` gives
211
+ * object URLs). Undefined for a key: the resource's own image `data:` URL or web URL (fetched
212
+ * as it is shown), else a box of the picture's size; `null` (or "") for a key: that box (an
213
+ * app that does not fetch web URLs found in documents says so here). `null` clears it.
214
+ */
215
+ resource?: ((key: string, resource: ResourceJSON) => string | null | undefined) | null;
216
+ /**
217
+ * Where pasted and dropped image files go (ADR-0006's upload hook): the URL the app stores the
218
+ * file at (or a `data:` URL, opting in), and the alt text if it has asked for it. Without it,
219
+ * image files are not pasted or dropped. A picture inserted without alt text is marked, as an
220
+ * imported one is.
221
+ */
222
+ upload?:
223
+ | ((file: File) => Promise<string | { src: string; alt?: string; decorative?: boolean }>)
224
+ | null;
225
+ /**
226
+ * `false`: the content in one flow, without pages, headers or print rules (a story being edited
227
+ * on its page, ADR-0007). Set when the view is made. Default true.
228
+ */
229
+ paged?: boolean;
230
+ /** What a note's own mark shows, for the view of a note being edited. */
231
+ noteMark?: () => string;
75
232
  }
76
233
 
77
234
  const PLACEHOLDER_ATTR = "data-foli-placeholder";
235
+ /** On the span of a selected picture (it holds the resize handle). */
236
+ const PICTURE_SELECTED_ATTR = "data-foli-picture-selected";
237
+ /** On what shows a field the selection is in: Word shades it. */
238
+ const FIELD_SELECTED_ATTR = "data-foli-field-selected";
239
+ /** The smallest a picture gets by dragging its handle, in px. */
240
+ const MIN_PICTURE = 8;
78
241
  // Generated content is not document text: no caret stops inside it, a zero-height float keeps
79
242
  // the caret at the line start, and the empty alt text keeps screen readers on aria-placeholder.
80
- const STYLES = `[${PLACEHOLDER_ATTR}]::before{content:attr(${PLACEHOLDER_ATTR});content:attr(${PLACEHOLDER_ATTR}) / "";float:inline-start;height:0;pointer-events:none;color:GrayText}`;
243
+ const STYLES = `[${FIELD_SELECTED_ATTR}]{background-color:rgba(0,0,0,.14)}@media print{[${FIELD_SELECTED_ATTR}]{background-color:transparent}}.foli-in-story>.foli-page>:not(.foli-region){opacity:.45}.foli-story-mount{pointer-events:auto;outline:1px dashed GrayText;outline-offset:2px}.foli-story-mount>[contenteditable=true]:focus{outline:none}@media print{.foli-in-story>.foli-page>:not(.foli-region){opacity:1}.foli-story-mount{outline:none}}.${CELL_CLASS}{box-shadow:inset 0 0 0 9999px rgba(0,120,215,.22)}[${CELLS_ATTR}] ::selection{background:transparent}[data-foli-no-alt]{outline:2px dashed #b45309;outline-offset:-2px}@media print{[data-foli-no-alt]{outline:none}}[${PICTURE_SELECTED_ATTR}]{position:relative;outline:2px solid Highlight}[${PICTURE_SELECTED_ATTR}] [data-foli-resize]{position:absolute;right:-5px;bottom:-5px;width:10px;height:10px;box-sizing:border-box;border:1px solid Canvas;background:Highlight;cursor:nwse-resize;forced-color-adjust:none}@media print{[${PICTURE_SELECTED_ATTR}]{outline:none}[${PICTURE_SELECTED_ATTR}] [data-foli-resize]{display:none}}[${PLACEHOLDER_ATTR}]::before{content:attr(${PLACEHOLDER_ATTR});content:attr(${PLACEHOLDER_ATTR}) / "";float:inline-start;height:0;pointer-events:none;color:GrayText}${CONTROL_STYLES}${MATCH_STYLES}`;
81
244
 
82
245
  /**
83
246
  * Adds the view's stylesheet once per document or shadow root, when a placeholder is first shown
@@ -102,34 +265,20 @@ const VIEW_ATTR = "data-foli-view";
102
265
  let viewCount = 0;
103
266
 
104
267
  /**
105
- * Print rules for the page settings of the view whose host has `VIEW_ATTR` = `id`: one sheet of
106
- * its section's size per page (the last section's where named pages are not supported), without
107
- * margins (the page's padding holds them). A page is exactly as tall as a sheet (the flow keeps content inside it; the exact height absorbs its
108
- * half-pixel slack), with no gap after it. Content taller than a page (a line taller than a
109
- * page) is not cut: it prints over the next sheet.
268
+ * Print rules for the page settings of the view whose host has `VIEW_ATTR` = `id` (`print.ts`,
269
+ * shared with the read-only renderer and so with `@folijs/pdf`).
110
270
  * shortcut: `@page` is per document: with several editors of different page sizes on one web page, the last one's sheet size wins (each keeps its own page rules); print one editor per document until that is needed.
111
271
  */
112
- function printStyles(settings: DocumentSettings, sheets: readonly Sheet[], id: string): string {
113
- const { width, height } = settings.pageSize;
114
- const last = sheetOf(settings, 0).css;
115
- const pages = `[${VIEW_ATTR}="${id}"]>.foli-page`;
116
- // Sections with other page setups: a named page each (engines without named pages print
117
- // every sheet at the last section's size).
118
- const named = sheets.every((sheet) => sheet.css === last)
119
- ? ""
120
- : sheets
121
- .map(({ settings: { pageSize: size }, index }) => {
122
- const name = `foli-${id}-${index}`;
123
- return (
124
- `@page ${name}{size:${size.width}mm ${size.height}mm;margin:0}` +
125
- `${pages}[${SHEET_ATTR}="${index}"]{page:${name};height:${size.height}mm!important}`
126
- );
127
- })
128
- .join("");
129
- return (
130
- `@media print{@page{size:${width}mm ${height}mm;margin:0}` +
131
- `${pages}{height:${height}mm!important;margin-block:0!important;` +
132
- `break-after:page;break-inside:avoid}${pages}:last-child{break-after:auto}${named}}`
272
+ function viewPrintStyles(settings: DocumentSettings, sheets: readonly Sheet[], id: string): string {
273
+ const mm = ({ width, height }: { width: number; height: number }) => ({
274
+ width: `${width}mm`,
275
+ height: `${height}mm`,
276
+ });
277
+ return printStyles(
278
+ `[${VIEW_ATTR}="${id}"]>.foli-page`,
279
+ mm(settings.pageSize),
280
+ sheets.map(({ settings: { pageSize }, index }) => ({ ...mm(pageSize), index })),
281
+ id,
133
282
  );
134
283
  }
135
284
 
@@ -140,8 +289,8 @@ function hiddenIn(node: Node, stop: Node): boolean {
140
289
  return false;
141
290
  }
142
291
 
143
- /** The attribute naming a page's page setup (its index among the document's) for print. */
144
- const SHEET_ATTR = "data-foli-sheet";
292
+ /** The fields whose results depend on where things fall on the pages. */
293
+ const PAGE_DEPENDENT = new Set(["PAGE", "NUMPAGES", "SECTIONPAGES", "PAGEREF"]);
145
294
 
146
295
  /** A page setup: its settings (mm), the page style it gives, its index among the document's. */
147
296
  interface Sheet {
@@ -153,6 +302,9 @@ interface Sheet {
153
302
  function sheetOf(settings: DocumentSettings, index: number): Sheet {
154
303
  const { pageSize, margins } = settings;
155
304
  const css =
305
+ // The containing block, stacking context and formatting context of floating pictures: one
306
+ // reaching past the page's text makes the page taller, never overlaps the next page.
307
+ "position: relative; isolation: isolate; display: flow-root; " +
156
308
  `box-sizing: border-box; width: ${pageSize.width}mm; min-height: ${pageSize.height}mm; ` +
157
309
  `padding: ${margins.top}mm ${margins.right}mm ${margins.bottom}mm ${margins.left}mm;`;
158
310
  return { settings, css, index };
@@ -160,73 +312,208 @@ function sheetOf(settings: DocumentSettings, index: number): Sheet {
160
312
 
161
313
  /** The style each page element was last given (its `cssText` reads back normalized). */
162
314
  const pageSheets = new WeakMap<HTMLElement, string>();
315
+ /** The margins a header or footer gave each page element, as last written. */
316
+ const pagePads = new WeakMap<HTMLElement, string>();
317
+ /** What a view without pages gives its one flow of content. */
318
+ const UNPAGED_CSS = "display: flow-root; position: relative;";
319
+
320
+ /** A section as laid out: its page setup, its columns, what the flow needs of it. */
321
+ interface SectionLayout {
322
+ readonly sheet: Sheet;
323
+ readonly columns: ColumnsPx;
324
+ /** Columns of different widths: a block is measured in the one it lands in. */
325
+ readonly unequal: boolean;
326
+ readonly flow: FlowSection;
327
+ /** What a block's place depends on, besides its own content. */
328
+ readonly key: string;
329
+ }
163
330
 
164
- /** A block's section: its page setup, and whether the next block starts a new page. */
331
+ /** A block's section, and whether it is the section's first block. */
165
332
  interface BlockLayout {
166
333
  readonly sheet: Sheet;
167
- readonly breakAfter: boolean;
334
+ readonly section: SectionLayout;
335
+ readonly first: boolean;
336
+ }
337
+
338
+ /** A page's header or footer as drawn. */
339
+ interface RegionElement {
340
+ element: HTMLElement;
341
+ /** What it shows: the same object, the same drawing. */
342
+ drawing: object;
343
+ section: number;
344
+ /** Its story. */
345
+ id: string;
346
+ }
347
+
348
+ /** What a page shows of notes: at its feet, and after the text of each column. */
349
+ interface PageNoteElements {
350
+ foot: HTMLElement[];
351
+ flow: Map<string, HTMLElement[]>;
352
+ }
353
+
354
+ /** A story being edited on its page. */
355
+ interface StoryMount extends OpenStory {
356
+ /** The page and the region it is open in. */
357
+ page: number;
358
+ region: RegionElement;
359
+ wrapper: HTMLElement;
360
+ view: EditorView;
361
+ /** Moved to another page by a new layout: the focus went with the DOM. */
362
+ moved: boolean;
363
+ }
364
+
365
+ /** A header or footer being edited. */
366
+ type HeaderMount = StoryMount & { side: StorySide };
367
+
368
+ /** A fragment's place on its page. */
369
+ interface Slot {
370
+ band: number;
371
+ column: number;
372
+ /** The space above its band, when it opens one. */
373
+ lead: number | undefined;
374
+ /** A section's empty last paragraph: on the page, taking no room. */
375
+ mark: boolean;
376
+ }
377
+
378
+ const slotOf = (fragment: Fragment): Slot => ({
379
+ band: fragment.band ?? 0,
380
+ column: fragment.column ?? 0,
381
+ lead: fragment.lead,
382
+ mark: !!fragment.mark,
383
+ });
384
+
385
+ /** The document's sections and the blocks of each. */
386
+ function sectionSpans(doc: ModelNode, last: SectionJSON) {
387
+ const spans: { setup: SectionJSON; from: number; to: number }[] = [];
388
+ let from = 0;
389
+ doc.forEach((node, _, i) => {
390
+ const own = node.attrs.section as SectionJSON | null | undefined;
391
+ if (!own) return;
392
+ spans.push({ setup: own, from, to: i + 1 });
393
+ from = i + 1;
394
+ });
395
+ if (from < doc.childCount || !spans.length) spans.push({ setup: last, from, to: doc.childCount });
396
+ return spans;
168
397
  }
169
398
 
170
399
  /**
171
400
  * The section of each top-level block (the section a paragraph's `section` ends; the
172
- * envelope's for the blocks after the last such paragraph). A section starts a new page,
173
- * unless it is continuous with the same page setup as the one before (shortcut: a continuous
174
- * section with another page setup starts a new page; Word's even and odd page sections do not
175
- * add a blank page), as `renderDocument` lays sections out.
401
+ * envelope's for the blocks after the last such paragraph), as `renderDocument` lays sections
402
+ * out. By position: two paragraphs may end sections with one object. `box` gives a page's text
403
+ * height: null for a view without pages.
176
404
  */
177
- function sectionLayouts(doc: ModelNode, last: SectionJSON): BlockLayout[] {
405
+ function sectionLayouts(
406
+ spans: ReturnType<typeof sectionSpans>,
407
+ box: ((section: number, page: FlowPage) => number) | null,
408
+ ): BlockLayout[] {
178
409
  const sheets = new Map<string, Sheet>();
179
410
  const bySection = new Map<SectionJSON, Sheet>();
180
411
  const sheet = (section: SectionJSON) => {
181
412
  let found = bySection.get(section);
182
413
  if (!found) {
183
414
  const settings = sectionSettings(section);
184
- const css = sheetOf(settings, 0).css;
185
- found = sheets.get(css) ?? sheetOf(settings, sheets.size);
415
+ const css = box ? sheetOf(settings, 0).css : UNPAGED_CSS;
416
+ found = sheets.get(css) ?? { ...sheetOf(settings, sheets.size), css };
186
417
  sheets.set(css, found);
187
418
  bySection.set(section, found);
188
419
  }
189
420
  return found;
190
421
  };
191
- const sections: SectionJSON[] = [];
192
- let section = last;
193
- for (let i = doc.childCount - 1; i >= 0; i--) {
194
- const own = doc.child(i).attrs.section as SectionJSON | null | undefined;
195
- if (own) section = own;
196
- sections[i] = section;
197
- }
198
- // Indexes in document order: the first page setup is 0.
199
- sections.forEach(sheet);
200
- return sections.map((own, i) => {
201
- const next = sections[i + 1];
202
- // By position, as `renderDocument`: two paragraphs may end sections with one object.
203
- const ends = !!next && !!doc.child(i).attrs.section;
204
- const breakAfter = ends && !(next.type === "continuous" && sheet(next).css === sheet(own).css);
205
- return { sheet: sheet(own), breakAfter };
422
+ const sheetByFlow = new Map<FlowSection, Sheet>();
423
+ const out: BlockLayout[] = [];
424
+ spans.forEach(({ setup, from: start, to }, s) => {
425
+ // Indexes in document order: the first page setup is 0.
426
+ const own = sheet(setup);
427
+ const next = spans[s + 1]?.setup;
428
+ const columns = columnsPx(setup);
429
+ const count = columns.widths.length;
430
+ const balanced =
431
+ !!next && count > 1 && next.type === "continuous" && sheet(next).css === own.css;
432
+ const flow: FlowSection = {
433
+ index: s,
434
+ start: setup.type ?? "nextPage",
435
+ columns: count,
436
+ balanced,
437
+ pageStart: setup.pageNumbers?.start,
438
+ box: (page) => ({ height: box ? box(s, page) : Number.POSITIVE_INFINITY }),
439
+ samePage: (other) => sheetByFlow.get(other)?.css === own.css,
440
+ };
441
+ sheetByFlow.set(flow, own);
442
+ const section: SectionLayout = {
443
+ sheet: own,
444
+ columns,
445
+ unequal: new Set(columns.widths).size > 1,
446
+ flow,
447
+ key: `${own.css}|${flow.start}|${flow.pageStart ?? ""}|${balanced}|${columnsKey(columns)}`,
448
+ };
449
+ for (let i = start; i < to; i++) out[i] = { sheet: own, section, first: i === start };
206
450
  });
451
+ return out;
207
452
  }
208
453
 
209
454
  /**
210
- * Initial pages (before a flow), moved where needed so that each page holds blocks of one
211
- * page setup: a block is measured in a page of its own section's width.
455
+ * Where blocks are before a flow: where they were (`known`), moved where needed so that each
456
+ * page holds blocks of one page setup and each section has a band of its own: a block is
457
+ * measured in a column of its own section's width.
212
458
  */
213
- function separateSheets(
459
+ function initialPlaces(
214
460
  pages: readonly (readonly number[])[],
215
461
  layout: readonly BlockLayout[],
216
- ): number[][] {
217
- const css: string[] = [];
218
- let floor = 0;
219
- return pages.map((list, i) =>
220
- list.map((p) => {
221
- const want = (layout[i] as BlockLayout).sheet.css;
222
- let page = Math.max(p, floor);
223
- // Only the last page used so far has a setup: the next one is free.
224
- if (css[page] !== undefined && css[page] !== want) page++;
225
- css[page] ??= want;
226
- floor = page;
462
+ known: readonly (readonly Slot[] | undefined)[],
463
+ ): { pages: number[][]; slots: Slot[][] } {
464
+ let page = 0;
465
+ let band = 0;
466
+ let column = 0;
467
+ let section: SectionLayout | undefined;
468
+ const slots: Slot[][] = [];
469
+ const placed = pages.map((list, i) => {
470
+ const own = (layout[i] as BlockLayout).section;
471
+ const out: Slot[] = [];
472
+ slots[i] = out;
473
+ return list.map((p, f) => {
474
+ let target = Math.max(p, page);
475
+ if (target === page && section && section !== own) {
476
+ // Only the last page used so far has a setup: the next one is free.
477
+ if (section.sheet.css !== own.sheet.css) target++;
478
+ else {
479
+ band++;
480
+ column = 0;
481
+ }
482
+ }
483
+ if (target > page) {
484
+ page = target;
485
+ band = 0;
486
+ column = 0;
487
+ }
488
+ section = own;
489
+ const was = known[i]?.[f];
490
+ column = Math.min(Math.max(column, was?.column ?? 0), own.columns.widths.length - 1);
491
+ out.push({
492
+ band,
493
+ column,
494
+ lead: was?.band === band ? was.lead : undefined,
495
+ mark: was?.mark ?? false,
496
+ });
227
497
  return page;
228
- }),
229
- );
498
+ });
499
+ });
500
+ return { pages: placed, slots };
501
+ }
502
+
503
+ /** Makes `list` the children of `parent`, moving as little as possible; returns what it removed. */
504
+ function fillElement(parent: HTMLElement, list: readonly HTMLElement[], removed: WeakSet<Node>) {
505
+ let at = parent.firstChild;
506
+ for (const dom of list) {
507
+ if (dom === at) at = at.nextSibling;
508
+ else parent.insertBefore(dom, at);
509
+ }
510
+ // What is left after the last placed one: strays, and blocks of later pages.
511
+ while (at) {
512
+ const next: ChildNode | null = at.nextSibling;
513
+ at.remove();
514
+ removed.add(at);
515
+ at = next;
516
+ }
230
517
  }
231
518
 
232
519
  /**
@@ -250,8 +537,26 @@ export class EditorView {
250
537
  private indexOf = new Map<BlockDesc, number>();
251
538
  /** The element that shows a node selection, if any. */
252
539
  private selectedDom: HTMLElement | null = null;
253
- /** The page of each fragment of each block. */
254
- private fragmentPages = new Map<BlockDesc, readonly number[]>();
540
+ /** The cells a cell selection marks, and the caret written in its head cell. */
541
+ private selectedCells: HTMLElement[] = [];
542
+ private cellCaret: number | null = null;
543
+ /** The pages of each top-level item (a paragraph's fragments, a table's wrappers), by node. */
544
+ private itemPages = new Map<ModelNode, readonly number[]>();
545
+ /** Where on its page each of those is (band and column). */
546
+ private itemSlots = new Map<ModelNode, readonly Slot[]>();
547
+ /** Each page's band elements, as last placed. */
548
+ private bands = new WeakMap<
549
+ HTMLElement,
550
+ { key: string; band: HTMLElement; columns: HTMLElement[] }[]
551
+ >();
552
+ /** Each table as last rendered, by node. */
553
+ private frames = new Map<ModelNode, FrameState>();
554
+ /** The table each wrapper element draws (part of). */
555
+ private frameOf = new Map<Node, Frame>();
556
+ /** Each table as last rendered, by its index among the top-level items. */
557
+ private frameAt: ({ node: ModelNode; state: FrameState } | undefined)[] = [];
558
+ /** Elements the view itself removed: the read-back does not take them for input. */
559
+ private viewRemoved = new WeakSet<Node>();
255
560
  /** The block each fragment element belongs to. */
256
561
  private owner = new Map<Node, BlockDesc>();
257
562
  /** The page elements, in order; the host's only children. */
@@ -295,9 +600,12 @@ export class EditorView {
295
600
  private readonly resizeObserver: ResizeObserver | null;
296
601
  private readonly observed = new Set<Element>();
297
602
  private relayoutPending = false;
298
- private composing = false;
603
+ /** A composition runs in this view. */
604
+ composing = false;
299
605
  /** Set by Ctrl/Cmd+Shift+V for the paste event it triggers. */
300
606
  private plainPaste = false;
607
+ /** How deep `renumberNotes` has rendered again. */
608
+ private renumbering = 0;
301
609
  /** Blocks whose DOM the browser changed: the next render rebuilds them. */
302
610
  private readonly dirty = new Set<BlockDesc>();
303
611
  /** DOM mutations not yet read back (kept while a composition is running). */
@@ -316,12 +624,82 @@ export class EditorView {
316
624
  private readonly addedTabIndex: boolean;
317
625
  /** Renders the document's blocks; made by the first render. */
318
626
  private word: WordRenderer | null = null;
627
+ /** Where pasted and dropped image files go (`EditorViewOptions.upload`). */
628
+ private upload: EditorViewOptions["upload"];
629
+ /** The selected picture's span (with its resize handle). */
630
+ private selectedPicture: HTMLElement | null = null;
631
+ /** A picture being resized: its position, element, size at the press, scale, the press. */
632
+ private resize: {
633
+ pos: number;
634
+ img: HTMLElement;
635
+ width: number;
636
+ height: number;
637
+ scale: number;
638
+ /** The widest it may get (layout px). */
639
+ max: number;
640
+ x: number;
641
+ y: number;
642
+ style: string;
643
+ } | null = null;
644
+ /** The app's URLs for pictures' images (`EditorViewOptions.resource`). */
645
+ private resource: EditorViewOptions["resource"];
319
646
  /** How tracked changes show. */
320
647
  private review: ReviewView = "markup";
648
+ /** Whether fields show their codes (`toggleFieldCodes`). */
649
+ private fieldCodes = false;
650
+ /** The elements shaded for the fields the selection is in. */
651
+ private shadedFields: Element[] = [];
321
652
  /** Fonts' normal line height ratios, measured once per family (Word's single spacing). */
322
653
  private readonly ratios = new Map<string, number>();
323
654
  /** Web fonts loaded since the v3 blocks were drawn: the next render draws them again. */
324
655
  private fontsChanged = false;
656
+ /** Whether content goes on pages (`EditorViewOptions.paged`). */
657
+ private readonly paged: boolean;
658
+ /** The headers and footers of the pages; none without pages. */
659
+ private readonly regions: PageRegions | null;
660
+ /** Each page as last flowed. */
661
+ private facts: PageFacts[] = [];
662
+ /** The header and footer element of each page, as last drawn. */
663
+ private pageRegions: { header?: RegionElement; footer?: RegionElement }[] = [];
664
+ /** Each page's margins, when a header or footer pushes them. */
665
+ private pageMargins: { top: string; bottom: string }[] = [];
666
+ /** What the header and footer heights were when last laid out (`PageRegions.key`). */
667
+ private regionsKey = "";
668
+ /** What `regionsKey` was computed from. */
669
+ private regionsFor: { stories: unknown; settings: unknown; sections: SectionJSON[] } | null =
670
+ null;
671
+ /** Footnotes and endnotes on the pages; none without pages. */
672
+ private readonly notes: PageNotes | null;
673
+ /** What each page shows of them. */
674
+ private pageNotes: PageNoteElements[] = [];
675
+ /** Their elements by what they show. */
676
+ private noteElements = new Map<string, HTMLElement>();
677
+ /** The page each note starts on, as last flowed: numbers can restart on each. */
678
+ private notePages = new Map<string, number>();
679
+ /** What the note references showed when last drawn. */
680
+ private shownNotes = "";
681
+ /** The layout and boxes of the last flow, to draw notes again from. */
682
+ private flowLayout: readonly BlockLayout[] = [];
683
+ private flowBoxes: readonly BlockBox[] = [];
684
+ /** What this view's note mark shows (`EditorViewOptions.noteMark`). */
685
+ private readonly noteMark: (() => string) | undefined;
686
+ /** Puts everything on its page again, as the last render left it. */
687
+ private placeAgain: (() => void) | null = null;
688
+ /** The story being edited on its page, if any (ADR-0007). */
689
+ private mount: StoryMount | null = null;
690
+ /** What find shows, and which tree this view draws of it (a mounted story's view: its own). */
691
+ private found: FoundMatches | null = null;
692
+ private matchStory: string | null = null;
693
+ private readonly matchMarks: MatchMarks;
694
+ /** The pages marked, as a key; the frame waiting to look again. */
695
+ private matchPages = "";
696
+ private matchFrame = 0;
697
+ /** The body's selection before the press of a double click in a page's margin. */
698
+ private pressSelection: Selection | null = null;
699
+ /** The listeners on the host, to remove them. */
700
+ private readonly listeners: [string, EventListener][] = [];
701
+ /** The frames, titles and pop-ups of content controls. */
702
+ private readonly controlChrome: ControlChrome;
325
703
 
326
704
  constructor(
327
705
  readonly host: HTMLElement,
@@ -329,6 +707,39 @@ export class EditorView {
329
707
  options: EditorViewOptions = {},
330
708
  ) {
331
709
  this.state = editor.state;
710
+ this.matchMarks = new MatchMarks(host.ownerDocument);
711
+ this.paged = options.paged !== false;
712
+ this.noteMark = options.noteMark;
713
+ const view = this;
714
+ this.controlChrome = new ControlChrome({
715
+ host,
716
+ editor,
717
+ state: () => view.state,
718
+ editable: () => view.editable && !view.mount,
719
+ pages: () => view.pages,
720
+ scale: () => view.scale(),
721
+ rects: (range) => view.controlRects(range),
722
+ contentRects: (range) => view.controlContentRects(range),
723
+ posFromDOM: (node, offset) => view.posFromDOM(node, offset),
724
+ focus: () => view.focus(),
725
+ injectStyles: () => injectStyles(host),
726
+ });
727
+ const storyOptions = {
728
+ get review() {
729
+ return view.review;
730
+ },
731
+ get fieldCodes() {
732
+ return view.fieldCodes;
733
+ },
734
+ lineRatio: (family: string) => this.lineRatio(family),
735
+ resource: (key: string, resource: ResourceJSON) => this.resource?.(key, resource),
736
+ measureIn: () => this.pages[0] ?? host,
737
+ scale: () => this.scale(),
738
+ };
739
+ this.regions = this.paged
740
+ ? new PageRegions(host.ownerDocument, storyOptions, new WeakMap())
741
+ : null;
742
+ this.notes = this.paged ? new PageNotes(host.ownerDocument, storyOptions, new WeakMap()) : null;
332
743
  host.setAttribute("role", "textbox");
333
744
  host.setAttribute("aria-multiline", "true");
334
745
  host.setAttribute(VIEW_ATTR, this.id);
@@ -339,32 +750,53 @@ export class EditorView {
339
750
  host.style.overflowWrap = "break-word";
340
751
  host.replaceChildren();
341
752
  this.review = trackState(this.state)?.view ?? "markup";
753
+ this.fieldCodes = fieldCodesShown(this.state);
342
754
  this.resizeObserver =
343
755
  typeof ResizeObserver === "undefined" ? null : new ResizeObserver(this.onResize);
344
756
  this.observer = new MutationObserver(this.onMutations);
345
757
  this.observer.observe(host, { childList: true, characterData: true, subtree: true });
758
+ // The picture resolver before the first render: no image drawn from a URL the app refuses.
759
+ this.resource = options.resource ?? undefined;
346
760
  this.render();
347
761
  this.setOptions(options);
348
762
 
349
- host.addEventListener("beforeinput", this.onBeforeInput);
350
- host.addEventListener("focus", this.onFocus);
351
- host.addEventListener("keydown", this.onKeyDown);
352
- host.addEventListener("input", this.onInput);
353
- host.addEventListener("compositionstart", this.onCompositionStart);
354
- host.addEventListener("compositionend", this.onCompositionEnd);
355
- host.addEventListener("blur", this.onBlur);
356
- host.addEventListener("mousedown", this.onMouseDown);
357
- host.addEventListener("copy", this.onCopy);
358
- host.addEventListener("cut", this.onCut);
359
- host.addEventListener("paste", this.onPaste);
360
- host.addEventListener("click", this.onClick);
361
- host.addEventListener("auxclick", this.onClick);
763
+ this.listen("beforeinput", this.onBeforeInput);
764
+ this.listen("focus", this.onFocus);
765
+ this.listen("keydown", this.onKeyDown);
766
+ this.listen("input", this.onInput);
767
+ this.listen("compositionstart", this.onCompositionStart);
768
+ this.listen("compositionend", this.onCompositionEnd);
769
+ this.listen("blur", this.onBlur);
770
+ this.listen("mousedown", this.onPress);
771
+ this.listen("mousemove", this.onMouseMove);
772
+ this.listen("mouseleave", () => this.controlChrome.hover(null));
773
+ this.listen("copy", this.onCopy);
774
+ this.listen("cut", this.onCut);
775
+ this.listen("paste", this.onPaste);
776
+ this.listen("dragover", this.onDragOver);
777
+ this.listen("drop", this.onDrop);
778
+ this.listen("click", this.onClick);
779
+ this.listen("auxclick", this.onClick);
780
+ this.claimStories();
362
781
  host.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
363
782
  host.ownerDocument.fonts?.addEventListener("loadingdone", this.onFontsLoaded);
364
783
  this.unsubscribe = editor.subscribe((state) => this.update(state));
365
784
  }
366
785
 
786
+ /** Adds a listener for the body's events: a story open on a page has its own view. */
787
+ private listen<E extends Event>(type: string, handler: (event: E) => void): void {
788
+ const listener: EventListener = (event) => {
789
+ if (!this.mount?.wrapper.contains(event.target as Node | null)) handler(event as E);
790
+ };
791
+ this.host.addEventListener(type, listener);
792
+ this.listeners.push([type, listener]);
793
+ }
794
+
367
795
  destroy(): void {
796
+ this.closeStory(false);
797
+ this.showFound(null);
798
+ this.controlChrome.destroy();
799
+ if (this.editor.storyView === this.stories) this.editor.storyView = null;
368
800
  this.destroyed = true;
369
801
  this.unsubscribe();
370
802
  this.host.ownerDocument.fonts?.removeEventListener("loadingdone", this.onFontsLoaded);
@@ -372,19 +804,9 @@ export class EditorView {
372
804
  this.resizeObserver?.disconnect();
373
805
  for (const style of this.printStyles) style.remove();
374
806
  const { host } = this;
375
- host.removeEventListener("beforeinput", this.onBeforeInput);
376
- host.removeEventListener("focus", this.onFocus);
377
- host.removeEventListener("keydown", this.onKeyDown);
378
- host.removeEventListener("input", this.onInput);
379
- host.removeEventListener("compositionstart", this.onCompositionStart);
380
- host.removeEventListener("compositionend", this.onCompositionEnd);
381
- host.removeEventListener("blur", this.onBlur);
382
- host.removeEventListener("mousedown", this.onMouseDown);
383
- host.removeEventListener("copy", this.onCopy);
384
- host.removeEventListener("cut", this.onCut);
385
- host.removeEventListener("paste", this.onPaste);
386
- host.removeEventListener("click", this.onClick);
387
- host.removeEventListener("auxclick", this.onClick);
807
+ for (const [type, listener] of this.listeners) host.removeEventListener(type, listener);
808
+ this.endDrag();
809
+ this.endResize();
388
810
  host.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
389
811
  const owned = [
390
812
  "contenteditable",
@@ -404,6 +826,10 @@ export class EditorView {
404
826
 
405
827
  /** Focuses the host, shows the model selection in it and scrolls it into view. */
406
828
  focus(): void {
829
+ if (this.mount) {
830
+ this.mount.view.focus();
831
+ return;
832
+ }
407
833
  this.host.focus();
408
834
  this.writeSelection(true);
409
835
  // The focus handler scrolls only when it writes the selection itself, and a DOM selection
@@ -418,12 +844,34 @@ export class EditorView {
418
844
  // Finish a running composition while its text can still go into the model.
419
845
  if (!options.editable && this.composing) this.onCompositionEnd();
420
846
  this.editable = options.editable;
847
+ if (!this.editable) this.closeStory(false);
848
+ // A selected picture's handle only while it can be resized.
849
+ this.endResize();
850
+ this.showSelectedPicture();
421
851
  }
422
852
  if (options.placeholder !== undefined) this.placeholder = options.placeholder;
853
+ if (options.upload !== undefined) this.upload = options.upload ?? undefined;
854
+ this.mount?.view.setOptions({
855
+ ...(options.upload !== undefined ? { upload: options.upload } : {}),
856
+ ...(options.resource !== undefined ? { resource: options.resource } : {}),
857
+ });
858
+ // null clears the resolver (stored as none): the same as none is no change.
859
+ const resource = options.resource ?? undefined;
860
+ if (options.resource !== undefined && resource !== this.resource) {
861
+ this.resource = resource;
862
+ // Every picture again, from the new URLs: after a running composition, keeping the
863
+ // selection.
864
+ if (this.word) {
865
+ if (this.composing) this.onCompositionEnd();
866
+ this.word = null;
867
+ this.render();
868
+ this.writeSelection(false);
869
+ }
870
+ }
423
871
 
424
872
  // Read-only: no caret and no browser editing; the text stays selectable and copyable.
425
- host.setAttribute("contenteditable", String(this.editable));
426
- if (this.editable) host.removeAttribute("aria-readonly");
873
+ host.setAttribute("contenteditable", String(this.editable && !this.mount));
874
+ if (this.editable && !this.mount) host.removeAttribute("aria-readonly");
427
875
  else host.setAttribute("aria-readonly", "true");
428
876
  if (this.placeholder) host.setAttribute("aria-placeholder", this.placeholder);
429
877
  else host.removeAttribute("aria-placeholder");
@@ -451,6 +899,8 @@ export class EditorView {
451
899
  // ---------- rendering ----------
452
900
 
453
901
  private update(state: EditorState): void {
902
+ // A resize is of the picture at its position when it started: the document changed, over.
903
+ if (state.doc !== this.state.doc) this.onResizeCancel();
454
904
  const review = trackState(state)?.view ?? "markup";
455
905
  // Another review view (`setReviewView`): every block drawn again, by a new renderer.
456
906
  const reviewChanged = review !== this.review;
@@ -458,10 +908,32 @@ export class EditorView {
458
908
  this.review = review;
459
909
  this.word = null;
460
910
  }
461
- const docChanged = state.doc !== this.state.doc || reviewChanged;
911
+ // Codes shown or hidden: every block and story drawn again.
912
+ const codes = fieldCodesShown(state);
913
+ const codesChanged = codes !== this.fieldCodes;
914
+ if (codesChanged) {
915
+ this.fieldCodes = codes;
916
+ this.word = null;
917
+ }
918
+ const before = wordContext(this.state)?.envelope;
919
+ const envelope = wordContext(state)?.envelope;
920
+ // The last section's setup and the settings live in the envelope: changing them leaves the
921
+ // tree as it is. So does a story's change, which only its occurrences show.
922
+ const docChanged =
923
+ state.doc !== this.state.doc ||
924
+ reviewChanged ||
925
+ codesChanged ||
926
+ envelope?.section !== before?.section ||
927
+ envelope?.settings !== before?.settings;
928
+ const storiesChanged = envelope?.stories !== before?.stories;
462
929
  const selectionChanged = !state.selection.eq(this.state.selection);
930
+ // Another document: the story being edited closes.
931
+ const lost = !!this.mount && wordContext(state)?.id !== wordContext(this.state)?.id;
463
932
  this.state = state;
464
- if (docChanged) this.render();
933
+ if (docChanged || (storiesChanged && !this.redrawRegions())) this.render();
934
+ if (lost) this.closeStory(true);
935
+ // The open story has its own editor, which hears nothing of this.
936
+ if (codesChanged) this.mount?.view.update(this.mount.view.editor.state);
465
937
  this.showSelectedNode();
466
938
  this.writeSelection(docChanged);
467
939
  // shortcut: scrolls for every change while focused; once remote or plugin changes exist, scroll only for local input (a transaction flag).
@@ -503,32 +975,88 @@ export class EditorView {
503
975
  * Measurements are cached by node and the flow restarts at the first changed block (5.4).
504
976
  */
505
977
  private render(): void {
978
+ try {
979
+ this.renderPages();
980
+ } catch (error) {
981
+ // What it had changed is not input: read back, it would render and fail again, for ever.
982
+ this.observer.takeRecords();
983
+ this.pending = [];
984
+ throw error;
985
+ }
986
+ }
987
+
988
+ private renderPages(): void {
506
989
  const { doc } = this.state;
507
990
  const ownerDocument = this.host.ownerDocument;
508
991
  // A new document (envelope) gets its renderer; nothing rendered before is reused then. An
509
992
  // editor's state always has one (`createEditor`).
510
993
  const context = wordContext(this.state) as WordContext;
511
994
  // Fonts loaded: a new renderer (new line heights), but not while a composition runs in a
512
- // block it would redraw.
995
+ // block it would redraw. What only stories or the settings changed leaves blocks as they are.
996
+ const drawn = this.word?.context;
513
997
  const renewed =
514
- context !== (this.word?.context ?? null) || (this.fontsChanged && !this.composing);
998
+ !drawn ||
999
+ drawn.id !== context.id ||
1000
+ drawn.resolver !== context.resolver ||
1001
+ drawn.envelope.section !== context.envelope.section ||
1002
+ drawn.envelope.resources !== context.envelope.resources ||
1003
+ drawn.envelope.comments !== context.envelope.comments ||
1004
+ (this.fontsChanged && !this.composing);
515
1005
  if (renewed) this.fontsChanged = false;
516
1006
  let word = this.word as WordRenderer;
1007
+ if (!renewed) word.context = context;
517
1008
  if (renewed) {
1009
+ // A document with pictures: the mark of one without alt text is the view's stylesheet's.
1010
+ if (context.envelope.resources) injectStyles(this.host);
518
1011
  word = this.word = new WordRenderer(
519
1012
  context,
520
1013
  ownerDocument,
521
1014
  this.lineRatio,
522
1015
  false,
523
1016
  this.review,
1017
+ imageSource(context.envelope.resources, this.resource ?? undefined),
1018
+ this.fieldCodes,
524
1019
  );
525
1020
  this.invalidateLayout();
526
1021
  }
527
- word.prepare(doc);
528
- const layout = sectionLayouts(doc, context.envelope.section);
1022
+ const references = this.noteReferences();
1023
+ word.setNotes(noteTexts(references), this.noteMark?.());
1024
+ // The blocks the view renders (paragraphs in table cells among them) and the page flow's
1025
+ // items (top-level paragraphs and opaque blocks, and tables).
1026
+ const { units, items } = collect(doc, context.resolver);
1027
+ word.prepare(
1028
+ units.map((unit) => unit.node),
1029
+ (i) => {
1030
+ const unit = units[i] as Unit;
1031
+ const previous = units[i - 1];
1032
+ // Siblings: one ends where the other starts.
1033
+ return unit.cell && previous && previous.pos + previous.node.nodeSize === unit.pos
1034
+ ? { node: previous.node, cell: unit.cell }
1035
+ : null;
1036
+ },
1037
+ );
1038
+ // A story's view has none of the body's sections: its one flow is not a page's.
1039
+ const spans = sectionSpans(doc, this.paged ? context.envelope.section : {});
1040
+ const { regions } = this;
1041
+ regions?.setDocument(
1042
+ context.envelope,
1043
+ spans.map((span) => span.setup),
1044
+ context.resolver,
1045
+ );
1046
+ const { notes } = this;
1047
+ notes?.setDocument(
1048
+ context.envelope,
1049
+ spans.map((span) => span.setup),
1050
+ context.resolver,
1051
+ references,
1052
+ );
1053
+ const layout = sectionLayouts(
1054
+ spans,
1055
+ regions && ((section, page) => regions.boxHeight(section, page)),
1056
+ );
529
1057
  doc.forEach((node, _, i) => {
530
- const { sheet, breakAfter } = layout[i] as BlockLayout;
531
- const key = `${sheet.css}${breakAfter ? "|break" : ""}`;
1058
+ const { section, first } = layout[i] as BlockLayout;
1059
+ const key = `${section.key}${first ? "|first" : ""}`;
532
1060
  const before = this.layoutKeys.get(node);
533
1061
  if (before !== undefined && before !== key) this.stale.add(node);
534
1062
  this.layoutKeys.set(node, key);
@@ -536,53 +1064,152 @@ export class EditorView {
536
1064
  const previous = new Map(
537
1065
  this.blocks.filter((desc) => !this.dirty.has(desc)).map((desc) => [desc.node, desc]),
538
1066
  );
539
- const previousPages = this.fragmentPages;
1067
+ const previousPages = this.itemPages;
1068
+ const previousFrames = this.frames;
540
1069
  this.dirty.clear();
541
1070
  const dropLines = this.linesStale && !this.composing;
542
1071
  if (dropLines) {
543
1072
  this.linesStale = false;
544
1073
  this.flowed = null;
545
1074
  }
1075
+ // What can be reused: a block whose list number, comment shading or cell formatting changed
1076
+ // (an edit before it) is redrawn.
1077
+ const reusable = units.map((unit, i) => {
1078
+ const found = renewed ? undefined : previous.get(unit.node);
1079
+ if (found && found.key === word.key(i, unit.cell)) return found;
1080
+ if (found) this.stale.add(unit.node);
1081
+ return undefined;
1082
+ });
1083
+ this.staleAroundFloats(
1084
+ doc,
1085
+ previousPages,
1086
+ new Set(units.filter((_, i) => !reusable[i]).map((unit) => unit.node)),
1087
+ );
1088
+ // A table is measured again (drawn whole first) when it changed, went stale, or one of its
1089
+ // blocks is redrawn or stale; its blocks with it.
1090
+ const remeasureUnit = units.map(() => false);
1091
+ for (const item of items) {
1092
+ const frame = item.frame;
1093
+ if (!frame) continue;
1094
+ let stale = dropLines || !this.measures.has(frame.node) || this.stale.has(frame.node);
1095
+ for (let u = frame.first; !stale && u < frame.end; u++)
1096
+ stale = !reusable[u] || this.stale.has((units[u] as Unit).node);
1097
+ if (!stale) continue;
1098
+ this.stale.add(frame.node);
1099
+ for (let u = frame.first; u < frame.end; u++) remeasureUnit[u] = true;
1100
+ }
546
1101
  let blocks: WordBlockDesc[] = [];
547
- const starts: number[] = [];
548
- doc.forEach((node, pos) => {
549
- let reused = renewed ? undefined : previous.get(node);
550
- // A block whose list number or comment shading changed (an edit before it) is redrawn.
551
- if (reused && reused.key !== word.key(blocks.length)) {
552
- reused = undefined;
553
- this.stale.add(node);
554
- }
1102
+ // Nodes still in the document: an old block or table at an index is only taken over (during
1103
+ // a composition) when its node is gone, never when an insertion moved it along.
1104
+ const present = new Set<ModelNode>(units.map((unit) => unit.node));
1105
+ for (const item of items) if (item.frame) present.add(item.frame.node);
1106
+ units.forEach((unit, i) => {
1107
+ const { node } = unit;
1108
+ let reused = reusable[i];
555
1109
  // A split block about to be measured again (fonts, CSS) is rendered whole first: each
556
1110
  // fragment's end breaks its line, so its lines would depend on where it was split before.
557
- const remeasure = dropLines || !this.measures.has(node) || this.stale.has(node);
1111
+ const remeasure =
1112
+ remeasureUnit[i] || dropLines || !this.measures.has(node) || this.stale.has(node);
558
1113
  if (reused && reused.fragments.length > 1 && remeasure && !this.composing) reused = undefined;
559
1114
  if (reused) previous.delete(node);
560
- blocks.push(reused ?? word.render(node, blocks.length));
561
- starts.push(pos);
1115
+ const desc = reused ?? word.render(node, i, [], unit.cell);
1116
+ blocks.push(desc);
1117
+ // Drawn again in a table cell: the new block takes the old one's place there, so a table
1118
+ // kept as it is (during a composition, which moves nothing) still holds it. During a
1119
+ // composition a block whose node changed takes the place of the block drawn at its index.
1120
+ const atIndex = this.blocks[i];
1121
+ const old = reused
1122
+ ? undefined
1123
+ : (previous.get(node) ??
1124
+ (this.composing &&
1125
+ atIndex &&
1126
+ !present.has(atIndex.node) &&
1127
+ previous.get(atIndex.node) === atIndex
1128
+ ? atIndex
1129
+ : undefined));
1130
+ const first = old?.fragments[0];
1131
+ if (old && first?.isConnected && first.parentElement?.closest(`[${FRAME_ATTR}]`)) {
1132
+ first.replaceWith(...desc.fragments);
1133
+ for (const fragment of old.fragments.slice(1)) fragment.remove();
1134
+ for (const fragment of old.fragments) this.viewRemoved.add(fragment);
1135
+ previous.delete(old.node);
1136
+ }
562
1137
  });
563
1138
  for (const stale of previous.values())
564
- for (const fragment of stale.fragments) fragment.remove();
1139
+ for (const fragment of stale.fragments) {
1140
+ fragment.remove();
1141
+ this.viewRemoved.add(fragment);
1142
+ }
565
1143
  this.applyPrintStyles(layout);
1144
+ const doc_ = this.host.ownerDocument;
1145
+ const frames = new Map<ModelNode, FrameState>();
1146
+ /** A table drawn whole, on one page: what is measured. */
1147
+ const whole = (frame: Frame): FrameState => {
1148
+ const rows = frame.rows.map((_, r) => r);
1149
+ const wrapper = frameElement(
1150
+ frame,
1151
+ rows,
1152
+ [],
1153
+ (r, c) => this.cellContent(frame, r, c, blocks, () => true),
1154
+ doc_,
1155
+ );
1156
+ return { wrappers: [wrapper], pages: [0], key: "" };
1157
+ };
1158
+ // Before the flow, each item where it was (a new one joins the page of the item before it);
1159
+ // a table that changed is drawn whole on that page.
566
1160
  let last = 0;
567
- let pages = blocks.map((desc) => {
568
- const before = previousPages.get(desc);
1161
+ let pages = items.map((item, i) => {
1162
+ const node = doc.child(i);
1163
+ const before = previousPages.get(node);
1164
+ if (item.frame) {
1165
+ let state = previousFrames.get(node);
1166
+ // During a composition nothing moves: a table that changed keeps the wrappers drawn at
1167
+ // its place (its redrawn blocks took their old ones' places above).
1168
+ const at = this.frameAt[i];
1169
+ if (!state && this.composing && at && !present.has(at.node)) state = at.state;
1170
+ if (!state || (this.stale.has(node) && !this.composing)) state = whole(item.frame);
1171
+ frames.set(node, state);
1172
+ const pagesBefore = before ?? (state === at?.state ? state.pages : undefined);
1173
+ return state.wrappers.map((_, f) => (last = Math.max(last, pagesBefore?.[f] ?? last)));
1174
+ }
1175
+ const desc = blocks[item.unit] as WordBlockDesc;
569
1176
  return desc.fragments.map((_, f) => (last = Math.max(last, before?.[f] ?? last)));
570
1177
  });
571
- pages = separateSheets(pages, layout);
572
- this.place(blocks, pages, layout);
1178
+ const initial = initialPlaces(
1179
+ pages,
1180
+ layout,
1181
+ items.map((_, i) => this.itemSlots.get(doc.child(i))),
1182
+ );
1183
+ pages = initial.pages;
1184
+ let slots = initial.slots;
1185
+ const elementsOf = (item: FlowItem, i: number): readonly HTMLElement[] =>
1186
+ item.frame
1187
+ ? (frames.get(doc.child(i)) as FrameState).wrappers
1188
+ : (blocks[item.unit] as WordBlockDesc).fragments;
1189
+ this.place(
1190
+ items.map((item, i) => elementsOf(item, i)),
1191
+ pages,
1192
+ slots,
1193
+ layout,
1194
+ );
573
1195
  if (!this.composing) {
574
1196
  // DOM reads only for blocks without a valid measurement (new, changed or stale ones).
575
1197
  let scale: number | undefined;
576
1198
  const layoutPx = () => {
577
- scale ??= layoutScale(this.pages[0] as HTMLElement, (this.sheets[0] as Sheet).settings);
1199
+ scale ??= this.scale();
578
1200
  return scale;
579
1201
  };
1202
+ // A header or footer of another height moves every page's text: no flow is reused.
1203
+ if (regions && this.regionsChanged(regions, spans)) this.flowed = null;
580
1204
  if (dropLines)
581
1205
  for (const desc of blocks) {
582
1206
  const measure = this.measures.get(desc.node);
583
- if (measure) delete measure.lines;
1207
+ if (measure) {
1208
+ delete measure.lines;
1209
+ delete measure.widths;
1210
+ }
584
1211
  }
585
- const nodes = blocks.map((desc) => desc.node);
1212
+ const nodes = items.map((_, i) => doc.child(i));
586
1213
  // A block's spacing depends on its neighbours' styles: reuse stops a block earlier.
587
1214
  const reuse = this.flowed ? reuseOf(this.flowed, nodes, this.stale, 1) : undefined;
588
1215
  const measureOf = (desc: BlockDesc) => {
@@ -599,33 +1226,221 @@ export class EditorView {
599
1226
  found.lines ??= measureLines(desc, layoutPx());
600
1227
  return found.lines;
601
1228
  };
602
- const boxes = blocks.map((desc, i) =>
603
- wordBox(blocks, i, measureOf(desc), () => lines(desc), layout[i] as BlockLayout),
1229
+ /** A block's height and lines at a column's width, wherever it is now. */
1230
+ const atWidth = (desc: BlockDesc, width: number, kept: boolean): WidthMeasure => {
1231
+ const measure = measureOf(desc);
1232
+ const widths = measure.widths ?? new Map<number, WidthMeasure>();
1233
+ measure.widths = widths;
1234
+ const known = widths.get(width);
1235
+ if (known) return known;
1236
+ const read = <T>(measure: () => T): T => {
1237
+ for (const { style } of desc.fragments) {
1238
+ style.boxSizing = "border-box";
1239
+ style.width = `${width}px`;
1240
+ }
1241
+ const value = measure();
1242
+ for (const { style } of desc.fragments) {
1243
+ style.boxSizing = "";
1244
+ style.width = "";
1245
+ }
1246
+ return value;
1247
+ };
1248
+ const { height } = read(() => measureBox(desc, layoutPx()));
1249
+ let all: Lines | undefined;
1250
+ const found: WidthMeasure = {
1251
+ height,
1252
+ all: () => {
1253
+ all ??= read(() => measureLines(desc, layoutPx()));
1254
+ return all;
1255
+ },
1256
+ lines: () => (kept ? [height] : found.all().bottoms),
1257
+ };
1258
+ widths.set(width, found);
1259
+ return found;
1260
+ };
1261
+ const tableOf = (frame: Frame, i: number) => {
1262
+ let found = this.measures.get(frame.node);
1263
+ if (!found?.table || this.stale.delete(frame.node)) {
1264
+ const wrapper = (frames.get(doc.child(i)) as FrameState).wrappers[0] as HTMLElement;
1265
+ // Its blocks are measured with it (their heights, for a resize later).
1266
+ for (let u = frame.first; u < frame.end; u++) {
1267
+ const desc = blocks[u] as WordBlockDesc;
1268
+ this.stale.delete(desc.node);
1269
+ this.measures.set(desc.node, measureBox(desc, layoutPx()));
1270
+ }
1271
+ found = measureTable(frame, wrapper, blocks, layoutPx());
1272
+ this.measures.set(frame.node, found);
1273
+ }
1274
+ return found;
1275
+ };
1276
+ const words = items.map((item) =>
1277
+ item.frame ? TABLE_WORD : (blocks[item.unit] as WordBlockDesc).word,
604
1278
  );
605
- const result = flowFrom(boxes, contentHeight(this.editor.settings), WORD_RULES, reuse);
1279
+ const endnotes = notes?.endnotes();
1280
+ const boxes = items.map((item, i) => {
1281
+ const own = layout[i] as BlockLayout;
1282
+ const pageHeight = contentHeight(own.sheet.settings);
1283
+ const index = own.section.flow.index ?? 0;
1284
+ const noteOf = (story: string) => notes?.footnote(story, index) ?? null;
1285
+ // Endnotes follow the last block of their section, or of the document.
1286
+ const after =
1287
+ (layout[i + 1] as BlockLayout | undefined)?.section !== own.section
1288
+ ? { endnotes: endnotes?.get(index) }
1289
+ : {};
1290
+ if (item.frame) {
1291
+ const frame = item.frame;
1292
+ const measure = tableOf(frame, i);
1293
+ const breaks = () => breaksOf(frame, measure, blocks, pageHeight, lines);
1294
+ // A page break before the next paragraph ends its page.
1295
+ return {
1296
+ ...tableBox(frame, measure, pageHeight, !!words[i + 1]?.pageBreakBefore, breaks),
1297
+ section: own.section.flow,
1298
+ notes: tableNotes(frame, measure, blocks, lines, breaks, noteOf),
1299
+ ...after,
1300
+ };
1301
+ }
1302
+ const desc = blocks[item.unit] as WordBlockDesc;
1303
+ return {
1304
+ ...wordBox(
1305
+ words,
1306
+ i,
1307
+ desc,
1308
+ measureOf(desc),
1309
+ () => lines(desc),
1310
+ own,
1311
+ atWidth,
1312
+ context.resolver.addsParagraphSpacing,
1313
+ noteOf,
1314
+ ),
1315
+ ...after,
1316
+ };
1317
+ });
1318
+ const rules = {
1319
+ ...WORD_RULES,
1320
+ addSpacing: context.resolver.addsParagraphSpacing,
1321
+ evenAndOddHeaders: context.envelope.settings?.evenAndOddHeaders === true,
1322
+ notes: notes?.flowRules(),
1323
+ };
1324
+ const flowHeight = contentHeight(this.editor.settings);
1325
+ let result = flowFrom(boxes, flowHeight, rules, reuse);
1326
+ let facts = pagesOf(boxes, result);
1327
+ // The page count is known once flowed; a header holding it can change what fits.
1328
+ for (let pass = 0; regions && pass < 2 && regions.settle(facts); pass++) {
1329
+ result = flowFrom(boxes, flowHeight, rules);
1330
+ facts = pagesOf(boxes, result);
1331
+ }
1332
+ this.facts = facts;
606
1333
  this.flowed = { nodes, result };
1334
+ this.flowLayout = layout;
1335
+ this.flowBoxes = boxes;
607
1336
  this.stale.clear();
608
1337
  const flowed = result.fragments;
609
- blocks = blocks.map((desc, i) => {
1338
+ slots = flowed.map((fragments) => fragments.map(slotOf));
1339
+ // Paragraphs: split where their fragments start. Tables: the rows each fragment shows,
1340
+ // and their blocks split where a row is.
1341
+ const splitsOf = new Map<number, number[]>();
1342
+ const parts = new Map<number, { parts: TablePart[]; partOf: Map<number, number[]> }>();
1343
+ items.forEach((item, i) => {
610
1344
  const fragments = flowed[i] ?? [];
611
- const contentStart = (starts[i] as number) + 1;
612
- const splits = fragments.slice(1).map((fragment) => {
613
- const offset = lines(desc).starts[fragment.fromLine] as number;
614
- // Never split a grapheme cluster across pages.
615
- return clusterBoundary(doc, contentStart + offset, false) - contentStart;
616
- });
1345
+ if (item.unit !== undefined) {
1346
+ const desc = blocks[item.unit] as WordBlockDesc;
1347
+ const contentStart = ((units[item.unit] as Unit).pos as number) + 1;
1348
+ const { section } = layout[i] as BlockLayout;
1349
+ splitsOf.set(
1350
+ item.unit,
1351
+ fragments.slice(1).map((fragment) => {
1352
+ // Line numbers are those of the column the fragment is in.
1353
+ const measured = section.unequal
1354
+ ? atWidth(desc, section.columns.widths[fragment.column ?? 0] as number, false).all()
1355
+ : lines(desc);
1356
+ const offset = measured.starts[fragment.fromLine] as number;
1357
+ // Never split a grapheme cluster across pages.
1358
+ return clusterBoundary(doc, contentStart + offset, false) - contentStart;
1359
+ }),
1360
+ );
1361
+ return;
1362
+ }
1363
+ const frame = item.frame;
1364
+ const measure = this.measures.get(frame.node) as Measure;
1365
+ const cut = cutTable(frame, measure, fragments, blocks, lines);
1366
+ parts.set(i, cut);
1367
+ for (const [u, at] of cut.splits) {
1368
+ const contentStart = (units[u] as Unit).pos + 1;
1369
+ splitsOf.set(
1370
+ u,
1371
+ at.map((offset) => clusterBoundary(doc, contentStart + offset, false) - contentStart),
1372
+ );
1373
+ }
1374
+ });
1375
+ blocks = blocks.map((desc, u) => {
1376
+ const splits = splitsOf.get(u) ?? [];
617
1377
  const same =
618
1378
  splits.length === desc.splits.length && splits.every((at, k) => at === desc.splits[k]);
619
- return same ? desc : word.render(desc.node, i, splits);
1379
+ return same ? desc : word.render(desc.node, u, splits, (units[u] as Unit).cell);
1380
+ });
1381
+ pages = items.map((item, i) => {
1382
+ const fragments = flowed[i] ?? [];
1383
+ if (!item.frame) return fragments.map((fragment) => fragment.page);
1384
+ const node = doc.child(i);
1385
+ const cut = parts.get(i) as { parts: TablePart[]; partOf: Map<number, number[]> };
1386
+ const key = JSON.stringify([cut.parts, [...cut.partOf]]);
1387
+ const kept = frames.get(node) as FrameState;
1388
+ const pagesOf = fragments.map((fragment) => fragment.page);
1389
+ // The same cut of the same table, its blocks' elements all in it: its wrappers stay.
1390
+ if (kept.key === key && holdsAll(kept, item.frame, blocks)) {
1391
+ frames.set(node, { ...kept, pages: pagesOf });
1392
+ return pagesOf;
1393
+ }
1394
+ const wrappers = cut.parts.map((part, k) =>
1395
+ frameElement(
1396
+ item.frame,
1397
+ part.rows,
1398
+ part.headers,
1399
+ (r, c) =>
1400
+ this.cellContent(item.frame, r, c, blocks, (u, f) => cut.partOf.get(u)?.[f] === k),
1401
+ doc_,
1402
+ ),
1403
+ );
1404
+ frames.set(node, { wrappers, pages: pagesOf, key });
1405
+ return pagesOf;
620
1406
  });
621
- pages = flowed.map((fragments) => fragments.map((fragment) => fragment.page));
622
- applyGaps(blocks, pages, boxes);
623
- this.place(blocks, pages, layout);
1407
+ const firsts = items.map((item, i) =>
1408
+ item.frame
1409
+ ? ((frames.get(doc.child(i)) as FrameState).wrappers[0] as HTMLElement)
1410
+ : (blocks[item.unit] as WordBlockDesc).dom,
1411
+ );
1412
+ applyGaps(firsts, result.gaps);
1413
+ this.drawRegions();
1414
+ this.drawNotes();
1415
+ this.place(
1416
+ items.map((item, i) => elementsOf(item, i)),
1417
+ pages,
1418
+ slots,
1419
+ layout,
1420
+ );
1421
+ this.afterPlace();
624
1422
  }
1423
+ const placed = items.map((item, i) => elementsOf(item, i));
1424
+ const placedPages = pages;
1425
+ const placedSlots = slots;
1426
+ this.placeAgain = () => this.place(placed, placedPages, placedSlots, layout);
1427
+ // (Wrappers no longer drawn are not in a page: `place` removed them.)
1428
+ this.frames = frames;
1429
+ this.frameAt = items.map((item, i) => {
1430
+ const state = item.frame && frames.get(doc.child(i));
1431
+ return state ? { node: doc.child(i), state } : undefined;
1432
+ });
1433
+ this.frameOf = new Map();
1434
+ items.forEach((item, i) => {
1435
+ if (!item.frame) return;
1436
+ for (const wrapper of (frames.get(doc.child(i)) as FrameState).wrappers)
1437
+ this.frameOf.set(wrapper, item.frame);
1438
+ });
625
1439
  this.blocks = blocks;
626
- this.starts = starts;
1440
+ this.starts = units.map((unit) => unit.pos);
627
1441
  this.indexOf = new Map(blocks.map((desc, i) => [desc, i]));
628
- this.fragmentPages = new Map(blocks.map((desc, i) => [desc, pages[i] ?? []]));
1442
+ this.itemPages = new Map(items.map((_, i) => [doc.child(i), pages[i] ?? []]));
1443
+ this.itemSlots = new Map(items.map((_, i) => [doc.child(i), slots[i] ?? []]));
629
1444
  this.owner = new Map(
630
1445
  blocks.flatMap((desc) => desc.fragments.map((fragment) => [fragment, desc] as const)),
631
1446
  );
@@ -637,6 +1452,1081 @@ export class EditorView {
637
1452
  // changed before this render: the touched blocks are read back at compositionend.
638
1453
  const records = this.observer.takeRecords();
639
1454
  if (this.composing) this.pending.push(...records);
1455
+ this.renumberNotes();
1456
+ }
1457
+
1458
+ /** The note references shown, with their numbers as the last flow's pages make them. */
1459
+ private noteReferences(): NoteNumber[] {
1460
+ if (!this.paged) return [];
1461
+ const { doc } = this.state;
1462
+ const { envelope } = wordContext(this.state) as WordContext;
1463
+ const hideDeleted = this.review !== "markup";
1464
+ const all = noteNumbers(doc, envelope, {
1465
+ hideDeleted,
1466
+ pageOf: (_pos, story) => this.notePages.get(story),
1467
+ });
1468
+ this.shownNotes = JSON.stringify(all.map((n) => n.text));
1469
+ return hideDeleted ? all.filter((n) => !n.deleted) : all;
1470
+ }
1471
+
1472
+ /**
1473
+ * Numbers that restart on each page depend on the flow just made: when they came out otherwise,
1474
+ * once more with them (their width can move a line), at most twice.
1475
+ */
1476
+ private renumberNotes(): void {
1477
+ if (!this.notes || this.composing || this.renumbering > 1) return;
1478
+ const { envelope } = wordContext(this.state) as WordContext;
1479
+ const each = this.sections().some(
1480
+ (section) => noteProperties(envelope, "footnote", section).restart === "eachPage",
1481
+ );
1482
+ if (!each) return;
1483
+ const shown = this.shownNotes;
1484
+ this.noteReferences();
1485
+ if (this.shownNotes === shown) return;
1486
+ this.renumbering++;
1487
+ try {
1488
+ this.renderPages();
1489
+ } finally {
1490
+ this.renumbering = 0;
1491
+ }
1492
+ }
1493
+
1494
+ /** The section of each page's bands in the last flow, and each note's place on the pages. */
1495
+ private drawNotes(): void {
1496
+ const { notes, flowed, facts, mount } = this;
1497
+ if (!notes) return;
1498
+ const pieces = flowed ? notePieces(flowed.result) : [];
1499
+ const notePages = new Map<string, number>();
1500
+ for (const piece of pieces)
1501
+ if (!piece.fromLine && !notePages.has(piece.id)) notePages.set(piece.id, piece.page);
1502
+ this.notePages = notePages;
1503
+ const bandSections = new Map<string, number>();
1504
+ flowed?.result.fragments.forEach((fragments, i) => {
1505
+ const index = (this.flowLayout[i] as BlockLayout | undefined)?.section.flow.index ?? 0;
1506
+ for (const f of fragments) bandSections.set(`${f.page}|${f.band ?? 0}`, index);
1507
+ });
1508
+ const groups: NoteGroup[] = notes.groups(
1509
+ pieces,
1510
+ (page, band) =>
1511
+ bandSections.get(`${page}|${band}`) ??
1512
+ bandSections.get(`${page}|0`) ??
1513
+ facts[page]?.section ??
1514
+ 0,
1515
+ );
1516
+ const foot = groups.filter((group) => !group.inFlow);
1517
+ const known = this.noteElements;
1518
+ const elements = new Map<string, HTMLElement>();
1519
+ const shown: PageNoteElements[] = [];
1520
+ const note = mount?.side === "note" ? mount : null;
1521
+ for (const group of groups) {
1522
+ const { settings } = this.sheetOfPage(group.page);
1523
+ const fact = facts[group.page];
1524
+ const bottom = fact?.sectionPages
1525
+ ? (this.regions as PageRegions).margins(fact.section, fact).bottom
1526
+ : settings.margins.bottom * PX_PER_MM;
1527
+ const place = group.inFlow
1528
+ ? null
1529
+ : notes.footPlace(
1530
+ { left: settings.margins.left * PX_PER_MM, bottom },
1531
+ notes.stacked(group, foot),
1532
+ );
1533
+ // Footnotes beneath the text keep the space after the paragraph above them.
1534
+ const lead =
1535
+ group.inFlow && !group.pieces[0]?.end && flowed
1536
+ ? spaceAfterText(this.flowBoxes, flowed.result, group.page, group.band, group.column)
1537
+ : 0;
1538
+ const key = `${group.page}|${group.band}|${group.column}|${group.inFlow}|${place?.left}|${place?.bottom}|${lead}|${notes.keyOf(group)}`;
1539
+ let element = known.get(key);
1540
+ if (!element) {
1541
+ element = notes.groupElement(
1542
+ group,
1543
+ place,
1544
+ (piece) =>
1545
+ piece.id === note?.id && !piece.fromLine
1546
+ ? note.region.element
1547
+ : notes.pieceElement(piece, group),
1548
+ lead,
1549
+ );
1550
+ if (note && element.contains(note.wrapper)) note.moved = true;
1551
+ }
1552
+ elements.set(key, element);
1553
+ const page = shown[group.page] ?? { foot: [], flow: new Map<string, HTMLElement[]>() };
1554
+ shown[group.page] = page;
1555
+ if (!group.inFlow) page.foot.push(element);
1556
+ else {
1557
+ const slot = `${group.band}|${group.column}`;
1558
+ page.flow.set(slot, [...(page.flow.get(slot) ?? []), element]);
1559
+ }
1560
+ }
1561
+ this.noteElements = elements;
1562
+ this.pageNotes = Array.from(
1563
+ { length: shown.length },
1564
+ (_, p) => shown[p] ?? { foot: [], flow: new Map() },
1565
+ );
1566
+ if (!note) return;
1567
+ // Its reference went (undone, or hidden with the changes): the note closes.
1568
+ const page = notePages.get(note.id);
1569
+ if (page === undefined) queueMicrotask(() => this.closeStory(true));
1570
+ else note.page = page;
1571
+ }
1572
+
1573
+ /** Layout px per px on screen: what a scaled ancestor (`transform`, `zoom`) multiplies by. */
1574
+ private scale(): number {
1575
+ const page = this.pages[0];
1576
+ if (!page) return 1;
1577
+ return this.paged
1578
+ ? layoutScale(page, (this.sheets[0] as Sheet).settings)
1579
+ : page.getBoundingClientRect().width / page.offsetWidth || 1;
1580
+ }
1581
+
1582
+ /** Whether the headers' and footers' heights differ from when the pages were last flowed. */
1583
+ private regionsChanged(regions: PageRegions, spans: readonly { setup: SectionJSON }[]): boolean {
1584
+ const { stories, settings } = (wordContext(this.state) as WordContext).envelope;
1585
+ const sections = spans.map((span) => span.setup);
1586
+ const known = this.regionsFor;
1587
+ if (
1588
+ known &&
1589
+ known.stories === stories &&
1590
+ known.settings === settings &&
1591
+ known.sections.length === sections.length &&
1592
+ known.sections.every((section, i) => section === sections[i])
1593
+ )
1594
+ return false;
1595
+ this.regionsFor = { stories, settings, sections };
1596
+ const key = `${regions.key()}|${this.notes?.key() ?? ""}`;
1597
+ // Even and odd headers also decide the blank pages: the flow depends on them.
1598
+ const changed =
1599
+ key !== this.regionsKey ||
1600
+ (known?.settings !== settings &&
1601
+ (known?.settings as WordSettingsJSON | undefined)?.evenAndOddHeaders !==
1602
+ settings?.evenAndOddHeaders);
1603
+ this.regionsKey = key;
1604
+ return changed;
1605
+ }
1606
+
1607
+ /**
1608
+ * Gives every page the header and footer the last flow says, redrawing those that changed. The
1609
+ * one holding the story being edited stays; it follows the story if its page no longer shows it.
1610
+ */
1611
+ private drawRegions(): void {
1612
+ const { regions, facts } = this;
1613
+ // A note open for editing is `drawNotes`' to look after.
1614
+ const mount = this.mount?.side === "note" ? null : (this.mount as HeaderMount | null);
1615
+ if (!regions) return;
1616
+ const sides = ["header", "footer"] as const;
1617
+ const wanted = facts.map((page) =>
1618
+ // Word's blank page before an even or odd page section has neither.
1619
+ page.sectionPages
1620
+ ? {
1621
+ header: regions.drawing(page.section, "header", page),
1622
+ footer: regions.drawing(page.section, "footer", page),
1623
+ }
1624
+ : { header: null, footer: null },
1625
+ );
1626
+ const shows = (p: number) => !!mount && wanted[p]?.[mount.side]?.id === mount.id;
1627
+ // Its page, while it shows it. Replaced there (the section unlinked, another variant turned
1628
+ // on) it does not follow the old story to another page: the page's own opens.
1629
+ const replaced = !!mount && facts[mount.page]?.section === mount.section;
1630
+ const home = !mount
1631
+ ? -1
1632
+ : shows(mount.page)
1633
+ ? mount.page
1634
+ : replaced
1635
+ ? -1
1636
+ : wanted.findIndex((_, p) => shows(p));
1637
+ this.pageRegions = facts.map((page, p) => {
1638
+ const own: EditorView["pageRegions"][number] = {};
1639
+ for (const side of sides) {
1640
+ const drawing = wanted[p]?.[side];
1641
+ if (!drawing) continue;
1642
+ if (mount && p === home && side === mount.side) {
1643
+ own[side] = mount.region;
1644
+ if (mount.region.drawing !== drawing.content) {
1645
+ mount.region.drawing = drawing.content;
1646
+ const copy = drawing.content.content.cloneNode(true) as HTMLElement;
1647
+ copy.style.display = "none";
1648
+ mount.region.element
1649
+ .querySelector(`:scope > .${REGION_CONTENT_CLASS}`)
1650
+ ?.replaceWith(copy);
1651
+ mount.wrapper.style.paddingBottom = copy.style.paddingBottom;
1652
+ }
1653
+ continue;
1654
+ }
1655
+ const known = this.pageRegions[p]?.[side];
1656
+ if (known?.drawing === drawing.content && known.section === page.section) {
1657
+ own[side] = known;
1658
+ continue;
1659
+ }
1660
+ const element = regions.element(page.section, side);
1661
+ element.append(drawing.content.content.cloneNode(true));
1662
+ own[side] = { element, drawing: drawing.content, section: page.section, id: drawing.id };
1663
+ }
1664
+ return own;
1665
+ });
1666
+ this.pageMargins = facts.map((page, p) => {
1667
+ if (!page.sectionPages) return { top: "", bottom: "" };
1668
+ const { top, bottom } = regions.margins(page.section, page);
1669
+ const { margins } = this.sheetOfPage(p).settings;
1670
+ return {
1671
+ top: Math.abs(top - margins.top * PX_PER_MM) < 0.01 ? "" : `${top}px`,
1672
+ bottom: Math.abs(bottom - margins.bottom * PX_PER_MM) < 0.01 ? "" : `${bottom}px`,
1673
+ };
1674
+ });
1675
+ if (!mount) return;
1676
+ // Not shown anywhere any more (a variant turned on or off): the page's own story opens.
1677
+ if (home < 0) queueMicrotask(this.reopenStory);
1678
+ else if (home !== mount.page) {
1679
+ mount.page = home;
1680
+ mount.moved = true;
1681
+ }
1682
+ }
1683
+
1684
+ /** The page setup page `p` has, or will have once placed. */
1685
+ private sheetOfPage(p: number): Sheet {
1686
+ return this.sheets[p] ?? this.sheets[this.sheets.length - 1] ?? this.lastSheet();
1687
+ }
1688
+
1689
+ /**
1690
+ * After a story changed: its occurrences redrawn. False when a height changed, which takes a
1691
+ * new flow (`render`), or during a composition.
1692
+ */
1693
+ private redrawRegions(): boolean {
1694
+ const { regions } = this;
1695
+ if (!regions) return true;
1696
+ if (this.composing) return true;
1697
+ const context = wordContext(this.state) as WordContext;
1698
+ const spans = sectionSpans(this.state.doc, context.envelope.section);
1699
+ regions.setDocument(
1700
+ context.envelope,
1701
+ spans.map((span) => span.setup),
1702
+ context.resolver,
1703
+ );
1704
+ this.notes?.setDocument(
1705
+ context.envelope,
1706
+ spans.map((span) => span.setup),
1707
+ context.resolver,
1708
+ this.noteReferences(),
1709
+ );
1710
+ if (this.regionsChanged(regions, spans)) {
1711
+ this.flowed = null;
1712
+ return false;
1713
+ }
1714
+ this.drawRegions();
1715
+ this.drawNotes();
1716
+ this.placeAgain?.();
1717
+ this.afterPlace();
1718
+ this.observer.takeRecords();
1719
+ return true;
1720
+ }
1721
+
1722
+ /** The story being edited, moved with its region: the focus goes back to it. */
1723
+ private afterPlace(): void {
1724
+ this.drawControls();
1725
+ this.drawMatches();
1726
+ if (!this.mount?.moved) return;
1727
+ this.mount.moved = false;
1728
+ this.mount.view.focus();
1729
+ }
1730
+
1731
+ // ---------- stories on their pages (ADR-0007) ----------
1732
+
1733
+ /** What the toolbar and code open stories through (`Editor.storyView`). */
1734
+ private readonly stories: StoryView = ((view: EditorView) => ({
1735
+ get open(): OpenStory | null {
1736
+ const { mount } = view;
1737
+ return mount
1738
+ ? { id: mount.id, side: mount.side, variant: mount.variant, section: mount.section }
1739
+ : null;
1740
+ },
1741
+ edit: (side, page) => view.openStory(side, page),
1742
+ editNote: (id) => view.openNote(id),
1743
+ toReference: () => view.toReference(),
1744
+ close: () => view.closeStory(),
1745
+ get fieldLayout() {
1746
+ return view.fieldLayout();
1747
+ },
1748
+ updateFields: (options, editor) => view.updateFields(options, editor),
1749
+ showMatches: (found) => view.showMatches(found),
1750
+ reveal: (target, options) => view.reveal(target, options),
1751
+ goToPage: (page, options) => view.goToPage(page, options),
1752
+ focus: () => view.focus(),
1753
+ }))(this);
1754
+
1755
+ /** Makes this view the one `Editor.storyView` speaks for, telling listeners if it was not. */
1756
+ private claimStories(): void {
1757
+ if (!this.paged || this.editor.storyView === this.stories) return;
1758
+ const first = !this.editor.storyView;
1759
+ this.editor.storyView = this.stories;
1760
+ if (!first) this.editor.storyChanged();
1761
+ }
1762
+
1763
+ // ---------- find, and going places (11.11) ----------
1764
+
1765
+ /**
1766
+ * Marks what find found: on the pages, in the story open, and in the drawn copies of the others.
1767
+ * Nothing of it is in the document or the pages' DOM, and it does not print. The current match is
1768
+ * scrolled to when it is where the view can show it.
1769
+ */
1770
+ showMatches(found: FoundMatches | null): void {
1771
+ this.showFound(found);
1772
+ const { current, scroll } = found ?? {};
1773
+ if (!current || !scroll) return;
1774
+ if (current.story === this.matchStory) this.scrollToRange(current.from, current.to);
1775
+ else if (current.story === this.mount?.id)
1776
+ this.mount?.view.scrollToRange(current.from, current.to);
1777
+ }
1778
+
1779
+ /** The screen ranges of `from..to` in one paragraph: one per text node it covers. */
1780
+ private rangesOf(from: number, to: number): Range[] {
1781
+ const { doc } = this.state;
1782
+ if (to > doc.content.size) return [];
1783
+ const $from = doc.resolve(from);
1784
+ if (!$from.parent.isTextblock) return [];
1785
+ const desc = this.blocks[this.blockFrom($from.before())];
1786
+ if (!desc) return [];
1787
+ const start = $from.start();
1788
+ const out: Range[] = [];
1789
+ for (const leaf of desc.leaves) {
1790
+ const at = start + leaf.offset;
1791
+ const a = Math.max(from, at);
1792
+ const b = Math.min(to, at + leaf.size);
1793
+ if (a >= b || hiddenIn(leaf.dom, desc.dom)) continue;
1794
+ const range = this.host.ownerDocument.createRange();
1795
+ if (leaf.dom.nodeType === Node.TEXT_NODE) {
1796
+ range.setStart(leaf.dom, a - at);
1797
+ range.setEnd(leaf.dom, b - at);
1798
+ } else range.selectNodeContents(leaf.dom);
1799
+ out.push(range);
1800
+ }
1801
+ return out;
1802
+ }
1803
+
1804
+ /** The pages on the screen and a screen around it: only these carry marks. */
1805
+ private pagesNearView(): Set<number> {
1806
+ const height = this.host.ownerDocument.defaultView?.innerHeight ?? 0;
1807
+ const near = new Set<number>();
1808
+ this.pages.forEach((page, i) => {
1809
+ const { top, bottom } = page.getBoundingClientRect();
1810
+ if (bottom >= -height && top <= 2 * height) near.add(i);
1811
+ });
1812
+ return near;
1813
+ }
1814
+
1815
+ private drawMatches(): void {
1816
+ const { found, mount } = this;
1817
+ if (mount) {
1818
+ mount.view.matchStory = mount.id;
1819
+ mount.view.showFound(found);
1820
+ }
1821
+ if (!found) {
1822
+ this.matchMarks.set([], []);
1823
+ this.matchPages = "";
1824
+ return;
1825
+ }
1826
+ injectStyles(this.host);
1827
+ const { doc } = this.state;
1828
+ const near = this.pagesNearView();
1829
+ this.matchPages = [...near].join();
1830
+ // What the near pages hold, as positions: of the body's top-level nodes on them.
1831
+ let low = 0;
1832
+ let high = doc.content.size;
1833
+ if (this.paged) {
1834
+ low = high + 1;
1835
+ high = -1;
1836
+ doc.forEach((node, offset) => {
1837
+ const pages = this.itemPages.get(node);
1838
+ if (pages && !pages.some((page) => near.has(page))) return;
1839
+ low = Math.min(low, offset);
1840
+ high = Math.max(high, offset + node.nodeSize);
1841
+ });
1842
+ }
1843
+ // A tree's matches stand together, in order: those near are found by halving.
1844
+ const { matches } = found;
1845
+ let start = matches.findIndex((m) => m.story === this.matchStory);
1846
+ if (start < 0) start = matches.length;
1847
+ let end = start;
1848
+ while (end < matches.length && matches[end]?.story === this.matchStory) end++;
1849
+ let first = start;
1850
+ for (let last = end; first < last; ) {
1851
+ const mid = (first + last) >> 1;
1852
+ if ((matches[mid] as FindMatch).to <= low) first = mid + 1;
1853
+ else last = mid;
1854
+ }
1855
+ const all: Range[] = [];
1856
+ for (let i = first; i < end && (matches[i] as FindMatch).from < high; i++) {
1857
+ const { from, to } = matches[i] as FindMatch;
1858
+ all.push(...this.rangesOf(from, to));
1859
+ }
1860
+ const others = new Set<string>();
1861
+ for (const [i, { story }] of matches.entries())
1862
+ if ((i < start || i >= end) && story !== null && story !== mount?.id) others.add(story);
1863
+ const { current, query, matchCase, wholeWord } = found;
1864
+ const here = current?.story === this.matchStory ? current : null;
1865
+ if (others.size) {
1866
+ const options = { matchCase, wholeWord };
1867
+ const add = (root: Element | null | undefined) => {
1868
+ if (root) all.push(...rangesInText(root, query, options));
1869
+ };
1870
+ for (const p of near) {
1871
+ const { header, footer } = this.pageRegions[p] ?? {};
1872
+ for (const region of [header, footer])
1873
+ if (region && others.has(region.id))
1874
+ add(region.element.querySelector(`:scope > .${REGION_CONTENT_CLASS}`));
1875
+ for (const note of this.pages[p]?.querySelectorAll(`[${NOTE_ATTR}]`) ?? [])
1876
+ if (others.has(note.getAttribute(NOTE_ATTR) as string)) add(note);
1877
+ }
1878
+ }
1879
+ this.matchMarks.set(all, here ? this.rangesOf(here.from, here.to) : []);
1880
+ }
1881
+
1882
+ /** Scrolling brings other pages near: their marks are drawn, once per frame. */
1883
+ private readonly onMatchScroll = (): void => {
1884
+ const win = this.host.ownerDocument.defaultView;
1885
+ if (this.matchFrame || !win) return;
1886
+ this.matchFrame = win.requestAnimationFrame(() => {
1887
+ this.matchFrame = 0;
1888
+ if (this.found && [...this.pagesNearView()].join() !== this.matchPages) this.drawMatches();
1889
+ });
1890
+ };
1891
+
1892
+ /** What find shows here, marked; a story's view is told by its page's view. */
1893
+ private showFound(found: FoundMatches | null): void {
1894
+ const doc = this.host.ownerDocument;
1895
+ if (this.paged && !this.found !== !found) {
1896
+ if (found) doc.addEventListener("scroll", this.onMatchScroll, SCROLL_OPTIONS);
1897
+ else doc.removeEventListener("scroll", this.onMatchScroll, SCROLL_OPTIONS);
1898
+ }
1899
+ this.found = found;
1900
+ this.drawMatches();
1901
+ }
1902
+
1903
+ private scrollToRange(from: number, to: number): void {
1904
+ let rect = this.rangesOf(from, to)[0]?.getClientRects?.()[0];
1905
+ if (!rect) {
1906
+ // A place, not a stretch of text: what holds it.
1907
+ const { node } = this.domFromPos(from);
1908
+ rect = (node instanceof Element ? node : node.parentElement)?.getBoundingClientRect();
1909
+ }
1910
+ // With room around it: a panel may float over the top of the window.
1911
+ if (rect)
1912
+ scrollRectIntoView(this.host, { top: rect.top - REVEAL_ABOVE, bottom: rect.bottom + 48 });
1913
+ }
1914
+
1915
+ /** Opens story `id` where a page shows it, leaving the focus where it is. */
1916
+ private openForReveal(id: string): boolean {
1917
+ const kind = wordContext(this.state)?.stories.get(id)?.kind;
1918
+ if (kind === "footnote" || kind === "endnote") return this.openNote(id, false);
1919
+ if (kind !== "header" && kind !== "footer") return false;
1920
+ const page = this.pageRegions.findIndex((regions) => regions[kind]?.id === id);
1921
+ return page >= 0 && this.openStory(kind, page, false, false);
1922
+ }
1923
+
1924
+ /**
1925
+ * Selects `target` and scrolls to it: in the body (leaving a story that is open), or in its story,
1926
+ * opened where it is. `focus`: the document takes the focus. False when no page shows it.
1927
+ */
1928
+ reveal({ story, from, to }: DocumentTarget, { focus = false } = {}): boolean {
1929
+ if (story === null) {
1930
+ this.closeStory(false);
1931
+ const { doc } = this.state;
1932
+ if (to > doc.content.size) return false;
1933
+ this.editor.dispatch(this.state.tr.setSelection(TextSelection.create(doc, from, to)));
1934
+ if (focus) this.focus();
1935
+ this.scrollToRange(from, to);
1936
+ return true;
1937
+ }
1938
+ if (this.mount?.id !== story && !this.openForReveal(story)) return false;
1939
+ const { mount } = this;
1940
+ if (!mount) return false;
1941
+ mount.view.editor.select(from, to);
1942
+ if (focus) mount.view.focus();
1943
+ mount.view.scrollToRange(from, to);
1944
+ return true;
1945
+ }
1946
+
1947
+ /** The caret to the start of page `page` (1-based) and the page into view. */
1948
+ goToPage(page: number, { focus = false } = {}): boolean {
1949
+ const element = this.pages[page - 1];
1950
+ if (!element) return false;
1951
+ this.closeStory(false);
1952
+ search: for (const [i, desc] of this.blocks.entries()) {
1953
+ for (const [f, fragment] of desc.fragments.entries()) {
1954
+ if (fragment.closest(".foli-page") !== element) continue;
1955
+ const start = (this.starts[i] as number) + 1 + (f ? (desc.splits[f - 1] as number) : 0);
1956
+ const { doc } = this.state;
1957
+ this.editor.dispatch(
1958
+ this.state.tr.setSelection(
1959
+ Selection.near(doc.resolve(Math.min(start, doc.content.size))),
1960
+ ),
1961
+ );
1962
+ break search;
1963
+ }
1964
+ }
1965
+ if (focus) this.focus();
1966
+ scrollRectIntoView(this.host, element.getBoundingClientRect());
1967
+ return true;
1968
+ }
1969
+
1970
+ /** Word's keys for finding and going places, when the app shows something for them. */
1971
+ private navigationKey(name: string): boolean {
1972
+ const request = Object.hasOwn(NAVIGATION_KEYS, name) ? NAVIGATION_KEYS[name] : undefined;
1973
+ return !!request && this.editor.navigation?.(request) === true;
1974
+ }
1975
+
1976
+ // ---------- content controls ----------
1977
+
1978
+ /** The frames of content controls, drawn again (a render takes them off the pages). */
1979
+ private drawControls(): void {
1980
+ if (!this.composing) this.controlChrome.draw(!this.mount);
1981
+ }
1982
+
1983
+ /** Where a control's content is on the screen: its lines, or its blocks by page. */
1984
+ private controlRects(range: ControlRange): Box[] {
1985
+ if (range.level !== "inline") {
1986
+ const byPage = new Map<Element | null, Box>();
1987
+ for (let i = this.blockFrom(range.from); i < this.blocks.length; i++) {
1988
+ if ((this.starts[i] as number) >= range.to) break;
1989
+ for (const fragment of (this.blocks[i] as WordBlockDesc).fragments) {
1990
+ if (!this.host.contains(fragment)) continue;
1991
+ const rect = fragment.getBoundingClientRect();
1992
+ const page = fragment.closest(".foli-page,.foli-story-flow");
1993
+ const known = byPage.get(page);
1994
+ const left = Math.min(known?.left ?? rect.left, rect.left);
1995
+ const top = Math.min(known?.top ?? rect.top, rect.top);
1996
+ byPage.set(
1997
+ page,
1998
+ boxOf(
1999
+ left,
2000
+ top,
2001
+ Math.max(known?.right ?? rect.right, rect.right) - left,
2002
+ Math.max(known?.bottom ?? rect.bottom, rect.bottom) - top,
2003
+ ),
2004
+ );
2005
+ }
2006
+ }
2007
+ return [...byPage.values()];
2008
+ }
2009
+ return this.controlContentRects(range);
2010
+ }
2011
+
2012
+ /** Where what a control's content shows is on the screen. */
2013
+ private controlContentRects(range: ControlRange): Box[] {
2014
+ const dom = this.host.ownerDocument.createRange();
2015
+ const start = this.domFromPos(range.contentFrom);
2016
+ const end = this.domFromPos(range.contentTo);
2017
+ dom.setStart(start.node, start.offset);
2018
+ dom.setEnd(end.node, end.offset);
2019
+ const rects = [...(dom.getClientRects?.() ?? [])].filter((rect) => rect.width > 0);
2020
+ if (rects.length) return rects;
2021
+ // Nothing in it: a thin box where it is.
2022
+ const element =
2023
+ start.node.nodeType === Node.ELEMENT_NODE
2024
+ ? (start.node as Element)
2025
+ : start.node.parentElement;
2026
+ const rect = dom.getBoundingClientRect?.();
2027
+ const box = rect?.height ? rect : element?.getBoundingClientRect();
2028
+ return box ? [boxOf(box.left, box.top, 4, box.height)] : [];
2029
+ }
2030
+
2031
+ /**
2032
+ * The keys of content controls: Alt+Down opens a list or date picker, and Left and Right stop on
2033
+ * each side of a control's edge, as Word's caret does (browsers cannot see the difference).
2034
+ */
2035
+ private controlKey(name: string): boolean {
2036
+ if (name === "Alt-ArrowDown") return this.controlChrome.open();
2037
+ if (name !== "ArrowLeft" && name !== "ArrowRight") return false;
2038
+ const { selection, doc } = this.state;
2039
+ if (!(selection instanceof TextSelection) || !wordContext(this.state)?.envelope.controls)
2040
+ return false;
2041
+ const forward = name === "ArrowRight";
2042
+ const range = controlAt(doc, selection.from);
2043
+ if (!selection.empty) {
2044
+ // A placeholder is one thing: the arrows go past it.
2045
+ if (
2046
+ range?.level !== "inline" ||
2047
+ !controlProperties(this.state, range.id)?.placeholder?.showing ||
2048
+ selection.from !== range.contentFrom ||
2049
+ selection.to !== range.contentTo
2050
+ )
2051
+ return false;
2052
+ this.dispatch(
2053
+ this.state.tr.setSelection(TextSelection.create(doc, forward ? range.to : range.from)),
2054
+ );
2055
+ return true;
2056
+ }
2057
+ const { $from } = selection;
2058
+ const next = forward ? $from.nodeAfter : $from.nodeBefore;
2059
+ if (next?.type.name !== "controlStart" && next?.type.name !== "controlEnd") return false;
2060
+ this.dispatch(
2061
+ this.state.tr.setSelection(TextSelection.create(doc, $from.pos + (forward ? 1 : -1))),
2062
+ );
2063
+ return true;
2064
+ }
2065
+
2066
+ // ---------- fields ----------
2067
+
2068
+ /** The pages as last flowed, as fields need them; null without pages. */
2069
+ private fieldLayout(): FieldLayout | null {
2070
+ if (!this.regions || !this.facts.length) return null;
2071
+ return {
2072
+ pages: this.facts.length,
2073
+ pageAt: (pos) => {
2074
+ const { node } = this.domFromPos(Math.min(pos, this.state.doc.content.size));
2075
+ const element =
2076
+ node.nodeType === Node.ELEMENT_NODE ? (node as Element) : node.parentElement;
2077
+ const page = this.facts[this.pages.indexOf(element?.closest(".foli-page") as HTMLElement)];
2078
+ if (!page) return null;
2079
+ const format = this.sections()[page.section]?.pageNumbers?.format;
2080
+ return { number: page.number, sectionPages: page.sectionPages, format };
2081
+ },
2082
+ };
2083
+ }
2084
+
2085
+ /**
2086
+ * Updates fields from the pages shown: all of them, or those `options.only` says, of the body or
2087
+ * of `editor` (a story's). What that does to the pages is taken in by a second pass over what
2088
+ * depends on them, in the same undo step.
2089
+ */
2090
+ updateFields(options: UpdateFieldsOptions = {}, editor: Editor = this.editor): FieldsReport {
2091
+ // A story's view has no pages: the view of the body has.
2092
+ const main = this.regions ? null : this.editor.storyView;
2093
+ if (main) return main.updateFields(options, editor);
2094
+ if (this.composing) this.onCompositionEnd();
2095
+ const report = updateFields(editor, { ...options, layout: this.fieldLayout() });
2096
+ const { only } = options;
2097
+ const range = !!only && typeof only !== "function";
2098
+ if (!report.updated || (range && !report.rebuilt)) return report;
2099
+ const follows = (field: Field) =>
2100
+ range
2101
+ ? field.parent?.name === "TOC"
2102
+ : PAGE_DEPENDENT.has(field.name) && (typeof only !== "function" || only(field));
2103
+ const again = updateFields(editor, {
2104
+ ...options,
2105
+ layout: this.fieldLayout(),
2106
+ only: follows,
2107
+ continues: true,
2108
+ });
2109
+ return { ...report, updated: report.updated + again.updated };
2110
+ }
2111
+
2112
+ /**
2113
+ * Prints what the document is now: fields updated (one undo step), then the browser's dialog.
2114
+ */
2115
+ print(): void {
2116
+ try {
2117
+ this.updateFields();
2118
+ } finally {
2119
+ this.host.ownerDocument.defaultView?.print();
2120
+ }
2121
+ }
2122
+
2123
+ /**
2124
+ * Left and Right next to a field's markers: the browser's move starts where something can be
2125
+ * seen, or the markers (empty elements) cost WebKit a key press each. With codes shown the
2126
+ * view makes the move itself, over the whole field; whether it did.
2127
+ */
2128
+ private skipFieldParts(event: KeyboardEvent): boolean {
2129
+ const forward = event.key === "ArrowRight";
2130
+ if ((!forward && event.key !== "ArrowLeft") || event.ctrlKey || event.altKey || event.metaKey)
2131
+ return false;
2132
+ const { selection, doc } = this.state;
2133
+ // Shift extends by itself: an extended DOM selection would lose its anchor to the same spot.
2134
+ if (!(selection instanceof TextSelection) || event.shiftKey || !selection.empty) return false;
2135
+ const stop = caretStop(this.state, selection.head, forward);
2136
+ const sel = this.host.ownerDocument.getSelection();
2137
+ if (stop === selection.head || !sel) return false;
2138
+ if (this.fieldCodes) {
2139
+ this.dispatch(this.state.tr.setSelection(TextSelection.create(doc, stop)));
2140
+ return true;
2141
+ }
2142
+ const { node, offset } = this.domFromPos(stop);
2143
+ sel.collapse(node, offset);
2144
+ return false;
2145
+ }
2146
+
2147
+ /** F9 and Alt+F9, as in Word. */
2148
+ private fieldKey(name: string): boolean {
2149
+ if (name === "Alt-F9") {
2150
+ this.run(toggleFieldCodes);
2151
+ return true;
2152
+ }
2153
+ if (name !== "F9") return false;
2154
+ if (!this.editable) return true;
2155
+ const { selection } = this.state;
2156
+ this.updateFields(
2157
+ selection instanceof AllSelection ? {} : { only: { from: selection.from, to: selection.to } },
2158
+ );
2159
+ return true;
2160
+ }
2161
+
2162
+ /** Shades what shows the fields the selection is in (not printed): the outermost of each. */
2163
+ private showSelectedFields(): void {
2164
+ const { selection, doc } = this.state;
2165
+ const wanted = new Set<Element>();
2166
+ const fields = selection instanceof TextSelection ? fieldsIn(doc) : [];
2167
+ const touched = (field: Field) =>
2168
+ selection.empty
2169
+ ? field.from < selection.from && selection.from < field.to
2170
+ : field.from < selection.to && field.to > selection.from;
2171
+ for (const field of fields) {
2172
+ if (!touched(field) || (field.parent && touched(field.parent))) continue;
2173
+ const [from, to] = this.fieldCodes
2174
+ ? [field.from, field.codeEnd + 1]
2175
+ : [field.resultFrom, field.resultTo];
2176
+ const first = Math.max(this.blockFrom(from) - 1, 0);
2177
+ for (let i = first; i < this.blocks.length; i++) {
2178
+ const start = (this.starts[i] as number) + 1;
2179
+ if (start > to) break;
2180
+ const desc = this.blocks[i] as WordBlockDesc;
2181
+ for (const leaf of desc.leaves) {
2182
+ const at = start + leaf.offset;
2183
+ if (at + leaf.size <= from || at >= to || !leaf.size) continue;
2184
+ if (hiddenIn(leaf.dom, desc.dom)) continue;
2185
+ const element = leaf.dom.nodeType === Node.TEXT_NODE ? leaf.dom.parentElement : leaf.dom;
2186
+ if (element instanceof Element && element.textContent) wanted.add(element);
2187
+ }
2188
+ }
2189
+ }
2190
+ for (const element of this.shadedFields)
2191
+ if (!wanted.has(element)) element.removeAttribute(FIELD_SELECTED_ATTR);
2192
+ if (wanted.size) injectStyles(this.host);
2193
+ for (const element of wanted) element.setAttribute(FIELD_SELECTED_ATTR, "");
2194
+ this.shadedFields = [...wanted];
2195
+ }
2196
+
2197
+ /** The sections of the document, in order. */
2198
+ private sections(): SectionJSON[] {
2199
+ const { envelope } = wordContext(this.state) as WordContext;
2200
+ return sectionSpans(this.state.doc, envelope.section).map((span) => span.setup);
2201
+ }
2202
+
2203
+ /** The page the selection's head is on. */
2204
+ private selectionPage(): number {
2205
+ const { node } = this.domFromPos(this.state.selection.head);
2206
+ const element = node.nodeType === Node.ELEMENT_NODE ? (node as Element) : node.parentElement;
2207
+ return Math.max(this.pages.indexOf(element?.closest(".foli-page") as HTMLElement), 0);
2208
+ }
2209
+
2210
+ /**
2211
+ * Opens the header or footer of page `at` (by default the selection's) for editing where it is;
2212
+ * made first when the page has none. Whether it is open now.
2213
+ */
2214
+ openStory(side: StorySide, at = this.selectionPage(), create = true, focus = true): boolean {
2215
+ if (!this.regions || !this.editable || this.composing) return false;
2216
+ // Word's blank page has none: the next page's.
2217
+ let p = at;
2218
+ while (this.facts[p] && !this.facts[p]?.sectionPages) p++;
2219
+ const page = this.facts[p];
2220
+ if (!page) return false;
2221
+ const context = wordContext(this.state) as WordContext;
2222
+ const setup = this.sections()[page.section] as SectionJSON;
2223
+ const even = context.envelope.settings?.evenAndOddHeaders === true;
2224
+ const variant = pageVariant(setup, page, even);
2225
+ const before = storyOfSection(this.sections(), page.section, side, variant);
2226
+ if (this.mount?.id === before?.id && this.mount?.side === side && this.mount?.page === p) {
2227
+ if (focus) this.mount?.view.focus();
2228
+ return true;
2229
+ }
2230
+ this.closeStory(false);
2231
+ if (!before && (!create || !this.editor.run(ensureStory(side, variant, page.section))))
2232
+ return false;
2233
+ const found = storyOfSection(this.sections(), page.section, side, variant);
2234
+ const editor = found && this.editor.story(found.id);
2235
+ const region = this.pageRegions[p]?.[side];
2236
+ if (!found || !editor || !region) return false;
2237
+ this.mountStory(
2238
+ editor,
2239
+ { id: found.id, side, variant, section: page.section, page: p, region },
2240
+ side === "header" ? "Header" : "Footer",
2241
+ undefined,
2242
+ focus,
2243
+ );
2244
+ return true;
2245
+ }
2246
+
2247
+ /**
2248
+ * Opens note `id`, or the one whose reference is at the selection, in place: shown whole at its
2249
+ * reference's page. Whether it is open now.
2250
+ */
2251
+ openNote(id?: string, focus = true): boolean {
2252
+ const { notes } = this;
2253
+ if (!notes || !this.editable || this.composing) return false;
2254
+ const story = id ?? noteAtSelection(this.state)?.story;
2255
+ if (!story) return false;
2256
+ if (this.mount?.id === story) {
2257
+ if (focus) this.mount.view.focus();
2258
+ return true;
2259
+ }
2260
+ this.closeStory(false);
2261
+ const editor = this.editor.story(story);
2262
+ if (!editor) return false;
2263
+ notes.open = story;
2264
+ this.flowed = null;
2265
+ this.render();
2266
+ const element = this.host.querySelector<HTMLElement>(`[${NOTE_ATTR}="${CSS.escape(story)}"]`);
2267
+ const page = this.notePages.get(story);
2268
+ if (!element || page === undefined) {
2269
+ notes.open = null;
2270
+ this.flowed = null;
2271
+ this.render();
2272
+ return false;
2273
+ }
2274
+ const region = { element, drawing: {}, section: 0, id: story };
2275
+ const texts = () =>
2276
+ noteTexts(noteNumbers(this.state.doc, (wordContext(this.state) as WordContext).envelope));
2277
+ this.mountStory(
2278
+ editor,
2279
+ { id: story, side: "note", variant: "default", section: 0, page, region },
2280
+ "Note",
2281
+ () => texts().get(story) ?? "",
2282
+ focus,
2283
+ );
2284
+ editor.select(Selection.atEnd(editor.state.doc).from);
2285
+ return true;
2286
+ }
2287
+
2288
+ /** From the note being edited back to its reference, the caret after it. */
2289
+ private toReference(): boolean {
2290
+ const { mount } = this;
2291
+ if (mount?.side !== "note") return false;
2292
+ const reference = noteNumbers(
2293
+ this.state.doc,
2294
+ (wordContext(this.state) as WordContext).envelope,
2295
+ ).find((n) => n.story === mount.id);
2296
+ this.closeStory(false);
2297
+ if (reference)
2298
+ this.dispatch(
2299
+ this.state.tr.setSelection(TextSelection.create(this.state.doc, reference.pos + 1)),
2300
+ );
2301
+ this.focus();
2302
+ return true;
2303
+ }
2304
+
2305
+ /** Puts `editor`'s story on its page, in `place`, the body read-only and dimmed around it. */
2306
+ private mountStory(
2307
+ editor: Editor,
2308
+ place: Omit<StoryMount, "wrapper" | "view" | "moved">,
2309
+ label: string,
2310
+ noteMark?: () => string,
2311
+ focus = true,
2312
+ ): void {
2313
+ const { region } = place;
2314
+ injectStyles(this.host);
2315
+ this.observer.disconnect();
2316
+ this.host.setAttribute("contenteditable", "false");
2317
+ this.host.setAttribute("aria-readonly", "true");
2318
+ this.host.classList.add("foli-in-story");
2319
+ const doc = this.host.ownerDocument;
2320
+ const wrapper = doc.createElement("div");
2321
+ wrapper.className = "foli-story-mount";
2322
+ wrapper.setAttribute("contenteditable", "false");
2323
+ wrapper.style.userSelect = "text";
2324
+ wrapper.style.setProperty("-webkit-user-select", "text");
2325
+ const inner = doc.createElement("div");
2326
+ inner.setAttribute("aria-label", label);
2327
+ wrapper.append(inner);
2328
+ const shown = region.element.querySelector<HTMLElement>(`:scope > .${REGION_CONTENT_CLASS}`);
2329
+ if (shown) {
2330
+ shown.style.display = "none";
2331
+ wrapper.style.paddingBottom = shown.style.paddingBottom;
2332
+ }
2333
+ region.element.append(wrapper);
2334
+ const view = new EditorView(inner, editor, {
2335
+ paged: false,
2336
+ upload: this.upload ?? null,
2337
+ resource: this.resource ?? null,
2338
+ ...(noteMark ? { noteMark } : {}),
2339
+ });
2340
+ wrapper.addEventListener("keydown", (event) => {
2341
+ if (event.isComposing || view.composing) return;
2342
+ if (isNoteKey(event) && this.toReference()) {
2343
+ // Not on to the body, which would open the note again.
2344
+ event.preventDefault();
2345
+ event.stopPropagation();
2346
+ return;
2347
+ }
2348
+ if (event.key !== "Escape") return;
2349
+ event.preventDefault();
2350
+ this.closeStory(true);
2351
+ });
2352
+ this.mount = { ...place, wrapper, view, moved: false };
2353
+ // With several views of the editor, the one in use answers for its story.
2354
+ wrapper.addEventListener("focusin", () => this.claimStories());
2355
+ this.claimStories();
2356
+ if (focus) view.focus();
2357
+ this.drawMatches();
2358
+ this.editor.storyChanged();
2359
+ }
2360
+
2361
+ /** Finishes a running composition, its text going into the model. */
2362
+ endComposition(): void {
2363
+ if (this.composing) this.onCompositionEnd();
2364
+ }
2365
+
2366
+ /** Leaves the story being edited; `focus`: the body takes the focus, with its selection back. */
2367
+ closeStory(focus = true): void {
2368
+ const { mount } = this;
2369
+ if (!mount) return;
2370
+ mount.view.endComposition();
2371
+ this.mount = null;
2372
+ mount.view.destroy();
2373
+ mount.wrapper.remove();
2374
+ const shown = mount.region.element.querySelector<HTMLElement>(
2375
+ `:scope > .${REGION_CONTENT_CLASS}`,
2376
+ );
2377
+ if (shown) shown.style.display = "";
2378
+ if (mount.side === "note" && this.notes) {
2379
+ this.notes.open = null;
2380
+ this.flowed = null;
2381
+ if (!this.destroyed) this.render();
2382
+ }
2383
+ this.host.classList.remove("foli-in-story");
2384
+ this.host.setAttribute("contenteditable", String(this.editable));
2385
+ if (this.editable) this.host.removeAttribute("aria-readonly");
2386
+ this.observer.takeRecords();
2387
+ this.observer.observe(this.host, { childList: true, characterData: true, subtree: true });
2388
+ if (focus && !this.destroyed) this.focus();
2389
+ if (!this.destroyed) this.drawMatches();
2390
+ this.editor.storyChanged();
2391
+ }
2392
+
2393
+ /** The page's own story, after what was open is shown nowhere any more. */
2394
+ private reopenStory = (): void => {
2395
+ const { mount } = this;
2396
+ if (!mount || mount.side === "note" || this.facts.length === 0) return;
2397
+ const { side, page, id } = mount;
2398
+ // A story that went (undone) is not made again.
2399
+ const create = !!wordContext(this.state)?.stories.has(id);
2400
+ this.closeStory(false);
2401
+ if (!this.openStory(side, Math.min(page, this.facts.length - 1), create)) this.focus();
2402
+ };
2403
+
2404
+ /** The margin of a page a mouse event is in, if it is on the page itself. */
2405
+ private marginAt(event: MouseEvent): { side: StorySide; page: number } | null {
2406
+ const element = event.target as Element | null;
2407
+ const page = this.pages.indexOf(element as HTMLElement);
2408
+ if (page < 0 || !this.regions) return null;
2409
+ const box = (element as Element).getBoundingClientRect();
2410
+ const scale = this.scale();
2411
+ const style = getComputedStyle(element as Element);
2412
+ const y = (event.clientY - box.top) / scale;
2413
+ if (y < Number.parseFloat(style.paddingTop)) return { side: "header", page };
2414
+ return y > box.height / scale - Number.parseFloat(style.paddingBottom)
2415
+ ? { side: "footer", page }
2416
+ : null;
2417
+ }
2418
+
2419
+ /**
2420
+ * A press outside the story being edited leaves it. The second press of a double click in a
2421
+ * page's margin opens its header or footer, the body's selection kept: on the press, since the
2422
+ * first click may have scrolled the page (Firefox) and the double click would land elsewhere.
2423
+ */
2424
+ private onPress = (event: MouseEvent): void => {
2425
+ this.closeStory(false);
2426
+ // A note on the page, or the number of its reference: the second press opens the note.
2427
+ const target = event.target instanceof Element ? event.target : null;
2428
+ const onNote = target?.closest(`[${NOTE_ATTR}]`);
2429
+ const number = target?.closest(`[${NOTE_REF_ATTR}]`);
2430
+ const story = onNote?.getAttribute(NOTE_ATTR) ?? number?.getAttribute(NOTE_REF_ATTR);
2431
+ if (story && event.button === 0 && !event.shiftKey) {
2432
+ const opens = event.detail === 2 && this.editable && isNoteStory(this.state, story);
2433
+ if (onNote || opens) event.preventDefault();
2434
+ if (opens) {
2435
+ if (this.openNote(story) && onNote)
2436
+ this.mount?.view.placeCaret(event.clientX, event.clientY);
2437
+ return;
2438
+ }
2439
+ if (onNote) return;
2440
+ }
2441
+ const margin = event.button === 0 && !event.shiftKey ? this.marginAt(event) : null;
2442
+ if (margin && event.detail > 1) {
2443
+ event.preventDefault();
2444
+ if (event.detail > 2 || !this.editable) return;
2445
+ const selection = this.pressSelection;
2446
+ this.pressSelection = null;
2447
+ if (selection && !selection.eq(this.state.selection))
2448
+ this.editor.dispatch(this.state.tr.setSelection(selection));
2449
+ if (this.openStory(margin.side, margin.page))
2450
+ this.mount?.view.placeCaret(event.clientX, event.clientY);
2451
+ return;
2452
+ }
2453
+ // What the body shows now is what leaving the story comes back to (`selectionchange` comes
2454
+ // late, and the browser may select something on the way to the second press).
2455
+ if (margin && this.hasFocus()) this.syncSelection();
2456
+ this.pressSelection = margin ? this.state.selection : null;
2457
+ // On a header or footer a press is not for the body: it places no caret.
2458
+ if (margin && this.pageRegions[margin.page]?.[margin.side]) {
2459
+ event.preventDefault();
2460
+ if (!this.hasFocus()) {
2461
+ this.pointerFocus = true;
2462
+ this.host.focus({ preventScroll: true });
2463
+ this.writeSelection(true);
2464
+ }
2465
+ return;
2466
+ }
2467
+ this.onMouseDown(event);
2468
+ };
2469
+
2470
+ /** Puts the caret at a point of the window, if it is on this view's content. */
2471
+ placeCaret(x: number, y: number): void {
2472
+ const pos = this.posAtPoint(x, y);
2473
+ if (pos !== null)
2474
+ this.editor.dispatch(
2475
+ this.state.tr.setSelection(TextSelection.near(this.state.doc.resolve(pos))),
2476
+ );
2477
+ }
2478
+
2479
+ /** The model position at a point of the window, or null. */
2480
+ private posAtPoint(x: number, y: number): number | null {
2481
+ const doc = this.host.ownerDocument as Document & {
2482
+ caretPositionFromPoint?: (
2483
+ x: number,
2484
+ y: number,
2485
+ ) => { offsetNode: Node; offset: number } | null;
2486
+ caretRangeFromPoint?: (x: number, y: number) => Range | null;
2487
+ };
2488
+ const point = doc.caretPositionFromPoint?.(x, y);
2489
+ const range = point ? null : doc.caretRangeFromPoint?.(x, y);
2490
+ const node = point?.offsetNode ?? range?.startContainer;
2491
+ const offset = point?.offset ?? range?.startOffset ?? 0;
2492
+ return node && this.host.contains(node) ? this.posFromDOM(node, offset) : null;
2493
+ }
2494
+
2495
+ /**
2496
+ * A floating picture reaches into the blocks after its paragraph (their lines go around it):
2497
+ * a block that changed (new, drawn again or stale) on a page holding one has the blocks after
2498
+ * it on that page and the next measured again. A new block counts on the page of the block
2499
+ * before it, where `place` first puts it, and the next (it may have been that page's first);
2500
+ * only blocks that changed reach on, not the ones this marks, so an edit re-measures three
2501
+ * pages at most.
2502
+ */
2503
+ private staleAroundFloats(
2504
+ doc: ModelNode,
2505
+ pagesOf: ReadonlyMap<ModelNode, readonly number[]>,
2506
+ redrawn: ReadonlySet<ModelNode>,
2507
+ ): void {
2508
+ const blocks: { node: ModelNode; pages: readonly number[]; changed: boolean }[] = [];
2509
+ let last = 0;
2510
+ doc.forEach((node) => {
2511
+ const known = pagesOf.get(node);
2512
+ const pages = known?.length ? known : [last, last + 1];
2513
+ last = known?.length ? (known[known.length - 1] as number) : last;
2514
+ blocks.push({ node, pages, changed: !known || redrawn.has(node) || this.stale.has(node) });
2515
+ });
2516
+ // The pages floats are on now, and were on before (a float deleted or made inline leaves
2517
+ // lines that went around it).
2518
+ const floatPages = new Set<number>();
2519
+ for (const { node, pages } of blocks)
2520
+ if (holdsFloat(node)) for (const p of pages) floatPages.add(p);
2521
+ for (const [node, pages] of pagesOf)
2522
+ if (holdsFloat(node)) for (const p of pages) floatPages.add(p);
2523
+ if (!floatPages.size) return;
2524
+ let reach = -1;
2525
+ for (const { node, pages, changed } of blocks) {
2526
+ if ((pages[0] as number) <= reach) this.stale.add(node);
2527
+ if (changed && pages.some((p) => floatPages.has(p)))
2528
+ reach = Math.max(reach, (pages[pages.length - 1] as number) + 1);
2529
+ }
640
2530
  }
641
2531
 
642
2532
  /** A font's normal line height ratio, measured outside the host (no input to read back). */
@@ -652,25 +2542,34 @@ export class EditorView {
652
2542
 
653
2543
  /**
654
2544
  * Puts each fragment of each block into its page (pages are non-decreasing in document
655
- * order), creating and removing pages as needed, and gives each page the page setup of its
656
- * blocks' section (one per page: `separateSheets`, section breaks). Anything else in the host
657
- * or a page (stray DOM) is removed.
2545
+ * order) and, on a page with several sections or columns, into its band's column, creating
2546
+ * and removing pages as needed, and gives each page the page setup of its first section.
2547
+ * Anything else in the host or a page (stray DOM) is removed.
658
2548
  */
659
2549
  private place(
660
- blocks: readonly BlockDesc[],
2550
+ elements: readonly (readonly HTMLElement[])[],
661
2551
  pages: readonly (readonly number[])[],
2552
+ slots: readonly (readonly Slot[])[],
662
2553
  layout: readonly BlockLayout[],
663
2554
  ): void {
664
2555
  const { host } = this;
665
- const items = blocks.flatMap((desc, i) =>
666
- desc.fragments.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0 })),
2556
+ const items = elements.flatMap((list, i) =>
2557
+ list.map((dom, f) => ({
2558
+ dom,
2559
+ page: pages[i]?.[f] ?? 0,
2560
+ slot: slots[i]?.[f] as Slot,
2561
+ section: (layout[i] as BlockLayout).section,
2562
+ })),
667
2563
  );
668
- const count = (items[items.length - 1]?.page ?? 0) + 1;
2564
+ // A note can reach pages no text is on.
2565
+ const count = Math.max((items[items.length - 1]?.page ?? 0) + 1, this.pageNotes.length);
669
2566
  const sheets: Sheet[] = [];
670
2567
  pages.forEach((list, i) => {
671
2568
  for (const p of list) sheets[p] ??= (layout[i] as BlockLayout).sheet;
672
2569
  });
673
- // A page no block starts on (none yet) takes the setup of the page before it.
2570
+ // A page no block is on has the setup of the page after it (Word's blank page before an
2571
+ // even or odd page section); the last, one with no blocks yet, of the page before it.
2572
+ for (let p = count - 1; p >= 0; p--) if (sheets[p + 1]) sheets[p] ??= sheets[p + 1] as Sheet;
674
2573
  for (let p = 0; p < count; p++)
675
2574
  sheets[p] ??=
676
2575
  sheets[p - 1] ?? (layout[0] as BlockLayout | undefined)?.sheet ?? this.lastSheet();
@@ -679,10 +2578,19 @@ export class EditorView {
679
2578
  this.sheets.forEach((sheet, p) => {
680
2579
  const page = this.pages[p] as HTMLElement;
681
2580
  const key = `${sheet.index} ${sheet.css}`;
682
- if (pageSheets.get(page) === key) return;
683
- pageSheets.set(page, key);
684
- page.style.cssText = sheet.css;
685
- page.setAttribute(SHEET_ATTR, String(sheet.index));
2581
+ if (pageSheets.get(page) !== key) {
2582
+ pageSheets.set(page, key);
2583
+ pagePads.delete(page);
2584
+ page.style.cssText = sheet.css;
2585
+ page.setAttribute(SHEET_ATTR, String(sheet.index));
2586
+ }
2587
+ const { top = "", bottom = "" } = this.pageMargins[p] ?? {};
2588
+ const pads = `${top} ${bottom}`;
2589
+ if ((pagePads.get(page) ?? " ") !== pads) {
2590
+ pagePads.set(page, pads);
2591
+ page.style.paddingTop = top;
2592
+ page.style.paddingBottom = bottom;
2593
+ }
686
2594
  });
687
2595
  // Pages first, in order; anything else in the host ends up after them.
688
2596
  let cursor = host.firstChild;
@@ -693,18 +2601,64 @@ export class EditorView {
693
2601
  let i = 0;
694
2602
  for (let p = 0; p < count; p++) {
695
2603
  const page = this.pages[p] as HTMLElement;
696
- let at = page.firstChild;
697
- for (; i < items.length && items[i]?.page === p; i++) {
698
- const { dom } = items[i] as (typeof items)[number];
699
- if (dom === at) at = at.nextSibling;
700
- else page.insertBefore(dom, at);
2604
+ const first = i;
2605
+ while (i < items.length && items[i]?.page === p) i++;
2606
+ const onPage = items.slice(first, i);
2607
+ const { header, footer } = this.pageRegions[p] ?? {};
2608
+ const notes = this.pageNotes[p];
2609
+ /** What follows the text of a column: its endnotes. */
2610
+ const after = (band: number, column: number) => notes?.flow.get(`${band}|${column}`) ?? [];
2611
+ /** A page's children: its header, what it holds, its notes, its footer. */
2612
+ const framed = (list: readonly HTMLElement[]) => [
2613
+ ...(header ? [header.element] : []),
2614
+ ...list,
2615
+ ...(notes?.foot ?? []),
2616
+ ...(footer ? [footer.element] : []),
2617
+ ];
2618
+ for (const { dom, slot } of onPage) {
2619
+ const position = slot.mark ? "absolute" : "";
2620
+ if (dom.style.position !== position) dom.style.position = position;
2621
+ }
2622
+ // One section in one column: the blocks are the page's children.
2623
+ const last = onPage[onPage.length - 1];
2624
+ if (!last || (!last.slot.band && last.section.columns.widths.length === 1)) {
2625
+ fillElement(
2626
+ page,
2627
+ framed([...onPage.map((item) => item.dom), ...after(0, 0)]),
2628
+ this.viewRemoved,
2629
+ );
2630
+ this.bands.delete(page);
2631
+ continue;
701
2632
  }
702
- // What is left after the last placed block: strays, and blocks of later pages.
703
- while (at) {
704
- const next: ChildNode | null = at.nextSibling;
705
- at.remove();
706
- at = next;
2633
+ const known = this.bands.get(page) ?? [];
2634
+ const bands: typeof known = [];
2635
+ for (const { section, slot } of onPage) {
2636
+ if (bands[slot.band]) continue;
2637
+ const key = columnsKey(section.columns);
2638
+ const reused = known[slot.band];
2639
+ bands[slot.band] =
2640
+ reused?.key === key
2641
+ ? reused
2642
+ : { key, ...bandElement(host.ownerDocument, section.columns) };
707
2643
  }
2644
+ this.bands.set(page, bands);
2645
+ fillElement(page, framed(bands.map((b) => b.band)), this.viewRemoved);
2646
+ bands.forEach((band, b) => {
2647
+ const inBand = onPage.filter((item) => item.slot.band === b);
2648
+ const lead = inBand[0]?.slot.lead;
2649
+ const margin = lead ? `${lead}px` : "";
2650
+ if (band.band.style.marginTop !== margin) band.band.style.marginTop = margin;
2651
+ band.columns.forEach((column, c) => {
2652
+ fillElement(
2653
+ column,
2654
+ [
2655
+ ...inBand.filter((item) => item.slot.column === c).map((item) => item.dom),
2656
+ ...after(b, c),
2657
+ ],
2658
+ this.viewRemoved,
2659
+ );
2660
+ });
2661
+ });
708
2662
  }
709
2663
  // Pages no longer needed and stray DOM in the host: all after the last page by now.
710
2664
  let rest = (this.pages[count - 1] as HTMLElement).nextSibling;
@@ -716,9 +2670,43 @@ export class EditorView {
716
2670
  this.pages.length = count;
717
2671
  }
718
2672
 
2673
+ /**
2674
+ * What a table's cell shows in one of its fragments: its blocks' elements that `takes` puts
2675
+ * there, and nested tables whole (where their first block goes).
2676
+ */
2677
+ private cellContent(
2678
+ frame: Frame,
2679
+ r: number,
2680
+ c: number,
2681
+ blocks: readonly WordBlockDesc[],
2682
+ takes: (unit: number, fragment: number) => boolean,
2683
+ ): Node[] {
2684
+ const out: Node[] = [];
2685
+ for (const item of frame.rows[r]?.cells[c]?.items ?? []) {
2686
+ if ("frame" in item) {
2687
+ const nested = item.frame;
2688
+ if (!takes(nested.first, 0)) continue;
2689
+ out.push(
2690
+ frameElement(
2691
+ nested,
2692
+ nested.rows.map((_, i) => i),
2693
+ [],
2694
+ (rr, cc) => this.cellContent(nested, rr, cc, blocks, () => true),
2695
+ this.host.ownerDocument,
2696
+ ),
2697
+ );
2698
+ continue;
2699
+ }
2700
+ (blocks[item.unit] as WordBlockDesc).fragments.forEach((fragment, f) => {
2701
+ if (takes(item.unit, f)) out.push(fragment);
2702
+ });
2703
+ }
2704
+ return out;
2705
+ }
2706
+
719
2707
  private createPage(): HTMLElement {
720
2708
  const page = this.host.ownerDocument.createElement("section");
721
- page.className = "foli-page";
2709
+ page.className = this.paged ? "foli-page" : "foli-story-flow";
722
2710
  return page;
723
2711
  }
724
2712
 
@@ -729,6 +2717,7 @@ export class EditorView {
729
2717
 
730
2718
  /** The print rules for the document's page setups, written when they change. */
731
2719
  private applyPrintStyles(layout: readonly BlockLayout[]): void {
2720
+ if (!this.paged) return;
732
2721
  const sheets = [...new Set(layout.map((block) => block.sheet))];
733
2722
  const key = [this.lastSheet(), ...sheets].map((sheet) => sheet.css).join("\n");
734
2723
  if (key === this.printKey) return;
@@ -742,7 +2731,7 @@ export class EditorView {
742
2731
  this.printStyles = parents.map((parent) => {
743
2732
  const style = doc.createElement("style");
744
2733
  style.setAttribute("data-foli-print", "");
745
- style.textContent = printStyles(this.editor.settings, sheets, this.id);
2734
+ style.textContent = viewPrintStyles(this.editor.settings, sheets, this.id);
746
2735
  parent.append(style);
747
2736
  return style;
748
2737
  });
@@ -752,6 +2741,9 @@ export class EditorView {
752
2741
  private invalidateLayout(): void {
753
2742
  this.measures = new WeakMap();
754
2743
  this.flowed = null;
2744
+ this.regionsFor = null;
2745
+ if (this.regions) this.regions.cache = new WeakMap();
2746
+ if (this.notes) this.notes.cache = new WeakMap();
755
2747
  }
756
2748
 
757
2749
  /** Re-flows the pages once web fonts have loaded: line heights and wrapping change. */
@@ -790,7 +2782,7 @@ export class EditorView {
790
2782
  if (!desc || !measured || this.stale.has(desc.node)) continue;
791
2783
  // A hidden host (display: none) reports every block as 0x0: nothing to re-flow.
792
2784
  if (!entry.contentRect.width) continue;
793
- scale ??= layoutScale(this.pages[0] as HTMLElement, (this.sheets[0] as Sheet).settings);
2785
+ scale ??= this.scale();
794
2786
  let height = 0;
795
2787
  for (const fragment of desc.fragments) height += fragment.getBoundingClientRect().height;
796
2788
  // A block is measured whole; each fragment of a split one keeps its padding and border,
@@ -817,7 +2809,7 @@ export class EditorView {
817
2809
  this.relayoutPending = false;
818
2810
  if (this.destroyed) return;
819
2811
  // compositionend flows what a composition kept from moving.
820
- if (this.composing) {
2812
+ if (this.composing || this.mount?.view.composing) {
821
2813
  this.unflowed = true;
822
2814
  return;
823
2815
  }
@@ -837,9 +2829,19 @@ export class EditorView {
837
2829
  return null;
838
2830
  }
839
2831
 
840
- /** Whether `node` holds blocks rather than content: the host or a page. */
2832
+ /**
2833
+ * Whether `node` holds blocks rather than content: the host, a page, a band or column of one,
2834
+ * or a table's wrapper, table, rows and cells.
2835
+ */
841
2836
  private holdsBlocks(node: Node): boolean {
842
- return node === this.host || this.pages.includes(node as HTMLElement);
2837
+ if (node === this.host || this.pages.includes(node as HTMLElement)) return true;
2838
+ if (node.nodeType !== Node.ELEMENT_NODE) return false;
2839
+ const element = node as Element;
2840
+ return (
2841
+ element.classList.contains(BAND_CLASS) ||
2842
+ element.classList.contains(COLUMN_CLASS) ||
2843
+ (element.hasAttribute(FRAME_ATTR) && !element.closest(`[${REPEATED_ATTR}]`))
2844
+ );
843
2845
  }
844
2846
 
845
2847
  /** Index of the first block that starts at or after `pos` (the block count if none). */
@@ -857,17 +2859,36 @@ export class EditorView {
857
2859
  /** Model position of a DOM point inside the host, or null if it is outside. */
858
2860
  posFromDOM(node: Node, offset: number): number | null {
859
2861
  const { host } = this;
2862
+ // In a header row drawn again (not document content): the first position below it.
2863
+ const at = node.nodeType === Node.ELEMENT_NODE ? (node as Element) : node.parentElement;
2864
+ const repeated = at?.closest(`[${REPEATED_ATTR}]`);
2865
+ if (repeated?.parentNode && host.contains(repeated)) {
2866
+ const parent = repeated.parentNode;
2867
+ return this.posFromDOM(parent, [...parent.childNodes].indexOf(repeated as ChildNode) + 1);
2868
+ }
860
2869
  if (this.holdsBlocks(node)) {
861
2870
  // Between fragments: the start of the first one after the point (a block start, or
862
2871
  // where a continuation starts), else the document end.
863
2872
  const range = host.ownerDocument.createRange();
864
2873
  range.setStart(node, offset);
2874
+ const posOf = (i: number, f: number) =>
2875
+ f === 0
2876
+ ? (this.starts[i] as number)
2877
+ : (this.starts[i] as number) +
2878
+ 1 +
2879
+ ((this.blocks[i] as BlockDesc).splits[f - 1] as number);
2880
+ // Without tables, blocks are in DOM order: the first one after the point. In a row split
2881
+ // across pages, a cell's continuation comes after the next cell: the earliest in the DOM.
2882
+ let best: { i: number; f: number; dom: HTMLElement } | null = null;
865
2883
  for (const [i, desc] of this.blocks.entries()) {
866
2884
  const f = desc.fragments.findIndex((fragment) => range.comparePoint(fragment, 0) >= 0);
867
- if (f === 0) return this.starts[i] as number;
868
- if (f > 0) return (this.starts[i] as number) + 1 + (desc.splits[f - 1] as number);
2885
+ if (f < 0) continue;
2886
+ const dom = desc.fragments[f] as HTMLElement;
2887
+ if (!this.frames.size) return posOf(i, f);
2888
+ if (!best || dom.compareDocumentPosition(best.dom) & Node.DOCUMENT_POSITION_FOLLOWING)
2889
+ best = { i, f, dom };
869
2890
  }
870
- return this.state.doc.content.size;
2891
+ return best ? posOf(best.i, best.f) : this.state.doc.content.size;
871
2892
  }
872
2893
  const element = this.blockElement(node);
873
2894
  const owner = element ? this.owner.get(element) : undefined;
@@ -947,25 +2968,47 @@ export class EditorView {
947
2968
  private readSelection(): Selection | null {
948
2969
  const sel = this.host.ownerDocument.getSelection();
949
2970
  if (!sel?.anchorNode || !sel.focusNode) return null;
2971
+ if (this.mount?.wrapper.contains(sel.anchorNode)) return null;
950
2972
  // A range around exactly one block leaf element (a rule): the node selection that wrote it.
951
2973
  // (Its end, mapped alone, would be the start of the next block, not the end of the rule.)
952
2974
  if (sel.anchorNode === sel.focusNode && Math.abs(sel.anchorOffset - sel.focusOffset) === 1) {
953
2975
  const child = sel.anchorNode.childNodes[Math.min(sel.anchorOffset, sel.focusOffset)];
2976
+ // Around a table's (first) wrapper: the table selected whole.
2977
+ const table = child && this.frameOf.get(child);
2978
+ if (table) return NodeSelection.create(this.state.doc, table.pos);
954
2979
  const owner = child && this.owner.get(child);
955
2980
  const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
956
2981
  if (owner && !owner.node.isTextblock && NodeSelection.isSelectable(owner.node))
957
2982
  return NodeSelection.create(this.state.doc, this.starts[index] as number);
958
2983
  }
959
- const anchor = this.posFromDOM(sel.anchorNode, sel.anchorOffset);
960
- const head = this.posFromDOM(sel.focusNode, sel.focusOffset);
2984
+ // Several ranges (Firefox selects table cells so, one range per cell): from the first cell
2985
+ // to the last (a range's start is in its cell; its end is after it).
2986
+ const many = sel.rangeCount > 1;
2987
+ const first = many ? sel.getRangeAt(0) : null;
2988
+ const lastRange = many ? sel.getRangeAt(sel.rangeCount - 1) : null;
2989
+ const anchor = first
2990
+ ? this.posFromDOM(first.startContainer, first.startOffset)
2991
+ : this.posFromDOM(sel.anchorNode, sel.anchorOffset);
2992
+ const head = lastRange
2993
+ ? this.posFromDOM(lastRange.startContainer, lastRange.startOffset)
2994
+ : this.posFromDOM(sel.focusNode, sel.focusOffset);
961
2995
  if (anchor === null || head === null) return null;
962
2996
  const { doc } = this.state;
2997
+ // The caret the view wrote for a cell selection (in its head cell): that selection.
2998
+ const current = this.state.selection;
2999
+ if (current instanceof CellSelection && anchor === head && anchor === this.cellCaret)
3000
+ return current;
3001
+ // Ends in two cells of one table: the cells between them.
3002
+ const a = cellAround(doc, anchor);
3003
+ const h = cellAround(doc, head);
3004
+ if (a && h && a.cell !== h.cell && a.table === h.table)
3005
+ return CellSelection.create(doc, a.cell, h.cell);
963
3006
  // Exactly around a selectable block leaf (a rule): the node selection that wrote it.
964
3007
  const from = Math.min(anchor, head);
965
3008
  const node = doc.nodeAt(from);
966
3009
  if (
967
3010
  node &&
968
- node.isBlock &&
3011
+ (node.isBlock || node.type.name === "picture") &&
969
3012
  node.isAtom &&
970
3013
  Math.max(anchor, head) === from + node.nodeSize &&
971
3014
  NodeSelection.isSelectable(node)
@@ -982,9 +3025,73 @@ export class EditorView {
982
3025
  return desc && this.starts[this.indexOf.get(desc) ?? -1] === selection.from ? desc : null;
983
3026
  }
984
3027
 
3028
+ /** The span of the picture a node selection selects, if it selects one. */
3029
+ private pictureSpan(pos: number): HTMLElement | null {
3030
+ for (const img of this.host.querySelectorAll(`[${PICTURE_ATTR}]`)) {
3031
+ const span = img.parentElement;
3032
+ // A floating picture's place in the text is its anchor.
3033
+ if (span && this.posFromDOM(FLOAT_ANCHORS.get(span) ?? span, 0) === pos) return span;
3034
+ }
3035
+ return null;
3036
+ }
3037
+
3038
+ /** Marks the selected picture and gives it a resize handle (when the document is editable). */
3039
+ private showSelectedPicture(): void {
3040
+ const { selection } = this.state;
3041
+ const span =
3042
+ selection instanceof NodeSelection && selection.node.type.name === "picture"
3043
+ ? this.pictureSpan(selection.from)
3044
+ : null;
3045
+ const handled = !!span?.querySelector("[data-foli-resize]");
3046
+ if (span === this.selectedPicture && (!span || handled === this.editable)) return;
3047
+ this.selectedPicture?.removeAttribute(PICTURE_SELECTED_ATTR);
3048
+ this.selectedPicture?.querySelector("[data-foli-resize]")?.remove();
3049
+ this.selectedPicture = span;
3050
+ if (!span) return;
3051
+ injectStyles(this.host);
3052
+ span.setAttribute(PICTURE_SELECTED_ATTR, "");
3053
+ if (!this.editable) return;
3054
+ const handle = this.host.ownerDocument.createElement("span");
3055
+ handle.setAttribute("data-foli-resize", "");
3056
+ handle.setAttribute("aria-hidden", "true");
3057
+ span.append(handle);
3058
+ }
3059
+
3060
+ /** Marks the cells of a cell selection (their table cell elements, on every page). */
3061
+ private showSelectedCells(): void {
3062
+ const { selection } = this.state;
3063
+ const cells: HTMLElement[] = [];
3064
+ if (selection instanceof CellSelection) {
3065
+ for (const pos of selection.cells) {
3066
+ const caret = Selection.near(this.state.doc.resolve(pos + 1), 1).from;
3067
+ const { node } = this.domFromPos(caret);
3068
+ const element =
3069
+ node.nodeType === Node.ELEMENT_NODE ? (node as Element) : node.parentElement;
3070
+ const td = element?.closest("td");
3071
+ if (td instanceof HTMLElement) cells.push(td);
3072
+ }
3073
+ }
3074
+ for (const td of this.selectedCells) if (!cells.includes(td)) td.classList.remove(CELL_CLASS);
3075
+ for (const td of cells) td.classList.add(CELL_CLASS);
3076
+ this.selectedCells = cells;
3077
+ this.host.toggleAttribute(CELLS_ATTR, cells.length > 0);
3078
+ if (cells.length) injectStyles(this.host);
3079
+ }
3080
+
3081
+ /** The first wrapper of a node-selected table, if a table is selected. */
3082
+ private selectedTable(): HTMLElement | null {
3083
+ const { selection } = this.state;
3084
+ if (!(selection instanceof NodeSelection) || selection.node.type.name !== "table") return null;
3085
+ return this.frames.get(selection.node)?.wrappers[0] ?? null;
3086
+ }
3087
+
985
3088
  /** Marks the element of a node-selected block, for styling (the DOM selection is around it). */
986
3089
  private showSelectedNode(): void {
987
- const dom = this.selectedBlock()?.dom ?? null;
3090
+ this.showSelectedCells();
3091
+ this.showSelectedPicture();
3092
+ this.showSelectedFields();
3093
+ this.drawControls();
3094
+ const dom = this.selectedBlock()?.dom ?? this.selectedTable();
988
3095
  if (dom === this.selectedDom) return;
989
3096
  this.selectedDom?.classList.remove(SELECTED_CLASS);
990
3097
  dom?.classList.add(SELECTED_CLASS);
@@ -1012,12 +3119,22 @@ export class EditorView {
1012
3119
  selection instanceof AllSelection
1013
3120
  ? TextSelection.between(selection.$anchor, selection.$head)
1014
3121
  : selection;
1015
- return dom.anchor === shown.anchor && dom.head === shown.head;
3122
+ if (dom.anchor === shown.anchor && dom.head === shown.head) return true;
3123
+ // Field markers take no room, and a control's edge is one place to the browser: the DOM
3124
+ // cannot tell their two sides apart.
3125
+ const { doc } = this.state;
3126
+ const texts = shown instanceof TextSelection && dom instanceof TextSelection;
3127
+ const same = (a: number, b: number) =>
3128
+ controlSpot(doc, a, b) ||
3129
+ (texts && doc.resolve(a).parent.inlineContent && sameSpot(doc, a, b));
3130
+ return same(dom.anchor, shown.anchor) && same(dom.head, shown.head);
1016
3131
  }
1017
3132
 
1018
3133
  private hasFocus(): boolean {
1019
3134
  const active = this.host.ownerDocument.activeElement;
1020
- return active === this.host || this.host.contains(active);
3135
+ return (
3136
+ (active === this.host || this.host.contains(active)) && !this.mount?.wrapper.contains(active)
3137
+ );
1021
3138
  }
1022
3139
 
1023
3140
  /** Writes the model selection to the DOM unless the DOM already shows it (keeps native affinity). */
@@ -1030,12 +3147,20 @@ export class EditorView {
1030
3147
  const current = this.readSelection();
1031
3148
  if (current && this.shows(current)) return;
1032
3149
  }
1033
- const selected = this.selectedBlock();
3150
+ const selected = this.selectedBlock()?.dom ?? this.selectedTable();
1034
3151
  if (selected) {
1035
- const point = before(selected.dom);
3152
+ const point = before(selected);
1036
3153
  sel.setBaseAndExtent(point.node, point.offset, point.node, point.offset + 1);
1037
3154
  return;
1038
3155
  }
3156
+ // Cells: drawn by their class; the native caret stays in the head cell (ADR-0006).
3157
+ if (selection instanceof CellSelection) {
3158
+ const caret = Selection.near(doc.resolve(selection.head + 1), 1).from;
3159
+ this.cellCaret = caret;
3160
+ const point = this.domFromPos(caret);
3161
+ sel.collapse(point.node, point.offset);
3162
+ return;
3163
+ }
1039
3164
  // Never show a caret inside a grapheme cluster (the core snaps only out of surrogate pairs).
1040
3165
  // The model takes the snapped selection back on its next read of the DOM.
1041
3166
  const from = clusterBoundary(doc, selection.from, false);
@@ -1059,7 +3184,7 @@ export class EditorView {
1059
3184
  */
1060
3185
  private dispatch(tr: Transaction): boolean {
1061
3186
  const marksAdded = tr.storedMarks !== null && tr.storedMarks !== this.state.storedMarks;
1062
- if (!this.editable && (tr.docChanged || marksAdded)) return false;
3187
+ if ((!this.editable || this.mount) && (tr.docChanged || marksAdded)) return false;
1063
3188
  this.editor.dispatch(tr);
1064
3189
  return true;
1065
3190
  }
@@ -1149,6 +3274,387 @@ export class EditorView {
1149
3274
  });
1150
3275
  }
1151
3276
 
3277
+ // ---------- column borders (10.7c) ----------
3278
+
3279
+ /** A column border being dragged: its table and column, the column's width, the press, the guide. */
3280
+ private drag: {
3281
+ table: ModelNode;
3282
+ column: number;
3283
+ width: number;
3284
+ startX: number;
3285
+ perTwip: number;
3286
+ guide: HTMLElement;
3287
+ } | null = null;
3288
+ /** Whether this view set the host's cursor (an embedder's own cursor is left alone). */
3289
+ private resizeCursor = false;
3290
+
3291
+ /**
3292
+ * The column border of a top-level table near the pointer (within 4 px): an edge of the cell
3293
+ * under it (a grid line through a merged cell is no border), or the table's right edge from
3294
+ * outside; as the grid column left of it, with the table's px per twip. None in read-only
3295
+ * mode, during a composition, or while tracking (column widths do not change then).
3296
+ */
3297
+ private columnBorder(
3298
+ event: MouseEvent,
3299
+ ): { table: ModelNode; column: number; perTwip: number; rect: DOMRect } | null {
3300
+ if (!this.editable || this.composing || trackState(this.state)?.on) return null;
3301
+ const target = event.target as Element | null;
3302
+ const wrapper = target?.closest?.(`[${FRAME_ATTR}="table"]`);
3303
+ const element = wrapper?.querySelector(`:scope > table[${FRAME_ATTR}]`);
3304
+ if (!wrapper || !element || !this.host.contains(wrapper)) return null;
3305
+ let table: ModelNode | undefined;
3306
+ for (const [node, frame] of this.frames)
3307
+ if (frame.wrappers.includes(wrapper as HTMLElement)) table = node;
3308
+ const grid = (table?.attrs.grid as number[] | undefined) ?? [];
3309
+ const total = grid.reduce((a, b) => a + b, 0);
3310
+ if (!table || !total) return null;
3311
+ const rect = element.getBoundingClientRect();
3312
+ const perTwip = rect.width / total;
3313
+ const edges: number[] = [];
3314
+ let x = rect.left;
3315
+ for (const width of grid) {
3316
+ x += width * perTwip;
3317
+ edges.push(x);
3318
+ }
3319
+ const near = (column: number) => Math.abs(event.clientX - (edges[column] as number)) <= 4;
3320
+ // The grid lines that are borders here: the cell's own edges, the table's right edge from
3321
+ // outside it, any line on the table's own border area (none in a row's empty places).
3322
+ const cell = target?.closest("td");
3323
+ let columns: number[];
3324
+ if (cell && element.contains(cell)) {
3325
+ const box = cell.getBoundingClientRect();
3326
+ const at = (line: number) => edges.findIndex((edge) => Math.abs(edge - line) <= 3);
3327
+ columns = [at(box.left), at(box.right)].filter((c) => c >= 0);
3328
+ } else if (target === element) columns = grid.map((_w, i) => i);
3329
+ else if (element.contains(target)) columns = [];
3330
+ else columns = [grid.length - 1];
3331
+ const column = columns.find(near);
3332
+ return column === undefined ? null : { table, column, perTwip, rect };
3333
+ }
3334
+
3335
+ /** The pointer over a column border shows that it can be dragged. */
3336
+ private onMouseMove = (event: MouseEvent): void => {
3337
+ if (this.drag) return;
3338
+ if (event.buttons === 0) this.controlChrome.hover(event.target);
3339
+ const near = event.buttons === 0 && this.columnBorder(event) !== null;
3340
+ if (near === this.resizeCursor) return;
3341
+ this.resizeCursor = near;
3342
+ this.host.style.cursor = near ? "col-resize" : "";
3343
+ };
3344
+
3345
+ /**
3346
+ * A press on a column border (no Shift: Shift-click extends the selection) starts dragging it:
3347
+ * a guide line follows the pointer and the release moves the border by as much as the pointer
3348
+ * moved (`setColumnWidth`); a press without a move changes nothing; Escape, the button let go
3349
+ * elsewhere or the window losing the focus cancel.
3350
+ */
3351
+ private startColumnDrag(event: MouseEvent): boolean {
3352
+ this.endDrag();
3353
+ if (event.shiftKey) return false;
3354
+ const border = this.columnBorder(event);
3355
+ if (!border) return false;
3356
+ // No caret or text selection from this press. Focus taken by it keeps the selection the
3357
+ // model has (the press places none).
3358
+ event.preventDefault();
3359
+ if (!this.hasFocus()) {
3360
+ this.host.focus({ preventScroll: true });
3361
+ this.writeSelection(true);
3362
+ }
3363
+ const doc = this.host.ownerDocument;
3364
+ const guide = doc.createElement("div");
3365
+ guide.setAttribute("aria-hidden", "true");
3366
+ Object.assign(guide.style, {
3367
+ position: "fixed",
3368
+ top: `${border.rect.top}px`,
3369
+ height: `${border.rect.height}px`,
3370
+ left: `${event.clientX}px`,
3371
+ width: "0",
3372
+ borderLeft: "1px dashed GrayText",
3373
+ pointerEvents: "none",
3374
+ zIndex: "2147483647",
3375
+ });
3376
+ doc.body.append(guide);
3377
+ const width = (border.table.attrs.grid as number[])[border.column] as number;
3378
+ this.drag = { ...border, width, startX: event.clientX, guide };
3379
+ doc.addEventListener("mousemove", this.onDragMove);
3380
+ doc.addEventListener("mouseup", this.onDragEnd);
3381
+ doc.addEventListener("keydown", this.onDragKey, true);
3382
+ doc.defaultView?.addEventListener("blur", this.onDragBlur);
3383
+ return true;
3384
+ }
3385
+
3386
+ private onDragMove = (event: MouseEvent): void => {
3387
+ if (!this.drag) return;
3388
+ // The button let go where no mouseup reached the page (another window, a menu): cancelled.
3389
+ if ((event.buttons & 1) === 0) this.endDrag();
3390
+ else this.drag.guide.style.left = `${event.clientX}px`;
3391
+ };
3392
+
3393
+ private onDragEnd = (event: MouseEvent): void => {
3394
+ const drag = this.endDrag();
3395
+ if (!drag) return;
3396
+ const moved = event.clientX - drag.startX;
3397
+ // A click on a border (no real move) is no resize.
3398
+ if (Math.abs(moved) < 2) return;
3399
+ // The table's position: a top-level block's.
3400
+ let pos = -1;
3401
+ this.state.doc.forEach((node, offset) => {
3402
+ if (node === drag.table) pos = offset;
3403
+ });
3404
+ if (pos >= 0) this.run(setColumnWidth(pos, drag.column, drag.width + moved / drag.perTwip));
3405
+ };
3406
+
3407
+ private onDragKey = (event: KeyboardEvent): void => {
3408
+ if (event.key !== "Escape") return;
3409
+ event.preventDefault();
3410
+ event.stopPropagation();
3411
+ this.endDrag();
3412
+ };
3413
+
3414
+ private onDragBlur = (): void => {
3415
+ this.endDrag();
3416
+ };
3417
+
3418
+ /** Ends a drag (its guide and listeners gone) and returns it. */
3419
+ private endDrag(): NonNullable<EditorView["drag"]> | null {
3420
+ const { drag } = this;
3421
+ if (!drag) return null;
3422
+ this.drag = null;
3423
+ drag.guide.remove();
3424
+ const doc = this.host.ownerDocument;
3425
+ doc.removeEventListener("mousemove", this.onDragMove);
3426
+ doc.removeEventListener("mouseup", this.onDragEnd);
3427
+ doc.removeEventListener("keydown", this.onDragKey, true);
3428
+ doc.defaultView?.removeEventListener("blur", this.onDragBlur);
3429
+ if (this.resizeCursor) {
3430
+ this.resizeCursor = false;
3431
+ this.host.style.cursor = "";
3432
+ }
3433
+ return drag;
3434
+ }
3435
+
3436
+ // ---------- pictures (10.8d) ----------
3437
+
3438
+ /**
3439
+ * A press on a picture selects it (a node selection); on the selected picture's handle it
3440
+ * starts a resize that keeps its aspect ratio (`setPictureSize` on release, Escape cancels).
3441
+ */
3442
+ private pictureMouseDown(event: MouseEvent): boolean {
3443
+ this.endResize();
3444
+ if (event.shiftKey || this.composing) return false;
3445
+ const target = event.target as Element | null;
3446
+ const span = target?.closest?.(`[${PICTURE_ATTR}], [data-foli-resize]`)?.parentElement ?? null;
3447
+ if (!span || !this.host.contains(span)) return false;
3448
+ const pos = this.posFromDOM(FLOAT_ANCHORS.get(span) ?? span, 0);
3449
+ if (pos === null) return false;
3450
+ event.preventDefault();
3451
+ if (!this.hasFocus()) this.host.focus({ preventScroll: true });
3452
+ if (!(this.state.selection instanceof NodeSelection && this.state.selection.from === pos))
3453
+ this.dispatch(this.state.tr.setSelection(NodeSelection.create(this.state.doc, pos)));
3454
+ // Already selected: written again (the focus may have put a caret in the host).
3455
+ else this.writeSelection(true);
3456
+ const img = span.querySelector(`[${PICTURE_ATTR}]`) as HTMLElement | null;
3457
+ if (!img || !target?.closest("[data-foli-resize]") || !this.editable) return true;
3458
+ const rect = img.getBoundingClientRect();
3459
+ const width = Number.parseFloat(img.style.width) || rect.width;
3460
+ const scale = rect.width / width || 1;
3461
+ this.resize = {
3462
+ pos,
3463
+ img,
3464
+ width: rect.width,
3465
+ height: rect.height,
3466
+ scale,
3467
+ // No wider than the page's text (layout px).
3468
+ max: Math.max(this.textWidthEmu() / EMU_PER_PX, MIN_PICTURE),
3469
+ x: event.clientX,
3470
+ y: event.clientY,
3471
+ style: img.getAttribute("style") ?? "",
3472
+ };
3473
+ const doc = this.host.ownerDocument;
3474
+ doc.addEventListener("mousemove", this.onResizeMove);
3475
+ doc.addEventListener("mouseup", this.onResizeEnd);
3476
+ doc.addEventListener("keydown", this.onResizeKey, true);
3477
+ doc.defaultView?.addEventListener("blur", this.onResizeCancel);
3478
+ return true;
3479
+ }
3480
+
3481
+ /** The size (layout px) a resize gives at the pointer: the larger move, the ratio kept. */
3482
+ private resizedTo(event: MouseEvent): { width: number; height: number } {
3483
+ const r = this.resize as NonNullable<EditorView["resize"]>;
3484
+ const ratio = r.height / r.width;
3485
+ const dx = event.clientX - r.x;
3486
+ const dy = (event.clientY - r.y) / ratio;
3487
+ const width = Math.min(
3488
+ Math.max((r.width + (Math.abs(dx) > Math.abs(dy) ? dx : dy)) / r.scale, MIN_PICTURE),
3489
+ r.max,
3490
+ );
3491
+ return { width, height: width * ratio };
3492
+ }
3493
+
3494
+ private onResizeMove = (event: MouseEvent): void => {
3495
+ if (!this.resize) return;
3496
+ if ((event.buttons & 1) === 0) {
3497
+ this.onResizeCancel();
3498
+ return;
3499
+ }
3500
+ const { width, height } = this.resizedTo(event);
3501
+ this.resize.img.style.width = `${width}px`;
3502
+ this.resize.img.style.height = `${height}px`;
3503
+ };
3504
+
3505
+ private onResizeEnd = (event: MouseEvent): void => {
3506
+ if (!this.resize) return;
3507
+ const { width, height } = this.resizedTo(event);
3508
+ const r = this.endResize();
3509
+ if (!r) return;
3510
+ // No real move: nothing changes (a jiggle drawn while moving goes back).
3511
+ const moved = Math.abs(event.clientX - r.x) >= 2 || Math.abs(event.clientY - r.y) >= 2;
3512
+ const applied =
3513
+ moved &&
3514
+ this.run(
3515
+ setPictureSize(r.pos, Math.round(width * EMU_PER_PX), Math.round(height * EMU_PER_PX)),
3516
+ );
3517
+ // Not applied (no move, tracking, the picture gone): as it was.
3518
+ if (!applied) r.img.setAttribute("style", r.style);
3519
+ };
3520
+
3521
+ private onResizeKey = (event: KeyboardEvent): void => {
3522
+ if (event.key !== "Escape") return;
3523
+ event.preventDefault();
3524
+ event.stopPropagation();
3525
+ this.onResizeCancel();
3526
+ };
3527
+
3528
+ private onResizeCancel = (): void => {
3529
+ const r = this.endResize();
3530
+ if (r) r.img.setAttribute("style", r.style);
3531
+ };
3532
+
3533
+ /** Ends a resize (its listeners gone) and returns it. */
3534
+ private endResize(): NonNullable<EditorView["resize"]> | null {
3535
+ const r = this.resize;
3536
+ if (!r) return null;
3537
+ this.resize = null;
3538
+ const doc = this.host.ownerDocument;
3539
+ doc.removeEventListener("mousemove", this.onResizeMove);
3540
+ doc.removeEventListener("mouseup", this.onResizeEnd);
3541
+ doc.removeEventListener("keydown", this.onResizeKey, true);
3542
+ doc.defaultView?.removeEventListener("blur", this.onResizeCancel);
3543
+ return r;
3544
+ }
3545
+
3546
+ private textWidthEmu(): number {
3547
+ return textWidthEmu(this.state);
3548
+ }
3549
+
3550
+ /** Image files in a transfer (paste or drop), when the app takes uploads. */
3551
+ private imageFiles(data: DataTransfer | null): File[] {
3552
+ if (!this.upload || !this.editable || !data) return [];
3553
+ // A clipboard object from code may have no files.
3554
+ return [...(data.files ?? [])].filter((file) => file.type.startsWith("image/"));
3555
+ }
3556
+
3557
+ /** Whether a drag carries files (from outside the page). */
3558
+ private static carriesFiles = (event: DragEvent) =>
3559
+ [...(event.dataTransfer?.types ?? [])].includes("Files");
3560
+
3561
+ private onDragOver = (event: DragEvent): void => {
3562
+ if (!EditorView.carriesFiles(event)) return;
3563
+ // Files dropped here never open in the page (unsaved work would be lost).
3564
+ event.preventDefault();
3565
+ const images = [...(event.dataTransfer?.items ?? [])].some((i) => i.type.startsWith("image/"));
3566
+ if (event.dataTransfer)
3567
+ event.dataTransfer.dropEffect = images && this.upload && this.editable ? "copy" : "none";
3568
+ };
3569
+
3570
+ private onDrop = (event: DragEvent): void => {
3571
+ if (!EditorView.carriesFiles(event)) return;
3572
+ event.preventDefault();
3573
+ const files = this.imageFiles(event.dataTransfer);
3574
+ if (!files.length || this.composing) return;
3575
+ // The place the files were dropped.
3576
+ const pos = this.posAtPoint(event.clientX, event.clientY);
3577
+ if (pos !== null)
3578
+ this.dispatch(this.state.tr.setSelection(TextSelection.near(this.state.doc.resolve(pos))));
3579
+ void this.insertFiles(files);
3580
+ };
3581
+
3582
+ /**
3583
+ * Inserts image files where the selection is now, one picture each, in order: each measured
3584
+ * first (one the browser cannot show is skipped, not uploaded), then given to the `upload`
3585
+ * option, then inserted at its natural size (96 px per inch) no wider than the page's text,
3586
+ * where the selection was, however the document changed meanwhile (after a composition that
3587
+ * runs then). A file whose upload fails is skipped (reported on the console). Resolves to
3588
+ * the number inserted (none without `upload`); never rejects.
3589
+ */
3590
+ async insertFiles(files: readonly File[]): Promise<number> {
3591
+ const upload = this.upload;
3592
+ if (!upload || !this.editable) return 0;
3593
+ // The insertion point, mapped through every change until the pictures go in.
3594
+ let at = this.state.selection.from;
3595
+ const replace = !this.state.selection.empty;
3596
+ // Another document (`setDocument` notifies with no transaction): the files are not for it.
3597
+ let lost = false;
3598
+ let mapped = this.state.doc;
3599
+ // The user's own selection while a picture goes in, mapped, to give back after it.
3600
+ let user: Selection | null = null;
3601
+ const unsubscribe = this.editor.subscribe((state, transactions) => {
3602
+ for (const tr of transactions) {
3603
+ at = tr.mapping.map(at);
3604
+ if (user) user = user.map(tr.doc, tr.mapping);
3605
+ }
3606
+ if (!transactions.length && state.doc !== mapped) lost = true;
3607
+ mapped = state.doc;
3608
+ });
3609
+ let inserted = 0;
3610
+ try {
3611
+ for (const file of files) {
3612
+ if (!file.type.startsWith("image/")) continue;
3613
+ const size = await measureImageFile(file, this.host.ownerDocument);
3614
+ if (this.destroyed) return inserted;
3615
+ if (!size) continue;
3616
+ let answer: Awaited<ReturnType<NonNullable<EditorViewOptions["upload"]>>>;
3617
+ try {
3618
+ answer = await upload(file);
3619
+ } catch (error) {
3620
+ console.warn(`Foli: the upload of ${file.name} failed`, error);
3621
+ continue;
3622
+ }
3623
+ const { src, alt, decorative } =
3624
+ typeof answer === "string" ? { src: answer } : (answer ?? { src: "" });
3625
+ if (typeof src !== "string" || !src) continue;
3626
+ // The browser owns the DOM during a composition: the picture goes in after it.
3627
+ while (this.composing && !this.destroyed) await new Promise((r) => setTimeout(r, 50));
3628
+ if (this.destroyed || !this.editable || lost) return inserted;
3629
+ const scale = Math.min(1, this.textWidthEmu() / (size.width * EMU_PER_PX));
3630
+ // A `data:` URL says its own type (an app may have converted the file).
3631
+ const type = /^data:([^;,]+)/i.exec(src)?.[1]?.toLowerCase() ?? file.type;
3632
+ const picture = {
3633
+ contentType: type,
3634
+ ...(src.startsWith("data:") ? { data: src } : { url: src }),
3635
+ width: Math.max(1, Math.round(size.width * EMU_PER_PX * scale)),
3636
+ height: Math.max(1, Math.round(size.height * EMU_PER_PX * scale)),
3637
+ ...(typeof alt === "string" && alt.trim() ? { alt } : {}),
3638
+ ...(decorative === true ? { decorative } : {}),
3639
+ };
3640
+ const { doc, selection } = this.state;
3641
+ const pos = Math.min(at, doc.content.size);
3642
+ // The first picture replaces what was selected at the paste (still selected there).
3643
+ const here = replace && inserted === 0 && selection.from === pos;
3644
+ // A caret the user moved elsewhere meanwhile stays there.
3645
+ const elsewhere = !here && !(selection.empty && selection.from === pos);
3646
+ user = elsewhere ? selection : null;
3647
+ if (!here) this.dispatch(this.state.tr.setSelection(TextSelection.near(doc.resolve(pos))));
3648
+ if (this.run(insertPicture(picture, { requireAlt: false }))) inserted++;
3649
+ if (user) this.dispatch(this.state.tr.setSelection(user));
3650
+ user = null;
3651
+ }
3652
+ return inserted;
3653
+ } finally {
3654
+ unsubscribe();
3655
+ }
3656
+ }
3657
+
1152
3658
  /**
1153
3659
  * Triple-click selects the clicked block's content. Chromium and WebKit natively extend the
1154
3660
  * selection to the start of the next block, so typing over it would merge the two blocks.
@@ -1159,6 +3665,35 @@ export class EditorView {
1159
3665
  // focuses nothing (prevented, middle button) must not skip the next keyboard focus.
1160
3666
  if (this.pointerFocus) setTimeout(() => (this.pointerFocus = false));
1161
3667
  if (event.button !== 0) return;
3668
+ if (this.startColumnDrag(event)) return;
3669
+ if (this.pictureMouseDown(event)) return;
3670
+ // A click puts a caret where it lands, even on the one a cell selection wrote.
3671
+ if (!event.shiftKey) this.cellCaret = null;
3672
+ // A header row drawn again is not document content: the caret goes below it.
3673
+ const repeated = (event.target as Element | null)?.closest?.(`[${REPEATED_ATTR}]`);
3674
+ if (repeated && this.host.contains(repeated) && !event.shiftKey) {
3675
+ const pos = this.posFromDOM(repeated, 0);
3676
+ if (pos !== null) {
3677
+ event.preventDefault();
3678
+ if (!this.hasFocus()) this.host.focus({ preventScroll: true });
3679
+ const $pos = this.state.doc.resolve(pos);
3680
+ this.dispatch(this.state.tr.setSelection(Selection.near($pos)));
3681
+ }
3682
+ return;
3683
+ }
3684
+ // Word's blank page before an even or odd page section holds nothing: the caret goes to the
3685
+ // section after it (the browser would put it at the document's start).
3686
+ const blank = event.target as HTMLElement;
3687
+ if (!event.shiftKey && this.pages.includes(blank) && !blank.firstChild) {
3688
+ const pos = this.posFromDOM(blank, 0);
3689
+ if (pos !== null) {
3690
+ event.preventDefault();
3691
+ if (!this.hasFocus()) this.host.focus({ preventScroll: true });
3692
+ this.dispatch(this.state.tr.setSelection(Selection.near(this.state.doc.resolve(pos))));
3693
+ this.writeSelection(true);
3694
+ }
3695
+ return;
3696
+ }
1162
3697
  const element = this.blockElement(event.target as Node | null);
1163
3698
  const owner = element ? this.owner.get(element) : undefined;
1164
3699
  const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
@@ -1187,6 +3722,7 @@ export class EditorView {
1187
3722
  */
1188
3723
  private onClick = (event: MouseEvent): void => {
1189
3724
  const target = event.target;
3725
+ if (event.type === "click" && !event.shiftKey && this.controlChrome.click(event)) return;
1190
3726
  const element = target instanceof Element ? target.closest("a") : null;
1191
3727
  if (!element || !this.host.contains(element)) return;
1192
3728
  event.preventDefault();
@@ -1207,13 +3743,36 @@ export class EditorView {
1207
3743
  }
1208
3744
 
1209
3745
  private onKeyDown = (event: KeyboardEvent): void => {
3746
+ // The host itself focused while a story is open (Shift+Tab): it is read-only, and its selection
3747
+ // is what leaving the story comes back to.
3748
+ if (this.mount) {
3749
+ if (event.key === "Escape") {
3750
+ event.preventDefault();
3751
+ this.closeStory(true);
3752
+ }
3753
+ return;
3754
+ }
1210
3755
  if (event.isComposing || this.composing) return;
1211
3756
  this.syncSelection();
1212
3757
  if (this.crossFragmentEdge(event) || this.crossListNumber(event)) {
1213
3758
  event.preventDefault();
1214
3759
  return;
1215
3760
  }
3761
+ if (this.skipFieldParts(event)) {
3762
+ event.preventDefault();
3763
+ return;
3764
+ }
1216
3765
  const name = keyName(event);
3766
+ if (
3767
+ this.documentEdgeKey(name) ||
3768
+ this.fieldKey(name) ||
3769
+ this.controlKey(name) ||
3770
+ this.noteKey(event, name) ||
3771
+ this.navigationKey(name)
3772
+ ) {
3773
+ event.preventDefault();
3774
+ return;
3775
+ }
1217
3776
  // Ctrl/Cmd+Shift+V: the paste event that follows uses only the plain text.
1218
3777
  this.plainPaste = name === "Mod-Shift-v";
1219
3778
  // Tab and Shift+Tab move the focus on in read-only mode, and right after Escape where Tab
@@ -1230,27 +3789,84 @@ export class EditorView {
1230
3789
  }
1231
3790
  // Up/Down on a textblock's first/last line next to a rule select it (only the view knows
1232
3791
  // lines; measured only when a rule is beside the block); else the browser moves the caret.
3792
+ // Shift+arrows in a table: cells selected grow by a cell; from text in a cell, Shift+Up or
3793
+ // Down starts a cell selection once the head is on the cell's first or last line.
3794
+ const shift: Record<string, ["row" | "column", -1 | 1]> = {
3795
+ "Shift-ArrowUp": ["row", -1],
3796
+ "Shift-ArrowDown": ["row", 1],
3797
+ "Shift-ArrowLeft": ["column", -1],
3798
+ "Shift-ArrowRight": ["column", 1],
3799
+ };
3800
+ const growing = Object.hasOwn(shift, name) ? shift[name] : undefined;
3801
+ if (growing) {
3802
+ const [axis, dir] = growing;
3803
+ const grow = extendCellSelection(axis, dir);
3804
+ const leaving =
3805
+ this.state.selection instanceof CellSelection ||
3806
+ (axis === "row" && this.caretOnEdgeLine(dir, true));
3807
+ if (leaving && grow(this.state) && this.run(grow)) {
3808
+ event.preventDefault();
3809
+ return;
3810
+ }
3811
+ }
1233
3812
  const vertical = name === "ArrowUp" ? -1 : name === "ArrowDown" ? 1 : 0;
3813
+ // In a table, from a cell's first or last line: the cell above or below, or out of the
3814
+ // table (browsers go to the next cell in the DOM, or across pages to the wrong row).
3815
+ const cells = vertical ? goToCellVertically(vertical as -1 | 1) : null;
3816
+ // (A selection of a cell's whole content, Tab's, moves as the cell: no line to measure.)
3817
+ const onEdge = () => !this.state.selection.empty || this.caretOnEdgeLine(vertical as -1 | 1);
3818
+ if (cells?.(this.state) && onEdge() && this.run(cells)) {
3819
+ event.preventDefault();
3820
+ return;
3821
+ }
1234
3822
  const across = vertical ? arrowAcrossLeaf(vertical, "line") : null;
1235
3823
  if (across?.(this.state) && this.caretOnEdgeLine(vertical as -1 | 1) && this.run(across)) {
1236
3824
  event.preventDefault();
1237
3825
  }
1238
3826
  };
1239
3827
 
3828
+ /** Word's keys for notes, and Shift+Alt+N from a reference to its note. */
3829
+ private noteKey(event: KeyboardEvent, name: string): boolean {
3830
+ if (isNoteKey(event)) return this.openNote();
3831
+ const kind = name === "Mod-Alt-f" ? "footnote" : name === "Mod-Alt-d" ? "endnote" : null;
3832
+ if (!kind || !this.editable || !this.notes) return false;
3833
+ return this.run(insertNote(kind)) && this.openNote();
3834
+ }
3835
+
3836
+ /**
3837
+ * Ctrl+Home and Ctrl+End (with Shift, extending) on pages with headers and footers: the browser
3838
+ * stops at the first or last place before what it cannot edit, so the model says where.
3839
+ */
3840
+ private documentEdgeKey(name: string): boolean {
3841
+ const shift = name.startsWith("Mod-Shift-");
3842
+ const key = name.replace("Mod-Shift-", "Mod-");
3843
+ if ((key !== "Mod-Home" && key !== "Mod-End") || !this.editable) return false;
3844
+ if (!this.pageRegions.some((page) => page.header || page.footer)) return false;
3845
+ const { doc, selection } = this.state;
3846
+ const edge = key === "Mod-Home" ? Selection.atStart(doc) : Selection.atEnd(doc);
3847
+ const next = shift ? TextSelection.between(selection.$anchor, edge.$head) : edge;
3848
+ this.dispatch(this.state.tr.setSelection(next).setStoredMarks(null));
3849
+ return true;
3850
+ }
3851
+
1240
3852
  /**
1241
3853
  * Whether the caret is on the first (`dir` -1) or last (1) line of its textblock, in the
1242
3854
  * block's first or last fragment (a block split across pages has several).
1243
3855
  */
1244
- private caretOnEdgeLine(dir: -1 | 1): boolean {
3856
+ private caretOnEdgeLine(dir: -1 | 1, focusOnly = false): boolean {
1245
3857
  const sel = this.host.ownerDocument.getSelection();
1246
- if (!sel?.rangeCount || !sel.isCollapsed || !sel.focusNode) return false;
3858
+ // `focusOnly`: a range's head (Shift+arrows), else only a caret.
3859
+ if (!sel?.rangeCount || (!focusOnly && !sel.isCollapsed) || !sel.focusNode) return false;
1247
3860
  const element = this.blockElement(sel.focusNode);
1248
3861
  const desc = element ? this.owner.get(element) : undefined;
1249
3862
  if (!desc?.node.isTextblock) return false;
1250
3863
  const fragment = desc.fragments[dir < 0 ? 0 : desc.fragments.length - 1];
1251
3864
  if (!fragment || element !== fragment) return false;
1252
3865
  if (!desc.node.content.size) return true;
1253
- const caret = sel.getRangeAt(0).getClientRects()[0];
3866
+ const at = this.host.ownerDocument.createRange();
3867
+ at.setStart(sel.focusNode, sel.focusOffset);
3868
+ at.collapse(true);
3869
+ const caret = at.getClientRects()[0];
1254
3870
  const lines = this.host.ownerDocument.createRange();
1255
3871
  lines.selectNodeContents(fragment);
1256
3872
  const rects = lines.getClientRects();
@@ -1367,9 +3983,10 @@ export class EditorView {
1367
3983
  * and so is the scroll position.
1368
3984
  */
1369
3985
  private onFocus = (): void => {
3986
+ this.claimStories();
1370
3987
  const pointer = this.pointerFocus;
1371
3988
  this.pointerFocus = false;
1372
- if (pointer) return;
3989
+ if (pointer || this.mount) return;
1373
3990
  const current = this.readSelection();
1374
3991
  if (current && this.shows(current)) return;
1375
3992
  this.writeSelection(true);
@@ -1383,13 +4000,13 @@ export class EditorView {
1383
4000
  };
1384
4001
 
1385
4002
  private onMutations = (records: MutationRecord[]): void => {
1386
- this.pending.push(...records);
1387
- if (!this.composing) this.flush();
4003
+ this.pending.push(...records.filter((r) => !handleOnly(r)));
4004
+ if (!this.composing && this.pending.length) this.flush();
1388
4005
  };
1389
4006
 
1390
4007
  /** Reads back every DOM change recorded so far. */
1391
4008
  private flush(): void {
1392
- const records = [...this.pending, ...this.observer.takeRecords()];
4009
+ const records = [...this.pending, ...this.observer.takeRecords().filter((r) => !handleOnly(r))];
1393
4010
  this.pending = [];
1394
4011
  if (records.length) this.readBack(records);
1395
4012
  }
@@ -1426,26 +4043,51 @@ export class EditorView {
1426
4043
  else if ((node as Element).getAttribute?.("contenteditable") === "false") return;
1427
4044
  else node.childNodes.forEach(walk);
1428
4045
  };
1429
- let first = true;
1430
- // Block-level nodes in order: inside pages and containers, and anything else in the host.
1431
- const blockLevel: Node[] = [];
4046
+ // Block-level nodes: inside pages and tables, and anything else in the host.
4047
+ let stray = false;
1432
4048
  const collect = (parent: Node) => {
1433
4049
  for (const child of parent.childNodes) {
4050
+ if (this.owner.has(child)) continue;
4051
+ // Drawn, not document content (a repeated header row): no text of the model.
4052
+ if ((child as Element).getAttribute?.("contenteditable") === "false") continue;
1434
4053
  if (this.holdsBlocks(child)) collect(child);
1435
- else blockLevel.push(child);
4054
+ // Text outside every block (an element the browser added): a block the model does not
4055
+ // have. An empty stray node (an extension's marker) holds none; the re-render removes it.
4056
+ else if (child.textContent) stray = true;
1436
4057
  }
1437
4058
  };
1438
4059
  collect(this.host);
1439
- let previousOwner: BlockDesc | undefined;
1440
- for (const child of blockLevel) {
1441
- const owner = this.owner.get(child);
1442
- // An empty stray node (an extension's marker) holds no text; the re-render removes it.
1443
- if (!owner && !child.textContent) continue;
1444
- // The fragments of one block are one text; anything else starts a new block.
1445
- if (!first && !(owner && owner === previousOwner)) domText += BLOCK_SEPARATOR;
4060
+ if (stray) {
4061
+ // shortcut: a change that adds blocks cannot be read back yet; it is dropped.
4062
+ console.warn("Foli: discarded a DOM change that adds blocks or line breaks");
4063
+ this.rerender();
4064
+ return;
4065
+ }
4066
+ // Each block's fragments are one text, blocks in document order (a row split across pages
4067
+ // has its cells' fragments on two pages).
4068
+ // A block whose elements the browser removed (merging it into another) has no text there.
4069
+ // One missing without a recorded removal was never placed (drawn during a composition):
4070
+ // its text counts as unchanged, never as deleted.
4071
+ const removed = new Set(
4072
+ records.flatMap((record) => [...record.removedNodes]).filter((n) => !this.viewRemoved.has(n)),
4073
+ );
4074
+ const removedByInput = (node: Node) => {
4075
+ for (let at: Node | null = node; at; at = at.parentNode) if (removed.has(at)) return true;
4076
+ return false;
4077
+ };
4078
+ let first = true;
4079
+ for (const desc of this.blocks) {
4080
+ const shown = desc.fragments.filter((fragment) => this.host.contains(fragment));
4081
+ if (!shown.length && !desc.fragments.some(removedByInput)) {
4082
+ if (!first) domText += BLOCK_SEPARATOR;
4083
+ first = false;
4084
+ domText += textOfBlock(desc.node);
4085
+ continue;
4086
+ }
4087
+ if (!shown.length) continue;
4088
+ if (!first) domText += BLOCK_SEPARATOR;
1446
4089
  first = false;
1447
- previousOwner = owner;
1448
- walk(child);
4090
+ for (const fragment of shown) walk(fragment);
1449
4091
  }
1450
4092
 
1451
4093
  const { doc } = this.state;
@@ -1454,14 +4096,7 @@ export class EditorView {
1454
4096
  this.blocks.forEach(({ node: block }, i) => {
1455
4097
  if (i > 0) modelText += BLOCK_SEPARATOR;
1456
4098
  lineStarts.push(modelText.length);
1457
- block.forEach((child) => {
1458
- // A tab is text in the DOM (a "\t" text node).
1459
- modelText += child.isText
1460
- ? (child.text ?? "")
1461
- : child.type.name === "tab"
1462
- ? "\t"
1463
- : HARD_BREAK;
1464
- });
4099
+ modelText += textOfBlock(block);
1465
4100
  });
1466
4101
  /** Model position of an offset in `modelText`. */
1467
4102
  const posAt = (offset: number): number => {
@@ -1538,14 +4173,17 @@ export class EditorView {
1538
4173
  if (selection.empty || !event.clipboardData) return;
1539
4174
  event.preventDefault();
1540
4175
  const context = wordContext(this.state) as WordContext;
4176
+ // Selected cells are copied as a table of their own (ADR-0006).
4177
+ const table = selection instanceof CellSelection ? cellsAsTable(selection) : null;
4178
+ const source = table ? doc.type.create(null, table) : doc;
1541
4179
  const { text, html, json } = serializeRange(
1542
- doc,
1543
- selection.from,
1544
- selection.to,
4180
+ source,
4181
+ table ? 0 : selection.from,
4182
+ table ? source.content.size : selection.to,
1545
4183
  this.host.ownerDocument,
1546
4184
  { context, ratio: this.lineRatio },
1547
4185
  );
1548
- event.clipboardData.setData("text/plain", text);
4186
+ event.clipboardData.setData("text/plain", table ? cellsText(table) : text);
1549
4187
  event.clipboardData.setData("text/html", html);
1550
4188
  event.clipboardData.setData(FOLI_MIME, json);
1551
4189
  };
@@ -1566,6 +4204,12 @@ export class EditorView {
1566
4204
  if (this.composing) return;
1567
4205
  this.syncSelection();
1568
4206
  const data = event.clipboardData;
4207
+ // An image alone (a screenshot, an image copied from a page): a picture.
4208
+ const files = plain ? [] : this.imageFiles(data);
4209
+ if (files.length && !data.getData(FOLI_MIME) && !data.getData("text/plain").trim()) {
4210
+ void this.insertFiles(files);
4211
+ return;
4212
+ }
1569
4213
  this.paste(
1570
4214
  plain ? { getData: (type) => (type === "text/plain" ? data.getData(type) : "") } : data,
1571
4215
  !plain,
@@ -1583,6 +4227,9 @@ export class EditorView {
1583
4227
  */
1584
4228
  paste(data: Pick<DataTransfer, "getData">, autolink = true): boolean {
1585
4229
  const { state } = this;
4230
+ // A text control takes the text alone.
4231
+ const plainText = data.getData("text/plain");
4232
+ if (plainText && this.run(insertControlText(plainText))) return true;
1586
4233
  const text = autolink && !data.getData(FOLI_MIME) ? data.getData("text/plain") : "";
1587
4234
  const href = text ? autolinkHref(text) : null;
1588
4235
  if (href) {
@@ -1611,7 +4258,7 @@ export class EditorView {
1611
4258
  // One empty paragraph: nothing to paste (a lone opaque block is something).
1612
4259
  const only = pasted?.doc.childCount === 1 ? pasted.doc.firstChild : null;
1613
4260
  if (!pasted || (only?.isTextblock && !only.content.size)) return false;
1614
- const { doc, open, envelope } = pasted;
4261
+ const { doc, open, envelope, notes } = pasted;
1615
4262
  // As a slice (text joins the text around the caret); where that cannot be (an opaque block
1616
4263
  // at an end), as whole blocks at the caret.
1617
4264
  const asSlice = (tr: Transaction) => {
@@ -1632,17 +4279,27 @@ export class EditorView {
1632
4279
  if (open) throw new TransformError("Open content is pasted as a slice");
1633
4280
  insertBlocks(tr, doc);
1634
4281
  };
1635
- const strategies = [asSlice, asBlocks];
4282
+ // Rows (a table alone) into a table fill its cells from the selected one (ADR-0006).
4283
+ const intoCells = (tr: Transaction) => {
4284
+ if (only?.type.name !== "table" || !pasteCells(tr, only))
4285
+ throw new TransformError("Only rows are pasted into cells");
4286
+ };
4287
+ const strategies = [intoCells, asSlice, asBlocks];
1636
4288
  for (const strategy of strategies) {
1637
4289
  const tr = state.tr;
1638
4290
  try {
1639
- tr.deleteSelection();
4291
+ // Other content over selected cells goes into the anchor cell; across a table's edge,
4292
+ // whole rows go (`deleteSelectionKeepingTables`).
4293
+ if (strategy !== intoCells && !tr.selection.empty) deleteSelectionKeepingTables(tr, true);
1640
4294
  strategy(tr);
4295
+ // A pasted table never ends the body nor touches another table (Word's rules).
4296
+ keepTablesApart(tr);
1641
4297
  const current = wordContext(state)?.envelope;
1642
4298
  if (envelope && current && envelope !== current) {
1643
4299
  withEnvelope(tr, envelope);
1644
4300
  setComments(tr, current.comments, envelope.comments);
1645
4301
  }
4302
+ for (const { id, story } of notes ?? []) tr.step(new StoryStep(id, null, story));
1646
4303
  } catch (error) {
1647
4304
  if (error instanceof TransformError) continue;
1648
4305
  throw error;
@@ -1653,10 +4310,23 @@ export class EditorView {
1653
4310
  }
1654
4311
 
1655
4312
  private onSelectionChange = (): void => {
1656
- if (!this.composing && this.hasFocus()) this.syncSelection();
4313
+ if (!this.composing && !this.mount && this.hasFocus()) this.syncSelection();
1657
4314
  };
1658
4315
  }
1659
4316
 
4317
+ /** Copied cells as text, as spreadsheets read it: a tab between cells, a line per row. */
4318
+ function cellsText(table: ModelNode): string {
4319
+ const rows: string[] = [];
4320
+ table.forEach((row) => {
4321
+ const cells: string[] = [];
4322
+ row.forEach((cell) => {
4323
+ cells.push(cell.textBetween(0, cell.content.size, " "));
4324
+ });
4325
+ rows.push(cells.join("\t"));
4326
+ });
4327
+ return rows.join("\n");
4328
+ }
4329
+
1660
4330
  /**
1661
4331
  * Pastes whole blocks at the caret (after deleting the selection): before or after the caret's
1662
4332
  * paragraph, else between its two halves (an empty one is replaced as a slice first).
@@ -1687,13 +4357,210 @@ function layoutScale(page: HTMLElement, settings: DocumentSettings): number {
1687
4357
  }
1688
4358
 
1689
4359
  /** A block's measurement: border-box height across its fragments (layout px), margins, lines. */
1690
- interface Measure {
4360
+ export interface Measure {
1691
4361
  height: number;
1692
4362
  marginTop: number;
1693
4363
  marginBottom: number;
1694
4364
  /** Vertical padding and border, which every fragment of a split block repeats. */
1695
4365
  box: number;
1696
4366
  lines?: Lines;
4367
+ /** At the widths of columns it may land in, when a section's columns differ. */
4368
+ widths?: Map<number, WidthMeasure>;
4369
+ /** A table's rows and blocks. */
4370
+ table?: TableMeasure;
4371
+ }
4372
+
4373
+ /** A block measured at a width other than where it is. */
4374
+ interface WidthMeasure {
4375
+ height: number;
4376
+ lines(): readonly number[];
4377
+ all(): Lines;
4378
+ }
4379
+
4380
+ /** The innermost cell around pos (the position before it) and its table's, or null. */
4381
+ function cellAround(doc: ModelNode, pos: number): { cell: number; table: number } | null {
4382
+ const $pos = doc.resolve(pos);
4383
+ for (let d = $pos.depth; d > 2; d--)
4384
+ if ($pos.node(d).type.name === "tableCell")
4385
+ return { cell: $pos.before(d), table: $pos.before(d - 2) };
4386
+ return null;
4387
+ }
4388
+
4389
+ /** A block's text as the read-back compares it: a tab "\t", other inline leaves one character. */
4390
+ function textOfBlock(block: ModelNode): string {
4391
+ let text = "";
4392
+ block.forEach((child) => {
4393
+ // A tab is text in the DOM (a "\t" text node).
4394
+ text += child.isText ? (child.text ?? "") : child.type.name === "tab" ? "\t" : HARD_BREAK;
4395
+ });
4396
+ return text;
4397
+ }
4398
+
4399
+ /** Whether a table's wrappers hold every element of its blocks (none was drawn anew). */
4400
+ function holdsAll(state: FrameState, frame: Frame, blocks: readonly WordBlockDesc[]): boolean {
4401
+ for (let u = frame.first; u < frame.end; u++)
4402
+ for (const fragment of (blocks[u] as WordBlockDesc).fragments)
4403
+ if (!state.wrappers.some((wrapper) => wrapper.contains(fragment))) return false;
4404
+ return true;
4405
+ }
4406
+
4407
+ /** Measures a table drawn whole: its height, its rows and where its blocks start. */
4408
+ function measureTable(
4409
+ frame: Frame,
4410
+ wrapper: HTMLElement,
4411
+ blocks: readonly WordBlockDesc[],
4412
+ scale: number,
4413
+ ): Measure {
4414
+ const box = wrapper.getBoundingClientRect();
4415
+ const rows = [...wrapper.querySelectorAll(":scope > table > tbody > tr")].map((tr) => {
4416
+ const rect = tr.getBoundingClientRect();
4417
+ return { top: (rect.top - box.top) / scale, bottom: (rect.bottom - box.top) / scale };
4418
+ });
4419
+ const tops = new Map<number, number | null>();
4420
+ for (let u = frame.first; u < frame.end; u++) {
4421
+ const dom = (blocks[u] as WordBlockDesc).dom;
4422
+ // A block of a cell a merge covers is not shown: it goes with its row.
4423
+ const hidden = !!dom.closest(`[${FRAME_ATTR}="covered"]`);
4424
+ tops.set(u, hidden ? null : (dom.getBoundingClientRect().top - box.top) / scale);
4425
+ }
4426
+ return {
4427
+ height: box.height / scale,
4428
+ marginTop: 0,
4429
+ marginBottom: 0,
4430
+ box: 0,
4431
+ table: { rows, tops },
4432
+ };
4433
+ }
4434
+
4435
+ /**
4436
+ * Where a table may break across pages (from its top, sorted): after each row, and inside a row
4437
+ * at its cells' line ends, unless the row may not split (`cantSplit`, unless taller than a
4438
+ * page), is part of a vertical merge or holds a nested table (shortcut: those split only
4439
+ * between rows; a nested table stays whole within its row).
4440
+ */
4441
+ export function breaksOf(
4442
+ frame: Frame,
4443
+ measure: Measure,
4444
+ blocks: readonly WordBlockDesc[],
4445
+ pageHeight: number,
4446
+ lines: (desc: BlockDesc) => Lines,
4447
+ ): number[] {
4448
+ const t = measure.table as TableMeasure;
4449
+ if (t.breaks) return t.breaks;
4450
+ const out: number[] = [];
4451
+ frame.rows.forEach((row, r) => {
4452
+ const { top, bottom } = t.rows[r] ?? { top: 0, bottom: 0 };
4453
+ const merged = row.cells.some((cell) => cell.vMerge !== null);
4454
+ const nested = row.cells.some((cell) => cell.items.some((item) => "frame" in item));
4455
+ const splits = (!row.cantSplit || bottom - top > pageHeight) && !merged && !nested;
4456
+ if (splits)
4457
+ for (const cell of row.cells)
4458
+ for (const item of cell.items) {
4459
+ if ("frame" in item) continue;
4460
+ const unitTop = t.tops.get(item.unit);
4461
+ if (unitTop === null || unitTop === undefined) continue;
4462
+ for (const b of lines(blocks[item.unit] as WordBlockDesc).bottoms) {
4463
+ const y = unitTop + b;
4464
+ if (y > top + 0.5 && y < bottom - 0.5) out.push(y);
4465
+ }
4466
+ }
4467
+ out.push(r === frame.rows.length - 1 ? Math.max(bottom, measure.height) : bottom);
4468
+ });
4469
+ out.sort((a, b) => a - b);
4470
+ t.breaks = out.filter((y, k) => k === 0 || y - (out[k - 1] as number) > 0.5);
4471
+ return t.breaks;
4472
+ }
4473
+
4474
+ /** What the flow needs of a table: its height, where it may break, its header rows' height. */
4475
+ function tableBox(
4476
+ frame: Frame,
4477
+ measure: Measure,
4478
+ pageHeight: number,
4479
+ breakAfter: boolean,
4480
+ breaks: () => number[],
4481
+ ): BlockBox {
4482
+ const t = measure.table as TableMeasure;
4483
+ const header = frame.headers ? (t.rows[frame.headers - 1]?.bottom ?? 0) : 0;
4484
+ return {
4485
+ height: measure.height,
4486
+ marginTop: 0,
4487
+ marginBottom: 0,
4488
+ pageHeight,
4489
+ repeat: header,
4490
+ // Word keeps no lines together across a table's rows (a cell's paragraph splits anywhere).
4491
+ anyLine: true,
4492
+ lines: breaks,
4493
+ breaksAfter: () => (breakAfter ? [breaks().length - 1] : []),
4494
+ };
4495
+ }
4496
+
4497
+ /**
4498
+ * A flowed table cut into its fragments: the rows each shows (a row split across pages in
4499
+ * both), the header rows drawn again above a continuation, the fragment of the table each
4500
+ * block's fragments go in, and where a block of a split row splits (content offsets).
4501
+ */
4502
+ export function cutTable(
4503
+ frame: Frame,
4504
+ measure: Measure,
4505
+ fragments: readonly { fromLine: number; toLine: number }[],
4506
+ blocks: readonly WordBlockDesc[],
4507
+ lines: (desc: BlockDesc) => Lines,
4508
+ ): { parts: TablePart[]; partOf: Map<number, number[]>; splits: Map<number, number[]> } {
4509
+ const t = measure.table as TableMeasure;
4510
+ const all = frame.rows.map((_, r) => r);
4511
+ const partOf = new Map<number, number[]>();
4512
+ const splits = new Map<number, number[]>();
4513
+ if (fragments.length <= 1 || !t.breaks) {
4514
+ for (let u = frame.first; u < frame.end; u++) partOf.set(u, [0]);
4515
+ return { parts: [{ rows: all, headers: [] }], partOf, splits };
4516
+ }
4517
+ const breaks = t.breaks;
4518
+ const bounds = fragments.map((f) => [
4519
+ f.fromLine ? (breaks[f.fromLine - 1] as number) : 0,
4520
+ f.toLine === Number.POSITIVE_INFINITY ? measure.height : (breaks[f.toLine - 1] as number),
4521
+ ]) as [number, number][];
4522
+ const parts = bounds.map(([y0, y1], k): TablePart => {
4523
+ const rows = all.filter((r) => {
4524
+ const row = t.rows[r] ?? { top: 0, bottom: 0 };
4525
+ return row.top < y1 - 0.5 && row.bottom > y0 + 0.5;
4526
+ });
4527
+ const repeat = k > 0 && frame.headers > 0 && (rows[0] ?? 0) >= frame.headers;
4528
+ return { rows, headers: repeat ? all.slice(0, frame.headers) : [] };
4529
+ });
4530
+ frame.rows.forEach((row, r) => {
4531
+ const ks = parts.flatMap((part, k) => (part.rows.includes(r) ? [k] : []));
4532
+ const firstPart = ks[0] ?? 0;
4533
+ for (const cell of row.cells)
4534
+ for (const item of cell.items) {
4535
+ if ("frame" in item) {
4536
+ for (let u = item.frame.first; u < item.frame.end; u++) partOf.set(u, [firstPart]);
4537
+ continue;
4538
+ }
4539
+ const u = item.unit;
4540
+ const top = t.tops.get(u);
4541
+ if (ks.length < 2 || top === null || top === undefined) {
4542
+ partOf.set(u, [firstPart]);
4543
+ continue;
4544
+ }
4545
+ // Each line on the page its bottom fits; consecutive lines on one page are a fragment.
4546
+ const { starts, bottoms } = lines(blocks[u] as WordBlockDesc);
4547
+ const runs: number[] = [];
4548
+ const at: number[] = [];
4549
+ bottoms.forEach((b, i) => {
4550
+ const y = top + b;
4551
+ const k =
4552
+ ks.find((part) => y <= (bounds[part] as [number, number])[1] + 0.5) ??
4553
+ (ks.at(-1) as number);
4554
+ if (runs.at(-1) !== k) {
4555
+ if (runs.length) at.push(starts[i] as number);
4556
+ runs.push(k);
4557
+ }
4558
+ });
4559
+ partOf.set(u, runs.length ? runs : [firstPart]);
4560
+ if (at.length) splits.set(u, at);
4561
+ }
4562
+ });
4563
+ return { parts, partOf, splits };
1697
4564
  }
1698
4565
 
1699
4566
  /** Reads a block's height (in layout px) and vertical margins from the DOM. */
@@ -1720,76 +4587,126 @@ function measureBox(desc: BlockDesc, scale: number): Measure {
1720
4587
  /**
1721
4588
  * What the flow needs of a block: its measurement, its lines (on demand), Word's spacing before
1722
4589
  * and after (next to its neighbours), keep with next, keep lines together (not for a block
1723
- * taller than a page, or one with a page break in it), page breaks ending their line's page,
1724
- * and a page break before the next block ending this one's page.
4590
+ * taller than a page, or one with a break in it), page and column breaks ending their line's
4591
+ * page or column, and a page break before the next block ending this one's page.
1725
4592
  */
1726
4593
  function wordBox(
1727
- blocks: readonly WordBlockDesc[],
4594
+ words: readonly WordInfo[],
1728
4595
  i: number,
4596
+ desc: WordBlockDesc,
1729
4597
  measure: Measure,
1730
4598
  lines: () => Lines,
1731
4599
  layout: BlockLayout,
4600
+ atWidth: (desc: BlockDesc, width: number, kept: boolean) => WidthMeasure,
4601
+ adds: boolean,
4602
+ noteOf: (story: string) => FlowNote | null,
1732
4603
  ): BlockBox {
1733
4604
  const pageHeight = contentHeight(layout.sheet.settings);
1734
- const desc = blocks[i] as WordBlockDesc;
1735
- const next = blocks[i + 1];
1736
- const { before, after } = spacing(blocks[i - 1]?.word, desc.word, next?.word);
1737
- const pageBreaks = desc.leaves.filter(
1738
- (leaf) =>
1739
- leaf.dom.nodeType !== Node.TEXT_NODE && (leaf.dom as Element).hasAttribute(PAGE_BREAK_ATTR),
1740
- );
1741
- const hasBreak = pageBreaks.length > 0;
1742
- const kept = desc.word.keepLines && !hasBreak && measure.height <= pageHeight;
4605
+ const { section } = layout;
4606
+ // Without pages nothing is kept off the next one, and a page break ends nothing.
4607
+ const paged = layout.sheet.css !== UNPAGED_CSS;
4608
+ const next = words[i + 1] ? { word: words[i + 1] as WordInfo } : undefined;
4609
+ const { before, after } = spacing(words[i - 1], desc.word, next?.word, adds);
4610
+ const leavesWith = (attr: string) =>
4611
+ desc.leaves.filter(
4612
+ (leaf) => leaf.dom.nodeType !== Node.TEXT_NODE && (leaf.dom as Element).hasAttribute(attr),
4613
+ );
4614
+ const pageBreaks = leavesWith(PAGE_BREAK_ATTR);
4615
+ const columnBreaks = leavesWith(WORD_COLUMN_BREAK_ATTR);
4616
+ const hasBreak = pageBreaks.length + columnBreaks.length > 0;
4617
+ const keep = desc.word.keepLines && !hasBreak;
4618
+ const kept = keep && measure.height <= pageHeight;
1743
4619
  const bottoms = () => (kept ? [measure.height] : lines().bottoms);
4620
+ /** The block as it is in `column`, when the columns' widths differ. */
4621
+ const inColumn = (column: number) =>
4622
+ atWidth(desc, section.columns.widths[column] as number, keep);
4623
+ // The line holding a break, among the column's lines: the last starting at or before it.
4624
+ const linesOf = (leaves: readonly LeafDesc[], column = 0) => {
4625
+ if (!leaves.length) return [];
4626
+ const { starts } = section.unequal ? inColumn(column).all() : lines();
4627
+ return leaves.map((leaf) => {
4628
+ let line = starts.length - 1;
4629
+ while (line > 0 && (starts[line] as number) > leaf.offset) line--;
4630
+ return line;
4631
+ });
4632
+ };
4633
+ const references = referencesIn(desc.node);
4634
+ const notes = references.flatMap((ref) => {
4635
+ const note = noteOf(ref.story);
4636
+ return note ? [{ note, offset: ref.offset - 1 }] : [];
4637
+ });
1744
4638
  return {
4639
+ notes: notes.length
4640
+ ? (column) => {
4641
+ if (kept) return notes.map(({ note }) => ({ line: 0, note }));
4642
+ const { starts } = section.unequal ? inColumn(column).all() : lines();
4643
+ return notes.map(({ note, offset }) => {
4644
+ let line = starts.length - 1;
4645
+ while (line > 0 && (starts[line] as number) > offset) line--;
4646
+ return { line, note };
4647
+ });
4648
+ }
4649
+ : undefined,
1745
4650
  height: measure.height,
1746
4651
  marginTop: before,
1747
4652
  marginBottom: after,
1748
4653
  keepWithNext: desc.word.keepNext,
1749
4654
  pageHeight,
4655
+ section: section.flow,
4656
+ sectionMark: !!desc.node.attrs.section && desc.word.empty,
4657
+ inColumn: section.unequal ? inColumn : undefined,
1750
4658
  lines: bottoms,
1751
- breaksAfter: () => {
1752
- // The line holding each break: the last one starting at or before it.
1753
- const breaks = pageBreaks.map((leaf) => {
1754
- const { starts } = lines();
1755
- let line = starts.length - 1;
1756
- while (line > 0 && (starts[line] as number) > leaf.offset) line--;
1757
- return line;
1758
- });
1759
- if (next?.word.pageBreakBefore || layout.breakAfter) breaks.push(bottoms().length - 1);
4659
+ columnBreaksAfter: (column) => linesOf(columnBreaks, column),
4660
+ breaksAfter: (column = 0) => {
4661
+ if (!paged) return [];
4662
+ const breaks = linesOf(pageBreaks, column);
4663
+ if (next?.word.pageBreakBefore)
4664
+ breaks.push((section.unequal ? inColumn(column).lines() : bottoms()).length - 1);
1760
4665
  return breaks;
1761
4666
  },
1762
4667
  };
1763
4668
  }
1764
4669
 
4670
+ /** The footnotes a table refers to, each on the break at or after its reference's line. */
4671
+ function tableNotes(
4672
+ frame: Frame,
4673
+ measure: Measure,
4674
+ blocks: readonly WordBlockDesc[],
4675
+ lines: (desc: BlockDesc) => Lines,
4676
+ breaks: () => number[],
4677
+ noteOf: (story: string) => FlowNote | null,
4678
+ ): BlockBox["notes"] {
4679
+ const t = measure.table as TableMeasure;
4680
+ const found: { note: FlowNote; unit: number; offset: number }[] = [];
4681
+ for (let unit = frame.first; unit < frame.end; unit++)
4682
+ for (const ref of referencesIn((blocks[unit] as WordBlockDesc).node)) {
4683
+ const note = noteOf(ref.story);
4684
+ if (note && t.tops.get(unit) != null) found.push({ note, unit, offset: ref.offset - 1 });
4685
+ }
4686
+ if (!found.length) return undefined;
4687
+ return () => {
4688
+ const list = breaks();
4689
+ return found.map(({ note, unit, offset }) => {
4690
+ const { starts, bottoms } = lines(blocks[unit] as WordBlockDesc);
4691
+ let k = starts.length - 1;
4692
+ while (k > 0 && (starts[k] as number) > offset) k--;
4693
+ const y = (t.tops.get(unit) as number) + (bottoms[k] as number);
4694
+ const line = list.findIndex((b) => b >= y - 0.5);
4695
+ return { line: line < 0 ? list.length - 1 : line, note };
4696
+ });
4697
+ };
4698
+ }
4699
+
1765
4700
  /**
1766
- * Writes Word's space above each v3 block as its top margin: the space after the block above
1767
- * and the space before this one, on the same page; at the top of a page only its space before,
1768
- * and only on the first page or after an explicit break (a page the text flowed onto drops it).
1769
- * Written only when it changes.
4701
+ * Writes Word's space above each v3 block, as the flow worked it out, as its top margin. Written
4702
+ * only when it changes.
1770
4703
  */
1771
- function applyGaps(
1772
- blocks: readonly BlockDesc[],
1773
- pages: readonly (readonly number[])[],
1774
- boxes: readonly BlockBox[],
1775
- ): void {
1776
- blocks.forEach((desc, i) => {
1777
- const page = pages[i]?.[0] ?? 0;
1778
- const above = pages[i - 1];
1779
- const box = boxes[i] as BlockBox;
1780
- let gap: number;
1781
- if (above && above[above.length - 1] === page)
1782
- gap = (boxes[i - 1] as BlockBox).marginBottom + box.marginTop;
1783
- else {
1784
- const prior = boxes[i - 1];
1785
- const breaks = prior?.breaksAfter?.() ?? [];
1786
- const forced =
1787
- page === 0 || (!!prior && breaks.length > 0 && breaks.includes(prior.lines().length - 1));
1788
- gap = forced ? box.marginTop : 0;
1789
- }
1790
- if (gaps.get(desc.dom) === gap) return;
1791
- gaps.set(desc.dom, gap);
1792
- desc.dom.style.marginTop = `${gap}px`;
4704
+ function applyGaps(firsts: readonly HTMLElement[], spaces: readonly number[]): void {
4705
+ firsts.forEach((dom, i) => {
4706
+ const gap = spaces[i] ?? 0;
4707
+ if (gaps.get(dom) === gap) return;
4708
+ gaps.set(dom, gap);
4709
+ dom.style.marginTop = `${gap}px`;
1793
4710
  });
1794
4711
  }
1795
4712
 
@@ -1829,7 +4746,7 @@ function reuseOf(
1829
4746
  };
1830
4747
  }
1831
4748
 
1832
- interface Lines {
4749
+ export interface Lines {
1833
4750
  /** Content offset where each line starts. */
1834
4751
  starts: number[];
1835
4752
  /** Bottom of each line box, in layout px from the block's top, as if it were not split. */
@@ -1864,6 +4781,8 @@ function measureLines(desc: BlockDesc, scale: number): Lines {
1864
4781
  if (!fragment.contains(leaf.dom)) continue;
1865
4782
  if (leaf.dom.nodeType !== Node.TEXT_NODE) {
1866
4783
  const br = leaf.dom as Element;
4784
+ // A raised number says nothing about where its line is.
4785
+ if (br.hasAttribute(NOTE_NUMBER_ATTR)) continue;
1867
4786
  items.push({ offset: leaf.offset, rect: () => br.getBoundingClientRect() });
1868
4787
  continue;
1869
4788
  }
@@ -1968,7 +4887,7 @@ function clusterBoundary(doc: ModelNode, pos: number, forward: boolean): number
1968
4887
  * Scrolls every scrollable ancestor of `from`, then the window, so that `rect` is inside its
1969
4888
  * visible area (minus `scroll-padding`, e.g. for a sticky toolbar). Vertical only: text wraps.
1970
4889
  */
1971
- function scrollRectIntoView(from: HTMLElement, rect: DOMRect): void {
4890
+ function scrollRectIntoView(from: HTMLElement, rect: Pick<DOMRect, "top" | "bottom">): void {
1972
4891
  const doc = from.ownerDocument;
1973
4892
  const win = doc.defaultView;
1974
4893
  if (!win) return;
@@ -1996,6 +4915,27 @@ function scrollRectIntoView(from: HTMLElement, rect: DOMRect): void {
1996
4915
  if (move) win.scrollBy(0, move);
1997
4916
  }
1998
4917
 
4918
+ const SCROLL_OPTIONS = { capture: true, passive: true };
4919
+ /** Room kept above what is scrolled to for find, in px. */
4920
+ const REVEAL_ABOVE = 200;
4921
+
4922
+ /** Word's keys for finding and going places. */
4923
+ const NAVIGATION_KEYS: Readonly<Record<string, NavigationRequest>> = {
4924
+ "Mod-f": "find",
4925
+ "Mod-h": "replace",
4926
+ "Mod-g": "goTo",
4927
+ F3: "next",
4928
+ "Shift-F3": "previous",
4929
+ "Mod-Shift-F5": "bookmarks",
4930
+ };
4931
+
4932
+ /** Shift+Alt+N: from a note's reference to the note, and back. */
4933
+ const isNoteKey = (event: KeyboardEvent) =>
4934
+ event.altKey && event.shiftKey && !event.ctrlKey && !event.metaKey && event.code === "KeyN";
4935
+
4936
+ /** Whether story `id` of `state`'s document exists (a number can outlive its note on screen). */
4937
+ const isNoteStory = (state: EditorState, id: string) => !!wordContext(state)?.stories.has(id);
4938
+
1999
4939
  function before(node: Node): DomPoint {
2000
4940
  const parent = node.parentNode as Node;
2001
4941
  return { node: parent, offset: Array.prototype.indexOf.call(parent.childNodes, node) };
@@ -2035,3 +4975,81 @@ export function keyName(event: KeyboardEvent): string {
2035
4975
  if (mod) name = `Mod-${name}`;
2036
4976
  return name;
2037
4977
  }
4978
+
4979
+ /**
4980
+ * The text width of a document's (last) section in EMU (635 per twip; Word's Letter page and
4981
+ * margins where it does not say): the widest a picture is inserted or resized.
4982
+ * shortcut: the last section's, not the caret's section or table cell; use the caret's when
4983
+ * documents mix page sizes.
4984
+ */
4985
+ export function textWidthEmu(state: EditorState): number {
4986
+ const section = wordContext(state)?.envelope.section;
4987
+ return (
4988
+ ((section?.pageSize?.width ?? 12_240) -
4989
+ (section?.margins?.left ?? 1440) -
4990
+ (section?.margins?.right ?? 1440)) *
4991
+ 635
4992
+ );
4993
+ }
4994
+
4995
+ /** A file's image's natural size (CSS px) from a local object URL, before any upload. */
4996
+ export async function measureImageFile(
4997
+ file: File,
4998
+ doc: Document,
4999
+ ): Promise<{ width: number; height: number } | null> {
5000
+ if (typeof URL.createObjectURL !== "function") return null;
5001
+ const url = URL.createObjectURL(file);
5002
+ try {
5003
+ return await naturalSize(url, doc);
5004
+ } finally {
5005
+ URL.revokeObjectURL(url);
5006
+ }
5007
+ }
5008
+
5009
+ /** An image's natural size (CSS px), or null when it does not load. */
5010
+ async function naturalSize(
5011
+ src: string,
5012
+ doc: Document,
5013
+ ): Promise<{ width: number; height: number } | null> {
5014
+ const img = doc.createElement("img");
5015
+ // Load events, not decode(): WebKit rejects decode() for an image outside the document.
5016
+ const loaded = new Promise<boolean>((resolve) => {
5017
+ img.onload = () => resolve(true);
5018
+ img.onerror = () => resolve(false);
5019
+ });
5020
+ img.src = src;
5021
+ if (!(await loaded)) return null;
5022
+ return img.naturalWidth && img.naturalHeight
5023
+ ? { width: img.naturalWidth, height: img.naturalHeight }
5024
+ : null;
5025
+ }
5026
+
5027
+ /** Whether a block holds a floating picture (cached per node: nodes do not change). */
5028
+ const floats = new WeakMap<ModelNode, boolean>();
5029
+ function holdsFloat(node: ModelNode): boolean {
5030
+ let found = floats.get(node);
5031
+ if (found === undefined) {
5032
+ found = false;
5033
+ node.descendants((child) => {
5034
+ if (child.type.name === "picture" && child.attrs.float) found = true;
5035
+ return !found;
5036
+ });
5037
+ floats.set(node, found);
5038
+ }
5039
+ return found;
5040
+ }
5041
+
5042
+ /** A change that only adds or removes the view's own marks (a resize handle, a control's frame). */
5043
+ function handleOnly(record: MutationRecord): boolean {
5044
+ const nodes = [...record.addedNodes, ...record.removedNodes];
5045
+ return (
5046
+ record.type === "childList" &&
5047
+ nodes.length > 0 &&
5048
+ nodes.every(
5049
+ (n) =>
5050
+ n.nodeType === 1 &&
5051
+ ((n as Element).hasAttribute("data-foli-resize") ||
5052
+ (n as Element).hasAttribute(CONTROL_UI_ATTR)),
5053
+ )
5054
+ );
5055
+ }