@folijs/view 0.5.0 → 1.0.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 (82) hide show
  1. package/CHANGELOG.md +194 -0
  2. package/README.md +1 -1
  3. package/dist/clipboard.d.ts +1 -49
  4. package/dist/clipboard.d.ts.map +1 -1
  5. package/dist/clipboard.js +65 -13
  6. package/dist/clipboard.js.map +1 -1
  7. package/dist/extension.d.ts +90 -0
  8. package/dist/extension.d.ts.map +1 -0
  9. package/dist/extension.js +152 -0
  10. package/dist/extension.js.map +1 -0
  11. package/dist/index.d.ts +2 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/layout/flow.d.ts +1 -109
  15. package/dist/layout/flow.d.ts.map +1 -1
  16. package/dist/layout/flow.js +808 -103
  17. package/dist/layout/flow.js.map +1 -1
  18. package/dist/print.d.ts +6 -0
  19. package/dist/print.d.ts.map +1 -0
  20. package/dist/print.js +35 -0
  21. package/dist/print.js.map +1 -0
  22. package/dist/render.d.ts +1 -24
  23. package/dist/render.d.ts.map +1 -1
  24. package/dist/render.js +4 -1
  25. package/dist/render.js.map +1 -1
  26. package/dist/view.d.ts +244 -64
  27. package/dist/view.d.ts.map +1 -1
  28. package/dist/view.js +1945 -215
  29. package/dist/view.js.map +1 -1
  30. package/dist/word/blocks.d.ts +0 -146
  31. package/dist/word/blocks.d.ts.map +1 -1
  32. package/dist/word/blocks.js +294 -59
  33. package/dist/word/blocks.js.map +1 -1
  34. package/dist/word/columns.d.ts +2 -0
  35. package/dist/word/columns.d.ts.map +1 -0
  36. package/dist/word/columns.js +63 -0
  37. package/dist/word/columns.js.map +1 -0
  38. package/dist/word/controls.d.ts +2 -0
  39. package/dist/word/controls.d.ts.map +1 -0
  40. package/dist/word/controls.js +416 -0
  41. package/dist/word/controls.js.map +1 -0
  42. package/dist/word/edit.d.ts +1 -71
  43. package/dist/word/edit.d.ts.map +1 -1
  44. package/dist/word/edit.js +338 -29
  45. package/dist/word/edit.js.map +1 -1
  46. package/dist/word/matches.d.ts +2 -0
  47. package/dist/word/matches.d.ts.map +1 -0
  48. package/dist/word/matches.js +102 -0
  49. package/dist/word/matches.js.map +1 -0
  50. package/dist/word/notes.d.ts +2 -0
  51. package/dist/word/notes.d.ts.map +1 -0
  52. package/dist/word/notes.js +403 -0
  53. package/dist/word/notes.js.map +1 -0
  54. package/dist/word/pages.d.ts +30 -20
  55. package/dist/word/pages.d.ts.map +1 -1
  56. package/dist/word/pages.js +421 -229
  57. package/dist/word/pages.js.map +1 -1
  58. package/dist/word/regions.d.ts +2 -0
  59. package/dist/word/regions.d.ts.map +1 -0
  60. package/dist/word/regions.js +388 -0
  61. package/dist/word/regions.js.map +1 -0
  62. package/dist/word/table.d.ts +1 -78
  63. package/dist/word/table.d.ts.map +1 -1
  64. package/dist/word/table.js +13 -3
  65. package/dist/word/table.js.map +1 -1
  66. package/package.json +6 -3
  67. package/src/clipboard.ts +93 -20
  68. package/src/extension.ts +267 -0
  69. package/src/index.ts +10 -0
  70. package/src/layout/flow.ts +997 -116
  71. package/src/print.ts +55 -0
  72. package/src/render.ts +6 -1
  73. package/src/view.ts +2178 -245
  74. package/src/word/blocks.ts +339 -62
  75. package/src/word/columns.ts +81 -0
  76. package/src/word/controls.ts +457 -0
  77. package/src/word/edit.ts +381 -31
  78. package/src/word/matches.ts +104 -0
  79. package/src/word/notes.ts +464 -0
  80. package/src/word/pages.ts +518 -221
  81. package/src/word/regions.ts +488 -0
  82. package/src/word/table.ts +33 -8
package/dist/view.js CHANGED
@@ -1,10 +1,18 @@
1
- import { AllSelection, arrowAcrossLeaf, autolinkHref, CellSelection, cellsAsTable, closeHistory, deleteBackward, deleteForward, deleteSelection, deleteSelectionKeepingTables, extendCellSelection, fitPaste, fitPastedV2, goToCellVertically, insertHardBreak, insertLink, insertPicture, insertText, isSafeHref, keepTablesApart, marksAt, NodeSelection, parseContentV2, pasteCells, redo, Selection, Slice, sectionSettings, setColumnWidth, setComments, setLink, setPictureSize, splitBlock, TextSelection, TransformError, toggleMark, trackState, typedMarks, undo, withEnvelope, wordContext, } from "@folijs/core";
1
+ import { AllSelection, arrowAcrossLeaf, autolinkHref, CellSelection, cellsAsTable, closeHistory, controlAt, controlProperties, deleteBackward, deleteForward, deleteSelection, ensureStory, extendCellSelection, fieldCodesShown, fieldsIn, goToCellVertically, insertControlText, insertHardBreak, insertLink, insertNote, insertPicture, insertText, isSafeHref, marksAt, NodeSelection, noteAtSelection, noteNumbers, noteProperties, noteTexts, pageVariant, parseContentV2, pasteCells, redo, Selection, Slice, sectionSettings, setColumnWidth, setLink, setPictureSize, splitBlock, storyOfSection, TextSelection, TransformError, toggleFieldCodes, toggleMark, trackState, undo, updateFields, } from "@folijs/core";
2
+ import { caretStop, controlSpot, deleteSelectionKeepingTables, fitPaste, fitPastedV2, keepTablesApart, referencesIn, StoryStep, sameSpot, setComments, typedMarks, viewKeys, withEnvelope, wordContext, } from "@folijs/core/internal";
2
3
  import { docFromClipboard, FOLI_MIME, serializeRange } from "./clipboard.js";
3
- import { contentHeight, DEFAULT_RULES, flowFrom, PX_PER_MM, } from "./layout/flow.js";
4
+ import { checkAttrs, decorationsByBlock, reportError, viewsOf, } from "./extension.js";
5
+ import { contentHeight, DEFAULT_RULES, flowFrom, notePieces, PX_PER_MM, pagesOf, spaceAfterText, } from "./layout/flow.js";
6
+ import { printStyles, SHEET_ATTR } from "./print.js";
4
7
  import { PAGE_BREAK_ATTR } from "./render.js";
5
- import { EMU_PER_PX, imageSource, PICTURE_ATTR } from "./word/blocks.js";
8
+ import { EMU_PER_PX, imageSource, NOTE_NUMBER_ATTR, NOTE_REF_ATTR, PICTURE_ATTR, WORD_COLUMN_BREAK_ATTR, } from "./word/blocks.js";
9
+ import { BAND_CLASS, bandElement, COLUMN_CLASS, columnsKey, columnsPx, } from "./word/columns.js";
10
+ import { boxOf, CONTROL_STYLES, CONTROL_UI_ATTR, ControlChrome, } from "./word/controls.js";
6
11
  import { FLOAT_ANCHORS, spacing, WordRenderer, } from "./word/edit.js";
12
+ import { MATCH_STYLES, MatchMarks, rangesInText } from "./word/matches.js";
13
+ import { NOTE_ATTR, PageNotes } from "./word/notes.js";
7
14
  import { measureLineRatio } from "./word/pages.js";
15
+ import { PageRegions, REGION_CONTENT_CLASS } from "./word/regions.js";
8
16
  import { collect, FRAME_ATTR, frameElement, REPEATED_ATTR, } from "./word/table.js";
9
17
  /** What the flow needs of a table: no paragraph spacing or keep rules of its own. */
10
18
  const TABLE_WORD = {
@@ -15,6 +23,7 @@ const TABLE_WORD = {
15
23
  pageBreakBefore: false,
16
24
  style: null,
17
25
  contextual: false,
26
+ empty: false,
18
27
  };
19
28
  /** Word's paragraph spacing for a schema v3 document (`flow`'s `word` spacing). */
20
29
  const WORD_RULES = { ...DEFAULT_RULES, spacing: "word" };
@@ -27,11 +36,13 @@ const CELLS_ATTR = "data-foli-cells";
27
36
  const PLACEHOLDER_ATTR = "data-foli-placeholder";
28
37
  /** On the span of a selected picture (it holds the resize handle). */
29
38
  const PICTURE_SELECTED_ATTR = "data-foli-picture-selected";
39
+ /** On what shows a field the selection is in: Word shades it. */
40
+ const FIELD_SELECTED_ATTR = "data-foli-field-selected";
30
41
  /** The smallest a picture gets by dragging its handle, in px. */
31
42
  const MIN_PICTURE = 8;
32
43
  // Generated content is not document text: no caret stops inside it, a zero-height float keeps
33
44
  // the caret at the line start, and the empty alt text keeps screen readers on aria-placeholder.
34
- 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}`;
45
+ 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}`;
35
46
  /**
36
47
  * Adds the view's stylesheet once per document or shadow root, when a placeholder is first shown
37
48
  * (by then the host is usually mounted where it will stay).
@@ -53,31 +64,16 @@ function injectStyles(host) {
53
64
  const VIEW_ATTR = "data-foli-view";
54
65
  let viewCount = 0;
55
66
  /**
56
- * Print rules for the page settings of the view whose host has `VIEW_ATTR` = `id`: one sheet of
57
- * its section's size per page (the last section's where named pages are not supported), without
58
- * 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
59
- * half-pixel slack), with no gap after it. Content taller than a page (a line taller than a
60
- * page) is not cut: it prints over the next sheet.
67
+ * Print rules for the page settings of the view whose host has `VIEW_ATTR` = `id` (`print.ts`,
68
+ * shared with the read-only renderer and so with `@folijs/pdf`).
61
69
  * 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.
62
70
  */
63
- function printStyles(settings, sheets, id) {
64
- const { width, height } = settings.pageSize;
65
- const last = sheetOf(settings, 0).css;
66
- const pages = `[${VIEW_ATTR}="${id}"]>.foli-page`;
67
- // Sections with other page setups: a named page each (engines without named pages print
68
- // every sheet at the last section's size).
69
- const named = sheets.every((sheet) => sheet.css === last)
70
- ? ""
71
- : sheets
72
- .map(({ settings: { pageSize: size }, index }) => {
73
- const name = `foli-${id}-${index}`;
74
- return (`@page ${name}{size:${size.width}mm ${size.height}mm;margin:0}` +
75
- `${pages}[${SHEET_ATTR}="${index}"]{page:${name};height:${size.height}mm!important}`);
76
- })
77
- .join("");
78
- return (`@media print{@page{size:${width}mm ${height}mm;margin:0}` +
79
- `${pages}{height:${height}mm!important;margin-block:0!important;` +
80
- `break-after:page;break-inside:avoid}${pages}:last-child{break-after:auto}${named}}`);
71
+ function viewPrintStyles(settings, sheets, id) {
72
+ const mm = ({ width, height }) => ({
73
+ width: `${width}mm`,
74
+ height: `${height}mm`,
75
+ });
76
+ return printStyles(`[${VIEW_ATTR}="${id}"]>.foli-page`, mm(settings.pageSize), sheets.map(({ settings: { pageSize }, index }) => ({ ...mm(pageSize), index })), id);
81
77
  }
82
78
  /** Whether `node` is inside an element of `stop` that is not displayed (hidden deleted text). */
83
79
  function hiddenIn(node, stop) {
@@ -86,8 +82,8 @@ function hiddenIn(node, stop) {
86
82
  return true;
87
83
  return false;
88
84
  }
89
- /** The attribute naming a page's page setup (its index among the document's) for print. */
90
- const SHEET_ATTR = "data-foli-sheet";
85
+ /** The fields whose results depend on where things fall on the pages. */
86
+ const PAGE_DEPENDENT = new Set(["PAGE", "NUMPAGES", "SECTIONPAGES", "PAGEREF"]);
91
87
  function sheetOf(settings, index) {
92
88
  const { pageSize, margins } = settings;
93
89
  const css =
@@ -100,62 +96,143 @@ function sheetOf(settings, index) {
100
96
  }
101
97
  /** The style each page element was last given (its `cssText` reads back normalized). */
102
98
  const pageSheets = new WeakMap();
99
+ /** The margins a header or footer gave each page element, as last written. */
100
+ const pagePads = new WeakMap();
101
+ /** What a view without pages gives its one flow of content. */
102
+ const UNPAGED_CSS = "display: flow-root; position: relative;";
103
+ const slotOf = (fragment) => ({
104
+ band: fragment.band ?? 0,
105
+ column: fragment.column ?? 0,
106
+ lead: fragment.lead,
107
+ mark: !!fragment.mark,
108
+ });
109
+ /** The document's sections and the blocks of each. */
110
+ function sectionSpans(doc, last) {
111
+ const spans = [];
112
+ let from = 0;
113
+ doc.forEach((node, _, i) => {
114
+ const own = node.attrs.section;
115
+ if (!own)
116
+ return;
117
+ spans.push({ setup: own, from, to: i + 1 });
118
+ from = i + 1;
119
+ });
120
+ if (from < doc.childCount || !spans.length)
121
+ spans.push({ setup: last, from, to: doc.childCount });
122
+ return spans;
123
+ }
103
124
  /**
104
125
  * The section of each top-level block (the section a paragraph's `section` ends; the
105
- * envelope's for the blocks after the last such paragraph). A section starts a new page,
106
- * unless it is continuous with the same page setup as the one before (shortcut: a continuous
107
- * section with another page setup starts a new page; Word's even and odd page sections do not
108
- * add a blank page), as `renderDocument` lays sections out.
126
+ * envelope's for the blocks after the last such paragraph), as `renderDocument` lays sections
127
+ * out. By position: two paragraphs may end sections with one object. `box` gives a page's text
128
+ * height: null for a view without pages.
109
129
  */
110
- function sectionLayouts(doc, last) {
130
+ function sectionLayouts(spans, box) {
111
131
  const sheets = new Map();
112
132
  const bySection = new Map();
113
133
  const sheet = (section) => {
114
134
  let found = bySection.get(section);
115
135
  if (!found) {
116
136
  const settings = sectionSettings(section);
117
- const css = sheetOf(settings, 0).css;
118
- found = sheets.get(css) ?? sheetOf(settings, sheets.size);
137
+ const css = box ? sheetOf(settings, 0).css : UNPAGED_CSS;
138
+ found = sheets.get(css) ?? { ...sheetOf(settings, sheets.size), css };
119
139
  sheets.set(css, found);
120
140
  bySection.set(section, found);
121
141
  }
122
142
  return found;
123
143
  };
124
- const sections = [];
125
- let section = last;
126
- for (let i = doc.childCount - 1; i >= 0; i--) {
127
- const own = doc.child(i).attrs.section;
128
- if (own)
129
- section = own;
130
- sections[i] = section;
131
- }
132
- // Indexes in document order: the first page setup is 0.
133
- sections.forEach(sheet);
134
- return sections.map((own, i) => {
135
- const next = sections[i + 1];
136
- // By position, as `renderDocument`: two paragraphs may end sections with one object.
137
- const ends = !!next && !!doc.child(i).attrs.section;
138
- const breakAfter = ends && !(next.type === "continuous" && sheet(next).css === sheet(own).css);
139
- return { sheet: sheet(own), breakAfter };
144
+ const sheetByFlow = new Map();
145
+ const out = [];
146
+ spans.forEach(({ setup, from: start, to }, s) => {
147
+ // Indexes in document order: the first page setup is 0.
148
+ const own = sheet(setup);
149
+ const next = spans[s + 1]?.setup;
150
+ const columns = columnsPx(setup);
151
+ const count = columns.widths.length;
152
+ const balanced = !!next && count > 1 && next.type === "continuous" && sheet(next).css === own.css;
153
+ const flow = {
154
+ index: s,
155
+ start: setup.type ?? "nextPage",
156
+ columns: count,
157
+ balanced,
158
+ pageStart: setup.pageNumbers?.start,
159
+ box: (page) => ({ height: box ? box(s, page) : Number.POSITIVE_INFINITY }),
160
+ samePage: (other) => sheetByFlow.get(other)?.css === own.css,
161
+ };
162
+ sheetByFlow.set(flow, own);
163
+ const section = {
164
+ sheet: own,
165
+ columns,
166
+ unequal: new Set(columns.widths).size > 1,
167
+ flow,
168
+ key: `${own.css}|${flow.start}|${flow.pageStart ?? ""}|${balanced}|${columnsKey(columns)}`,
169
+ };
170
+ for (let i = start; i < to; i++)
171
+ out[i] = { sheet: own, section, first: i === start };
140
172
  });
173
+ return out;
141
174
  }
142
175
  /**
143
- * Initial pages (before a flow), moved where needed so that each page holds blocks of one
144
- * page setup: a block is measured in a page of its own section's width.
176
+ * Where blocks are before a flow: where they were (`known`), moved where needed so that each
177
+ * page holds blocks of one page setup and each section has a band of its own: a block is
178
+ * measured in a column of its own section's width.
145
179
  */
146
- function separateSheets(pages, layout) {
147
- const css = [];
148
- let floor = 0;
149
- return pages.map((list, i) => list.map((p) => {
150
- const want = layout[i].sheet.css;
151
- let page = Math.max(p, floor);
152
- // Only the last page used so far has a setup: the next one is free.
153
- if (css[page] !== undefined && css[page] !== want)
154
- page++;
155
- css[page] ??= want;
156
- floor = page;
157
- return page;
158
- }));
180
+ function initialPlaces(pages, layout, known) {
181
+ let page = 0;
182
+ let band = 0;
183
+ let column = 0;
184
+ let section;
185
+ const slots = [];
186
+ const placed = pages.map((list, i) => {
187
+ const own = layout[i].section;
188
+ const out = [];
189
+ slots[i] = out;
190
+ return list.map((p, f) => {
191
+ let target = Math.max(p, page);
192
+ if (target === page && section && section !== own) {
193
+ // Only the last page used so far has a setup: the next one is free.
194
+ if (section.sheet.css !== own.sheet.css)
195
+ target++;
196
+ else {
197
+ band++;
198
+ column = 0;
199
+ }
200
+ }
201
+ if (target > page) {
202
+ page = target;
203
+ band = 0;
204
+ column = 0;
205
+ }
206
+ section = own;
207
+ const was = known[i]?.[f];
208
+ column = Math.min(Math.max(column, was?.column ?? 0), own.columns.widths.length - 1);
209
+ out.push({
210
+ band,
211
+ column,
212
+ lead: was?.band === band ? was.lead : undefined,
213
+ mark: was?.mark ?? false,
214
+ });
215
+ return page;
216
+ });
217
+ });
218
+ return { pages: placed, slots };
219
+ }
220
+ /** Makes `list` the children of `parent`, moving as little as possible; returns what it removed. */
221
+ function fillElement(parent, list, removed) {
222
+ let at = parent.firstChild;
223
+ for (const dom of list) {
224
+ if (dom === at)
225
+ at = at.nextSibling;
226
+ else
227
+ parent.insertBefore(dom, at);
228
+ }
229
+ // What is left after the last placed one: strays, and blocks of later pages.
230
+ while (at) {
231
+ const next = at.nextSibling;
232
+ at.remove();
233
+ removed.add(at);
234
+ at = next;
235
+ }
159
236
  }
160
237
  /**
161
238
  * The editable view of an `Editor` from `@folijs/core`: renders its state into one
@@ -185,6 +262,10 @@ export class EditorView {
185
262
  cellCaret = null;
186
263
  /** The pages of each top-level item (a paragraph's fragments, a table's wrappers), by node. */
187
264
  itemPages = new Map();
265
+ /** Where on its page each of those is (band and column). */
266
+ itemSlots = new Map();
267
+ /** Each page's band elements, as last placed. */
268
+ bands = new WeakMap();
188
269
  /** Each table as last rendered, by node. */
189
270
  frames = new Map();
190
271
  /** The table each wrapper element draws (part of). */
@@ -236,9 +317,12 @@ export class EditorView {
236
317
  resizeObserver;
237
318
  observed = new Set();
238
319
  relayoutPending = false;
320
+ /** A composition runs in this view. */
239
321
  composing = false;
240
322
  /** Set by Ctrl/Cmd+Shift+V for the paste event it triggers. */
241
323
  plainPaste = false;
324
+ /** How deep `renumberNotes` has rendered again. */
325
+ renumbering = 0;
242
326
  /** Blocks whose DOM the browser changed: the next render rebuilds them. */
243
327
  dirty = new Set();
244
328
  /** DOM mutations not yet read back (kept while a composition is running). */
@@ -267,14 +351,105 @@ export class EditorView {
267
351
  resource;
268
352
  /** How tracked changes show. */
269
353
  review = "markup";
354
+ /** Whether fields show their codes (`toggleFieldCodes`). */
355
+ fieldCodes = false;
356
+ /** The elements shaded for the fields the selection is in. */
357
+ shadedFields = [];
270
358
  /** Fonts' normal line height ratios, measured once per family (Word's single spacing). */
271
359
  ratios = new Map();
272
360
  /** Web fonts loaded since the v3 blocks were drawn: the next render draws them again. */
273
361
  fontsChanged = false;
362
+ /** Whether content goes on pages (`EditorViewOptions.paged`). */
363
+ paged;
364
+ /** The headers and footers of the pages; none without pages. */
365
+ regions;
366
+ /** Each page as last flowed. */
367
+ facts = [];
368
+ /** The header and footer element of each page, as last drawn. */
369
+ pageRegions = [];
370
+ /** Each page's margins, when a header or footer pushes them. */
371
+ pageMargins = [];
372
+ /** What the header and footer heights were when last laid out (`PageRegions.key`). */
373
+ regionsKey = "";
374
+ /** What `regionsKey` was computed from. */
375
+ regionsFor = null;
376
+ /** Footnotes and endnotes on the pages; none without pages. */
377
+ notes;
378
+ /** What each page shows of them. */
379
+ pageNotes = [];
380
+ /** Their elements by what they show. */
381
+ noteElements = new Map();
382
+ /** The page each note starts on, as last flowed: numbers can restart on each. */
383
+ notePages = new Map();
384
+ /** What the note references showed when last drawn. */
385
+ shownNotes = "";
386
+ /** The layout and boxes of the last flow, to draw notes again from. */
387
+ flowLayout = [];
388
+ flowBoxes = [];
389
+ /** What this view's note mark shows (`EditorViewOptions.noteMark`). */
390
+ noteMark;
391
+ /** Puts everything on its page again, as the last render left it. */
392
+ placeAgain = null;
393
+ /** The story being edited on its page, if any (ADR-0007). */
394
+ mount = null;
395
+ /** What find shows, and which tree this view draws of it (a mounted story's view: its own). */
396
+ found = null;
397
+ matchStory = null;
398
+ matchMarks;
399
+ /** The pages marked, as a key; the frame waiting to look again. */
400
+ matchPages = "";
401
+ matchFrame = 0;
402
+ /** The body's selection before the press of a double click in a page's margin. */
403
+ pressSelection = null;
404
+ /** The listeners on the host, to remove them. */
405
+ listeners = [];
406
+ /** The frames, titles and pop-ups of content controls. */
407
+ controlChrome;
408
+ /** The editor's view extensions' node and mark views, decorations and plugin views. */
409
+ views;
410
+ decorators;
411
+ decorations = [];
412
+ decorationKey = "";
413
+ pluginViews = [];
414
+ /** What node views drew and the view still shows (their `destroy` when it no longer does). */
415
+ drawn = [];
274
416
  constructor(host, editor, options = {}) {
275
417
  this.host = host;
276
418
  this.editor = editor;
277
419
  this.state = editor.state;
420
+ this.matchMarks = new MatchMarks(host.ownerDocument);
421
+ this.paged = options.paged !== false;
422
+ this.noteMark = options.noteMark;
423
+ const view = this;
424
+ this.controlChrome = new ControlChrome({
425
+ host,
426
+ editor,
427
+ state: () => view.state,
428
+ editable: () => view.editable && !view.mount,
429
+ pages: () => view.pages,
430
+ scale: () => view.scale(),
431
+ rects: (range) => view.controlRects(range),
432
+ contentRects: (range) => view.controlContentRects(range),
433
+ posFromDOM: (node, offset) => view.posFromDOM(node, offset),
434
+ focus: () => view.focus(),
435
+ injectStyles: () => injectStyles(host),
436
+ });
437
+ const storyOptions = {
438
+ get review() {
439
+ return view.review;
440
+ },
441
+ get fieldCodes() {
442
+ return view.fieldCodes;
443
+ },
444
+ lineRatio: (family) => this.lineRatio(family),
445
+ resource: (key, resource) => this.resource?.(key, resource),
446
+ measureIn: () => this.pages[0] ?? host,
447
+ scale: () => this.scale(),
448
+ };
449
+ this.regions = this.paged
450
+ ? new PageRegions(host.ownerDocument, storyOptions, new WeakMap())
451
+ : null;
452
+ this.notes = this.paged ? new PageNotes(host.ownerDocument, storyOptions, new WeakMap()) : null;
278
453
  host.setAttribute("role", "textbox");
279
454
  host.setAttribute("aria-multiline", "true");
280
455
  host.setAttribute(VIEW_ATTR, this.id);
@@ -286,35 +461,125 @@ export class EditorView {
286
461
  host.style.overflowWrap = "break-word";
287
462
  host.replaceChildren();
288
463
  this.review = trackState(this.state)?.view ?? "markup";
464
+ this.fieldCodes = fieldCodesShown(this.state);
289
465
  this.resizeObserver =
290
466
  typeof ResizeObserver === "undefined" ? null : new ResizeObserver(this.onResize);
291
467
  this.observer = new MutationObserver(this.onMutations);
292
468
  this.observer.observe(host, { childList: true, characterData: true, subtree: true });
293
469
  // The picture resolver before the first render: no image drawn from a URL the app refuses.
294
470
  this.resource = options.resource ?? undefined;
471
+ const extensions = editor.extensions;
472
+ this.views = viewsOf(extensions);
473
+ this.decorators = extensions.flatMap((e) => (e.decorations ? [e.decorations.bind(e)] : []));
474
+ this.decorate(this.state);
295
475
  this.render();
296
476
  this.setOptions(options);
297
- host.addEventListener("beforeinput", this.onBeforeInput);
298
- host.addEventListener("focus", this.onFocus);
299
- host.addEventListener("keydown", this.onKeyDown);
300
- host.addEventListener("input", this.onInput);
301
- host.addEventListener("compositionstart", this.onCompositionStart);
302
- host.addEventListener("compositionend", this.onCompositionEnd);
303
- host.addEventListener("blur", this.onBlur);
304
- host.addEventListener("mousedown", this.onMouseDown);
305
- host.addEventListener("mousemove", this.onMouseMove);
306
- host.addEventListener("copy", this.onCopy);
307
- host.addEventListener("cut", this.onCut);
308
- host.addEventListener("paste", this.onPaste);
309
- host.addEventListener("dragover", this.onDragOver);
310
- host.addEventListener("drop", this.onDrop);
311
- host.addEventListener("click", this.onClick);
312
- host.addEventListener("auxclick", this.onClick);
477
+ this.listen("beforeinput", this.onBeforeInput);
478
+ this.listen("focus", this.onFocus);
479
+ this.listen("keydown", this.onKeyDown);
480
+ this.listen("input", this.onInput);
481
+ this.listen("compositionstart", this.onCompositionStart);
482
+ this.listen("compositionend", this.onCompositionEnd);
483
+ this.listen("blur", this.onBlur);
484
+ this.listen("mousedown", this.onPress);
485
+ this.listen("mousemove", this.onMouseMove);
486
+ this.listen("mouseleave", () => this.controlChrome.hover(null));
487
+ this.listen("copy", this.onCopy);
488
+ this.listen("cut", this.onCut);
489
+ this.listen("paste", this.onPaste);
490
+ this.listen("dragover", this.onDragOver);
491
+ this.listen("drop", this.onDrop);
492
+ this.listen("click", this.onClick);
493
+ this.listen("auxclick", this.onClick);
494
+ this.claimStories();
313
495
  host.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
314
496
  host.ownerDocument.fonts?.addEventListener("loadingdone", this.onFontsLoaded);
315
497
  this.unsubscribe = editor.subscribe((state) => this.update(state));
498
+ for (const extension of extensions) {
499
+ try {
500
+ if (extension.view)
501
+ this.pluginViews.push(extension.view(this));
502
+ }
503
+ catch (error) {
504
+ reportError(error);
505
+ }
506
+ }
507
+ }
508
+ /** Calls `hook` for each plugin view, reporting what throws. */
509
+ eachPluginView(hook) {
510
+ for (const view of this.pluginViews) {
511
+ try {
512
+ hook(view);
513
+ }
514
+ catch (error) {
515
+ reportError(error);
516
+ }
517
+ }
518
+ }
519
+ /** Destroys node views' drawings the host no longer holds (all of them: `all`). */
520
+ dropDrawn(all) {
521
+ let kept = 0;
522
+ for (const drawn of this.drawn) {
523
+ if (!all && this.host.contains(drawn.box)) {
524
+ this.drawn[kept++] = drawn;
525
+ continue;
526
+ }
527
+ try {
528
+ drawn.view.destroy?.(drawn.root);
529
+ }
530
+ catch (error) {
531
+ reportError(error);
532
+ }
533
+ }
534
+ this.drawn.length = kept;
535
+ }
536
+ /** Asks the extensions for `state`'s decorations; whether they changed. */
537
+ decorate(state) {
538
+ if (!this.decorators.length)
539
+ return false;
540
+ // A failing extension, or a decoration with a refused attribute, is reported and left out.
541
+ const decorations = this.decorators.flatMap((decorate) => {
542
+ try {
543
+ return (decorate?.(state) ?? []).filter((decoration) => {
544
+ try {
545
+ checkAttrs(decoration.attrs);
546
+ return true;
547
+ }
548
+ catch (error) {
549
+ reportError(error);
550
+ return false;
551
+ }
552
+ });
553
+ }
554
+ catch (error) {
555
+ reportError(error);
556
+ return [];
557
+ }
558
+ });
559
+ const key = JSON.stringify(decorations);
560
+ if (key === this.decorationKey)
561
+ return false;
562
+ this.decorations = decorations;
563
+ this.decorationKey = key;
564
+ return true;
565
+ }
566
+ /** Adds a listener for the body's events: a story open on a page has its own view. */
567
+ listen(type, handler) {
568
+ const listener = (event) => {
569
+ if (!this.mount?.wrapper.contains(event.target))
570
+ handler(event);
571
+ };
572
+ this.host.addEventListener(type, listener);
573
+ this.listeners.push([type, listener]);
316
574
  }
317
575
  destroy() {
576
+ this.eachPluginView((view) => view.destroy?.());
577
+ this.pluginViews = [];
578
+ this.closeStory(false);
579
+ this.showFound(null);
580
+ this.controlChrome.destroy();
581
+ if (this.editor.storyView === this.stories)
582
+ this.editor.storyView = null;
318
583
  this.destroyed = true;
319
584
  this.unsubscribe();
320
585
  this.host.ownerDocument.fonts?.removeEventListener("loadingdone", this.onFontsLoaded);
@@ -323,24 +588,10 @@ export class EditorView {
323
588
  for (const style of this.printStyles)
324
589
  style.remove();
325
590
  const { host } = this;
326
- host.removeEventListener("beforeinput", this.onBeforeInput);
327
- host.removeEventListener("focus", this.onFocus);
328
- host.removeEventListener("keydown", this.onKeyDown);
329
- host.removeEventListener("input", this.onInput);
330
- host.removeEventListener("compositionstart", this.onCompositionStart);
331
- host.removeEventListener("compositionend", this.onCompositionEnd);
332
- host.removeEventListener("blur", this.onBlur);
333
- host.removeEventListener("mousedown", this.onMouseDown);
334
- host.removeEventListener("mousemove", this.onMouseMove);
591
+ for (const [type, listener] of this.listeners)
592
+ host.removeEventListener(type, listener);
335
593
  this.endDrag();
336
- host.removeEventListener("copy", this.onCopy);
337
- host.removeEventListener("cut", this.onCut);
338
- host.removeEventListener("paste", this.onPaste);
339
- host.removeEventListener("dragover", this.onDragOver);
340
- host.removeEventListener("drop", this.onDrop);
341
594
  this.endResize();
342
- host.removeEventListener("click", this.onClick);
343
- host.removeEventListener("auxclick", this.onClick);
344
595
  host.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
345
596
  const owned = [
346
597
  "contenteditable",
@@ -359,9 +610,14 @@ export class EditorView {
359
610
  if (!host.getAttribute("style"))
360
611
  host.removeAttribute("style");
361
612
  host.replaceChildren();
613
+ this.dropDrawn(true);
362
614
  }
363
615
  /** Focuses the host, shows the model selection in it and scrolls it into view. */
364
616
  focus() {
617
+ if (this.mount) {
618
+ this.mount.view.focus();
619
+ return;
620
+ }
365
621
  this.host.focus();
366
622
  this.writeSelection(true);
367
623
  // The focus handler scrolls only when it writes the selection itself, and a DOM selection
@@ -376,6 +632,8 @@ export class EditorView {
376
632
  if (!options.editable && this.composing)
377
633
  this.onCompositionEnd();
378
634
  this.editable = options.editable;
635
+ if (!this.editable)
636
+ this.closeStory(false);
379
637
  // A selected picture's handle only while it can be resized.
380
638
  this.endResize();
381
639
  this.showSelectedPicture();
@@ -384,6 +642,10 @@ export class EditorView {
384
642
  this.placeholder = options.placeholder;
385
643
  if (options.upload !== undefined)
386
644
  this.upload = options.upload ?? undefined;
645
+ this.mount?.view.setOptions({
646
+ ...(options.upload !== undefined ? { upload: options.upload } : {}),
647
+ ...(options.resource !== undefined ? { resource: options.resource } : {}),
648
+ });
387
649
  // null clears the resolver (stored as none): the same as none is no change.
388
650
  const resource = options.resource ?? undefined;
389
651
  if (options.resource !== undefined && resource !== this.resource) {
@@ -399,8 +661,8 @@ export class EditorView {
399
661
  }
400
662
  }
401
663
  // Read-only: no caret and no browser editing; the text stays selectable and copyable.
402
- host.setAttribute("contenteditable", String(this.editable));
403
- if (this.editable)
664
+ host.setAttribute("contenteditable", String(this.editable && !this.mount));
665
+ if (this.editable && !this.mount)
404
666
  host.removeAttribute("aria-readonly");
405
667
  else
406
668
  host.setAttribute("aria-readonly", "true");
@@ -438,16 +700,44 @@ export class EditorView {
438
700
  this.review = review;
439
701
  this.word = null;
440
702
  }
441
- const docChanged = state.doc !== this.state.doc || reviewChanged;
703
+ // Codes shown or hidden: every block and story drawn again.
704
+ const codes = fieldCodesShown(state);
705
+ const codesChanged = codes !== this.fieldCodes;
706
+ if (codesChanged) {
707
+ this.fieldCodes = codes;
708
+ this.word = null;
709
+ }
710
+ const before = wordContext(this.state)?.envelope;
711
+ const envelope = wordContext(state)?.envelope;
712
+ // The last section's setup and the settings live in the envelope: changing them leaves the
713
+ // tree as it is. So does a story's change, which only its occurrences show.
714
+ const docChanged = state.doc !== this.state.doc ||
715
+ reviewChanged ||
716
+ codesChanged ||
717
+ envelope?.section !== before?.section ||
718
+ envelope?.settings !== before?.settings;
719
+ const storiesChanged = envelope?.stories !== before?.stories;
442
720
  const selectionChanged = !state.selection.eq(this.state.selection);
721
+ // Another document: the story being edited closes.
722
+ const lost = !!this.mount && wordContext(state)?.id !== wordContext(this.state)?.id;
723
+ const previous = this.state;
443
724
  this.state = state;
444
- if (docChanged)
725
+ // Decorations that changed redraw their blocks (the others are reused).
726
+ const decorated = this.decorate(state);
727
+ if (docChanged || decorated || (storiesChanged && !this.redrawRegions()))
445
728
  this.render();
729
+ if (lost)
730
+ this.closeStory(true);
731
+ // The open story has its own editor, which hears nothing of this.
732
+ if (codesChanged)
733
+ this.mount?.view.update(this.mount.view.editor.state);
446
734
  this.showSelectedNode();
447
- this.writeSelection(docChanged);
735
+ // Redrawn blocks may have held the DOM selection.
736
+ this.writeSelection(docChanged || decorated);
448
737
  // shortcut: scrolls for every change while focused; once remote or plugin changes exist, scroll only for local input (a transaction flag).
449
738
  if (docChanged || selectionChanged)
450
739
  this.scrollToSelection();
740
+ this.eachPluginView((view) => view.update?.(this, previous));
451
741
  }
452
742
  /**
453
743
  * Scrolls the selection head into view. Browsers do it for their own edits and caret moves,
@@ -485,32 +775,72 @@ export class EditorView {
485
775
  * Measurements are cached by node and the flow restarts at the first changed block (5.4).
486
776
  */
487
777
  render() {
778
+ try {
779
+ this.renderPages();
780
+ if (this.drawn.length)
781
+ this.dropDrawn(false);
782
+ }
783
+ catch (error) {
784
+ // What it had changed is not input: read back, it would render and fail again, for ever.
785
+ this.observer.takeRecords();
786
+ this.pending = [];
787
+ throw error;
788
+ }
789
+ }
790
+ renderPages() {
488
791
  const { doc } = this.state;
489
792
  const ownerDocument = this.host.ownerDocument;
490
793
  // A new document (envelope) gets its renderer; nothing rendered before is reused then. An
491
794
  // editor's state always has one (`createEditor`).
492
795
  const context = wordContext(this.state);
493
796
  // Fonts loaded: a new renderer (new line heights), but not while a composition runs in a
494
- // block it would redraw.
495
- const renewed = context !== (this.word?.context ?? null) || (this.fontsChanged && !this.composing);
797
+ // block it would redraw. What only stories or the settings changed leaves blocks as they are.
798
+ const drawn = this.word?.context;
799
+ const renewed = !drawn ||
800
+ drawn.id !== context.id ||
801
+ drawn.resolver !== context.resolver ||
802
+ drawn.envelope.section !== context.envelope.section ||
803
+ drawn.envelope.resources !== context.envelope.resources ||
804
+ drawn.envelope.comments !== context.envelope.comments ||
805
+ (this.fontsChanged && !this.composing);
496
806
  if (renewed)
497
807
  this.fontsChanged = false;
498
808
  let word = this.word;
809
+ if (!renewed)
810
+ word.context = context;
499
811
  if (renewed) {
500
812
  // A document with pictures: the mark of one without alt text is the view's stylesheet's.
501
813
  if (context.envelope.resources)
502
814
  injectStyles(this.host);
503
- word = this.word = new WordRenderer(context, ownerDocument, this.lineRatio, false, this.review, imageSource(context.envelope.resources, this.resource ?? undefined));
815
+ word = this.word = new WordRenderer(context, ownerDocument, this.lineRatio, false, this.review, imageSource(context.envelope.resources, this.resource ?? undefined), this.fieldCodes);
816
+ word.views = this.views;
817
+ word.drawn = this.drawn;
504
818
  this.invalidateLayout();
505
819
  }
820
+ const references = this.noteReferences();
821
+ word.setNotes(noteTexts(references), this.noteMark?.());
506
822
  // The blocks the view renders (paragraphs in table cells among them) and the page flow's
507
823
  // items (top-level paragraphs and opaque blocks, and tables).
508
824
  const { units, items } = collect(doc, context.resolver);
509
- word.prepare(units.map((unit) => unit.node));
510
- const layout = sectionLayouts(doc, context.envelope.section);
825
+ word.decorations = this.decorations.length ? decorationsByBlock(units, this.decorations) : [];
826
+ word.prepare(units.map((unit) => unit.node), (i) => {
827
+ const unit = units[i];
828
+ const previous = units[i - 1];
829
+ // Siblings: one ends where the other starts.
830
+ return unit.cell && previous && previous.pos + previous.node.nodeSize === unit.pos
831
+ ? { node: previous.node, cell: unit.cell }
832
+ : null;
833
+ });
834
+ // A story's view has none of the body's sections: its one flow is not a page's.
835
+ const spans = sectionSpans(doc, this.paged ? context.envelope.section : {});
836
+ const { regions } = this;
837
+ regions?.setDocument(context.envelope, spans.map((span) => span.setup), context.resolver);
838
+ const { notes } = this;
839
+ notes?.setDocument(context.envelope, spans.map((span) => span.setup), context.resolver, references);
840
+ const layout = sectionLayouts(spans, regions && ((section, page) => regions.boxHeight(section, page)));
511
841
  doc.forEach((node, _, i) => {
512
- const { sheet, breakAfter } = layout[i];
513
- const key = `${sheet.css}${breakAfter ? "|break" : ""}`;
842
+ const { section, first } = layout[i];
843
+ const key = `${section.key}${first ? "|first" : ""}`;
514
844
  const before = this.layoutKeys.get(node);
515
845
  if (before !== undefined && before !== key)
516
846
  this.stale.add(node);
@@ -630,23 +960,30 @@ export class EditorView {
630
960
  const desc = blocks[item.unit];
631
961
  return desc.fragments.map((_, f) => (last = Math.max(last, before?.[f] ?? last)));
632
962
  });
633
- pages = separateSheets(pages, layout);
963
+ const initial = initialPlaces(pages, layout, items.map((_, i) => this.itemSlots.get(doc.child(i))));
964
+ pages = initial.pages;
965
+ let slots = initial.slots;
634
966
  const elementsOf = (item, i) => item.frame
635
967
  ? frames.get(doc.child(i)).wrappers
636
968
  : blocks[item.unit].fragments;
637
- this.place(items.map((item, i) => elementsOf(item, i)), pages, layout);
969
+ this.place(items.map((item, i) => elementsOf(item, i)), pages, slots, layout);
638
970
  if (!this.composing) {
639
971
  // DOM reads only for blocks without a valid measurement (new, changed or stale ones).
640
972
  let scale;
641
973
  const layoutPx = () => {
642
- scale ??= layoutScale(this.pages[0], this.sheets[0].settings);
974
+ scale ??= this.scale();
643
975
  return scale;
644
976
  };
977
+ // A header or footer of another height moves every page's text: no flow is reused.
978
+ if (regions && this.regionsChanged(regions, spans))
979
+ this.flowed = null;
645
980
  if (dropLines)
646
981
  for (const desc of blocks) {
647
982
  const measure = this.measures.get(desc.node);
648
- if (measure)
983
+ if (measure) {
649
984
  delete measure.lines;
985
+ delete measure.widths;
986
+ }
650
987
  }
651
988
  const nodes = items.map((_, i) => doc.child(i));
652
989
  // A block's spacing depends on its neighbours' styles: reuse stops a block earlier.
@@ -665,6 +1002,39 @@ export class EditorView {
665
1002
  found.lines ??= measureLines(desc, layoutPx());
666
1003
  return found.lines;
667
1004
  };
1005
+ /** A block's height and lines at a column's width, wherever it is now. */
1006
+ const atWidth = (desc, width, kept) => {
1007
+ const measure = measureOf(desc);
1008
+ const widths = measure.widths ?? new Map();
1009
+ measure.widths = widths;
1010
+ const known = widths.get(width);
1011
+ if (known)
1012
+ return known;
1013
+ const read = (measure) => {
1014
+ for (const { style } of desc.fragments) {
1015
+ style.boxSizing = "border-box";
1016
+ style.width = `${width}px`;
1017
+ }
1018
+ const value = measure();
1019
+ for (const { style } of desc.fragments) {
1020
+ style.boxSizing = "";
1021
+ style.width = "";
1022
+ }
1023
+ return value;
1024
+ };
1025
+ const { height } = read(() => measureBox(desc, layoutPx()));
1026
+ let all;
1027
+ const found = {
1028
+ height,
1029
+ all: () => {
1030
+ all ??= read(() => measureLines(desc, layoutPx()));
1031
+ return all;
1032
+ },
1033
+ lines: () => (kept ? [height] : found.all().bottoms),
1034
+ };
1035
+ widths.set(width, found);
1036
+ return found;
1037
+ };
668
1038
  const tableOf = (frame, i) => {
669
1039
  let found = this.measures.get(frame.node);
670
1040
  if (!found?.table || this.stale.delete(frame.node)) {
@@ -681,22 +1051,55 @@ export class EditorView {
681
1051
  return found;
682
1052
  };
683
1053
  const words = items.map((item) => item.frame ? TABLE_WORD : blocks[item.unit].word);
1054
+ const endnotes = notes?.endnotes();
684
1055
  const boxes = items.map((item, i) => {
685
- const pageHeight = contentHeight(layout[i].sheet.settings);
1056
+ const own = layout[i];
1057
+ const pageHeight = contentHeight(own.sheet.settings);
1058
+ const index = own.section.flow.index ?? 0;
1059
+ const noteOf = (story) => notes?.footnote(story, index) ?? null;
1060
+ // Endnotes follow the last block of their section, or of the document.
1061
+ const after = layout[i + 1]?.section !== own.section
1062
+ ? { endnotes: endnotes?.get(index) }
1063
+ : {};
686
1064
  if (item.frame) {
687
1065
  const frame = item.frame;
688
1066
  const measure = tableOf(frame, i);
689
- // A section break after it, or a page break before the next paragraph, ends its page.
690
- const breakAfter = layout[i].breakAfter || !!words[i + 1]?.pageBreakBefore;
691
- return tableBox(frame, measure, pageHeight, breakAfter, () => breaksOf(frame, measure, blocks, pageHeight, lines));
1067
+ const breaks = () => breaksOf(frame, measure, blocks, pageHeight, lines);
1068
+ // A page break before the next paragraph ends its page.
1069
+ return {
1070
+ ...tableBox(frame, measure, pageHeight, !!words[i + 1]?.pageBreakBefore, breaks),
1071
+ section: own.section.flow,
1072
+ notes: tableNotes(frame, measure, blocks, lines, breaks, noteOf),
1073
+ ...after,
1074
+ };
692
1075
  }
693
1076
  const desc = blocks[item.unit];
694
- return wordBox(words, i, desc, measureOf(desc), () => lines(desc), layout[i]);
1077
+ return {
1078
+ ...wordBox(words, i, desc, measureOf(desc), () => lines(desc), own, atWidth, context.resolver.addsParagraphSpacing, noteOf),
1079
+ ...after,
1080
+ };
695
1081
  });
696
- const result = flowFrom(boxes, contentHeight(this.editor.settings), WORD_RULES, reuse);
1082
+ const rules = {
1083
+ ...WORD_RULES,
1084
+ addSpacing: context.resolver.addsParagraphSpacing,
1085
+ evenAndOddHeaders: context.envelope.settings?.evenAndOddHeaders === true,
1086
+ notes: notes?.flowRules(),
1087
+ };
1088
+ const flowHeight = contentHeight(this.editor.settings);
1089
+ let result = flowFrom(boxes, flowHeight, rules, reuse);
1090
+ let facts = pagesOf(boxes, result);
1091
+ // The page count is known once flowed; a header holding it can change what fits.
1092
+ for (let pass = 0; regions && pass < 2 && regions.settle(facts); pass++) {
1093
+ result = flowFrom(boxes, flowHeight, rules);
1094
+ facts = pagesOf(boxes, result);
1095
+ }
1096
+ this.facts = facts;
697
1097
  this.flowed = { nodes, result };
1098
+ this.flowLayout = layout;
1099
+ this.flowBoxes = boxes;
698
1100
  this.stale.clear();
699
1101
  const flowed = result.fragments;
1102
+ slots = flowed.map((fragments) => fragments.map(slotOf));
700
1103
  // Paragraphs: split where their fragments start. Tables: the rows each fragment shows,
701
1104
  // and their blocks split where a row is.
702
1105
  const splitsOf = new Map();
@@ -706,8 +1109,19 @@ export class EditorView {
706
1109
  if (item.unit !== undefined) {
707
1110
  const desc = blocks[item.unit];
708
1111
  const contentStart = units[item.unit].pos + 1;
1112
+ const { section } = layout[i];
1113
+ // A node view splits where its part's line ends (layout px).
1114
+ if (desc.parts) {
1115
+ const { bottoms } = lines(desc);
1116
+ splitsOf.set(item.unit, fragments.slice(1).map((fragment) => bottoms[fragment.fromLine - 1]));
1117
+ return;
1118
+ }
709
1119
  splitsOf.set(item.unit, fragments.slice(1).map((fragment) => {
710
- const offset = lines(desc).starts[fragment.fromLine];
1120
+ // Line numbers are those of the column the fragment is in.
1121
+ const measured = section.unequal
1122
+ ? atWidth(desc, section.columns.widths[fragment.column ?? 0], false).all()
1123
+ : lines(desc);
1124
+ const offset = measured.starts[fragment.fromLine];
711
1125
  // Never split a grapheme cluster across pages.
712
1126
  return clusterBoundary(doc, contentStart + offset, false) - contentStart;
713
1127
  }));
@@ -748,9 +1162,16 @@ export class EditorView {
748
1162
  const firsts = items.map((item, i) => item.frame
749
1163
  ? frames.get(doc.child(i)).wrappers[0]
750
1164
  : blocks[item.unit].dom);
751
- applyGaps(firsts, pages, boxes);
752
- this.place(items.map((item, i) => elementsOf(item, i)), pages, layout);
1165
+ applyGaps(firsts, result.gaps);
1166
+ this.drawRegions();
1167
+ this.drawNotes();
1168
+ this.place(items.map((item, i) => elementsOf(item, i)), pages, slots, layout);
1169
+ this.afterPlace();
753
1170
  }
1171
+ const placed = items.map((item, i) => elementsOf(item, i));
1172
+ const placedPages = pages;
1173
+ const placedSlots = slots;
1174
+ this.placeAgain = () => this.place(placed, placedPages, placedSlots, layout);
754
1175
  // (Wrappers no longer drawn are not in a page: `place` removed them.)
755
1176
  this.frames = frames;
756
1177
  this.frameAt = items.map((item, i) => {
@@ -768,6 +1189,7 @@ export class EditorView {
768
1189
  this.starts = units.map((unit) => unit.pos);
769
1190
  this.indexOf = new Map(blocks.map((desc, i) => [desc, i]));
770
1191
  this.itemPages = new Map(items.map((_, i) => [doc.child(i), pages[i] ?? []]));
1192
+ this.itemSlots = new Map(items.map((_, i) => [doc.child(i), slots[i] ?? []]));
771
1193
  this.owner = new Map(blocks.flatMap((desc) => desc.fragments.map((fragment) => [fragment, desc])));
772
1194
  this.unflowed = this.composing;
773
1195
  this.observeSizes();
@@ -778,6 +1200,1015 @@ export class EditorView {
778
1200
  const records = this.observer.takeRecords();
779
1201
  if (this.composing)
780
1202
  this.pending.push(...records);
1203
+ this.renumberNotes();
1204
+ }
1205
+ /** The note references shown, with their numbers as the last flow's pages make them. */
1206
+ noteReferences() {
1207
+ if (!this.paged)
1208
+ return [];
1209
+ const { doc } = this.state;
1210
+ const { envelope } = wordContext(this.state);
1211
+ const hideDeleted = this.review !== "markup";
1212
+ const all = noteNumbers(doc, envelope, {
1213
+ hideDeleted,
1214
+ pageOf: (_pos, story) => this.notePages.get(story),
1215
+ });
1216
+ this.shownNotes = JSON.stringify(all.map((n) => n.text));
1217
+ return hideDeleted ? all.filter((n) => !n.deleted) : all;
1218
+ }
1219
+ /**
1220
+ * Numbers that restart on each page depend on the flow just made: when they came out otherwise,
1221
+ * once more with them (their width can move a line), at most twice.
1222
+ */
1223
+ renumberNotes() {
1224
+ if (!this.notes || this.composing || this.renumbering > 1)
1225
+ return;
1226
+ const { envelope } = wordContext(this.state);
1227
+ const each = this.sections().some((section) => noteProperties(envelope, "footnote", section).restart === "eachPage");
1228
+ if (!each)
1229
+ return;
1230
+ const shown = this.shownNotes;
1231
+ this.noteReferences();
1232
+ if (this.shownNotes === shown)
1233
+ return;
1234
+ this.renumbering++;
1235
+ try {
1236
+ this.renderPages();
1237
+ }
1238
+ finally {
1239
+ this.renumbering = 0;
1240
+ }
1241
+ }
1242
+ /** The section of each page's bands in the last flow, and each note's place on the pages. */
1243
+ drawNotes() {
1244
+ const { notes, flowed, facts, mount } = this;
1245
+ if (!notes)
1246
+ return;
1247
+ const pieces = flowed ? notePieces(flowed.result) : [];
1248
+ const notePages = new Map();
1249
+ for (const piece of pieces)
1250
+ if (!piece.fromLine && !notePages.has(piece.id))
1251
+ notePages.set(piece.id, piece.page);
1252
+ this.notePages = notePages;
1253
+ const bandSections = new Map();
1254
+ flowed?.result.fragments.forEach((fragments, i) => {
1255
+ const index = this.flowLayout[i]?.section.flow.index ?? 0;
1256
+ for (const f of fragments)
1257
+ bandSections.set(`${f.page}|${f.band ?? 0}`, index);
1258
+ });
1259
+ const groups = notes.groups(pieces, (page, band) => bandSections.get(`${page}|${band}`) ??
1260
+ bandSections.get(`${page}|0`) ??
1261
+ facts[page]?.section ??
1262
+ 0);
1263
+ const foot = groups.filter((group) => !group.inFlow);
1264
+ const known = this.noteElements;
1265
+ const elements = new Map();
1266
+ const shown = [];
1267
+ const note = mount?.side === "note" ? mount : null;
1268
+ for (const group of groups) {
1269
+ const { settings } = this.sheetOfPage(group.page);
1270
+ const fact = facts[group.page];
1271
+ const bottom = fact?.sectionPages
1272
+ ? this.regions.margins(fact.section, fact).bottom
1273
+ : settings.margins.bottom * PX_PER_MM;
1274
+ const place = group.inFlow
1275
+ ? null
1276
+ : notes.footPlace({ left: settings.margins.left * PX_PER_MM, bottom }, notes.stacked(group, foot));
1277
+ // Footnotes beneath the text keep the space after the paragraph above them.
1278
+ const lead = group.inFlow && !group.pieces[0]?.end && flowed
1279
+ ? spaceAfterText(this.flowBoxes, flowed.result, group.page, group.band, group.column)
1280
+ : 0;
1281
+ const key = `${group.page}|${group.band}|${group.column}|${group.inFlow}|${place?.left}|${place?.bottom}|${lead}|${notes.keyOf(group)}`;
1282
+ let element = known.get(key);
1283
+ if (!element) {
1284
+ element = notes.groupElement(group, place, (piece) => piece.id === note?.id && !piece.fromLine
1285
+ ? note.region.element
1286
+ : notes.pieceElement(piece, group), lead);
1287
+ if (note && element.contains(note.wrapper))
1288
+ note.moved = true;
1289
+ }
1290
+ elements.set(key, element);
1291
+ const page = shown[group.page] ?? { foot: [], flow: new Map() };
1292
+ shown[group.page] = page;
1293
+ if (!group.inFlow)
1294
+ page.foot.push(element);
1295
+ else {
1296
+ const slot = `${group.band}|${group.column}`;
1297
+ page.flow.set(slot, [...(page.flow.get(slot) ?? []), element]);
1298
+ }
1299
+ }
1300
+ this.noteElements = elements;
1301
+ this.pageNotes = Array.from({ length: shown.length }, (_, p) => shown[p] ?? { foot: [], flow: new Map() });
1302
+ if (!note)
1303
+ return;
1304
+ // Its reference went (undone, or hidden with the changes): the note closes.
1305
+ const page = notePages.get(note.id);
1306
+ if (page === undefined)
1307
+ queueMicrotask(() => this.closeStory(true));
1308
+ else
1309
+ note.page = page;
1310
+ }
1311
+ /** Layout px per px on screen: what a scaled ancestor (`transform`, `zoom`) multiplies by. */
1312
+ scale() {
1313
+ const page = this.pages[0];
1314
+ if (!page)
1315
+ return 1;
1316
+ return this.paged
1317
+ ? layoutScale(page, this.sheets[0].settings)
1318
+ : page.getBoundingClientRect().width / page.offsetWidth || 1;
1319
+ }
1320
+ /** Whether the headers' and footers' heights differ from when the pages were last flowed. */
1321
+ regionsChanged(regions, spans) {
1322
+ const { stories, settings } = wordContext(this.state).envelope;
1323
+ const sections = spans.map((span) => span.setup);
1324
+ const known = this.regionsFor;
1325
+ if (known &&
1326
+ known.stories === stories &&
1327
+ known.settings === settings &&
1328
+ known.sections.length === sections.length &&
1329
+ known.sections.every((section, i) => section === sections[i]))
1330
+ return false;
1331
+ this.regionsFor = { stories, settings, sections };
1332
+ const key = `${regions.key()}|${this.notes?.key() ?? ""}`;
1333
+ // Even and odd headers also decide the blank pages: the flow depends on them.
1334
+ const changed = key !== this.regionsKey ||
1335
+ (known?.settings !== settings &&
1336
+ known?.settings?.evenAndOddHeaders !==
1337
+ settings?.evenAndOddHeaders);
1338
+ this.regionsKey = key;
1339
+ return changed;
1340
+ }
1341
+ /**
1342
+ * Gives every page the header and footer the last flow says, redrawing those that changed. The
1343
+ * one holding the story being edited stays; it follows the story if its page no longer shows it.
1344
+ */
1345
+ drawRegions() {
1346
+ const { regions, facts } = this;
1347
+ // A note open for editing is `drawNotes`' to look after.
1348
+ const mount = this.mount?.side === "note" ? null : this.mount;
1349
+ if (!regions)
1350
+ return;
1351
+ const sides = ["header", "footer"];
1352
+ const wanted = facts.map((page) =>
1353
+ // Word's blank page before an even or odd page section has neither.
1354
+ page.sectionPages
1355
+ ? {
1356
+ header: regions.drawing(page.section, "header", page),
1357
+ footer: regions.drawing(page.section, "footer", page),
1358
+ }
1359
+ : { header: null, footer: null });
1360
+ const shows = (p) => !!mount && wanted[p]?.[mount.side]?.id === mount.id;
1361
+ // Its page, while it shows it. Replaced there (the section unlinked, another variant turned
1362
+ // on) it does not follow the old story to another page: the page's own opens.
1363
+ const replaced = !!mount && facts[mount.page]?.section === mount.section;
1364
+ const home = !mount
1365
+ ? -1
1366
+ : shows(mount.page)
1367
+ ? mount.page
1368
+ : replaced
1369
+ ? -1
1370
+ : wanted.findIndex((_, p) => shows(p));
1371
+ this.pageRegions = facts.map((page, p) => {
1372
+ const own = {};
1373
+ for (const side of sides) {
1374
+ const drawing = wanted[p]?.[side];
1375
+ if (!drawing)
1376
+ continue;
1377
+ if (mount && p === home && side === mount.side) {
1378
+ own[side] = mount.region;
1379
+ if (mount.region.drawing !== drawing.content) {
1380
+ mount.region.drawing = drawing.content;
1381
+ const copy = drawing.content.content.cloneNode(true);
1382
+ copy.style.display = "none";
1383
+ mount.region.element
1384
+ .querySelector(`:scope > .${REGION_CONTENT_CLASS}`)
1385
+ ?.replaceWith(copy);
1386
+ mount.wrapper.style.paddingBottom = copy.style.paddingBottom;
1387
+ }
1388
+ continue;
1389
+ }
1390
+ const known = this.pageRegions[p]?.[side];
1391
+ if (known?.drawing === drawing.content && known.section === page.section) {
1392
+ own[side] = known;
1393
+ continue;
1394
+ }
1395
+ const element = regions.element(page.section, side);
1396
+ element.append(drawing.content.content.cloneNode(true));
1397
+ own[side] = { element, drawing: drawing.content, section: page.section, id: drawing.id };
1398
+ }
1399
+ return own;
1400
+ });
1401
+ this.pageMargins = facts.map((page, p) => {
1402
+ if (!page.sectionPages)
1403
+ return { top: "", bottom: "" };
1404
+ const { top, bottom } = regions.margins(page.section, page);
1405
+ const { margins } = this.sheetOfPage(p).settings;
1406
+ return {
1407
+ top: Math.abs(top - margins.top * PX_PER_MM) < 0.01 ? "" : `${top}px`,
1408
+ bottom: Math.abs(bottom - margins.bottom * PX_PER_MM) < 0.01 ? "" : `${bottom}px`,
1409
+ };
1410
+ });
1411
+ if (!mount)
1412
+ return;
1413
+ // Not shown anywhere any more (a variant turned on or off): the page's own story opens.
1414
+ if (home < 0)
1415
+ queueMicrotask(this.reopenStory);
1416
+ else if (home !== mount.page) {
1417
+ mount.page = home;
1418
+ mount.moved = true;
1419
+ }
1420
+ }
1421
+ /** The page setup page `p` has, or will have once placed. */
1422
+ sheetOfPage(p) {
1423
+ return this.sheets[p] ?? this.sheets[this.sheets.length - 1] ?? this.lastSheet();
1424
+ }
1425
+ /**
1426
+ * After a story changed: its occurrences redrawn. False when a height changed, which takes a
1427
+ * new flow (`render`), or during a composition.
1428
+ */
1429
+ redrawRegions() {
1430
+ const { regions } = this;
1431
+ if (!regions)
1432
+ return true;
1433
+ if (this.composing)
1434
+ return true;
1435
+ const context = wordContext(this.state);
1436
+ const spans = sectionSpans(this.state.doc, context.envelope.section);
1437
+ regions.setDocument(context.envelope, spans.map((span) => span.setup), context.resolver);
1438
+ this.notes?.setDocument(context.envelope, spans.map((span) => span.setup), context.resolver, this.noteReferences());
1439
+ if (this.regionsChanged(regions, spans)) {
1440
+ this.flowed = null;
1441
+ return false;
1442
+ }
1443
+ this.drawRegions();
1444
+ this.drawNotes();
1445
+ this.placeAgain?.();
1446
+ this.afterPlace();
1447
+ this.observer.takeRecords();
1448
+ return true;
1449
+ }
1450
+ /** The story being edited, moved with its region: the focus goes back to it. */
1451
+ afterPlace() {
1452
+ this.drawControls();
1453
+ this.drawMatches();
1454
+ if (!this.mount?.moved)
1455
+ return;
1456
+ this.mount.moved = false;
1457
+ this.mount.view.focus();
1458
+ }
1459
+ // ---------- stories on their pages (ADR-0007) ----------
1460
+ /** What the toolbar and code open stories through (`Editor.storyView`). */
1461
+ stories = ((view) => ({
1462
+ get open() {
1463
+ const { mount } = view;
1464
+ return mount
1465
+ ? { id: mount.id, side: mount.side, variant: mount.variant, section: mount.section }
1466
+ : null;
1467
+ },
1468
+ edit: (side, page) => view.openStory(side, page),
1469
+ editNote: (id) => view.openNote(id),
1470
+ toReference: () => view.toReference(),
1471
+ close: () => view.closeStory(),
1472
+ get fieldLayout() {
1473
+ return view.fieldLayout();
1474
+ },
1475
+ updateFields: (options, editor) => view.updateFields(options, editor),
1476
+ showMatches: (found) => view.showMatches(found),
1477
+ reveal: (target, options) => view.reveal(target, options),
1478
+ goToPage: (page, options) => view.goToPage(page, options),
1479
+ focus: () => view.focus(),
1480
+ }))(this);
1481
+ /** Makes this view the one `Editor.storyView` speaks for, telling listeners if it was not. */
1482
+ claimStories() {
1483
+ if (!this.paged || this.editor.storyView === this.stories)
1484
+ return;
1485
+ const first = !this.editor.storyView;
1486
+ this.editor.storyView = this.stories;
1487
+ if (!first)
1488
+ this.editor.storyChanged();
1489
+ }
1490
+ // ---------- find, and going places (11.11) ----------
1491
+ /**
1492
+ * Marks what find found: on the pages, in the story open, and in the drawn copies of the others.
1493
+ * Nothing of it is in the document or the pages' DOM, and it does not print. The current match is
1494
+ * scrolled to when it is where the view can show it.
1495
+ */
1496
+ showMatches(found) {
1497
+ this.showFound(found);
1498
+ const { current, scroll } = found ?? {};
1499
+ if (!current || !scroll)
1500
+ return;
1501
+ if (current.story === this.matchStory)
1502
+ this.scrollToRange(current.from, current.to);
1503
+ else if (current.story === this.mount?.id)
1504
+ this.mount?.view.scrollToRange(current.from, current.to);
1505
+ }
1506
+ /** The screen ranges of `from..to` in one paragraph: one per text node it covers. */
1507
+ rangesOf(from, to) {
1508
+ const { doc } = this.state;
1509
+ if (to > doc.content.size)
1510
+ return [];
1511
+ const $from = doc.resolve(from);
1512
+ if (!$from.parent.isTextblock)
1513
+ return [];
1514
+ const desc = this.blocks[this.blockFrom($from.before())];
1515
+ if (!desc)
1516
+ return [];
1517
+ const start = $from.start();
1518
+ const out = [];
1519
+ for (const leaf of desc.leaves) {
1520
+ const at = start + leaf.offset;
1521
+ const a = Math.max(from, at);
1522
+ const b = Math.min(to, at + leaf.size);
1523
+ if (a >= b || hiddenIn(leaf.dom, desc.dom))
1524
+ continue;
1525
+ const range = this.host.ownerDocument.createRange();
1526
+ if (leaf.dom.nodeType === Node.TEXT_NODE) {
1527
+ range.setStart(leaf.dom, a - at);
1528
+ range.setEnd(leaf.dom, b - at);
1529
+ }
1530
+ else
1531
+ range.selectNodeContents(leaf.dom);
1532
+ out.push(range);
1533
+ }
1534
+ return out;
1535
+ }
1536
+ /** The pages on the screen and a screen around it: only these carry marks. */
1537
+ pagesNearView() {
1538
+ const height = this.host.ownerDocument.defaultView?.innerHeight ?? 0;
1539
+ const near = new Set();
1540
+ this.pages.forEach((page, i) => {
1541
+ const { top, bottom } = page.getBoundingClientRect();
1542
+ if (bottom >= -height && top <= 2 * height)
1543
+ near.add(i);
1544
+ });
1545
+ return near;
1546
+ }
1547
+ drawMatches() {
1548
+ const { found, mount } = this;
1549
+ if (mount) {
1550
+ mount.view.matchStory = mount.id;
1551
+ mount.view.showFound(found);
1552
+ }
1553
+ if (!found) {
1554
+ this.matchMarks.set([], []);
1555
+ this.matchPages = "";
1556
+ return;
1557
+ }
1558
+ injectStyles(this.host);
1559
+ const { doc } = this.state;
1560
+ const near = this.pagesNearView();
1561
+ this.matchPages = [...near].join();
1562
+ // What the near pages hold, as positions: of the body's top-level nodes on them.
1563
+ let low = 0;
1564
+ let high = doc.content.size;
1565
+ if (this.paged) {
1566
+ low = high + 1;
1567
+ high = -1;
1568
+ doc.forEach((node, offset) => {
1569
+ const pages = this.itemPages.get(node);
1570
+ if (pages && !pages.some((page) => near.has(page)))
1571
+ return;
1572
+ low = Math.min(low, offset);
1573
+ high = Math.max(high, offset + node.nodeSize);
1574
+ });
1575
+ }
1576
+ // A tree's matches stand together, in order: those near are found by halving.
1577
+ const { matches } = found;
1578
+ let start = matches.findIndex((m) => m.story === this.matchStory);
1579
+ if (start < 0)
1580
+ start = matches.length;
1581
+ let end = start;
1582
+ while (end < matches.length && matches[end]?.story === this.matchStory)
1583
+ end++;
1584
+ let first = start;
1585
+ for (let last = end; first < last;) {
1586
+ const mid = (first + last) >> 1;
1587
+ if (matches[mid].to <= low)
1588
+ first = mid + 1;
1589
+ else
1590
+ last = mid;
1591
+ }
1592
+ const all = [];
1593
+ for (let i = first; i < end && matches[i].from < high; i++) {
1594
+ const { from, to } = matches[i];
1595
+ all.push(...this.rangesOf(from, to));
1596
+ }
1597
+ const others = new Set();
1598
+ for (const [i, { story }] of matches.entries())
1599
+ if ((i < start || i >= end) && story !== null && story !== mount?.id)
1600
+ others.add(story);
1601
+ const { current, query, matchCase, wholeWord } = found;
1602
+ const here = current?.story === this.matchStory ? current : null;
1603
+ if (others.size) {
1604
+ const options = { matchCase, wholeWord };
1605
+ const add = (root) => {
1606
+ if (root)
1607
+ all.push(...rangesInText(root, query, options));
1608
+ };
1609
+ for (const p of near) {
1610
+ const { header, footer } = this.pageRegions[p] ?? {};
1611
+ for (const region of [header, footer])
1612
+ if (region && others.has(region.id))
1613
+ add(region.element.querySelector(`:scope > .${REGION_CONTENT_CLASS}`));
1614
+ for (const note of this.pages[p]?.querySelectorAll(`[${NOTE_ATTR}]`) ?? [])
1615
+ if (others.has(note.getAttribute(NOTE_ATTR)))
1616
+ add(note);
1617
+ }
1618
+ }
1619
+ this.matchMarks.set(all, here ? this.rangesOf(here.from, here.to) : []);
1620
+ }
1621
+ /** Scrolling brings other pages near: their marks are drawn, once per frame. */
1622
+ onMatchScroll = () => {
1623
+ const win = this.host.ownerDocument.defaultView;
1624
+ if (this.matchFrame || !win)
1625
+ return;
1626
+ this.matchFrame = win.requestAnimationFrame(() => {
1627
+ this.matchFrame = 0;
1628
+ if (this.found && [...this.pagesNearView()].join() !== this.matchPages)
1629
+ this.drawMatches();
1630
+ });
1631
+ };
1632
+ /** What find shows here, marked; a story's view is told by its page's view. */
1633
+ showFound(found) {
1634
+ const doc = this.host.ownerDocument;
1635
+ if (this.paged && !this.found !== !found) {
1636
+ if (found)
1637
+ doc.addEventListener("scroll", this.onMatchScroll, SCROLL_OPTIONS);
1638
+ else
1639
+ doc.removeEventListener("scroll", this.onMatchScroll, SCROLL_OPTIONS);
1640
+ }
1641
+ this.found = found;
1642
+ this.drawMatches();
1643
+ }
1644
+ scrollToRange(from, to) {
1645
+ let rect = this.rangesOf(from, to)[0]?.getClientRects?.()[0];
1646
+ if (!rect) {
1647
+ // A place, not a stretch of text: what holds it.
1648
+ const { node } = this.domFromPos(from);
1649
+ rect = (node instanceof Element ? node : node.parentElement)?.getBoundingClientRect();
1650
+ }
1651
+ // With room around it: a panel may float over the top of the window.
1652
+ if (rect)
1653
+ scrollRectIntoView(this.host, { top: rect.top - REVEAL_ABOVE, bottom: rect.bottom + 48 });
1654
+ }
1655
+ /** Opens story `id` where a page shows it, leaving the focus where it is. */
1656
+ openForReveal(id) {
1657
+ const kind = wordContext(this.state)?.stories.get(id)?.kind;
1658
+ if (kind === "footnote" || kind === "endnote")
1659
+ return this.openNote(id, false);
1660
+ if (kind !== "header" && kind !== "footer")
1661
+ return false;
1662
+ const page = this.pageRegions.findIndex((regions) => regions[kind]?.id === id);
1663
+ return page >= 0 && this.openStory(kind, page, false, false);
1664
+ }
1665
+ /**
1666
+ * Selects `target` and scrolls to it: in the body (leaving a story that is open), or in its story,
1667
+ * opened where it is. `focus`: the document takes the focus. False when no page shows it.
1668
+ */
1669
+ reveal({ story, from, to }, { focus = false } = {}) {
1670
+ if (story === null) {
1671
+ this.closeStory(false);
1672
+ const { doc } = this.state;
1673
+ if (to > doc.content.size)
1674
+ return false;
1675
+ this.editor.dispatch(this.state.tr.setSelection(TextSelection.create(doc, from, to)));
1676
+ if (focus)
1677
+ this.focus();
1678
+ this.scrollToRange(from, to);
1679
+ return true;
1680
+ }
1681
+ if (this.mount?.id !== story && !this.openForReveal(story))
1682
+ return false;
1683
+ const { mount } = this;
1684
+ if (!mount)
1685
+ return false;
1686
+ mount.view.editor.select(from, to);
1687
+ if (focus)
1688
+ mount.view.focus();
1689
+ mount.view.scrollToRange(from, to);
1690
+ return true;
1691
+ }
1692
+ /** The caret to the start of page `page` (1-based) and the page into view. */
1693
+ goToPage(page, { focus = false } = {}) {
1694
+ const element = this.pages[page - 1];
1695
+ if (!element)
1696
+ return false;
1697
+ this.closeStory(false);
1698
+ search: for (const [i, desc] of this.blocks.entries()) {
1699
+ for (const [f, fragment] of desc.fragments.entries()) {
1700
+ if (fragment.closest(".foli-page") !== element)
1701
+ continue;
1702
+ // A block leaf's parts (a node view split across pages) are all before it.
1703
+ const start = desc.node.isTextblock
1704
+ ? this.starts[i] + 1 + (f ? desc.splits[f - 1] : 0)
1705
+ : this.starts[i];
1706
+ const { doc } = this.state;
1707
+ this.editor.dispatch(this.state.tr.setSelection(Selection.near(doc.resolve(Math.min(start, doc.content.size)))));
1708
+ break search;
1709
+ }
1710
+ }
1711
+ if (focus)
1712
+ this.focus();
1713
+ scrollRectIntoView(this.host, element.getBoundingClientRect());
1714
+ return true;
1715
+ }
1716
+ /** Word's keys for finding and going places, when the app shows something for them. */
1717
+ navigationKey(name) {
1718
+ const request = Object.hasOwn(NAVIGATION_KEYS, name) ? NAVIGATION_KEYS[name] : undefined;
1719
+ return !!request && this.editor.navigation?.(request) === true;
1720
+ }
1721
+ // ---------- content controls ----------
1722
+ /** The frames of content controls, drawn again (a render takes them off the pages). */
1723
+ drawControls() {
1724
+ if (!this.composing)
1725
+ this.controlChrome.draw(!this.mount);
1726
+ }
1727
+ /** Where a control's content is on the screen: its lines, or its blocks by page. */
1728
+ controlRects(range) {
1729
+ if (range.level !== "inline") {
1730
+ const byPage = new Map();
1731
+ for (let i = this.blockFrom(range.from); i < this.blocks.length; i++) {
1732
+ if (this.starts[i] >= range.to)
1733
+ break;
1734
+ for (const fragment of this.blocks[i].fragments) {
1735
+ if (!this.host.contains(fragment))
1736
+ continue;
1737
+ const rect = fragment.getBoundingClientRect();
1738
+ const page = fragment.closest(".foli-page,.foli-story-flow");
1739
+ const known = byPage.get(page);
1740
+ const left = Math.min(known?.left ?? rect.left, rect.left);
1741
+ const top = Math.min(known?.top ?? rect.top, rect.top);
1742
+ byPage.set(page, boxOf(left, top, Math.max(known?.right ?? rect.right, rect.right) - left, Math.max(known?.bottom ?? rect.bottom, rect.bottom) - top));
1743
+ }
1744
+ }
1745
+ return [...byPage.values()];
1746
+ }
1747
+ return this.controlContentRects(range);
1748
+ }
1749
+ /** Where what a control's content shows is on the screen. */
1750
+ controlContentRects(range) {
1751
+ const dom = this.host.ownerDocument.createRange();
1752
+ const start = this.domFromPos(range.contentFrom);
1753
+ const end = this.domFromPos(range.contentTo);
1754
+ dom.setStart(start.node, start.offset);
1755
+ dom.setEnd(end.node, end.offset);
1756
+ const rects = [...(dom.getClientRects?.() ?? [])].filter((rect) => rect.width > 0);
1757
+ if (rects.length)
1758
+ return rects;
1759
+ // Nothing in it: a thin box where it is.
1760
+ const element = start.node.nodeType === Node.ELEMENT_NODE
1761
+ ? start.node
1762
+ : start.node.parentElement;
1763
+ const rect = dom.getBoundingClientRect?.();
1764
+ const box = rect?.height ? rect : element?.getBoundingClientRect();
1765
+ return box ? [boxOf(box.left, box.top, 4, box.height)] : [];
1766
+ }
1767
+ /**
1768
+ * Left and Right stop on each side of a content control's edge, as Word's caret does (browsers
1769
+ * cannot see the difference). Alt+Down, which opens a list or date picker, is in `viewKey`.
1770
+ */
1771
+ controlKey(name) {
1772
+ if (name !== "ArrowLeft" && name !== "ArrowRight")
1773
+ return false;
1774
+ const { selection, doc } = this.state;
1775
+ if (!(selection instanceof TextSelection) || !wordContext(this.state)?.envelope.controls)
1776
+ return false;
1777
+ const forward = name === "ArrowRight";
1778
+ const range = controlAt(doc, selection.from);
1779
+ if (!selection.empty) {
1780
+ // A placeholder is one thing: the arrows go past it.
1781
+ if (range?.level !== "inline" ||
1782
+ !controlProperties(this.state, range.id)?.placeholder?.showing ||
1783
+ selection.from !== range.contentFrom ||
1784
+ selection.to !== range.contentTo)
1785
+ return false;
1786
+ this.dispatch(this.state.tr.setSelection(TextSelection.create(doc, forward ? range.to : range.from)));
1787
+ return true;
1788
+ }
1789
+ const { $from } = selection;
1790
+ const next = forward ? $from.nodeAfter : $from.nodeBefore;
1791
+ if (next?.type.name !== "controlStart" && next?.type.name !== "controlEnd")
1792
+ return false;
1793
+ this.dispatch(this.state.tr.setSelection(TextSelection.create(doc, $from.pos + (forward ? 1 : -1))));
1794
+ return true;
1795
+ }
1796
+ // ---------- fields ----------
1797
+ /** The pages as last flowed, as fields need them; null without pages. */
1798
+ fieldLayout() {
1799
+ if (!this.regions || !this.facts.length)
1800
+ return null;
1801
+ return {
1802
+ pages: this.facts.length,
1803
+ pageAt: (pos) => {
1804
+ const { node } = this.domFromPos(Math.min(pos, this.state.doc.content.size));
1805
+ const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
1806
+ const page = this.facts[this.pages.indexOf(element?.closest(".foli-page"))];
1807
+ if (!page)
1808
+ return null;
1809
+ const format = this.sections()[page.section]?.pageNumbers?.format;
1810
+ return { number: page.number, sectionPages: page.sectionPages, format };
1811
+ },
1812
+ };
1813
+ }
1814
+ /**
1815
+ * Updates fields from the pages shown: all of them, or those `options.only` says, of the body or
1816
+ * of `editor` (a story's). What that does to the pages is taken in by a second pass over what
1817
+ * depends on them, in the same undo step.
1818
+ */
1819
+ updateFields(options = {}, editor = this.editor) {
1820
+ // A story's view has no pages: the view of the body has.
1821
+ const main = this.regions ? null : this.editor.storyView;
1822
+ if (main)
1823
+ return main.updateFields(options, editor);
1824
+ if (this.composing)
1825
+ this.onCompositionEnd();
1826
+ const report = updateFields(editor, { ...options, layout: this.fieldLayout() });
1827
+ const { only } = options;
1828
+ const range = !!only && typeof only !== "function";
1829
+ if (!report.updated || (range && !report.rebuilt))
1830
+ return report;
1831
+ const follows = (field) => range
1832
+ ? field.parent?.name === "TOC"
1833
+ : PAGE_DEPENDENT.has(field.name) && (typeof only !== "function" || only(field));
1834
+ const again = updateFields(editor, {
1835
+ ...options,
1836
+ layout: this.fieldLayout(),
1837
+ only: follows,
1838
+ continues: true,
1839
+ });
1840
+ return { ...report, updated: report.updated + again.updated };
1841
+ }
1842
+ /**
1843
+ * Prints what the document is now: fields updated (one undo step), then the browser's dialog.
1844
+ */
1845
+ print() {
1846
+ try {
1847
+ this.updateFields();
1848
+ }
1849
+ finally {
1850
+ this.host.ownerDocument.defaultView?.print();
1851
+ }
1852
+ }
1853
+ /**
1854
+ * Left and Right next to a field's markers: the browser's move starts where something can be
1855
+ * seen, or the markers (empty elements) cost WebKit a key press each. With codes shown the
1856
+ * view makes the move itself, over the whole field; whether it did.
1857
+ */
1858
+ skipFieldParts(event) {
1859
+ const forward = event.key === "ArrowRight";
1860
+ if ((!forward && event.key !== "ArrowLeft") || event.ctrlKey || event.altKey || event.metaKey)
1861
+ return false;
1862
+ const { selection, doc } = this.state;
1863
+ // Shift extends by itself: an extended DOM selection would lose its anchor to the same spot.
1864
+ if (!(selection instanceof TextSelection) || event.shiftKey || !selection.empty)
1865
+ return false;
1866
+ const stop = caretStop(this.state, selection.head, forward);
1867
+ const sel = this.host.ownerDocument.getSelection();
1868
+ if (stop === selection.head || !sel)
1869
+ return false;
1870
+ if (this.fieldCodes) {
1871
+ this.dispatch(this.state.tr.setSelection(TextSelection.create(doc, stop)));
1872
+ return true;
1873
+ }
1874
+ const { node, offset } = this.domFromPos(stop);
1875
+ sel.collapse(node, offset);
1876
+ return false;
1877
+ }
1878
+ /** F9 and Alt+F9, as in Word. */
1879
+ fieldKey(name) {
1880
+ if (name === "Alt-F9") {
1881
+ this.run(toggleFieldCodes);
1882
+ return true;
1883
+ }
1884
+ if (name !== "F9")
1885
+ return false;
1886
+ if (!this.editable)
1887
+ return true;
1888
+ const { selection } = this.state;
1889
+ this.updateFields(selection instanceof AllSelection ? {} : { only: { from: selection.from, to: selection.to } });
1890
+ return true;
1891
+ }
1892
+ /** Shades what shows the fields the selection is in (not printed): the outermost of each. */
1893
+ showSelectedFields() {
1894
+ const { selection, doc } = this.state;
1895
+ const wanted = new Set();
1896
+ const fields = selection instanceof TextSelection ? fieldsIn(doc) : [];
1897
+ const touched = (field) => selection.empty
1898
+ ? field.from < selection.from && selection.from < field.to
1899
+ : field.from < selection.to && field.to > selection.from;
1900
+ for (const field of fields) {
1901
+ if (!touched(field) || (field.parent && touched(field.parent)))
1902
+ continue;
1903
+ const [from, to] = this.fieldCodes
1904
+ ? [field.from, field.codeEnd + 1]
1905
+ : [field.resultFrom, field.resultTo];
1906
+ const first = Math.max(this.blockFrom(from) - 1, 0);
1907
+ for (let i = first; i < this.blocks.length; i++) {
1908
+ const start = this.starts[i] + 1;
1909
+ if (start > to)
1910
+ break;
1911
+ const desc = this.blocks[i];
1912
+ for (const leaf of desc.leaves) {
1913
+ const at = start + leaf.offset;
1914
+ if (at + leaf.size <= from || at >= to || !leaf.size)
1915
+ continue;
1916
+ if (hiddenIn(leaf.dom, desc.dom))
1917
+ continue;
1918
+ const element = leaf.dom.nodeType === Node.TEXT_NODE ? leaf.dom.parentElement : leaf.dom;
1919
+ if (element instanceof Element && element.textContent)
1920
+ wanted.add(element);
1921
+ }
1922
+ }
1923
+ }
1924
+ for (const element of this.shadedFields)
1925
+ if (!wanted.has(element))
1926
+ element.removeAttribute(FIELD_SELECTED_ATTR);
1927
+ if (wanted.size)
1928
+ injectStyles(this.host);
1929
+ for (const element of wanted)
1930
+ element.setAttribute(FIELD_SELECTED_ATTR, "");
1931
+ this.shadedFields = [...wanted];
1932
+ }
1933
+ /** The sections of the document, in order. */
1934
+ sections() {
1935
+ const { envelope } = wordContext(this.state);
1936
+ return sectionSpans(this.state.doc, envelope.section).map((span) => span.setup);
1937
+ }
1938
+ /** The page the selection's head is on. */
1939
+ selectionPage() {
1940
+ const { node } = this.domFromPos(this.state.selection.head);
1941
+ const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
1942
+ return Math.max(this.pages.indexOf(element?.closest(".foli-page")), 0);
1943
+ }
1944
+ /**
1945
+ * Opens the header or footer of page `at` (by default the selection's) for editing where it is;
1946
+ * made first when the page has none. Whether it is open now.
1947
+ */
1948
+ openStory(side, at = this.selectionPage(), create = true, focus = true) {
1949
+ if (!this.regions || !this.editable || this.composing)
1950
+ return false;
1951
+ // Word's blank page has none: the next page's.
1952
+ let p = at;
1953
+ while (this.facts[p] && !this.facts[p]?.sectionPages)
1954
+ p++;
1955
+ const page = this.facts[p];
1956
+ if (!page)
1957
+ return false;
1958
+ const context = wordContext(this.state);
1959
+ const setup = this.sections()[page.section];
1960
+ const even = context.envelope.settings?.evenAndOddHeaders === true;
1961
+ const variant = pageVariant(setup, page, even);
1962
+ const before = storyOfSection(this.sections(), page.section, side, variant);
1963
+ if (this.mount?.id === before?.id && this.mount?.side === side && this.mount?.page === p) {
1964
+ if (focus)
1965
+ this.mount?.view.focus();
1966
+ return true;
1967
+ }
1968
+ this.closeStory(false);
1969
+ if (!before && (!create || !this.editor.run(ensureStory(side, variant, page.section))))
1970
+ return false;
1971
+ const found = storyOfSection(this.sections(), page.section, side, variant);
1972
+ const editor = found && this.editor.story(found.id);
1973
+ const region = this.pageRegions[p]?.[side];
1974
+ if (!found || !editor || !region)
1975
+ return false;
1976
+ this.mountStory(editor, { id: found.id, side, variant, section: page.section, page: p, region }, side === "header" ? "Header" : "Footer", undefined, focus);
1977
+ return true;
1978
+ }
1979
+ /**
1980
+ * Opens note `id`, or the one whose reference is at the selection, in place: shown whole at its
1981
+ * reference's page. Whether it is open now.
1982
+ */
1983
+ openNote(id, focus = true) {
1984
+ const { notes } = this;
1985
+ if (!notes || !this.editable || this.composing)
1986
+ return false;
1987
+ const story = id ?? noteAtSelection(this.state)?.story;
1988
+ if (!story)
1989
+ return false;
1990
+ if (this.mount?.id === story) {
1991
+ if (focus)
1992
+ this.mount.view.focus();
1993
+ return true;
1994
+ }
1995
+ this.closeStory(false);
1996
+ const editor = this.editor.story(story);
1997
+ if (!editor)
1998
+ return false;
1999
+ notes.open = story;
2000
+ this.flowed = null;
2001
+ this.render();
2002
+ const element = this.host.querySelector(`[${NOTE_ATTR}="${CSS.escape(story)}"]`);
2003
+ const page = this.notePages.get(story);
2004
+ if (!element || page === undefined) {
2005
+ notes.open = null;
2006
+ this.flowed = null;
2007
+ this.render();
2008
+ return false;
2009
+ }
2010
+ const region = { element, drawing: {}, section: 0, id: story };
2011
+ const texts = () => noteTexts(noteNumbers(this.state.doc, wordContext(this.state).envelope));
2012
+ this.mountStory(editor, { id: story, side: "note", variant: "default", section: 0, page, region }, "Note", () => texts().get(story) ?? "", focus);
2013
+ editor.select(Selection.atEnd(editor.state.doc).from);
2014
+ return true;
2015
+ }
2016
+ /** From the note being edited back to its reference, the caret after it. */
2017
+ toReference() {
2018
+ const { mount } = this;
2019
+ if (mount?.side !== "note")
2020
+ return false;
2021
+ const reference = noteNumbers(this.state.doc, wordContext(this.state).envelope).find((n) => n.story === mount.id);
2022
+ this.closeStory(false);
2023
+ if (reference)
2024
+ this.dispatch(this.state.tr.setSelection(TextSelection.create(this.state.doc, reference.pos + 1)));
2025
+ this.focus();
2026
+ return true;
2027
+ }
2028
+ /** Puts `editor`'s story on its page, in `place`, the body read-only and dimmed around it. */
2029
+ mountStory(editor, place, label, noteMark, focus = true) {
2030
+ const { region } = place;
2031
+ injectStyles(this.host);
2032
+ this.observer.disconnect();
2033
+ this.host.setAttribute("contenteditable", "false");
2034
+ this.host.setAttribute("aria-readonly", "true");
2035
+ this.host.classList.add("foli-in-story");
2036
+ const doc = this.host.ownerDocument;
2037
+ const wrapper = doc.createElement("div");
2038
+ wrapper.className = "foli-story-mount";
2039
+ wrapper.setAttribute("contenteditable", "false");
2040
+ wrapper.style.userSelect = "text";
2041
+ wrapper.style.setProperty("-webkit-user-select", "text");
2042
+ const inner = doc.createElement("div");
2043
+ inner.setAttribute("aria-label", label);
2044
+ wrapper.append(inner);
2045
+ const shown = region.element.querySelector(`:scope > .${REGION_CONTENT_CLASS}`);
2046
+ if (shown) {
2047
+ shown.style.display = "none";
2048
+ wrapper.style.paddingBottom = shown.style.paddingBottom;
2049
+ }
2050
+ region.element.append(wrapper);
2051
+ const view = new EditorView(inner, editor, {
2052
+ paged: false,
2053
+ upload: this.upload ?? null,
2054
+ resource: this.resource ?? null,
2055
+ ...(noteMark ? { noteMark } : {}),
2056
+ });
2057
+ wrapper.addEventListener("keydown", (event) => {
2058
+ if (event.isComposing || view.composing)
2059
+ return;
2060
+ // Unless the story's view ran a user's binding of the key.
2061
+ if (!event.defaultPrevented && keyName(event) === NOTE_KEY && this.toReference()) {
2062
+ // Not on to the body, which would open the note again.
2063
+ event.preventDefault();
2064
+ event.stopPropagation();
2065
+ return;
2066
+ }
2067
+ if (event.key !== "Escape")
2068
+ return;
2069
+ event.preventDefault();
2070
+ this.closeStory(true);
2071
+ });
2072
+ this.mount = { ...place, wrapper, view, moved: false };
2073
+ // With several views of the editor, the one in use answers for its story.
2074
+ wrapper.addEventListener("focusin", () => this.claimStories());
2075
+ this.claimStories();
2076
+ if (focus)
2077
+ view.focus();
2078
+ this.drawMatches();
2079
+ this.editor.storyChanged();
2080
+ }
2081
+ /** Finishes a running composition, its text going into the model. */
2082
+ endComposition() {
2083
+ if (this.composing)
2084
+ this.onCompositionEnd();
2085
+ }
2086
+ /** Leaves the story being edited; `focus`: the body takes the focus, with its selection back. */
2087
+ closeStory(focus = true) {
2088
+ const { mount } = this;
2089
+ if (!mount)
2090
+ return;
2091
+ mount.view.endComposition();
2092
+ this.mount = null;
2093
+ mount.view.destroy();
2094
+ mount.wrapper.remove();
2095
+ const shown = mount.region.element.querySelector(`:scope > .${REGION_CONTENT_CLASS}`);
2096
+ if (shown)
2097
+ shown.style.display = "";
2098
+ if (mount.side === "note" && this.notes) {
2099
+ this.notes.open = null;
2100
+ this.flowed = null;
2101
+ if (!this.destroyed)
2102
+ this.render();
2103
+ }
2104
+ this.host.classList.remove("foli-in-story");
2105
+ this.host.setAttribute("contenteditable", String(this.editable));
2106
+ if (this.editable)
2107
+ this.host.removeAttribute("aria-readonly");
2108
+ this.observer.takeRecords();
2109
+ this.observer.observe(this.host, { childList: true, characterData: true, subtree: true });
2110
+ if (focus && !this.destroyed)
2111
+ this.focus();
2112
+ if (!this.destroyed)
2113
+ this.drawMatches();
2114
+ this.editor.storyChanged();
2115
+ }
2116
+ /** The page's own story, after what was open is shown nowhere any more. */
2117
+ reopenStory = () => {
2118
+ const { mount } = this;
2119
+ if (!mount || mount.side === "note" || this.facts.length === 0)
2120
+ return;
2121
+ const { side, page, id } = mount;
2122
+ // A story that went (undone) is not made again.
2123
+ const create = !!wordContext(this.state)?.stories.has(id);
2124
+ this.closeStory(false);
2125
+ if (!this.openStory(side, Math.min(page, this.facts.length - 1), create))
2126
+ this.focus();
2127
+ };
2128
+ /** The margin of a page a mouse event is in, if it is on the page itself. */
2129
+ marginAt(event) {
2130
+ const element = event.target;
2131
+ const page = this.pages.indexOf(element);
2132
+ if (page < 0 || !this.regions)
2133
+ return null;
2134
+ const box = element.getBoundingClientRect();
2135
+ const scale = this.scale();
2136
+ const style = getComputedStyle(element);
2137
+ const y = (event.clientY - box.top) / scale;
2138
+ if (y < Number.parseFloat(style.paddingTop))
2139
+ return { side: "header", page };
2140
+ return y > box.height / scale - Number.parseFloat(style.paddingBottom)
2141
+ ? { side: "footer", page }
2142
+ : null;
2143
+ }
2144
+ /**
2145
+ * A press outside the story being edited leaves it. The second press of a double click in a
2146
+ * page's margin opens its header or footer, the body's selection kept: on the press, since the
2147
+ * first click may have scrolled the page (Firefox) and the double click would land elsewhere.
2148
+ */
2149
+ onPress = (event) => {
2150
+ this.closeStory(false);
2151
+ // A note on the page, or the number of its reference: the second press opens the note.
2152
+ const target = event.target instanceof Element ? event.target : null;
2153
+ const onNote = target?.closest(`[${NOTE_ATTR}]`);
2154
+ const number = target?.closest(`[${NOTE_REF_ATTR}]`);
2155
+ const story = onNote?.getAttribute(NOTE_ATTR) ?? number?.getAttribute(NOTE_REF_ATTR);
2156
+ if (story && event.button === 0 && !event.shiftKey) {
2157
+ const opens = event.detail === 2 && this.editable && isNoteStory(this.state, story);
2158
+ if (onNote || opens)
2159
+ event.preventDefault();
2160
+ if (opens) {
2161
+ if (this.openNote(story) && onNote)
2162
+ this.mount?.view.placeCaret(event.clientX, event.clientY);
2163
+ return;
2164
+ }
2165
+ if (onNote)
2166
+ return;
2167
+ }
2168
+ const margin = event.button === 0 && !event.shiftKey ? this.marginAt(event) : null;
2169
+ if (margin && event.detail > 1) {
2170
+ event.preventDefault();
2171
+ if (event.detail > 2 || !this.editable)
2172
+ return;
2173
+ const selection = this.pressSelection;
2174
+ this.pressSelection = null;
2175
+ if (selection && !selection.eq(this.state.selection))
2176
+ this.editor.dispatch(this.state.tr.setSelection(selection));
2177
+ if (this.openStory(margin.side, margin.page))
2178
+ this.mount?.view.placeCaret(event.clientX, event.clientY);
2179
+ return;
2180
+ }
2181
+ // What the body shows now is what leaving the story comes back to (`selectionchange` comes
2182
+ // late, and the browser may select something on the way to the second press).
2183
+ if (margin && this.hasFocus())
2184
+ this.syncSelection();
2185
+ this.pressSelection = margin ? this.state.selection : null;
2186
+ // On a header or footer a press is not for the body: it places no caret.
2187
+ if (margin && this.pageRegions[margin.page]?.[margin.side]) {
2188
+ event.preventDefault();
2189
+ if (!this.hasFocus()) {
2190
+ this.pointerFocus = true;
2191
+ this.host.focus({ preventScroll: true });
2192
+ this.writeSelection(true);
2193
+ }
2194
+ return;
2195
+ }
2196
+ this.onMouseDown(event);
2197
+ };
2198
+ /** Puts the caret at a point of the window, if it is on this view's content. */
2199
+ placeCaret(x, y) {
2200
+ const pos = this.posAtPoint(x, y);
2201
+ if (pos !== null)
2202
+ this.editor.dispatch(this.state.tr.setSelection(TextSelection.near(this.state.doc.resolve(pos))));
2203
+ }
2204
+ /** The model position at a point of the window, or null. */
2205
+ posAtPoint(x, y) {
2206
+ const doc = this.host.ownerDocument;
2207
+ const point = doc.caretPositionFromPoint?.(x, y);
2208
+ const range = point ? null : doc.caretRangeFromPoint?.(x, y);
2209
+ const node = point?.offsetNode ?? range?.startContainer;
2210
+ const offset = point?.offset ?? range?.startOffset ?? 0;
2211
+ return node && this.host.contains(node) ? this.posFromDOM(node, offset) : null;
781
2212
  }
782
2213
  /**
783
2214
  * A floating picture reaches into the blocks after its paragraph (their lines go around it):
@@ -829,20 +2260,30 @@ export class EditorView {
829
2260
  };
830
2261
  /**
831
2262
  * Puts each fragment of each block into its page (pages are non-decreasing in document
832
- * order), creating and removing pages as needed, and gives each page the page setup of its
833
- * blocks' section (one per page: `separateSheets`, section breaks). Anything else in the host
834
- * or a page (stray DOM) is removed.
2263
+ * order) and, on a page with several sections or columns, into its band's column, creating
2264
+ * and removing pages as needed, and gives each page the page setup of its first section.
2265
+ * Anything else in the host or a page (stray DOM) is removed.
835
2266
  */
836
- place(elements, pages, layout) {
2267
+ place(elements, pages, slots, layout) {
837
2268
  const { host } = this;
838
- const items = elements.flatMap((list, i) => list.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0 })));
839
- const count = (items[items.length - 1]?.page ?? 0) + 1;
2269
+ const items = elements.flatMap((list, i) => list.map((dom, f) => ({
2270
+ dom,
2271
+ page: pages[i]?.[f] ?? 0,
2272
+ slot: slots[i]?.[f],
2273
+ section: layout[i].section,
2274
+ })));
2275
+ // A note can reach pages no text is on.
2276
+ const count = Math.max((items[items.length - 1]?.page ?? 0) + 1, this.pageNotes.length);
840
2277
  const sheets = [];
841
2278
  pages.forEach((list, i) => {
842
2279
  for (const p of list)
843
2280
  sheets[p] ??= layout[i].sheet;
844
2281
  });
845
- // A page no block starts on (none yet) takes the setup of the page before it.
2282
+ // A page no block is on has the setup of the page after it (Word's blank page before an
2283
+ // even or odd page section); the last, one with no blocks yet, of the page before it.
2284
+ for (let p = count - 1; p >= 0; p--)
2285
+ if (sheets[p + 1])
2286
+ sheets[p] ??= sheets[p + 1];
846
2287
  for (let p = 0; p < count; p++)
847
2288
  sheets[p] ??=
848
2289
  sheets[p - 1] ?? layout[0]?.sheet ?? this.lastSheet();
@@ -852,11 +2293,19 @@ export class EditorView {
852
2293
  this.sheets.forEach((sheet, p) => {
853
2294
  const page = this.pages[p];
854
2295
  const key = `${sheet.index} ${sheet.css}`;
855
- if (pageSheets.get(page) === key)
856
- return;
857
- pageSheets.set(page, key);
858
- page.style.cssText = sheet.css;
859
- page.setAttribute(SHEET_ATTR, String(sheet.index));
2296
+ if (pageSheets.get(page) !== key) {
2297
+ pageSheets.set(page, key);
2298
+ pagePads.delete(page);
2299
+ page.style.cssText = sheet.css;
2300
+ page.setAttribute(SHEET_ATTR, String(sheet.index));
2301
+ }
2302
+ const { top = "", bottom = "" } = this.pageMargins[p] ?? {};
2303
+ const pads = `${top} ${bottom}`;
2304
+ if ((pagePads.get(page) ?? " ") !== pads) {
2305
+ pagePads.set(page, pads);
2306
+ page.style.paddingTop = top;
2307
+ page.style.paddingBottom = bottom;
2308
+ }
860
2309
  });
861
2310
  // Pages first, in order; anything else in the host ends up after them.
862
2311
  let cursor = host.firstChild;
@@ -869,21 +2318,60 @@ export class EditorView {
869
2318
  let i = 0;
870
2319
  for (let p = 0; p < count; p++) {
871
2320
  const page = this.pages[p];
872
- let at = page.firstChild;
873
- for (; i < items.length && items[i]?.page === p; i++) {
874
- const { dom } = items[i];
875
- if (dom === at)
876
- at = at.nextSibling;
877
- else
878
- page.insertBefore(dom, at);
2321
+ const first = i;
2322
+ while (i < items.length && items[i]?.page === p)
2323
+ i++;
2324
+ const onPage = items.slice(first, i);
2325
+ const { header, footer } = this.pageRegions[p] ?? {};
2326
+ const notes = this.pageNotes[p];
2327
+ /** What follows the text of a column: its endnotes. */
2328
+ const after = (band, column) => notes?.flow.get(`${band}|${column}`) ?? [];
2329
+ /** A page's children: its header, what it holds, its notes, its footer. */
2330
+ const framed = (list) => [
2331
+ ...(header ? [header.element] : []),
2332
+ ...list,
2333
+ ...(notes?.foot ?? []),
2334
+ ...(footer ? [footer.element] : []),
2335
+ ];
2336
+ for (const { dom, slot } of onPage) {
2337
+ const position = slot.mark ? "absolute" : "";
2338
+ if (dom.style.position !== position)
2339
+ dom.style.position = position;
2340
+ }
2341
+ // One section in one column: the blocks are the page's children.
2342
+ const last = onPage[onPage.length - 1];
2343
+ if (!last || (!last.slot.band && last.section.columns.widths.length === 1)) {
2344
+ fillElement(page, framed([...onPage.map((item) => item.dom), ...after(0, 0)]), this.viewRemoved);
2345
+ this.bands.delete(page);
2346
+ continue;
879
2347
  }
880
- // What is left after the last placed block: strays, and blocks of later pages.
881
- while (at) {
882
- const next = at.nextSibling;
883
- at.remove();
884
- this.viewRemoved.add(at);
885
- at = next;
2348
+ const known = this.bands.get(page) ?? [];
2349
+ const bands = [];
2350
+ for (const { section, slot } of onPage) {
2351
+ if (bands[slot.band])
2352
+ continue;
2353
+ const key = columnsKey(section.columns);
2354
+ const reused = known[slot.band];
2355
+ bands[slot.band] =
2356
+ reused?.key === key
2357
+ ? reused
2358
+ : { key, ...bandElement(host.ownerDocument, section.columns) };
886
2359
  }
2360
+ this.bands.set(page, bands);
2361
+ fillElement(page, framed(bands.map((b) => b.band)), this.viewRemoved);
2362
+ bands.forEach((band, b) => {
2363
+ const inBand = onPage.filter((item) => item.slot.band === b);
2364
+ const lead = inBand[0]?.slot.lead;
2365
+ const margin = lead ? `${lead}px` : "";
2366
+ if (band.band.style.marginTop !== margin)
2367
+ band.band.style.marginTop = margin;
2368
+ band.columns.forEach((column, c) => {
2369
+ fillElement(column, [
2370
+ ...inBand.filter((item) => item.slot.column === c).map((item) => item.dom),
2371
+ ...after(b, c),
2372
+ ], this.viewRemoved);
2373
+ });
2374
+ });
887
2375
  }
888
2376
  // Pages no longer needed and stray DOM in the host: all after the last page by now.
889
2377
  let rest = this.pages[count - 1].nextSibling;
@@ -917,7 +2405,7 @@ export class EditorView {
917
2405
  }
918
2406
  createPage() {
919
2407
  const page = this.host.ownerDocument.createElement("section");
920
- page.className = "foli-page";
2408
+ page.className = this.paged ? "foli-page" : "foli-story-flow";
921
2409
  return page;
922
2410
  }
923
2411
  /** The last section's page setup (the envelope's), for an empty document. */
@@ -926,6 +2414,8 @@ export class EditorView {
926
2414
  }
927
2415
  /** The print rules for the document's page setups, written when they change. */
928
2416
  applyPrintStyles(layout) {
2417
+ if (!this.paged)
2418
+ return;
929
2419
  const sheets = [...new Set(layout.map((block) => block.sheet))];
930
2420
  const key = [this.lastSheet(), ...sheets].map((sheet) => sheet.css).join("\n");
931
2421
  if (key === this.printKey)
@@ -942,7 +2432,7 @@ export class EditorView {
942
2432
  this.printStyles = parents.map((parent) => {
943
2433
  const style = doc.createElement("style");
944
2434
  style.setAttribute("data-foli-print", "");
945
- style.textContent = printStyles(this.editor.settings, sheets, this.id);
2435
+ style.textContent = viewPrintStyles(this.editor.settings, sheets, this.id);
946
2436
  parent.append(style);
947
2437
  return style;
948
2438
  });
@@ -951,6 +2441,11 @@ export class EditorView {
951
2441
  invalidateLayout() {
952
2442
  this.measures = new WeakMap();
953
2443
  this.flowed = null;
2444
+ this.regionsFor = null;
2445
+ if (this.regions)
2446
+ this.regions.cache = new WeakMap();
2447
+ if (this.notes)
2448
+ this.notes.cache = new WeakMap();
954
2449
  }
955
2450
  /** Re-flows the pages once web fonts have loaded: line heights and wrapping change. */
956
2451
  onFontsLoaded = () => {
@@ -991,7 +2486,7 @@ export class EditorView {
991
2486
  // A hidden host (display: none) reports every block as 0x0: nothing to re-flow.
992
2487
  if (!entry.contentRect.width)
993
2488
  continue;
994
- scale ??= layoutScale(this.pages[0], this.sheets[0].settings);
2489
+ scale ??= this.scale();
995
2490
  let height = 0;
996
2491
  for (const fragment of desc.fragments)
997
2492
  height += fragment.getBoundingClientRect().height;
@@ -1020,7 +2515,7 @@ export class EditorView {
1020
2515
  if (this.destroyed)
1021
2516
  return;
1022
2517
  // compositionend flows what a composition kept from moving.
1023
- if (this.composing) {
2518
+ if (this.composing || this.mount?.view.composing) {
1024
2519
  this.unflowed = true;
1025
2520
  return;
1026
2521
  }
@@ -1039,15 +2534,18 @@ export class EditorView {
1039
2534
  return null;
1040
2535
  }
1041
2536
  /**
1042
- * Whether `node` holds blocks rather than content: the host, a page, or a table's wrapper,
1043
- * table, rows and cells.
2537
+ * Whether `node` holds blocks rather than content: the host, a page, a band or column of one,
2538
+ * or a table's wrapper, table, rows and cells.
1044
2539
  */
1045
2540
  holdsBlocks(node) {
1046
- return (node === this.host ||
1047
- this.pages.includes(node) ||
1048
- (node.nodeType === Node.ELEMENT_NODE &&
1049
- node.hasAttribute(FRAME_ATTR) &&
1050
- !node.closest(`[${REPEATED_ATTR}]`)));
2541
+ if (node === this.host || this.pages.includes(node))
2542
+ return true;
2543
+ if (node.nodeType !== Node.ELEMENT_NODE)
2544
+ return false;
2545
+ const element = node;
2546
+ return (element.classList.contains(BAND_CLASS) ||
2547
+ element.classList.contains(COLUMN_CLASS) ||
2548
+ (element.hasAttribute(FRAME_ATTR) && !element.closest(`[${REPEATED_ATTR}]`)));
1051
2549
  }
1052
2550
  /** Index of the first block that starts at or after `pos` (the block count if none). */
1053
2551
  blockFrom(pos) {
@@ -1077,7 +2575,7 @@ export class EditorView {
1077
2575
  // where a continuation starts), else the document end.
1078
2576
  const range = host.ownerDocument.createRange();
1079
2577
  range.setStart(node, offset);
1080
- const posOf = (i, f) => f === 0
2578
+ const posOf = (i, f) => f === 0 || !this.blocks[i].node.isTextblock
1081
2579
  ? this.starts[i]
1082
2580
  : this.starts[i] +
1083
2581
  1 +
@@ -1176,6 +2674,8 @@ export class EditorView {
1176
2674
  const sel = this.host.ownerDocument.getSelection();
1177
2675
  if (!sel?.anchorNode || !sel.focusNode)
1178
2676
  return null;
2677
+ if (this.mount?.wrapper.contains(sel.anchorNode))
2678
+ return null;
1179
2679
  // A range around exactly one block leaf element (a rule): the node selection that wrote it.
1180
2680
  // (Its end, mapped alone, would be the start of the next block, not the end of the rule.)
1181
2681
  if (sel.anchorNode === sel.focusNode && Math.abs(sel.anchorOffset - sel.focusOffset) === 1) {
@@ -1299,6 +2799,8 @@ export class EditorView {
1299
2799
  showSelectedNode() {
1300
2800
  this.showSelectedCells();
1301
2801
  this.showSelectedPicture();
2802
+ this.showSelectedFields();
2803
+ this.drawControls();
1302
2804
  const dom = this.selectedBlock()?.dom ?? this.selectedTable();
1303
2805
  if (dom === this.selectedDom)
1304
2806
  return;
@@ -1326,11 +2828,19 @@ export class EditorView {
1326
2828
  const shown = selection instanceof AllSelection
1327
2829
  ? TextSelection.between(selection.$anchor, selection.$head)
1328
2830
  : selection;
1329
- return dom.anchor === shown.anchor && dom.head === shown.head;
2831
+ if (dom.anchor === shown.anchor && dom.head === shown.head)
2832
+ return true;
2833
+ // Field markers take no room, and a control's edge is one place to the browser: the DOM
2834
+ // cannot tell their two sides apart.
2835
+ const { doc } = this.state;
2836
+ const texts = shown instanceof TextSelection && dom instanceof TextSelection;
2837
+ const same = (a, b) => controlSpot(doc, a, b) ||
2838
+ (texts && doc.resolve(a).parent.inlineContent && sameSpot(doc, a, b));
2839
+ return same(dom.anchor, shown.anchor) && same(dom.head, shown.head);
1330
2840
  }
1331
2841
  hasFocus() {
1332
2842
  const active = this.host.ownerDocument.activeElement;
1333
- return active === this.host || this.host.contains(active);
2843
+ return ((active === this.host || this.host.contains(active)) && !this.mount?.wrapper.contains(active));
1334
2844
  }
1335
2845
  /** Writes the model selection to the DOM unless the DOM already shows it (keeps native affinity). */
1336
2846
  writeSelection(force) {
@@ -1379,7 +2889,7 @@ export class EditorView {
1379
2889
  */
1380
2890
  dispatch(tr) {
1381
2891
  const marksAdded = tr.storedMarks !== null && tr.storedMarks !== this.state.storedMarks;
1382
- if (!this.editable && (tr.docChanged || marksAdded))
2892
+ if ((!this.editable || this.mount) && (tr.docChanged || marksAdded))
1383
2893
  return false;
1384
2894
  this.editor.dispatch(tr);
1385
2895
  return true;
@@ -1467,13 +2977,31 @@ export class EditorView {
1467
2977
  return;
1468
2978
  this.run(type.endsWith("Forward") ? deleteForward(unit) : deleteBackward(unit));
1469
2979
  };
1470
- /** Runs the first command bound to `name` that applies, through the view's dispatch. */
2980
+ /**
2981
+ * Runs the first command bound to `name` that applies, through the view's dispatch; the view's
2982
+ * own keys where core's `viewKeys` plugin stands (after the user's plugins, before the
2983
+ * built-in keymaps).
2984
+ */
1471
2985
  runKey(name) {
1472
2986
  return this.state.plugins.some((plugin) => {
2987
+ if (plugin.key === viewKeys)
2988
+ return this.viewKey(name);
1473
2989
  const command = plugin.spec.keymap?.[name];
1474
2990
  return command ? this.run(command) : false;
1475
2991
  });
1476
2992
  }
2993
+ /**
2994
+ * The view's own overridable keys (ADR-0008, `docs/keyboard.md`): they need the pages, the
2995
+ * stories or the app's navigation UI, so they are not core commands. A user keymap binding the
2996
+ * same name runs first.
2997
+ */
2998
+ viewKey(name) {
2999
+ return (this.documentEdgeKey(name) ||
3000
+ this.fieldKey(name) ||
3001
+ (name === "Alt-ArrowDown" && this.controlChrome.open()) ||
3002
+ this.noteKey(name) ||
3003
+ this.navigationKey(name));
3004
+ }
1477
3005
  // ---------- column borders (10.7c) ----------
1478
3006
  /** A column border being dragged: its table and column, the column's width, the press, the guide. */
1479
3007
  drag = null;
@@ -1532,6 +3060,8 @@ export class EditorView {
1532
3060
  onMouseMove = (event) => {
1533
3061
  if (this.drag)
1534
3062
  return;
3063
+ if (event.buttons === 0)
3064
+ this.controlChrome.hover(event.target);
1535
3065
  const near = event.buttons === 0 && this.columnBorder(event) !== null;
1536
3066
  if (near === this.resizeCursor)
1537
3067
  return;
@@ -1772,12 +3302,7 @@ export class EditorView {
1772
3302
  if (!files.length || this.composing)
1773
3303
  return;
1774
3304
  // The place the files were dropped.
1775
- const doc = this.host.ownerDocument;
1776
- const point = doc.caretPositionFromPoint?.(event.clientX, event.clientY);
1777
- const range = point ? null : doc.caretRangeFromPoint?.(event.clientX, event.clientY);
1778
- const node = point?.offsetNode ?? range?.startContainer;
1779
- const offset = point?.offset ?? range?.startOffset ?? 0;
1780
- const pos = node ? this.posFromDOM(node, offset) : null;
3305
+ const pos = this.posAtPoint(event.clientX, event.clientY);
1781
3306
  if (pos !== null)
1782
3307
  this.dispatch(this.state.tr.setSelection(TextSelection.near(this.state.doc.resolve(pos))));
1783
3308
  void this.insertFiles(files);
@@ -1902,6 +3427,20 @@ export class EditorView {
1902
3427
  }
1903
3428
  return;
1904
3429
  }
3430
+ // Word's blank page before an even or odd page section holds nothing: the caret goes to the
3431
+ // section after it (the browser would put it at the document's start).
3432
+ const blank = event.target;
3433
+ if (!event.shiftKey && this.pages.includes(blank) && !blank.firstChild) {
3434
+ const pos = this.posFromDOM(blank, 0);
3435
+ if (pos !== null) {
3436
+ event.preventDefault();
3437
+ if (!this.hasFocus())
3438
+ this.host.focus({ preventScroll: true });
3439
+ this.dispatch(this.state.tr.setSelection(Selection.near(this.state.doc.resolve(pos))));
3440
+ this.writeSelection(true);
3441
+ }
3442
+ return;
3443
+ }
1905
3444
  const element = this.blockElement(event.target);
1906
3445
  const owner = element ? this.owner.get(element) : undefined;
1907
3446
  const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
@@ -1934,6 +3473,8 @@ export class EditorView {
1934
3473
  */
1935
3474
  onClick = (event) => {
1936
3475
  const target = event.target;
3476
+ if (event.type === "click" && !event.shiftKey && this.controlChrome.click(event))
3477
+ return;
1937
3478
  const element = target instanceof Element ? target.closest("a") : null;
1938
3479
  if (!element || !this.host.contains(element))
1939
3480
  return;
@@ -1956,6 +3497,15 @@ export class EditorView {
1956
3497
  return isSafeHref(href) ? href : null;
1957
3498
  }
1958
3499
  onKeyDown = (event) => {
3500
+ // The host itself focused while a story is open (Shift+Tab): it is read-only, and its selection
3501
+ // is what leaving the story comes back to.
3502
+ if (this.mount) {
3503
+ if (event.key === "Escape") {
3504
+ event.preventDefault();
3505
+ this.closeStory(true);
3506
+ }
3507
+ return;
3508
+ }
1959
3509
  if (event.isComposing || this.composing)
1960
3510
  return;
1961
3511
  this.syncSelection();
@@ -1963,7 +3513,15 @@ export class EditorView {
1963
3513
  event.preventDefault();
1964
3514
  return;
1965
3515
  }
3516
+ if (this.skipFieldParts(event)) {
3517
+ event.preventDefault();
3518
+ return;
3519
+ }
1966
3520
  const name = keyName(event);
3521
+ if (this.controlKey(name)) {
3522
+ event.preventDefault();
3523
+ return;
3524
+ }
1967
3525
  // Ctrl/Cmd+Shift+V: the paste event that follows uses only the plain text.
1968
3526
  this.plainPaste = name === "Mod-Shift-v";
1969
3527
  // Tab and Shift+Tab move the focus on in read-only mode, and right after Escape where Tab
@@ -2016,6 +3574,32 @@ export class EditorView {
2016
3574
  event.preventDefault();
2017
3575
  }
2018
3576
  };
3577
+ /** Word's keys for notes, and Shift+Alt+N from a reference to its note. */
3578
+ noteKey(name) {
3579
+ if (name === NOTE_KEY)
3580
+ return this.openNote();
3581
+ const kind = name === "Mod-Alt-f" ? "footnote" : name === "Mod-Alt-d" ? "endnote" : null;
3582
+ if (!kind || !this.editable || !this.notes)
3583
+ return false;
3584
+ return this.run(insertNote(kind)) && this.openNote();
3585
+ }
3586
+ /**
3587
+ * Ctrl+Home and Ctrl+End (with Shift, extending) on pages with headers and footers: the browser
3588
+ * stops at the first or last place before what it cannot edit, so the model says where.
3589
+ */
3590
+ documentEdgeKey(name) {
3591
+ const shift = name.startsWith("Mod-Shift-");
3592
+ const key = name.replace("Mod-Shift-", "Mod-");
3593
+ if ((key !== "Mod-Home" && key !== "Mod-End") || !this.editable)
3594
+ return false;
3595
+ if (!this.pageRegions.some((page) => page.header || page.footer))
3596
+ return false;
3597
+ const { doc, selection } = this.state;
3598
+ const edge = key === "Mod-Home" ? Selection.atStart(doc) : Selection.atEnd(doc);
3599
+ const next = shift ? TextSelection.between(selection.$anchor, edge.$head) : edge;
3600
+ this.dispatch(this.state.tr.setSelection(next).setStoredMarks(null));
3601
+ return true;
3602
+ }
2019
3603
  /**
2020
3604
  * Whether the caret is on the first (`dir` -1) or last (1) line of its textblock, in the
2021
3605
  * block's first or last fragment (a block split across pages has several).
@@ -2159,9 +3743,10 @@ export class EditorView {
2159
3743
  * and so is the scroll position.
2160
3744
  */
2161
3745
  onFocus = () => {
3746
+ this.claimStories();
2162
3747
  const pointer = this.pointerFocus;
2163
3748
  this.pointerFocus = false;
2164
- if (pointer)
3749
+ if (pointer || this.mount)
2165
3750
  return;
2166
3751
  const current = this.readSelection();
2167
3752
  if (current && this.shows(current))
@@ -2176,13 +3761,16 @@ export class EditorView {
2176
3761
  this.onCompositionEnd();
2177
3762
  };
2178
3763
  onMutations = (records) => {
2179
- this.pending.push(...records.filter((r) => !handleOnly(r)));
3764
+ this.pending.push(...records.filter((r) => !handleOnly(r) && !inNodeView(r)));
2180
3765
  if (!this.composing && this.pending.length)
2181
3766
  this.flush();
2182
3767
  };
2183
3768
  /** Reads back every DOM change recorded so far. */
2184
3769
  flush() {
2185
- const records = [...this.pending, ...this.observer.takeRecords().filter((r) => !handleOnly(r))];
3770
+ const records = [
3771
+ ...this.pending,
3772
+ ...this.observer.takeRecords().filter((r) => !handleOnly(r) && !inNodeView(r)),
3773
+ ];
2186
3774
  this.pending = [];
2187
3775
  if (records.length)
2188
3776
  this.readBack(records);
@@ -2354,6 +3942,37 @@ export class EditorView {
2354
3942
  this.writeSelection(true);
2355
3943
  }
2356
3944
  // ---------- clipboard ----------
3945
+ /**
3946
+ * A copied picture's image as another document can show and save it: its own `data:` or web
3947
+ * URL, else the image this view shows, as a `data:` URL (read from the drawn image when it is
3948
+ * an object URL: its bytes live in this page only). Nothing lasting known (an image not loaded
3949
+ * yet): as it is, and the paste brings the picture without its image.
3950
+ */
3951
+ portableResource(context) {
3952
+ const shown = imageSource(context.envelope.resources, this.resource ?? undefined);
3953
+ return (key, resource) => {
3954
+ if (resource.data !== undefined || /^https?:/i.test(resource.url ?? ""))
3955
+ return resource;
3956
+ const url = shown(key);
3957
+ if (url?.startsWith("data:image/"))
3958
+ return { contentType: resource.contentType, data: url };
3959
+ const img = [...this.host.querySelectorAll(`img[${PICTURE_ATTR}]`)].find((element) => element.getAttribute(PICTURE_ATTR) === key);
3960
+ if (img?.complete && img.naturalWidth > 0) {
3961
+ try {
3962
+ const canvas = this.host.ownerDocument.createElement("canvas");
3963
+ canvas.width = img.naturalWidth;
3964
+ canvas.height = img.naturalHeight;
3965
+ canvas.getContext("2d")?.drawImage(img, 0, 0);
3966
+ // PNG: the browser's encoding, the same pixels (JPEG's own bytes cannot be read here).
3967
+ return { contentType: "image/png", data: canvas.toDataURL("image/png") };
3968
+ }
3969
+ catch { } // a cross-origin image taints the canvas: keep what is known
3970
+ }
3971
+ // An image the page shows over the web lasts; an object URL does not (the paste then comes
3972
+ // without its image).
3973
+ return url && /^https?:/i.test(url) ? { contentType: resource.contentType, url } : resource;
3974
+ };
3975
+ }
2357
3976
  /** Copy writes the model's content (plain text, HTML, Foli JSON), never the browser's DOM. */
2358
3977
  onCopy = (event) => {
2359
3978
  this.syncSelection();
@@ -2365,7 +3984,7 @@ export class EditorView {
2365
3984
  // Selected cells are copied as a table of their own (ADR-0006).
2366
3985
  const table = selection instanceof CellSelection ? cellsAsTable(selection) : null;
2367
3986
  const source = table ? doc.type.create(null, table) : doc;
2368
- const { text, html, json } = serializeRange(source, table ? 0 : selection.from, table ? source.content.size : selection.to, this.host.ownerDocument, { context, ratio: this.lineRatio });
3987
+ const { text, html, json } = serializeRange(source, table ? 0 : selection.from, table ? source.content.size : selection.to, this.host.ownerDocument, { context, ratio: this.lineRatio, portable: this.portableResource(context) });
2369
3988
  event.clipboardData.setData("text/plain", table ? cellsText(table) : text);
2370
3989
  event.clipboardData.setData("text/html", html);
2371
3990
  event.clipboardData.setData(FOLI_MIME, json);
@@ -2407,6 +4026,10 @@ export class EditorView {
2407
4026
  */
2408
4027
  paste(data, autolink = true) {
2409
4028
  const { state } = this;
4029
+ // A text control takes the text alone.
4030
+ const plainText = data.getData("text/plain");
4031
+ if (plainText && this.run(insertControlText(plainText)))
4032
+ return true;
2410
4033
  const text = autolink && !data.getData(FOLI_MIME) ? data.getData("text/plain") : "";
2411
4034
  const href = text ? autolinkHref(text) : null;
2412
4035
  if (href) {
@@ -2432,7 +4055,7 @@ export class EditorView {
2432
4055
  const only = pasted?.doc.childCount === 1 ? pasted.doc.firstChild : null;
2433
4056
  if (!pasted || (only?.isTextblock && !only.content.size))
2434
4057
  return false;
2435
- const { doc, open, envelope } = pasted;
4058
+ const { doc, open, envelope, notes } = pasted;
2436
4059
  // As a slice (text joins the text around the caret); where that cannot be (an opaque block
2437
4060
  // at an end), as whole blocks at the caret.
2438
4061
  const asSlice = (tr) => {
@@ -2476,6 +4099,8 @@ export class EditorView {
2476
4099
  withEnvelope(tr, envelope);
2477
4100
  setComments(tr, current.comments, envelope.comments);
2478
4101
  }
4102
+ for (const { id, story } of notes ?? [])
4103
+ tr.step(new StoryStep(id, null, story));
2479
4104
  }
2480
4105
  catch (error) {
2481
4106
  if (error instanceof TransformError)
@@ -2487,7 +4112,7 @@ export class EditorView {
2487
4112
  return false;
2488
4113
  }
2489
4114
  onSelectionChange = () => {
2490
- if (!this.composing && this.hasFocus())
4115
+ if (!this.composing && !this.mount && this.hasFocus())
2491
4116
  this.syncSelection();
2492
4117
  };
2493
4118
  }
@@ -2585,6 +4210,7 @@ function measureTable(frame, wrapper, blocks, scale) {
2585
4210
  * at its cells' line ends, unless the row may not split (`cantSplit`, unless taller than a
2586
4211
  * page), is part of a vertical merge or holds a nested table (shortcut: those split only
2587
4212
  * between rows; a nested table stays whole within its row).
4213
+ * @internal
2588
4214
  */
2589
4215
  export function breaksOf(frame, measure, blocks, pageHeight, lines) {
2590
4216
  const t = measure.table;
@@ -2636,6 +4262,7 @@ function tableBox(frame, measure, pageHeight, breakAfter, breaks) {
2636
4262
  * A flowed table cut into its fragments: the rows each shows (a row split across pages in
2637
4263
  * both), the header rows drawn again above a continuation, the fragment of the table each
2638
4264
  * block's fragments go in, and where a block of a split row splits (content offsets).
4265
+ * @internal
2639
4266
  */
2640
4267
  export function cutTable(frame, measure, fragments, blocks, lines) {
2641
4268
  const t = measure.table;
@@ -2720,59 +4347,110 @@ function measureBox(desc, scale) {
2720
4347
  /**
2721
4348
  * What the flow needs of a block: its measurement, its lines (on demand), Word's spacing before
2722
4349
  * and after (next to its neighbours), keep with next, keep lines together (not for a block
2723
- * taller than a page, or one with a page break in it), page breaks ending their line's page,
2724
- * and a page break before the next block ending this one's page.
4350
+ * taller than a page, or one with a break in it), page and column breaks ending their line's
4351
+ * page or column, and a page break before the next block ending this one's page.
2725
4352
  */
2726
- function wordBox(words, i, desc, measure, lines, layout) {
4353
+ function wordBox(words, i, desc, measure, lines, layout, atWidth, adds, noteOf) {
2727
4354
  const pageHeight = contentHeight(layout.sheet.settings);
4355
+ const { section } = layout;
4356
+ // Without pages nothing is kept off the next one, and a page break ends nothing.
4357
+ const paged = layout.sheet.css !== UNPAGED_CSS;
2728
4358
  const next = words[i + 1] ? { word: words[i + 1] } : undefined;
2729
- const { before, after } = spacing(words[i - 1], desc.word, next?.word);
2730
- const pageBreaks = desc.leaves.filter((leaf) => leaf.dom.nodeType !== Node.TEXT_NODE && leaf.dom.hasAttribute(PAGE_BREAK_ATTR));
2731
- const hasBreak = pageBreaks.length > 0;
2732
- const kept = desc.word.keepLines && !hasBreak && measure.height <= pageHeight;
4359
+ const { before, after } = spacing(words[i - 1], desc.word, next?.word, adds);
4360
+ const leavesWith = (attr) => desc.leaves.filter((leaf) => leaf.dom.nodeType !== Node.TEXT_NODE && leaf.dom.hasAttribute(attr));
4361
+ const pageBreaks = leavesWith(PAGE_BREAK_ATTR);
4362
+ const columnBreaks = leavesWith(WORD_COLUMN_BREAK_ATTR);
4363
+ const hasBreak = pageBreaks.length + columnBreaks.length > 0;
4364
+ const keep = desc.word.keepLines && !hasBreak;
4365
+ const kept = keep && measure.height <= pageHeight;
2733
4366
  const bottoms = () => (kept ? [measure.height] : lines().bottoms);
4367
+ /** The block as it is in `column`, when the columns' widths differ. */
4368
+ const inColumn = (column) => atWidth(desc, section.columns.widths[column], keep);
4369
+ // The line holding a break, among the column's lines: the last starting at or before it.
4370
+ const linesOf = (leaves, column = 0) => {
4371
+ if (!leaves.length)
4372
+ return [];
4373
+ const { starts } = section.unequal ? inColumn(column).all() : lines();
4374
+ return leaves.map((leaf) => {
4375
+ let line = starts.length - 1;
4376
+ while (line > 0 && starts[line] > leaf.offset)
4377
+ line--;
4378
+ return line;
4379
+ });
4380
+ };
4381
+ const references = referencesIn(desc.node);
4382
+ const notes = references.flatMap((ref) => {
4383
+ const note = noteOf(ref.story);
4384
+ return note ? [{ note, offset: ref.offset - 1 }] : [];
4385
+ });
2734
4386
  return {
4387
+ notes: notes.length
4388
+ ? (column) => {
4389
+ if (kept)
4390
+ return notes.map(({ note }) => ({ line: 0, note }));
4391
+ const { starts } = section.unequal ? inColumn(column).all() : lines();
4392
+ return notes.map(({ note, offset }) => {
4393
+ let line = starts.length - 1;
4394
+ while (line > 0 && starts[line] > offset)
4395
+ line--;
4396
+ return { line, note };
4397
+ });
4398
+ }
4399
+ : undefined,
2735
4400
  height: measure.height,
2736
4401
  marginTop: before,
2737
4402
  marginBottom: after,
2738
4403
  keepWithNext: desc.word.keepNext,
4404
+ // A node view's parts are not lines: no widow or orphan control.
4405
+ anyLine: !!desc.parts,
2739
4406
  pageHeight,
4407
+ section: section.flow,
4408
+ sectionMark: !!desc.node.attrs.section && desc.word.empty,
4409
+ inColumn: section.unequal ? inColumn : undefined,
2740
4410
  lines: bottoms,
2741
- breaksAfter: () => {
2742
- // The line holding each break: the last one starting at or before it.
2743
- const breaks = pageBreaks.map((leaf) => {
2744
- const { starts } = lines();
2745
- let line = starts.length - 1;
2746
- while (line > 0 && starts[line] > leaf.offset)
2747
- line--;
2748
- return line;
2749
- });
2750
- if (next?.word.pageBreakBefore || layout.breakAfter)
2751
- breaks.push(bottoms().length - 1);
4411
+ columnBreaksAfter: (column) => linesOf(columnBreaks, column),
4412
+ breaksAfter: (column = 0) => {
4413
+ if (!paged)
4414
+ return [];
4415
+ const breaks = linesOf(pageBreaks, column);
4416
+ if (next?.word.pageBreakBefore)
4417
+ breaks.push((section.unequal ? inColumn(column).lines() : bottoms()).length - 1);
2752
4418
  return breaks;
2753
4419
  },
2754
4420
  };
2755
4421
  }
4422
+ /** The footnotes a table refers to, each on the break at or after its reference's line. */
4423
+ function tableNotes(frame, measure, blocks, lines, breaks, noteOf) {
4424
+ const t = measure.table;
4425
+ const found = [];
4426
+ for (let unit = frame.first; unit < frame.end; unit++)
4427
+ for (const ref of referencesIn(blocks[unit].node)) {
4428
+ const note = noteOf(ref.story);
4429
+ if (note && t.tops.get(unit) != null)
4430
+ found.push({ note, unit, offset: ref.offset - 1 });
4431
+ }
4432
+ if (!found.length)
4433
+ return undefined;
4434
+ return () => {
4435
+ const list = breaks();
4436
+ return found.map(({ note, unit, offset }) => {
4437
+ const { starts, bottoms } = lines(blocks[unit]);
4438
+ let k = starts.length - 1;
4439
+ while (k > 0 && starts[k] > offset)
4440
+ k--;
4441
+ const y = t.tops.get(unit) + bottoms[k];
4442
+ const line = list.findIndex((b) => b >= y - 0.5);
4443
+ return { line: line < 0 ? list.length - 1 : line, note };
4444
+ });
4445
+ };
4446
+ }
2756
4447
  /**
2757
- * Writes Word's space above each v3 block as its top margin: the space after the block above
2758
- * and the space before this one, on the same page; at the top of a page only its space before,
2759
- * and only on the first page or after an explicit break (a page the text flowed onto drops it).
2760
- * Written only when it changes.
4448
+ * Writes Word's space above each v3 block, as the flow worked it out, as its top margin. Written
4449
+ * only when it changes.
2761
4450
  */
2762
- function applyGaps(firsts, pages, boxes) {
4451
+ function applyGaps(firsts, spaces) {
2763
4452
  firsts.forEach((dom, i) => {
2764
- const page = pages[i]?.[0] ?? 0;
2765
- const above = pages[i - 1];
2766
- const box = boxes[i];
2767
- let gap;
2768
- if (above && above[above.length - 1] === page)
2769
- gap = boxes[i - 1].marginBottom + box.marginTop;
2770
- else {
2771
- const prior = boxes[i - 1];
2772
- const breaks = prior?.breaksAfter?.() ?? [];
2773
- const forced = page === 0 || (!!prior && breaks.length > 0 && breaks.includes(prior.lines().length - 1));
2774
- gap = forced ? box.marginTop : 0;
2775
- }
4453
+ const gap = spaces[i] ?? 0;
2776
4454
  if (gaps.get(dom) === gap)
2777
4455
  return;
2778
4456
  gaps.set(dom, gap);
@@ -2829,6 +4507,9 @@ function measureLines(desc, scale) {
2829
4507
  continue;
2830
4508
  if (leaf.dom.nodeType !== Node.TEXT_NODE) {
2831
4509
  const br = leaf.dom;
4510
+ // A raised number says nothing about where its line is.
4511
+ if (br.hasAttribute(NOTE_NUMBER_ATTR))
4512
+ continue;
2832
4513
  items.push({ offset: leaf.offset, rect: () => br.getBoundingClientRect() });
2833
4514
  continue;
2834
4515
  }
@@ -2851,6 +4532,16 @@ function measureLines(desc, scale) {
2851
4532
  !desc.leaves.some((l) => l.dom === tail))
2852
4533
  items.push({ offset: desc.node.content.size, rect: () => tail.getBoundingClientRect() });
2853
4534
  const from = f ? desc.splits[f - 1] : 0;
4535
+ const parts = desc.parts;
4536
+ if (!items.length && parts && desc.fragments.length === 1) {
4537
+ // A node view drawn whole: it may break after each of its root's children.
4538
+ for (const bottom of parts()) {
4539
+ starts.push(0);
4540
+ bottoms.push(bottom / scale);
4541
+ }
4542
+ base += box.height;
4543
+ continue;
4544
+ }
2854
4545
  if (!items.length) {
2855
4546
  starts.push(from);
2856
4547
  bottoms.push((base + box.height) / scale);
@@ -2957,6 +4648,22 @@ function scrollRectIntoView(from, rect) {
2957
4648
  if (move)
2958
4649
  win.scrollBy(0, move);
2959
4650
  }
4651
+ const SCROLL_OPTIONS = { capture: true, passive: true };
4652
+ /** Room kept above what is scrolled to for find, in px. */
4653
+ const REVEAL_ABOVE = 200;
4654
+ /** Word's keys for finding and going places. */
4655
+ const NAVIGATION_KEYS = {
4656
+ "Mod-f": "find",
4657
+ "Mod-h": "replace",
4658
+ "Mod-g": "goTo",
4659
+ F3: "next",
4660
+ "Shift-F3": "previous",
4661
+ "Mod-Shift-F5": "bookmarks",
4662
+ };
4663
+ /** Shift+Alt+N (Shift+Option+N): from a note's reference to the note, and back. */
4664
+ const NOTE_KEY = "Alt-Shift-n";
4665
+ /** Whether story `id` of `state`'s document exists (a number can outlive its note on screen). */
4666
+ const isNoteStory = (state, id) => !!wordContext(state)?.stories.has(id);
2960
4667
  function before(node) {
2961
4668
  const parent = node.parentNode;
2962
4669
  return { node: parent, offset: Array.prototype.indexOf.call(parent.childNodes, node) };
@@ -2982,7 +4689,19 @@ export function keyName(event) {
2982
4689
  const mod = IS_MAC ? event.metaKey : event.ctrlKey;
2983
4690
  // Non-Latin layouts: Ctrl+B still means "b" (use the physical key when the character is not a-z);
2984
4691
  // with Shift, Ctrl+Shift+7 still means "7" (the character is "&" or "/" depending on layout).
2985
- if (mod && !/^[a-z0-9]$/.test(key) && /^(Key[A-Z]|Digit[0-9])$/.test(event.code))
4692
+ // Option on macOS types a character (Option+N is a dead key): Alt+N still means "n". But AltGr
4693
+ // (Ctrl+Alt on Windows) typing a character is that character: "[" is AltGr+F on a Hungarian
4694
+ // layout, and must not be read as Ctrl+Alt+F (a footnote).
4695
+ // (macOS has no AltGr: some browsers report Option as AltGraph, and Option is handled above.)
4696
+ // shortcut: Ctrl+Alt giving any other character counts as AltGr (not all browsers report its
4697
+ // state), so Ctrl+Alt+F on a non-Latin layout is not Mod-Alt-f; drop the guess if they all do.
4698
+ const altGraph = !IS_MAC &&
4699
+ (event.getModifierState?.("AltGraph") ||
4700
+ (event.ctrlKey && event.altKey && key.length === 1 && !/^[a-z0-9]$/i.test(key)));
4701
+ if ((mod || event.altKey) &&
4702
+ !altGraph &&
4703
+ !/^[a-z0-9]$/.test(key) &&
4704
+ /^(Key[A-Z]|Digit[0-9])$/.test(event.code))
2986
4705
  key = event.code.slice(-1).toLowerCase();
2987
4706
  let name = key;
2988
4707
  if (event.shiftKey && key !== "Shift")
@@ -3050,11 +4769,22 @@ function holdsFloat(node) {
3050
4769
  }
3051
4770
  return found;
3052
4771
  }
3053
- /** A change that only adds or removes a picture's resize handle (the view's own, not input). */
4772
+ /**
4773
+ * A change a node view made to its own drawing (content loaded later, a chart drawn): not input,
4774
+ * never read back. Inside a custom node's box, which is not editable.
4775
+ */
4776
+ function inNodeView(record) {
4777
+ const { target } = record;
4778
+ const element = target.nodeType === 1 ? target : target.parentElement;
4779
+ return !!element?.closest('[data-foli-custom][contenteditable="false"]');
4780
+ }
4781
+ /** A change that only adds or removes the view's own marks (a resize handle, a control's frame). */
3054
4782
  function handleOnly(record) {
3055
4783
  const nodes = [...record.addedNodes, ...record.removedNodes];
3056
4784
  return (record.type === "childList" &&
3057
4785
  nodes.length > 0 &&
3058
- nodes.every((n) => n.nodeType === 1 && n.hasAttribute("data-foli-resize")));
4786
+ nodes.every((n) => n.nodeType === 1 &&
4787
+ (n.hasAttribute("data-foli-resize") ||
4788
+ n.hasAttribute(CONTROL_UI_ATTR))));
3059
4789
  }
3060
4790
  //# sourceMappingURL=view.js.map