@folijs/view 0.5.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 (61) hide show
  1. package/CHANGELOG.md +33 -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/layout/flow.d.ts +193 -20
  6. package/dist/layout/flow.d.ts.map +1 -1
  7. package/dist/layout/flow.js +789 -101
  8. package/dist/layout/flow.js.map +1 -1
  9. package/dist/print.d.ts +22 -0
  10. package/dist/print.d.ts.map +1 -0
  11. package/dist/print.js +31 -0
  12. package/dist/print.js.map +1 -0
  13. package/dist/view.d.ts +220 -7
  14. package/dist/view.d.ts.map +1 -1
  15. package/dist/view.js +1753 -208
  16. package/dist/view.js.map +1 -1
  17. package/dist/word/blocks.d.ts +30 -1
  18. package/dist/word/blocks.d.ts.map +1 -1
  19. package/dist/word/blocks.js +193 -40
  20. package/dist/word/blocks.js.map +1 -1
  21. package/dist/word/columns.d.ts +23 -0
  22. package/dist/word/columns.d.ts.map +1 -0
  23. package/dist/word/columns.js +51 -0
  24. package/dist/word/columns.js.map +1 -0
  25. package/dist/word/controls.d.ts +63 -0
  26. package/dist/word/controls.d.ts.map +1 -0
  27. package/dist/word/controls.js +411 -0
  28. package/dist/word/controls.js.map +1 -0
  29. package/dist/word/edit.d.ts +17 -5
  30. package/dist/word/edit.d.ts.map +1 -1
  31. package/dist/word/edit.js +157 -26
  32. package/dist/word/edit.js.map +1 -1
  33. package/dist/word/matches.d.ts +23 -0
  34. package/dist/word/matches.d.ts.map +1 -0
  35. package/dist/word/matches.js +97 -0
  36. package/dist/word/matches.js.map +1 -0
  37. package/dist/word/notes.d.ts +105 -0
  38. package/dist/word/notes.d.ts.map +1 -0
  39. package/dist/word/notes.js +392 -0
  40. package/dist/word/notes.js.map +1 -0
  41. package/dist/word/pages.d.ts +18 -13
  42. package/dist/word/pages.d.ts.map +1 -1
  43. package/dist/word/pages.js +420 -229
  44. package/dist/word/pages.js.map +1 -1
  45. package/dist/word/regions.d.ts +113 -0
  46. package/dist/word/regions.d.ts.map +1 -0
  47. package/dist/word/regions.js +374 -0
  48. package/dist/word/regions.js.map +1 -0
  49. package/package.json +2 -2
  50. package/src/clipboard.ts +3 -0
  51. package/src/layout/flow.ts +945 -110
  52. package/src/print.ts +48 -0
  53. package/src/view.ts +1957 -229
  54. package/src/word/blocks.ts +219 -36
  55. package/src/word/columns.ts +66 -0
  56. package/src/word/controls.ts +447 -0
  57. package/src/word/edit.ts +175 -23
  58. package/src/word/matches.ts +99 -0
  59. package/src/word/notes.ts +451 -0
  60. package/src/word/pages.ts +501 -220
  61. package/src/word/regions.ts +469 -0
package/src/view.ts CHANGED
@@ -4,50 +4,84 @@ import {
4
4
  autolinkHref,
5
5
  CellSelection,
6
6
  type Command,
7
+ type ControlRange,
8
+ caretStop,
7
9
  cellsAsTable,
8
10
  closeHistory,
11
+ controlAt,
12
+ controlProperties,
13
+ controlSpot,
9
14
  type DocumentSettings,
15
+ type DocumentTarget,
10
16
  deleteBackward,
11
17
  deleteForward,
12
18
  deleteSelection,
13
19
  deleteSelectionKeepingTables,
14
20
  type Editor,
15
21
  type EditorState,
22
+ ensureStory,
16
23
  extendCellSelection,
24
+ type Field,
25
+ type FieldLayout,
26
+ type FieldsReport,
27
+ type FindMatch,
28
+ type FoundMatches,
29
+ fieldCodesShown,
30
+ fieldsIn,
17
31
  fitPaste,
18
32
  fitPastedV2,
19
33
  goToCellVertically,
34
+ insertControlText,
20
35
  insertHardBreak,
21
36
  insertLink,
37
+ insertNote,
22
38
  insertPicture,
23
39
  insertText,
24
40
  isSafeHref,
25
41
  keepTablesApart,
26
42
  type Node as ModelNode,
27
43
  marksAt,
44
+ type NavigationRequest,
28
45
  NodeSelection,
46
+ type NoteNumber,
47
+ noteAtSelection,
48
+ noteNumbers,
49
+ noteProperties,
50
+ noteTexts,
51
+ type OpenStory,
52
+ pageVariant,
29
53
  parseContentV2,
30
54
  pasteCells,
31
55
  type ResourceJSON,
32
56
  type ReviewView,
33
57
  redo,
58
+ referencesIn,
34
59
  type SectionJSON,
35
60
  Selection,
36
61
  Slice,
62
+ type StorySide,
63
+ StoryStep,
64
+ type StoryView,
65
+ sameSpot,
37
66
  sectionSettings,
38
67
  setColumnWidth,
39
68
  setComments,
40
69
  setLink,
41
70
  setPictureSize,
42
71
  splitBlock,
72
+ storyOfSection,
43
73
  TextSelection,
44
74
  type Transaction,
45
75
  TransformError,
76
+ toggleFieldCodes,
46
77
  toggleMark,
47
78
  trackState,
48
79
  typedMarks,
80
+ type UpdateFieldsOptions,
49
81
  undo,
82
+ updateFields,
50
83
  type WordContext,
84
+ type WordSettingsJSON,
51
85
  withEnvelope,
52
86
  wordContext,
53
87
  } from "@folijs/core";
@@ -56,15 +90,45 @@ import {
56
90
  type BlockBox,
57
91
  contentHeight,
58
92
  DEFAULT_RULES,
93
+ type FlowNote,
94
+ type FlowPage,
59
95
  type FlowResult,
60
96
  type FlowRules,
97
+ type FlowSection,
98
+ type Fragment,
61
99
  flowFrom,
100
+ notePieces,
101
+ type PageFacts,
62
102
  PX_PER_MM,
103
+ pagesOf,
63
104
  type Reuse,
105
+ spaceAfterText,
64
106
  } from "./layout/flow.js";
65
- import { type BlockDesc, PAGE_BREAK_ATTR } from "./render.js";
66
-
67
- import { EMU_PER_PX, imageSource, PICTURE_ATTR } from "./word/blocks.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";
68
132
  import {
69
133
  FLOAT_ANCHORS,
70
134
  spacing,
@@ -72,7 +136,10 @@ import {
72
136
  type WordInfo,
73
137
  WordRenderer,
74
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";
75
141
  import { measureLineRatio } from "./word/pages.js";
142
+ import { PageRegions, REGION_CONTENT_CLASS } from "./word/regions.js";
76
143
  import {
77
144
  collect,
78
145
  type FlowItem,
@@ -92,6 +159,7 @@ const TABLE_WORD: WordInfo = {
92
159
  pageBreakBefore: false,
93
160
  style: null,
94
161
  contextual: false,
162
+ empty: false,
95
163
  };
96
164
 
97
165
  /** Where a table's fragment is: the rows it shows, the header rows drawn again above them. */
@@ -154,16 +222,25 @@ export interface EditorViewOptions {
154
222
  upload?:
155
223
  | ((file: File) => Promise<string | { src: string; alt?: string; decorative?: boolean }>)
156
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;
157
232
  }
158
233
 
159
234
  const PLACEHOLDER_ATTR = "data-foli-placeholder";
160
235
  /** On the span of a selected picture (it holds the resize handle). */
161
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";
162
239
  /** The smallest a picture gets by dragging its handle, in px. */
163
240
  const MIN_PICTURE = 8;
164
241
  // Generated content is not document text: no caret stops inside it, a zero-height float keeps
165
242
  // the caret at the line start, and the empty alt text keeps screen readers on aria-placeholder.
166
- const STYLES = `.${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}`;
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}`;
167
244
 
168
245
  /**
169
246
  * Adds the view's stylesheet once per document or shadow root, when a placeholder is first shown
@@ -188,34 +265,20 @@ const VIEW_ATTR = "data-foli-view";
188
265
  let viewCount = 0;
189
266
 
190
267
  /**
191
- * Print rules for the page settings of the view whose host has `VIEW_ATTR` = `id`: one sheet of
192
- * its section's size per page (the last section's where named pages are not supported), without
193
- * 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
194
- * half-pixel slack), with no gap after it. Content taller than a page (a line taller than a
195
- * 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`).
196
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.
197
271
  */
198
- function printStyles(settings: DocumentSettings, sheets: readonly Sheet[], id: string): string {
199
- const { width, height } = settings.pageSize;
200
- const last = sheetOf(settings, 0).css;
201
- const pages = `[${VIEW_ATTR}="${id}"]>.foli-page`;
202
- // Sections with other page setups: a named page each (engines without named pages print
203
- // every sheet at the last section's size).
204
- const named = sheets.every((sheet) => sheet.css === last)
205
- ? ""
206
- : sheets
207
- .map(({ settings: { pageSize: size }, index }) => {
208
- const name = `foli-${id}-${index}`;
209
- return (
210
- `@page ${name}{size:${size.width}mm ${size.height}mm;margin:0}` +
211
- `${pages}[${SHEET_ATTR}="${index}"]{page:${name};height:${size.height}mm!important}`
212
- );
213
- })
214
- .join("");
215
- return (
216
- `@media print{@page{size:${width}mm ${height}mm;margin:0}` +
217
- `${pages}{height:${height}mm!important;margin-block:0!important;` +
218
- `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,
219
282
  );
220
283
  }
221
284
 
@@ -226,8 +289,8 @@ function hiddenIn(node: Node, stop: Node): boolean {
226
289
  return false;
227
290
  }
228
291
 
229
- /** The attribute naming a page's page setup (its index among the document's) for print. */
230
- 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"]);
231
294
 
232
295
  /** A page setup: its settings (mm), the page style it gives, its index among the document's. */
233
296
  interface Sheet {
@@ -249,73 +312,208 @@ function sheetOf(settings: DocumentSettings, index: number): Sheet {
249
312
 
250
313
  /** The style each page element was last given (its `cssText` reads back normalized). */
251
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;";
252
319
 
253
- /** A block's section: its page setup, and whether the next block starts a new page. */
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
+ }
330
+
331
+ /** A block's section, and whether it is the section's first block. */
254
332
  interface BlockLayout {
255
333
  readonly sheet: Sheet;
256
- 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;
257
397
  }
258
398
 
259
399
  /**
260
400
  * The section of each top-level block (the section a paragraph's `section` ends; the
261
- * envelope's for the blocks after the last such paragraph). A section starts a new page,
262
- * unless it is continuous with the same page setup as the one before (shortcut: a continuous
263
- * section with another page setup starts a new page; Word's even and odd page sections do not
264
- * 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.
265
404
  */
266
- 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[] {
267
409
  const sheets = new Map<string, Sheet>();
268
410
  const bySection = new Map<SectionJSON, Sheet>();
269
411
  const sheet = (section: SectionJSON) => {
270
412
  let found = bySection.get(section);
271
413
  if (!found) {
272
414
  const settings = sectionSettings(section);
273
- const css = sheetOf(settings, 0).css;
274
- 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 };
275
417
  sheets.set(css, found);
276
418
  bySection.set(section, found);
277
419
  }
278
420
  return found;
279
421
  };
280
- const sections: SectionJSON[] = [];
281
- let section = last;
282
- for (let i = doc.childCount - 1; i >= 0; i--) {
283
- const own = doc.child(i).attrs.section as SectionJSON | null | undefined;
284
- if (own) section = own;
285
- sections[i] = section;
286
- }
287
- // Indexes in document order: the first page setup is 0.
288
- sections.forEach(sheet);
289
- return sections.map((own, i) => {
290
- const next = sections[i + 1];
291
- // By position, as `renderDocument`: two paragraphs may end sections with one object.
292
- const ends = !!next && !!doc.child(i).attrs.section;
293
- const breakAfter = ends && !(next.type === "continuous" && sheet(next).css === sheet(own).css);
294
- 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 };
295
450
  });
451
+ return out;
296
452
  }
297
453
 
298
454
  /**
299
- * Initial pages (before a flow), moved where needed so that each page holds blocks of one
300
- * 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.
301
458
  */
302
- function separateSheets(
459
+ function initialPlaces(
303
460
  pages: readonly (readonly number[])[],
304
461
  layout: readonly BlockLayout[],
305
- ): number[][] {
306
- const css: string[] = [];
307
- let floor = 0;
308
- return pages.map((list, i) =>
309
- list.map((p) => {
310
- const want = (layout[i] as BlockLayout).sheet.css;
311
- let page = Math.max(p, floor);
312
- // Only the last page used so far has a setup: the next one is free.
313
- if (css[page] !== undefined && css[page] !== want) page++;
314
- css[page] ??= want;
315
- 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
+ });
316
497
  return page;
317
- }),
318
- );
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
+ }
319
517
  }
320
518
 
321
519
  /**
@@ -344,6 +542,13 @@ export class EditorView {
344
542
  private cellCaret: number | null = null;
345
543
  /** The pages of each top-level item (a paragraph's fragments, a table's wrappers), by node. */
346
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
+ >();
347
552
  /** Each table as last rendered, by node. */
348
553
  private frames = new Map<ModelNode, FrameState>();
349
554
  /** The table each wrapper element draws (part of). */
@@ -395,9 +600,12 @@ export class EditorView {
395
600
  private readonly resizeObserver: ResizeObserver | null;
396
601
  private readonly observed = new Set<Element>();
397
602
  private relayoutPending = false;
398
- private composing = false;
603
+ /** A composition runs in this view. */
604
+ composing = false;
399
605
  /** Set by Ctrl/Cmd+Shift+V for the paste event it triggers. */
400
606
  private plainPaste = false;
607
+ /** How deep `renumberNotes` has rendered again. */
608
+ private renumbering = 0;
401
609
  /** Blocks whose DOM the browser changed: the next render rebuilds them. */
402
610
  private readonly dirty = new Set<BlockDesc>();
403
611
  /** DOM mutations not yet read back (kept while a composition is running). */
@@ -437,10 +645,61 @@ export class EditorView {
437
645
  private resource: EditorViewOptions["resource"];
438
646
  /** How tracked changes show. */
439
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[] = [];
440
652
  /** Fonts' normal line height ratios, measured once per family (Word's single spacing). */
441
653
  private readonly ratios = new Map<string, number>();
442
654
  /** Web fonts loaded since the v3 blocks were drawn: the next render draws them again. */
443
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;
444
703
 
445
704
  constructor(
446
705
  readonly host: HTMLElement,
@@ -448,6 +707,39 @@ export class EditorView {
448
707
  options: EditorViewOptions = {},
449
708
  ) {
450
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;
451
743
  host.setAttribute("role", "textbox");
452
744
  host.setAttribute("aria-multiline", "true");
453
745
  host.setAttribute(VIEW_ATTR, this.id);
@@ -458,6 +750,7 @@ export class EditorView {
458
750
  host.style.overflowWrap = "break-word";
459
751
  host.replaceChildren();
460
752
  this.review = trackState(this.state)?.view ?? "markup";
753
+ this.fieldCodes = fieldCodesShown(this.state);
461
754
  this.resizeObserver =
462
755
  typeof ResizeObserver === "undefined" ? null : new ResizeObserver(this.onResize);
463
756
  this.observer = new MutationObserver(this.onMutations);
@@ -467,28 +760,43 @@ export class EditorView {
467
760
  this.render();
468
761
  this.setOptions(options);
469
762
 
470
- host.addEventListener("beforeinput", this.onBeforeInput);
471
- host.addEventListener("focus", this.onFocus);
472
- host.addEventListener("keydown", this.onKeyDown);
473
- host.addEventListener("input", this.onInput);
474
- host.addEventListener("compositionstart", this.onCompositionStart);
475
- host.addEventListener("compositionend", this.onCompositionEnd);
476
- host.addEventListener("blur", this.onBlur);
477
- host.addEventListener("mousedown", this.onMouseDown);
478
- host.addEventListener("mousemove", this.onMouseMove);
479
- host.addEventListener("copy", this.onCopy);
480
- host.addEventListener("cut", this.onCut);
481
- host.addEventListener("paste", this.onPaste);
482
- host.addEventListener("dragover", this.onDragOver);
483
- host.addEventListener("drop", this.onDrop);
484
- host.addEventListener("click", this.onClick);
485
- 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();
486
781
  host.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
487
782
  host.ownerDocument.fonts?.addEventListener("loadingdone", this.onFontsLoaded);
488
783
  this.unsubscribe = editor.subscribe((state) => this.update(state));
489
784
  }
490
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
+
491
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;
492
800
  this.destroyed = true;
493
801
  this.unsubscribe();
494
802
  this.host.ownerDocument.fonts?.removeEventListener("loadingdone", this.onFontsLoaded);
@@ -496,24 +804,9 @@ export class EditorView {
496
804
  this.resizeObserver?.disconnect();
497
805
  for (const style of this.printStyles) style.remove();
498
806
  const { host } = this;
499
- host.removeEventListener("beforeinput", this.onBeforeInput);
500
- host.removeEventListener("focus", this.onFocus);
501
- host.removeEventListener("keydown", this.onKeyDown);
502
- host.removeEventListener("input", this.onInput);
503
- host.removeEventListener("compositionstart", this.onCompositionStart);
504
- host.removeEventListener("compositionend", this.onCompositionEnd);
505
- host.removeEventListener("blur", this.onBlur);
506
- host.removeEventListener("mousedown", this.onMouseDown);
507
- host.removeEventListener("mousemove", this.onMouseMove);
807
+ for (const [type, listener] of this.listeners) host.removeEventListener(type, listener);
508
808
  this.endDrag();
509
- host.removeEventListener("copy", this.onCopy);
510
- host.removeEventListener("cut", this.onCut);
511
- host.removeEventListener("paste", this.onPaste);
512
- host.removeEventListener("dragover", this.onDragOver);
513
- host.removeEventListener("drop", this.onDrop);
514
809
  this.endResize();
515
- host.removeEventListener("click", this.onClick);
516
- host.removeEventListener("auxclick", this.onClick);
517
810
  host.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
518
811
  const owned = [
519
812
  "contenteditable",
@@ -533,6 +826,10 @@ export class EditorView {
533
826
 
534
827
  /** Focuses the host, shows the model selection in it and scrolls it into view. */
535
828
  focus(): void {
829
+ if (this.mount) {
830
+ this.mount.view.focus();
831
+ return;
832
+ }
536
833
  this.host.focus();
537
834
  this.writeSelection(true);
538
835
  // The focus handler scrolls only when it writes the selection itself, and a DOM selection
@@ -547,12 +844,17 @@ export class EditorView {
547
844
  // Finish a running composition while its text can still go into the model.
548
845
  if (!options.editable && this.composing) this.onCompositionEnd();
549
846
  this.editable = options.editable;
847
+ if (!this.editable) this.closeStory(false);
550
848
  // A selected picture's handle only while it can be resized.
551
849
  this.endResize();
552
850
  this.showSelectedPicture();
553
851
  }
554
852
  if (options.placeholder !== undefined) this.placeholder = options.placeholder;
555
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
+ });
556
858
  // null clears the resolver (stored as none): the same as none is no change.
557
859
  const resource = options.resource ?? undefined;
558
860
  if (options.resource !== undefined && resource !== this.resource) {
@@ -568,8 +870,8 @@ export class EditorView {
568
870
  }
569
871
 
570
872
  // Read-only: no caret and no browser editing; the text stays selectable and copyable.
571
- host.setAttribute("contenteditable", String(this.editable));
572
- 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");
573
875
  else host.setAttribute("aria-readonly", "true");
574
876
  if (this.placeholder) host.setAttribute("aria-placeholder", this.placeholder);
575
877
  else host.removeAttribute("aria-placeholder");
@@ -606,10 +908,32 @@ export class EditorView {
606
908
  this.review = review;
607
909
  this.word = null;
608
910
  }
609
- 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;
610
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;
611
932
  this.state = state;
612
- 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);
613
937
  this.showSelectedNode();
614
938
  this.writeSelection(docChanged);
615
939
  // shortcut: scrolls for every change while focused; once remote or plugin changes exist, scroll only for local input (a transaction flag).
@@ -651,17 +975,36 @@ export class EditorView {
651
975
  * Measurements are cached by node and the flow restarts at the first changed block (5.4).
652
976
  */
653
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 {
654
989
  const { doc } = this.state;
655
990
  const ownerDocument = this.host.ownerDocument;
656
991
  // A new document (envelope) gets its renderer; nothing rendered before is reused then. An
657
992
  // editor's state always has one (`createEditor`).
658
993
  const context = wordContext(this.state) as WordContext;
659
994
  // Fonts loaded: a new renderer (new line heights), but not while a composition runs in a
660
- // 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;
661
997
  const renewed =
662
- 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);
663
1005
  if (renewed) this.fontsChanged = false;
664
1006
  let word = this.word as WordRenderer;
1007
+ if (!renewed) word.context = context;
665
1008
  if (renewed) {
666
1009
  // A document with pictures: the mark of one without alt text is the view's stylesheet's.
667
1010
  if (context.envelope.resources) injectStyles(this.host);
@@ -672,17 +1015,48 @@ export class EditorView {
672
1015
  false,
673
1016
  this.review,
674
1017
  imageSource(context.envelope.resources, this.resource ?? undefined),
1018
+ this.fieldCodes,
675
1019
  );
676
1020
  this.invalidateLayout();
677
1021
  }
1022
+ const references = this.noteReferences();
1023
+ word.setNotes(noteTexts(references), this.noteMark?.());
678
1024
  // The blocks the view renders (paragraphs in table cells among them) and the page flow's
679
1025
  // items (top-level paragraphs and opaque blocks, and tables).
680
1026
  const { units, items } = collect(doc, context.resolver);
681
- word.prepare(units.map((unit) => unit.node));
682
- const layout = sectionLayouts(doc, context.envelope.section);
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
+ );
683
1057
  doc.forEach((node, _, i) => {
684
- const { sheet, breakAfter } = layout[i] as BlockLayout;
685
- const key = `${sheet.css}${breakAfter ? "|break" : ""}`;
1058
+ const { section, first } = layout[i] as BlockLayout;
1059
+ const key = `${section.key}${first ? "|first" : ""}`;
686
1060
  const before = this.layoutKeys.get(node);
687
1061
  if (before !== undefined && before !== key) this.stale.add(node);
688
1062
  this.layoutKeys.set(node, key);
@@ -801,7 +1175,13 @@ export class EditorView {
801
1175
  const desc = blocks[item.unit] as WordBlockDesc;
802
1176
  return desc.fragments.map((_, f) => (last = Math.max(last, before?.[f] ?? last)));
803
1177
  });
804
- pages = separateSheets(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;
805
1185
  const elementsOf = (item: FlowItem, i: number): readonly HTMLElement[] =>
806
1186
  item.frame
807
1187
  ? (frames.get(doc.child(i)) as FrameState).wrappers
@@ -809,19 +1189,25 @@ export class EditorView {
809
1189
  this.place(
810
1190
  items.map((item, i) => elementsOf(item, i)),
811
1191
  pages,
1192
+ slots,
812
1193
  layout,
813
1194
  );
814
1195
  if (!this.composing) {
815
1196
  // DOM reads only for blocks without a valid measurement (new, changed or stale ones).
816
1197
  let scale: number | undefined;
817
1198
  const layoutPx = () => {
818
- scale ??= layoutScale(this.pages[0] as HTMLElement, (this.sheets[0] as Sheet).settings);
1199
+ scale ??= this.scale();
819
1200
  return scale;
820
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;
821
1204
  if (dropLines)
822
1205
  for (const desc of blocks) {
823
1206
  const measure = this.measures.get(desc.node);
824
- if (measure) delete measure.lines;
1207
+ if (measure) {
1208
+ delete measure.lines;
1209
+ delete measure.widths;
1210
+ }
825
1211
  }
826
1212
  const nodes = items.map((_, i) => doc.child(i));
827
1213
  // A block's spacing depends on its neighbours' styles: reuse stops a block earlier.
@@ -840,6 +1226,38 @@ export class EditorView {
840
1226
  found.lines ??= measureLines(desc, layoutPx());
841
1227
  return found.lines;
842
1228
  };
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
+ };
843
1261
  const tableOf = (frame: Frame, i: number) => {
844
1262
  let found = this.measures.get(frame.node);
845
1263
  if (!found?.table || this.stale.delete(frame.node)) {
@@ -858,32 +1276,66 @@ export class EditorView {
858
1276
  const words = items.map((item) =>
859
1277
  item.frame ? TABLE_WORD : (blocks[item.unit] as WordBlockDesc).word,
860
1278
  );
1279
+ const endnotes = notes?.endnotes();
861
1280
  const boxes = items.map((item, i) => {
862
- const pageHeight = contentHeight((layout[i] as BlockLayout).sheet.settings);
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
+ : {};
863
1290
  if (item.frame) {
864
1291
  const frame = item.frame;
865
1292
  const measure = tableOf(frame, i);
866
- // A section break after it, or a page break before the next paragraph, ends its page.
867
- const breakAfter =
868
- (layout[i] as BlockLayout).breakAfter || !!words[i + 1]?.pageBreakBefore;
869
- return tableBox(frame, measure, pageHeight, breakAfter, () =>
870
- breaksOf(frame, measure, blocks, pageHeight, lines),
871
- );
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
+ };
872
1301
  }
873
1302
  const desc = blocks[item.unit] as WordBlockDesc;
874
- return wordBox(
875
- words,
876
- i,
877
- desc,
878
- measureOf(desc),
879
- () => lines(desc),
880
- layout[i] as BlockLayout,
881
- );
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
+ };
882
1317
  });
883
- const result = flowFrom(boxes, contentHeight(this.editor.settings), WORD_RULES, reuse);
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;
884
1333
  this.flowed = { nodes, result };
1334
+ this.flowLayout = layout;
1335
+ this.flowBoxes = boxes;
885
1336
  this.stale.clear();
886
1337
  const flowed = result.fragments;
1338
+ slots = flowed.map((fragments) => fragments.map(slotOf));
887
1339
  // Paragraphs: split where their fragments start. Tables: the rows each fragment shows,
888
1340
  // and their blocks split where a row is.
889
1341
  const splitsOf = new Map<number, number[]>();
@@ -893,10 +1345,15 @@ export class EditorView {
893
1345
  if (item.unit !== undefined) {
894
1346
  const desc = blocks[item.unit] as WordBlockDesc;
895
1347
  const contentStart = ((units[item.unit] as Unit).pos as number) + 1;
1348
+ const { section } = layout[i] as BlockLayout;
896
1349
  splitsOf.set(
897
1350
  item.unit,
898
1351
  fragments.slice(1).map((fragment) => {
899
- const offset = lines(desc).starts[fragment.fromLine] as number;
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;
900
1357
  // Never split a grapheme cluster across pages.
901
1358
  return clusterBoundary(doc, contentStart + offset, false) - contentStart;
902
1359
  }),
@@ -952,13 +1409,21 @@ export class EditorView {
952
1409
  ? ((frames.get(doc.child(i)) as FrameState).wrappers[0] as HTMLElement)
953
1410
  : (blocks[item.unit] as WordBlockDesc).dom,
954
1411
  );
955
- applyGaps(firsts, pages, boxes);
1412
+ applyGaps(firsts, result.gaps);
1413
+ this.drawRegions();
1414
+ this.drawNotes();
956
1415
  this.place(
957
1416
  items.map((item, i) => elementsOf(item, i)),
958
1417
  pages,
1418
+ slots,
959
1419
  layout,
960
1420
  );
1421
+ this.afterPlace();
961
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);
962
1427
  // (Wrappers no longer drawn are not in a page: `place` removed them.)
963
1428
  this.frames = frames;
964
1429
  this.frameAt = items.map((item, i) => {
@@ -975,6 +1440,7 @@ export class EditorView {
975
1440
  this.starts = units.map((unit) => unit.pos);
976
1441
  this.indexOf = new Map(blocks.map((desc, i) => [desc, i]));
977
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] ?? []]));
978
1444
  this.owner = new Map(
979
1445
  blocks.flatMap((desc) => desc.fragments.map((fragment) => [fragment, desc] as const)),
980
1446
  );
@@ -986,6 +1452,1044 @@ export class EditorView {
986
1452
  // changed before this render: the touched blocks are read back at compositionend.
987
1453
  const records = this.observer.takeRecords();
988
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;
989
2493
  }
990
2494
 
991
2495
  /**
@@ -1038,25 +2542,34 @@ export class EditorView {
1038
2542
 
1039
2543
  /**
1040
2544
  * Puts each fragment of each block into its page (pages are non-decreasing in document
1041
- * order), creating and removing pages as needed, and gives each page the page setup of its
1042
- * blocks' section (one per page: `separateSheets`, section breaks). Anything else in the host
1043
- * 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.
1044
2548
  */
1045
2549
  private place(
1046
2550
  elements: readonly (readonly HTMLElement[])[],
1047
2551
  pages: readonly (readonly number[])[],
2552
+ slots: readonly (readonly Slot[])[],
1048
2553
  layout: readonly BlockLayout[],
1049
2554
  ): void {
1050
2555
  const { host } = this;
1051
2556
  const items = elements.flatMap((list, i) =>
1052
- list.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0 })),
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
+ })),
1053
2563
  );
1054
- 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);
1055
2566
  const sheets: Sheet[] = [];
1056
2567
  pages.forEach((list, i) => {
1057
2568
  for (const p of list) sheets[p] ??= (layout[i] as BlockLayout).sheet;
1058
2569
  });
1059
- // 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;
1060
2573
  for (let p = 0; p < count; p++)
1061
2574
  sheets[p] ??=
1062
2575
  sheets[p - 1] ?? (layout[0] as BlockLayout | undefined)?.sheet ?? this.lastSheet();
@@ -1065,10 +2578,19 @@ export class EditorView {
1065
2578
  this.sheets.forEach((sheet, p) => {
1066
2579
  const page = this.pages[p] as HTMLElement;
1067
2580
  const key = `${sheet.index} ${sheet.css}`;
1068
- if (pageSheets.get(page) === key) return;
1069
- pageSheets.set(page, key);
1070
- page.style.cssText = sheet.css;
1071
- 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
+ }
1072
2594
  });
1073
2595
  // Pages first, in order; anything else in the host ends up after them.
1074
2596
  let cursor = host.firstChild;
@@ -1079,19 +2601,64 @@ export class EditorView {
1079
2601
  let i = 0;
1080
2602
  for (let p = 0; p < count; p++) {
1081
2603
  const page = this.pages[p] as HTMLElement;
1082
- let at = page.firstChild;
1083
- for (; i < items.length && items[i]?.page === p; i++) {
1084
- const { dom } = items[i] as (typeof items)[number];
1085
- if (dom === at) at = at.nextSibling;
1086
- 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;
1087
2632
  }
1088
- // What is left after the last placed block: strays, and blocks of later pages.
1089
- while (at) {
1090
- const next: ChildNode | null = at.nextSibling;
1091
- at.remove();
1092
- this.viewRemoved.add(at);
1093
- 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) };
1094
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
+ });
1095
2662
  }
1096
2663
  // Pages no longer needed and stray DOM in the host: all after the last page by now.
1097
2664
  let rest = (this.pages[count - 1] as HTMLElement).nextSibling;
@@ -1139,7 +2706,7 @@ export class EditorView {
1139
2706
 
1140
2707
  private createPage(): HTMLElement {
1141
2708
  const page = this.host.ownerDocument.createElement("section");
1142
- page.className = "foli-page";
2709
+ page.className = this.paged ? "foli-page" : "foli-story-flow";
1143
2710
  return page;
1144
2711
  }
1145
2712
 
@@ -1150,6 +2717,7 @@ export class EditorView {
1150
2717
 
1151
2718
  /** The print rules for the document's page setups, written when they change. */
1152
2719
  private applyPrintStyles(layout: readonly BlockLayout[]): void {
2720
+ if (!this.paged) return;
1153
2721
  const sheets = [...new Set(layout.map((block) => block.sheet))];
1154
2722
  const key = [this.lastSheet(), ...sheets].map((sheet) => sheet.css).join("\n");
1155
2723
  if (key === this.printKey) return;
@@ -1163,7 +2731,7 @@ export class EditorView {
1163
2731
  this.printStyles = parents.map((parent) => {
1164
2732
  const style = doc.createElement("style");
1165
2733
  style.setAttribute("data-foli-print", "");
1166
- style.textContent = printStyles(this.editor.settings, sheets, this.id);
2734
+ style.textContent = viewPrintStyles(this.editor.settings, sheets, this.id);
1167
2735
  parent.append(style);
1168
2736
  return style;
1169
2737
  });
@@ -1173,6 +2741,9 @@ export class EditorView {
1173
2741
  private invalidateLayout(): void {
1174
2742
  this.measures = new WeakMap();
1175
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();
1176
2747
  }
1177
2748
 
1178
2749
  /** Re-flows the pages once web fonts have loaded: line heights and wrapping change. */
@@ -1211,7 +2782,7 @@ export class EditorView {
1211
2782
  if (!desc || !measured || this.stale.has(desc.node)) continue;
1212
2783
  // A hidden host (display: none) reports every block as 0x0: nothing to re-flow.
1213
2784
  if (!entry.contentRect.width) continue;
1214
- scale ??= layoutScale(this.pages[0] as HTMLElement, (this.sheets[0] as Sheet).settings);
2785
+ scale ??= this.scale();
1215
2786
  let height = 0;
1216
2787
  for (const fragment of desc.fragments) height += fragment.getBoundingClientRect().height;
1217
2788
  // A block is measured whole; each fragment of a split one keeps its padding and border,
@@ -1238,7 +2809,7 @@ export class EditorView {
1238
2809
  this.relayoutPending = false;
1239
2810
  if (this.destroyed) return;
1240
2811
  // compositionend flows what a composition kept from moving.
1241
- if (this.composing) {
2812
+ if (this.composing || this.mount?.view.composing) {
1242
2813
  this.unflowed = true;
1243
2814
  return;
1244
2815
  }
@@ -1259,16 +2830,17 @@ export class EditorView {
1259
2830
  }
1260
2831
 
1261
2832
  /**
1262
- * Whether `node` holds blocks rather than content: the host, a page, or a table's wrapper,
1263
- * table, rows and cells.
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.
1264
2835
  */
1265
2836
  private holdsBlocks(node: Node): boolean {
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;
1266
2840
  return (
1267
- node === this.host ||
1268
- this.pages.includes(node as HTMLElement) ||
1269
- (node.nodeType === Node.ELEMENT_NODE &&
1270
- (node as Element).hasAttribute(FRAME_ATTR) &&
1271
- !(node as Element).closest(`[${REPEATED_ATTR}]`))
2841
+ element.classList.contains(BAND_CLASS) ||
2842
+ element.classList.contains(COLUMN_CLASS) ||
2843
+ (element.hasAttribute(FRAME_ATTR) && !element.closest(`[${REPEATED_ATTR}]`))
1272
2844
  );
1273
2845
  }
1274
2846
 
@@ -1396,6 +2968,7 @@ export class EditorView {
1396
2968
  private readSelection(): Selection | null {
1397
2969
  const sel = this.host.ownerDocument.getSelection();
1398
2970
  if (!sel?.anchorNode || !sel.focusNode) return null;
2971
+ if (this.mount?.wrapper.contains(sel.anchorNode)) return null;
1399
2972
  // A range around exactly one block leaf element (a rule): the node selection that wrote it.
1400
2973
  // (Its end, mapped alone, would be the start of the next block, not the end of the rule.)
1401
2974
  if (sel.anchorNode === sel.focusNode && Math.abs(sel.anchorOffset - sel.focusOffset) === 1) {
@@ -1516,6 +3089,8 @@ export class EditorView {
1516
3089
  private showSelectedNode(): void {
1517
3090
  this.showSelectedCells();
1518
3091
  this.showSelectedPicture();
3092
+ this.showSelectedFields();
3093
+ this.drawControls();
1519
3094
  const dom = this.selectedBlock()?.dom ?? this.selectedTable();
1520
3095
  if (dom === this.selectedDom) return;
1521
3096
  this.selectedDom?.classList.remove(SELECTED_CLASS);
@@ -1544,12 +3119,22 @@ export class EditorView {
1544
3119
  selection instanceof AllSelection
1545
3120
  ? TextSelection.between(selection.$anchor, selection.$head)
1546
3121
  : selection;
1547
- 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);
1548
3131
  }
1549
3132
 
1550
3133
  private hasFocus(): boolean {
1551
3134
  const active = this.host.ownerDocument.activeElement;
1552
- return active === this.host || this.host.contains(active);
3135
+ return (
3136
+ (active === this.host || this.host.contains(active)) && !this.mount?.wrapper.contains(active)
3137
+ );
1553
3138
  }
1554
3139
 
1555
3140
  /** Writes the model selection to the DOM unless the DOM already shows it (keeps native affinity). */
@@ -1599,7 +3184,7 @@ export class EditorView {
1599
3184
  */
1600
3185
  private dispatch(tr: Transaction): boolean {
1601
3186
  const marksAdded = tr.storedMarks !== null && tr.storedMarks !== this.state.storedMarks;
1602
- if (!this.editable && (tr.docChanged || marksAdded)) return false;
3187
+ if ((!this.editable || this.mount) && (tr.docChanged || marksAdded)) return false;
1603
3188
  this.editor.dispatch(tr);
1604
3189
  return true;
1605
3190
  }
@@ -1750,6 +3335,7 @@ export class EditorView {
1750
3335
  /** The pointer over a column border shows that it can be dragged. */
1751
3336
  private onMouseMove = (event: MouseEvent): void => {
1752
3337
  if (this.drag) return;
3338
+ if (event.buttons === 0) this.controlChrome.hover(event.target);
1753
3339
  const near = event.buttons === 0 && this.columnBorder(event) !== null;
1754
3340
  if (near === this.resizeCursor) return;
1755
3341
  this.resizeCursor = near;
@@ -1987,18 +3573,7 @@ export class EditorView {
1987
3573
  const files = this.imageFiles(event.dataTransfer);
1988
3574
  if (!files.length || this.composing) return;
1989
3575
  // The place the files were dropped.
1990
- const doc = this.host.ownerDocument as Document & {
1991
- caretPositionFromPoint?: (
1992
- x: number,
1993
- y: number,
1994
- ) => { offsetNode: Node; offset: number } | null;
1995
- caretRangeFromPoint?: (x: number, y: number) => Range | null;
1996
- };
1997
- const point = doc.caretPositionFromPoint?.(event.clientX, event.clientY);
1998
- const range = point ? null : doc.caretRangeFromPoint?.(event.clientX, event.clientY);
1999
- const node = point?.offsetNode ?? range?.startContainer;
2000
- const offset = point?.offset ?? range?.startOffset ?? 0;
2001
- const pos = node ? this.posFromDOM(node, offset) : null;
3576
+ const pos = this.posAtPoint(event.clientX, event.clientY);
2002
3577
  if (pos !== null)
2003
3578
  this.dispatch(this.state.tr.setSelection(TextSelection.near(this.state.doc.resolve(pos))));
2004
3579
  void this.insertFiles(files);
@@ -2106,6 +3681,19 @@ export class EditorView {
2106
3681
  }
2107
3682
  return;
2108
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
+ }
2109
3697
  const element = this.blockElement(event.target as Node | null);
2110
3698
  const owner = element ? this.owner.get(element) : undefined;
2111
3699
  const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
@@ -2134,6 +3722,7 @@ export class EditorView {
2134
3722
  */
2135
3723
  private onClick = (event: MouseEvent): void => {
2136
3724
  const target = event.target;
3725
+ if (event.type === "click" && !event.shiftKey && this.controlChrome.click(event)) return;
2137
3726
  const element = target instanceof Element ? target.closest("a") : null;
2138
3727
  if (!element || !this.host.contains(element)) return;
2139
3728
  event.preventDefault();
@@ -2154,13 +3743,36 @@ export class EditorView {
2154
3743
  }
2155
3744
 
2156
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
+ }
2157
3755
  if (event.isComposing || this.composing) return;
2158
3756
  this.syncSelection();
2159
3757
  if (this.crossFragmentEdge(event) || this.crossListNumber(event)) {
2160
3758
  event.preventDefault();
2161
3759
  return;
2162
3760
  }
3761
+ if (this.skipFieldParts(event)) {
3762
+ event.preventDefault();
3763
+ return;
3764
+ }
2163
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
+ }
2164
3776
  // Ctrl/Cmd+Shift+V: the paste event that follows uses only the plain text.
2165
3777
  this.plainPaste = name === "Mod-Shift-v";
2166
3778
  // Tab and Shift+Tab move the focus on in read-only mode, and right after Escape where Tab
@@ -2213,6 +3825,30 @@ export class EditorView {
2213
3825
  }
2214
3826
  };
2215
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
+
2216
3852
  /**
2217
3853
  * Whether the caret is on the first (`dir` -1) or last (1) line of its textblock, in the
2218
3854
  * block's first or last fragment (a block split across pages has several).
@@ -2347,9 +3983,10 @@ export class EditorView {
2347
3983
  * and so is the scroll position.
2348
3984
  */
2349
3985
  private onFocus = (): void => {
3986
+ this.claimStories();
2350
3987
  const pointer = this.pointerFocus;
2351
3988
  this.pointerFocus = false;
2352
- if (pointer) return;
3989
+ if (pointer || this.mount) return;
2353
3990
  const current = this.readSelection();
2354
3991
  if (current && this.shows(current)) return;
2355
3992
  this.writeSelection(true);
@@ -2590,6 +4227,9 @@ export class EditorView {
2590
4227
  */
2591
4228
  paste(data: Pick<DataTransfer, "getData">, autolink = true): boolean {
2592
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;
2593
4233
  const text = autolink && !data.getData(FOLI_MIME) ? data.getData("text/plain") : "";
2594
4234
  const href = text ? autolinkHref(text) : null;
2595
4235
  if (href) {
@@ -2618,7 +4258,7 @@ export class EditorView {
2618
4258
  // One empty paragraph: nothing to paste (a lone opaque block is something).
2619
4259
  const only = pasted?.doc.childCount === 1 ? pasted.doc.firstChild : null;
2620
4260
  if (!pasted || (only?.isTextblock && !only.content.size)) return false;
2621
- const { doc, open, envelope } = pasted;
4261
+ const { doc, open, envelope, notes } = pasted;
2622
4262
  // As a slice (text joins the text around the caret); where that cannot be (an opaque block
2623
4263
  // at an end), as whole blocks at the caret.
2624
4264
  const asSlice = (tr: Transaction) => {
@@ -2659,6 +4299,7 @@ export class EditorView {
2659
4299
  withEnvelope(tr, envelope);
2660
4300
  setComments(tr, current.comments, envelope.comments);
2661
4301
  }
4302
+ for (const { id, story } of notes ?? []) tr.step(new StoryStep(id, null, story));
2662
4303
  } catch (error) {
2663
4304
  if (error instanceof TransformError) continue;
2664
4305
  throw error;
@@ -2669,7 +4310,7 @@ export class EditorView {
2669
4310
  }
2670
4311
 
2671
4312
  private onSelectionChange = (): void => {
2672
- if (!this.composing && this.hasFocus()) this.syncSelection();
4313
+ if (!this.composing && !this.mount && this.hasFocus()) this.syncSelection();
2673
4314
  };
2674
4315
  }
2675
4316
 
@@ -2723,10 +4364,19 @@ export interface Measure {
2723
4364
  /** Vertical padding and border, which every fragment of a split block repeats. */
2724
4365
  box: number;
2725
4366
  lines?: Lines;
4367
+ /** At the widths of columns it may land in, when a section's columns differ. */
4368
+ widths?: Map<number, WidthMeasure>;
2726
4369
  /** A table's rows and blocks. */
2727
4370
  table?: TableMeasure;
2728
4371
  }
2729
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
+
2730
4380
  /** The innermost cell around pos (the position before it) and its table's, or null. */
2731
4381
  function cellAround(doc: ModelNode, pos: number): { cell: number; table: number } | null {
2732
4382
  const $pos = doc.resolve(pos);
@@ -2937,8 +4587,8 @@ function measureBox(desc: BlockDesc, scale: number): Measure {
2937
4587
  /**
2938
4588
  * What the flow needs of a block: its measurement, its lines (on demand), Word's spacing before
2939
4589
  * and after (next to its neighbours), keep with next, keep lines together (not for a block
2940
- * taller than a page, or one with a page break in it), page breaks ending their line's page,
2941
- * 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.
2942
4592
  */
2943
4593
  function wordBox(
2944
4594
  words: readonly WordInfo[],
@@ -2947,63 +4597,113 @@ function wordBox(
2947
4597
  measure: Measure,
2948
4598
  lines: () => Lines,
2949
4599
  layout: BlockLayout,
4600
+ atWidth: (desc: BlockDesc, width: number, kept: boolean) => WidthMeasure,
4601
+ adds: boolean,
4602
+ noteOf: (story: string) => FlowNote | null,
2950
4603
  ): BlockBox {
2951
4604
  const pageHeight = contentHeight(layout.sheet.settings);
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;
2952
4608
  const next = words[i + 1] ? { word: words[i + 1] as WordInfo } : undefined;
2953
- const { before, after } = spacing(words[i - 1], desc.word, next?.word);
2954
- const pageBreaks = desc.leaves.filter(
2955
- (leaf) =>
2956
- leaf.dom.nodeType !== Node.TEXT_NODE && (leaf.dom as Element).hasAttribute(PAGE_BREAK_ATTR),
2957
- );
2958
- const hasBreak = pageBreaks.length > 0;
2959
- const kept = desc.word.keepLines && !hasBreak && measure.height <= pageHeight;
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;
2960
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
+ });
2961
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,
2962
4650
  height: measure.height,
2963
4651
  marginTop: before,
2964
4652
  marginBottom: after,
2965
4653
  keepWithNext: desc.word.keepNext,
2966
4654
  pageHeight,
4655
+ section: section.flow,
4656
+ sectionMark: !!desc.node.attrs.section && desc.word.empty,
4657
+ inColumn: section.unequal ? inColumn : undefined,
2967
4658
  lines: bottoms,
2968
- breaksAfter: () => {
2969
- // The line holding each break: the last one starting at or before it.
2970
- const breaks = pageBreaks.map((leaf) => {
2971
- const { starts } = lines();
2972
- let line = starts.length - 1;
2973
- while (line > 0 && (starts[line] as number) > leaf.offset) line--;
2974
- return line;
2975
- });
2976
- 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);
2977
4665
  return breaks;
2978
4666
  },
2979
4667
  };
2980
4668
  }
2981
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
+
2982
4700
  /**
2983
- * Writes Word's space above each v3 block as its top margin: the space after the block above
2984
- * and the space before this one, on the same page; at the top of a page only its space before,
2985
- * and only on the first page or after an explicit break (a page the text flowed onto drops it).
2986
- * 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.
2987
4703
  */
2988
- function applyGaps(
2989
- firsts: readonly HTMLElement[],
2990
- pages: readonly (readonly number[])[],
2991
- boxes: readonly BlockBox[],
2992
- ): void {
4704
+ function applyGaps(firsts: readonly HTMLElement[], spaces: readonly number[]): void {
2993
4705
  firsts.forEach((dom, i) => {
2994
- const page = pages[i]?.[0] ?? 0;
2995
- const above = pages[i - 1];
2996
- const box = boxes[i] as BlockBox;
2997
- let gap: number;
2998
- if (above && above[above.length - 1] === page)
2999
- gap = (boxes[i - 1] as BlockBox).marginBottom + box.marginTop;
3000
- else {
3001
- const prior = boxes[i - 1];
3002
- const breaks = prior?.breaksAfter?.() ?? [];
3003
- const forced =
3004
- page === 0 || (!!prior && breaks.length > 0 && breaks.includes(prior.lines().length - 1));
3005
- gap = forced ? box.marginTop : 0;
3006
- }
4706
+ const gap = spaces[i] ?? 0;
3007
4707
  if (gaps.get(dom) === gap) return;
3008
4708
  gaps.set(dom, gap);
3009
4709
  dom.style.marginTop = `${gap}px`;
@@ -3081,6 +4781,8 @@ function measureLines(desc: BlockDesc, scale: number): Lines {
3081
4781
  if (!fragment.contains(leaf.dom)) continue;
3082
4782
  if (leaf.dom.nodeType !== Node.TEXT_NODE) {
3083
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;
3084
4786
  items.push({ offset: leaf.offset, rect: () => br.getBoundingClientRect() });
3085
4787
  continue;
3086
4788
  }
@@ -3185,7 +4887,7 @@ function clusterBoundary(doc: ModelNode, pos: number, forward: boolean): number
3185
4887
  * Scrolls every scrollable ancestor of `from`, then the window, so that `rect` is inside its
3186
4888
  * visible area (minus `scroll-padding`, e.g. for a sticky toolbar). Vertical only: text wraps.
3187
4889
  */
3188
- function scrollRectIntoView(from: HTMLElement, rect: DOMRect): void {
4890
+ function scrollRectIntoView(from: HTMLElement, rect: Pick<DOMRect, "top" | "bottom">): void {
3189
4891
  const doc = from.ownerDocument;
3190
4892
  const win = doc.defaultView;
3191
4893
  if (!win) return;
@@ -3213,6 +4915,27 @@ function scrollRectIntoView(from: HTMLElement, rect: DOMRect): void {
3213
4915
  if (move) win.scrollBy(0, move);
3214
4916
  }
3215
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
+
3216
4939
  function before(node: Node): DomPoint {
3217
4940
  const parent = node.parentNode as Node;
3218
4941
  return { node: parent, offset: Array.prototype.indexOf.call(parent.childNodes, node) };
@@ -3316,12 +5039,17 @@ function holdsFloat(node: ModelNode): boolean {
3316
5039
  return found;
3317
5040
  }
3318
5041
 
3319
- /** A change that only adds or removes a picture's resize handle (the view's own, not input). */
5042
+ /** A change that only adds or removes the view's own marks (a resize handle, a control's frame). */
3320
5043
  function handleOnly(record: MutationRecord): boolean {
3321
5044
  const nodes = [...record.addedNodes, ...record.removedNodes];
3322
5045
  return (
3323
5046
  record.type === "childList" &&
3324
5047
  nodes.length > 0 &&
3325
- nodes.every((n) => n.nodeType === 1 && (n as Element).hasAttribute("data-foli-resize"))
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
+ )
3326
5054
  );
3327
5055
  }