@folijs/view 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +59 -0
- package/dist/clipboard.d.ts +3 -1
- package/dist/clipboard.d.ts.map +1 -1
- package/dist/clipboard.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/layout/flow.d.ts +195 -20
- package/dist/layout/flow.d.ts.map +1 -1
- package/dist/layout/flow.js +790 -102
- package/dist/layout/flow.js.map +1 -1
- package/dist/print.d.ts +22 -0
- package/dist/print.d.ts.map +1 -0
- package/dist/print.js +31 -0
- package/dist/print.js.map +1 -0
- package/dist/view.d.ts +407 -8
- package/dist/view.d.ts.map +1 -1
- package/dist/view.js +2956 -263
- package/dist/view.js.map +1 -1
- package/dist/word/blocks.d.ts +99 -2
- package/dist/word/blocks.d.ts.map +1 -1
- package/dist/word/blocks.js +535 -31
- package/dist/word/blocks.js.map +1 -1
- package/dist/word/columns.d.ts +23 -0
- package/dist/word/columns.d.ts.map +1 -0
- package/dist/word/columns.js +51 -0
- package/dist/word/columns.js.map +1 -0
- package/dist/word/controls.d.ts +63 -0
- package/dist/word/controls.d.ts.map +1 -0
- package/dist/word/controls.js +411 -0
- package/dist/word/controls.js.map +1 -0
- package/dist/word/edit.d.ts +32 -11
- package/dist/word/edit.d.ts.map +1 -1
- package/dist/word/edit.js +215 -33
- package/dist/word/edit.js.map +1 -1
- package/dist/word/matches.d.ts +23 -0
- package/dist/word/matches.d.ts.map +1 -0
- package/dist/word/matches.js +97 -0
- package/dist/word/matches.js.map +1 -0
- package/dist/word/notes.d.ts +105 -0
- package/dist/word/notes.d.ts.map +1 -0
- package/dist/word/notes.js +392 -0
- package/dist/word/notes.js.map +1 -0
- package/dist/word/pages.d.ts +26 -13
- package/dist/word/pages.d.ts.map +1 -1
- package/dist/word/pages.js +439 -203
- package/dist/word/pages.js.map +1 -1
- package/dist/word/regions.d.ts +113 -0
- package/dist/word/regions.d.ts.map +1 -0
- package/dist/word/regions.js +374 -0
- package/dist/word/regions.js.map +1 -0
- package/dist/word/table.d.ts +79 -0
- package/dist/word/table.d.ts.map +1 -0
- package/dist/word/table.js +210 -0
- package/dist/word/table.js.map +1 -0
- package/package.json +2 -2
- package/src/clipboard.ts +3 -0
- package/src/index.ts +8 -1
- package/src/layout/flow.ts +948 -111
- package/src/print.ts +48 -0
- package/src/view.ts +3291 -273
- package/src/word/blocks.ts +611 -28
- package/src/word/columns.ts +66 -0
- package/src/word/controls.ts +447 -0
- package/src/word/edit.ts +253 -30
- package/src/word/matches.ts +99 -0
- package/src/word/notes.ts +451 -0
- package/src/word/pages.ts +524 -192
- package/src/word/regions.ts +469 -0
- package/src/word/table.ts +267 -0
package/dist/view.js
CHANGED
|
@@ -1,17 +1,46 @@
|
|
|
1
|
-
import { AllSelection, arrowAcrossLeaf, autolinkHref, closeHistory, deleteBackward, deleteForward, deleteSelection, fitPaste, fitPastedV2, insertHardBreak, insertLink, insertText, isSafeHref, marksAt, NodeSelection, parseContentV2, redo, Selection, Slice, sectionSettings, setComments, setLink, splitBlock, TextSelection, TransformError, toggleMark, trackState, typedMarks, undo, withEnvelope, wordContext, } from "@folijs/core";
|
|
1
|
+
import { AllSelection, arrowAcrossLeaf, autolinkHref, CellSelection, caretStop, cellsAsTable, closeHistory, controlAt, controlProperties, controlSpot, deleteBackward, deleteForward, deleteSelection, deleteSelectionKeepingTables, ensureStory, extendCellSelection, fieldCodesShown, fieldsIn, fitPaste, fitPastedV2, goToCellVertically, insertControlText, insertHardBreak, insertLink, insertNote, insertPicture, insertText, isSafeHref, keepTablesApart, marksAt, NodeSelection, noteAtSelection, noteNumbers, noteProperties, noteTexts, pageVariant, parseContentV2, pasteCells, redo, referencesIn, Selection, Slice, StoryStep, sameSpot, sectionSettings, setColumnWidth, setComments, setLink, setPictureSize, splitBlock, storyOfSection, TextSelection, TransformError, toggleFieldCodes, toggleMark, trackState, typedMarks, undo, updateFields, withEnvelope, wordContext, } from "@folijs/core";
|
|
2
2
|
import { docFromClipboard, FOLI_MIME, serializeRange } from "./clipboard.js";
|
|
3
|
-
import { contentHeight, DEFAULT_RULES, flowFrom, PX_PER_MM, } from "./layout/flow.js";
|
|
3
|
+
import { contentHeight, DEFAULT_RULES, flowFrom, notePieces, PX_PER_MM, pagesOf, spaceAfterText, } from "./layout/flow.js";
|
|
4
|
+
import { printStyles, SHEET_ATTR } from "./print.js";
|
|
4
5
|
import { PAGE_BREAK_ATTR } from "./render.js";
|
|
5
|
-
import {
|
|
6
|
+
import { EMU_PER_PX, imageSource, NOTE_NUMBER_ATTR, NOTE_REF_ATTR, PICTURE_ATTR, WORD_COLUMN_BREAK_ATTR, } from "./word/blocks.js";
|
|
7
|
+
import { BAND_CLASS, bandElement, COLUMN_CLASS, columnsKey, columnsPx, } from "./word/columns.js";
|
|
8
|
+
import { boxOf, CONTROL_STYLES, CONTROL_UI_ATTR, ControlChrome, } from "./word/controls.js";
|
|
9
|
+
import { FLOAT_ANCHORS, spacing, WordRenderer, } from "./word/edit.js";
|
|
10
|
+
import { MATCH_STYLES, MatchMarks, rangesInText } from "./word/matches.js";
|
|
11
|
+
import { NOTE_ATTR, PageNotes } from "./word/notes.js";
|
|
6
12
|
import { measureLineRatio } from "./word/pages.js";
|
|
13
|
+
import { PageRegions, REGION_CONTENT_CLASS } from "./word/regions.js";
|
|
14
|
+
import { collect, FRAME_ATTR, frameElement, REPEATED_ATTR, } from "./word/table.js";
|
|
15
|
+
/** What the flow needs of a table: no paragraph spacing or keep rules of its own. */
|
|
16
|
+
const TABLE_WORD = {
|
|
17
|
+
before: 0,
|
|
18
|
+
after: 0,
|
|
19
|
+
keepNext: false,
|
|
20
|
+
keepLines: false,
|
|
21
|
+
pageBreakBefore: false,
|
|
22
|
+
style: null,
|
|
23
|
+
contextual: false,
|
|
24
|
+
empty: false,
|
|
25
|
+
};
|
|
7
26
|
/** Word's paragraph spacing for a schema v3 document (`flow`'s `word` spacing). */
|
|
8
27
|
const WORD_RULES = { ...DEFAULT_RULES, spacing: "word" };
|
|
9
28
|
/** Class of the element of a node-selected block (a rule). */
|
|
10
29
|
const SELECTED_CLASS = "foli-selected-node";
|
|
30
|
+
/** Marks a cell of a cell selection. */
|
|
31
|
+
const CELL_CLASS = "foli-selected-cell";
|
|
32
|
+
/** On the host while cells are selected: the browser's own highlight (in DOM order) is hidden. */
|
|
33
|
+
const CELLS_ATTR = "data-foli-cells";
|
|
11
34
|
const PLACEHOLDER_ATTR = "data-foli-placeholder";
|
|
35
|
+
/** On the span of a selected picture (it holds the resize handle). */
|
|
36
|
+
const PICTURE_SELECTED_ATTR = "data-foli-picture-selected";
|
|
37
|
+
/** On what shows a field the selection is in: Word shades it. */
|
|
38
|
+
const FIELD_SELECTED_ATTR = "data-foli-field-selected";
|
|
39
|
+
/** The smallest a picture gets by dragging its handle, in px. */
|
|
40
|
+
const MIN_PICTURE = 8;
|
|
12
41
|
// Generated content is not document text: no caret stops inside it, a zero-height float keeps
|
|
13
42
|
// the caret at the line start, and the empty alt text keeps screen readers on aria-placeholder.
|
|
14
|
-
const STYLES = `[${PLACEHOLDER_ATTR}]::before{content:attr(${PLACEHOLDER_ATTR});content:attr(${PLACEHOLDER_ATTR}) / "";float:inline-start;height:0;pointer-events:none;color:GrayText}`;
|
|
43
|
+
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}`;
|
|
15
44
|
/**
|
|
16
45
|
* Adds the view's stylesheet once per document or shadow root, when a placeholder is first shown
|
|
17
46
|
* (by then the host is usually mounted where it will stay).
|
|
@@ -33,31 +62,16 @@ function injectStyles(host) {
|
|
|
33
62
|
const VIEW_ATTR = "data-foli-view";
|
|
34
63
|
let viewCount = 0;
|
|
35
64
|
/**
|
|
36
|
-
* Print rules for the page settings of the view whose host has `VIEW_ATTR` = `id
|
|
37
|
-
*
|
|
38
|
-
* 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
|
|
39
|
-
* half-pixel slack), with no gap after it. Content taller than a page (a line taller than a
|
|
40
|
-
* page) is not cut: it prints over the next sheet.
|
|
65
|
+
* Print rules for the page settings of the view whose host has `VIEW_ATTR` = `id` (`print.ts`,
|
|
66
|
+
* shared with the read-only renderer and so with `@folijs/pdf`).
|
|
41
67
|
* 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.
|
|
42
68
|
*/
|
|
43
|
-
function
|
|
44
|
-
const { width, height }
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
const named = sheets.every((sheet) => sheet.css === last)
|
|
50
|
-
? ""
|
|
51
|
-
: sheets
|
|
52
|
-
.map(({ settings: { pageSize: size }, index }) => {
|
|
53
|
-
const name = `foli-${id}-${index}`;
|
|
54
|
-
return (`@page ${name}{size:${size.width}mm ${size.height}mm;margin:0}` +
|
|
55
|
-
`${pages}[${SHEET_ATTR}="${index}"]{page:${name};height:${size.height}mm!important}`);
|
|
56
|
-
})
|
|
57
|
-
.join("");
|
|
58
|
-
return (`@media print{@page{size:${width}mm ${height}mm;margin:0}` +
|
|
59
|
-
`${pages}{height:${height}mm!important;margin-block:0!important;` +
|
|
60
|
-
`break-after:page;break-inside:avoid}${pages}:last-child{break-after:auto}${named}}`);
|
|
69
|
+
function viewPrintStyles(settings, sheets, id) {
|
|
70
|
+
const mm = ({ width, height }) => ({
|
|
71
|
+
width: `${width}mm`,
|
|
72
|
+
height: `${height}mm`,
|
|
73
|
+
});
|
|
74
|
+
return printStyles(`[${VIEW_ATTR}="${id}"]>.foli-page`, mm(settings.pageSize), sheets.map(({ settings: { pageSize }, index }) => ({ ...mm(pageSize), index })), id);
|
|
61
75
|
}
|
|
62
76
|
/** Whether `node` is inside an element of `stop` that is not displayed (hidden deleted text). */
|
|
63
77
|
function hiddenIn(node, stop) {
|
|
@@ -66,72 +80,157 @@ function hiddenIn(node, stop) {
|
|
|
66
80
|
return true;
|
|
67
81
|
return false;
|
|
68
82
|
}
|
|
69
|
-
/** The
|
|
70
|
-
const
|
|
83
|
+
/** The fields whose results depend on where things fall on the pages. */
|
|
84
|
+
const PAGE_DEPENDENT = new Set(["PAGE", "NUMPAGES", "SECTIONPAGES", "PAGEREF"]);
|
|
71
85
|
function sheetOf(settings, index) {
|
|
72
86
|
const { pageSize, margins } = settings;
|
|
73
|
-
const css =
|
|
87
|
+
const css =
|
|
88
|
+
// The containing block, stacking context and formatting context of floating pictures: one
|
|
89
|
+
// reaching past the page's text makes the page taller, never overlaps the next page.
|
|
90
|
+
"position: relative; isolation: isolate; display: flow-root; " +
|
|
91
|
+
`box-sizing: border-box; width: ${pageSize.width}mm; min-height: ${pageSize.height}mm; ` +
|
|
74
92
|
`padding: ${margins.top}mm ${margins.right}mm ${margins.bottom}mm ${margins.left}mm;`;
|
|
75
93
|
return { settings, css, index };
|
|
76
94
|
}
|
|
77
95
|
/** The style each page element was last given (its `cssText` reads back normalized). */
|
|
78
96
|
const pageSheets = new WeakMap();
|
|
97
|
+
/** The margins a header or footer gave each page element, as last written. */
|
|
98
|
+
const pagePads = new WeakMap();
|
|
99
|
+
/** What a view without pages gives its one flow of content. */
|
|
100
|
+
const UNPAGED_CSS = "display: flow-root; position: relative;";
|
|
101
|
+
const slotOf = (fragment) => ({
|
|
102
|
+
band: fragment.band ?? 0,
|
|
103
|
+
column: fragment.column ?? 0,
|
|
104
|
+
lead: fragment.lead,
|
|
105
|
+
mark: !!fragment.mark,
|
|
106
|
+
});
|
|
107
|
+
/** The document's sections and the blocks of each. */
|
|
108
|
+
function sectionSpans(doc, last) {
|
|
109
|
+
const spans = [];
|
|
110
|
+
let from = 0;
|
|
111
|
+
doc.forEach((node, _, i) => {
|
|
112
|
+
const own = node.attrs.section;
|
|
113
|
+
if (!own)
|
|
114
|
+
return;
|
|
115
|
+
spans.push({ setup: own, from, to: i + 1 });
|
|
116
|
+
from = i + 1;
|
|
117
|
+
});
|
|
118
|
+
if (from < doc.childCount || !spans.length)
|
|
119
|
+
spans.push({ setup: last, from, to: doc.childCount });
|
|
120
|
+
return spans;
|
|
121
|
+
}
|
|
79
122
|
/**
|
|
80
123
|
* The section of each top-level block (the section a paragraph's `section` ends; the
|
|
81
|
-
* envelope's for the blocks after the last such paragraph)
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
* add a blank page), as `renderDocument` lays sections out.
|
|
124
|
+
* envelope's for the blocks after the last such paragraph), as `renderDocument` lays sections
|
|
125
|
+
* out. By position: two paragraphs may end sections with one object. `box` gives a page's text
|
|
126
|
+
* height: null for a view without pages.
|
|
85
127
|
*/
|
|
86
|
-
function sectionLayouts(
|
|
128
|
+
function sectionLayouts(spans, box) {
|
|
87
129
|
const sheets = new Map();
|
|
88
130
|
const bySection = new Map();
|
|
89
131
|
const sheet = (section) => {
|
|
90
132
|
let found = bySection.get(section);
|
|
91
133
|
if (!found) {
|
|
92
134
|
const settings = sectionSettings(section);
|
|
93
|
-
const css = sheetOf(settings, 0).css;
|
|
94
|
-
found = sheets.get(css) ?? sheetOf(settings, sheets.size);
|
|
135
|
+
const css = box ? sheetOf(settings, 0).css : UNPAGED_CSS;
|
|
136
|
+
found = sheets.get(css) ?? { ...sheetOf(settings, sheets.size), css };
|
|
95
137
|
sheets.set(css, found);
|
|
96
138
|
bySection.set(section, found);
|
|
97
139
|
}
|
|
98
140
|
return found;
|
|
99
141
|
};
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
142
|
+
const sheetByFlow = new Map();
|
|
143
|
+
const out = [];
|
|
144
|
+
spans.forEach(({ setup, from: start, to }, s) => {
|
|
145
|
+
// Indexes in document order: the first page setup is 0.
|
|
146
|
+
const own = sheet(setup);
|
|
147
|
+
const next = spans[s + 1]?.setup;
|
|
148
|
+
const columns = columnsPx(setup);
|
|
149
|
+
const count = columns.widths.length;
|
|
150
|
+
const balanced = !!next && count > 1 && next.type === "continuous" && sheet(next).css === own.css;
|
|
151
|
+
const flow = {
|
|
152
|
+
index: s,
|
|
153
|
+
start: setup.type ?? "nextPage",
|
|
154
|
+
columns: count,
|
|
155
|
+
balanced,
|
|
156
|
+
pageStart: setup.pageNumbers?.start,
|
|
157
|
+
box: (page) => ({ height: box ? box(s, page) : Number.POSITIVE_INFINITY }),
|
|
158
|
+
samePage: (other) => sheetByFlow.get(other)?.css === own.css,
|
|
159
|
+
};
|
|
160
|
+
sheetByFlow.set(flow, own);
|
|
161
|
+
const section = {
|
|
162
|
+
sheet: own,
|
|
163
|
+
columns,
|
|
164
|
+
unequal: new Set(columns.widths).size > 1,
|
|
165
|
+
flow,
|
|
166
|
+
key: `${own.css}|${flow.start}|${flow.pageStart ?? ""}|${balanced}|${columnsKey(columns)}`,
|
|
167
|
+
};
|
|
168
|
+
for (let i = start; i < to; i++)
|
|
169
|
+
out[i] = { sheet: own, section, first: i === start };
|
|
116
170
|
});
|
|
171
|
+
return out;
|
|
117
172
|
}
|
|
118
173
|
/**
|
|
119
|
-
*
|
|
120
|
-
* page setup
|
|
174
|
+
* Where blocks are before a flow: where they were (`known`), moved where needed so that each
|
|
175
|
+
* page holds blocks of one page setup and each section has a band of its own: a block is
|
|
176
|
+
* measured in a column of its own section's width.
|
|
121
177
|
*/
|
|
122
|
-
function
|
|
123
|
-
|
|
124
|
-
let
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
178
|
+
function initialPlaces(pages, layout, known) {
|
|
179
|
+
let page = 0;
|
|
180
|
+
let band = 0;
|
|
181
|
+
let column = 0;
|
|
182
|
+
let section;
|
|
183
|
+
const slots = [];
|
|
184
|
+
const placed = pages.map((list, i) => {
|
|
185
|
+
const own = layout[i].section;
|
|
186
|
+
const out = [];
|
|
187
|
+
slots[i] = out;
|
|
188
|
+
return list.map((p, f) => {
|
|
189
|
+
let target = Math.max(p, page);
|
|
190
|
+
if (target === page && section && section !== own) {
|
|
191
|
+
// Only the last page used so far has a setup: the next one is free.
|
|
192
|
+
if (section.sheet.css !== own.sheet.css)
|
|
193
|
+
target++;
|
|
194
|
+
else {
|
|
195
|
+
band++;
|
|
196
|
+
column = 0;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (target > page) {
|
|
200
|
+
page = target;
|
|
201
|
+
band = 0;
|
|
202
|
+
column = 0;
|
|
203
|
+
}
|
|
204
|
+
section = own;
|
|
205
|
+
const was = known[i]?.[f];
|
|
206
|
+
column = Math.min(Math.max(column, was?.column ?? 0), own.columns.widths.length - 1);
|
|
207
|
+
out.push({
|
|
208
|
+
band,
|
|
209
|
+
column,
|
|
210
|
+
lead: was?.band === band ? was.lead : undefined,
|
|
211
|
+
mark: was?.mark ?? false,
|
|
212
|
+
});
|
|
213
|
+
return page;
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
return { pages: placed, slots };
|
|
217
|
+
}
|
|
218
|
+
/** Makes `list` the children of `parent`, moving as little as possible; returns what it removed. */
|
|
219
|
+
function fillElement(parent, list, removed) {
|
|
220
|
+
let at = parent.firstChild;
|
|
221
|
+
for (const dom of list) {
|
|
222
|
+
if (dom === at)
|
|
223
|
+
at = at.nextSibling;
|
|
224
|
+
else
|
|
225
|
+
parent.insertBefore(dom, at);
|
|
226
|
+
}
|
|
227
|
+
// What is left after the last placed one: strays, and blocks of later pages.
|
|
228
|
+
while (at) {
|
|
229
|
+
const next = at.nextSibling;
|
|
230
|
+
at.remove();
|
|
231
|
+
removed.add(at);
|
|
232
|
+
at = next;
|
|
233
|
+
}
|
|
135
234
|
}
|
|
136
235
|
/**
|
|
137
236
|
* The editable view of an `Editor` from `@folijs/core`: renders its state into one
|
|
@@ -156,8 +255,23 @@ export class EditorView {
|
|
|
156
255
|
indexOf = new Map();
|
|
157
256
|
/** The element that shows a node selection, if any. */
|
|
158
257
|
selectedDom = null;
|
|
159
|
-
/** The
|
|
160
|
-
|
|
258
|
+
/** The cells a cell selection marks, and the caret written in its head cell. */
|
|
259
|
+
selectedCells = [];
|
|
260
|
+
cellCaret = null;
|
|
261
|
+
/** The pages of each top-level item (a paragraph's fragments, a table's wrappers), by node. */
|
|
262
|
+
itemPages = new Map();
|
|
263
|
+
/** Where on its page each of those is (band and column). */
|
|
264
|
+
itemSlots = new Map();
|
|
265
|
+
/** Each page's band elements, as last placed. */
|
|
266
|
+
bands = new WeakMap();
|
|
267
|
+
/** Each table as last rendered, by node. */
|
|
268
|
+
frames = new Map();
|
|
269
|
+
/** The table each wrapper element draws (part of). */
|
|
270
|
+
frameOf = new Map();
|
|
271
|
+
/** Each table as last rendered, by its index among the top-level items. */
|
|
272
|
+
frameAt = [];
|
|
273
|
+
/** Elements the view itself removed: the read-back does not take them for input. */
|
|
274
|
+
viewRemoved = new WeakSet();
|
|
161
275
|
/** The block each fragment element belongs to. */
|
|
162
276
|
owner = new Map();
|
|
163
277
|
/** The page elements, in order; the host's only children. */
|
|
@@ -201,9 +315,12 @@ export class EditorView {
|
|
|
201
315
|
resizeObserver;
|
|
202
316
|
observed = new Set();
|
|
203
317
|
relayoutPending = false;
|
|
318
|
+
/** A composition runs in this view. */
|
|
204
319
|
composing = false;
|
|
205
320
|
/** Set by Ctrl/Cmd+Shift+V for the paste event it triggers. */
|
|
206
321
|
plainPaste = false;
|
|
322
|
+
/** How deep `renumberNotes` has rendered again. */
|
|
323
|
+
renumbering = 0;
|
|
207
324
|
/** Blocks whose DOM the browser changed: the next render rebuilds them. */
|
|
208
325
|
dirty = new Set();
|
|
209
326
|
/** DOM mutations not yet read back (kept while a composition is running). */
|
|
@@ -222,16 +339,107 @@ export class EditorView {
|
|
|
222
339
|
addedTabIndex;
|
|
223
340
|
/** Renders the document's blocks; made by the first render. */
|
|
224
341
|
word = null;
|
|
342
|
+
/** Where pasted and dropped image files go (`EditorViewOptions.upload`). */
|
|
343
|
+
upload;
|
|
344
|
+
/** The selected picture's span (with its resize handle). */
|
|
345
|
+
selectedPicture = null;
|
|
346
|
+
/** A picture being resized: its position, element, size at the press, scale, the press. */
|
|
347
|
+
resize = null;
|
|
348
|
+
/** The app's URLs for pictures' images (`EditorViewOptions.resource`). */
|
|
349
|
+
resource;
|
|
225
350
|
/** How tracked changes show. */
|
|
226
351
|
review = "markup";
|
|
352
|
+
/** Whether fields show their codes (`toggleFieldCodes`). */
|
|
353
|
+
fieldCodes = false;
|
|
354
|
+
/** The elements shaded for the fields the selection is in. */
|
|
355
|
+
shadedFields = [];
|
|
227
356
|
/** Fonts' normal line height ratios, measured once per family (Word's single spacing). */
|
|
228
357
|
ratios = new Map();
|
|
229
358
|
/** Web fonts loaded since the v3 blocks were drawn: the next render draws them again. */
|
|
230
359
|
fontsChanged = false;
|
|
360
|
+
/** Whether content goes on pages (`EditorViewOptions.paged`). */
|
|
361
|
+
paged;
|
|
362
|
+
/** The headers and footers of the pages; none without pages. */
|
|
363
|
+
regions;
|
|
364
|
+
/** Each page as last flowed. */
|
|
365
|
+
facts = [];
|
|
366
|
+
/** The header and footer element of each page, as last drawn. */
|
|
367
|
+
pageRegions = [];
|
|
368
|
+
/** Each page's margins, when a header or footer pushes them. */
|
|
369
|
+
pageMargins = [];
|
|
370
|
+
/** What the header and footer heights were when last laid out (`PageRegions.key`). */
|
|
371
|
+
regionsKey = "";
|
|
372
|
+
/** What `regionsKey` was computed from. */
|
|
373
|
+
regionsFor = null;
|
|
374
|
+
/** Footnotes and endnotes on the pages; none without pages. */
|
|
375
|
+
notes;
|
|
376
|
+
/** What each page shows of them. */
|
|
377
|
+
pageNotes = [];
|
|
378
|
+
/** Their elements by what they show. */
|
|
379
|
+
noteElements = new Map();
|
|
380
|
+
/** The page each note starts on, as last flowed: numbers can restart on each. */
|
|
381
|
+
notePages = new Map();
|
|
382
|
+
/** What the note references showed when last drawn. */
|
|
383
|
+
shownNotes = "";
|
|
384
|
+
/** The layout and boxes of the last flow, to draw notes again from. */
|
|
385
|
+
flowLayout = [];
|
|
386
|
+
flowBoxes = [];
|
|
387
|
+
/** What this view's note mark shows (`EditorViewOptions.noteMark`). */
|
|
388
|
+
noteMark;
|
|
389
|
+
/** Puts everything on its page again, as the last render left it. */
|
|
390
|
+
placeAgain = null;
|
|
391
|
+
/** The story being edited on its page, if any (ADR-0007). */
|
|
392
|
+
mount = null;
|
|
393
|
+
/** What find shows, and which tree this view draws of it (a mounted story's view: its own). */
|
|
394
|
+
found = null;
|
|
395
|
+
matchStory = null;
|
|
396
|
+
matchMarks;
|
|
397
|
+
/** The pages marked, as a key; the frame waiting to look again. */
|
|
398
|
+
matchPages = "";
|
|
399
|
+
matchFrame = 0;
|
|
400
|
+
/** The body's selection before the press of a double click in a page's margin. */
|
|
401
|
+
pressSelection = null;
|
|
402
|
+
/** The listeners on the host, to remove them. */
|
|
403
|
+
listeners = [];
|
|
404
|
+
/** The frames, titles and pop-ups of content controls. */
|
|
405
|
+
controlChrome;
|
|
231
406
|
constructor(host, editor, options = {}) {
|
|
232
407
|
this.host = host;
|
|
233
408
|
this.editor = editor;
|
|
234
409
|
this.state = editor.state;
|
|
410
|
+
this.matchMarks = new MatchMarks(host.ownerDocument);
|
|
411
|
+
this.paged = options.paged !== false;
|
|
412
|
+
this.noteMark = options.noteMark;
|
|
413
|
+
const view = this;
|
|
414
|
+
this.controlChrome = new ControlChrome({
|
|
415
|
+
host,
|
|
416
|
+
editor,
|
|
417
|
+
state: () => view.state,
|
|
418
|
+
editable: () => view.editable && !view.mount,
|
|
419
|
+
pages: () => view.pages,
|
|
420
|
+
scale: () => view.scale(),
|
|
421
|
+
rects: (range) => view.controlRects(range),
|
|
422
|
+
contentRects: (range) => view.controlContentRects(range),
|
|
423
|
+
posFromDOM: (node, offset) => view.posFromDOM(node, offset),
|
|
424
|
+
focus: () => view.focus(),
|
|
425
|
+
injectStyles: () => injectStyles(host),
|
|
426
|
+
});
|
|
427
|
+
const storyOptions = {
|
|
428
|
+
get review() {
|
|
429
|
+
return view.review;
|
|
430
|
+
},
|
|
431
|
+
get fieldCodes() {
|
|
432
|
+
return view.fieldCodes;
|
|
433
|
+
},
|
|
434
|
+
lineRatio: (family) => this.lineRatio(family),
|
|
435
|
+
resource: (key, resource) => this.resource?.(key, resource),
|
|
436
|
+
measureIn: () => this.pages[0] ?? host,
|
|
437
|
+
scale: () => this.scale(),
|
|
438
|
+
};
|
|
439
|
+
this.regions = this.paged
|
|
440
|
+
? new PageRegions(host.ownerDocument, storyOptions, new WeakMap())
|
|
441
|
+
: null;
|
|
442
|
+
this.notes = this.paged ? new PageNotes(host.ownerDocument, storyOptions, new WeakMap()) : null;
|
|
235
443
|
host.setAttribute("role", "textbox");
|
|
236
444
|
host.setAttribute("aria-multiline", "true");
|
|
237
445
|
host.setAttribute(VIEW_ATTR, this.id);
|
|
@@ -243,30 +451,52 @@ export class EditorView {
|
|
|
243
451
|
host.style.overflowWrap = "break-word";
|
|
244
452
|
host.replaceChildren();
|
|
245
453
|
this.review = trackState(this.state)?.view ?? "markup";
|
|
454
|
+
this.fieldCodes = fieldCodesShown(this.state);
|
|
246
455
|
this.resizeObserver =
|
|
247
456
|
typeof ResizeObserver === "undefined" ? null : new ResizeObserver(this.onResize);
|
|
248
457
|
this.observer = new MutationObserver(this.onMutations);
|
|
249
458
|
this.observer.observe(host, { childList: true, characterData: true, subtree: true });
|
|
459
|
+
// The picture resolver before the first render: no image drawn from a URL the app refuses.
|
|
460
|
+
this.resource = options.resource ?? undefined;
|
|
250
461
|
this.render();
|
|
251
462
|
this.setOptions(options);
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
463
|
+
this.listen("beforeinput", this.onBeforeInput);
|
|
464
|
+
this.listen("focus", this.onFocus);
|
|
465
|
+
this.listen("keydown", this.onKeyDown);
|
|
466
|
+
this.listen("input", this.onInput);
|
|
467
|
+
this.listen("compositionstart", this.onCompositionStart);
|
|
468
|
+
this.listen("compositionend", this.onCompositionEnd);
|
|
469
|
+
this.listen("blur", this.onBlur);
|
|
470
|
+
this.listen("mousedown", this.onPress);
|
|
471
|
+
this.listen("mousemove", this.onMouseMove);
|
|
472
|
+
this.listen("mouseleave", () => this.controlChrome.hover(null));
|
|
473
|
+
this.listen("copy", this.onCopy);
|
|
474
|
+
this.listen("cut", this.onCut);
|
|
475
|
+
this.listen("paste", this.onPaste);
|
|
476
|
+
this.listen("dragover", this.onDragOver);
|
|
477
|
+
this.listen("drop", this.onDrop);
|
|
478
|
+
this.listen("click", this.onClick);
|
|
479
|
+
this.listen("auxclick", this.onClick);
|
|
480
|
+
this.claimStories();
|
|
265
481
|
host.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
|
|
266
482
|
host.ownerDocument.fonts?.addEventListener("loadingdone", this.onFontsLoaded);
|
|
267
483
|
this.unsubscribe = editor.subscribe((state) => this.update(state));
|
|
268
484
|
}
|
|
485
|
+
/** Adds a listener for the body's events: a story open on a page has its own view. */
|
|
486
|
+
listen(type, handler) {
|
|
487
|
+
const listener = (event) => {
|
|
488
|
+
if (!this.mount?.wrapper.contains(event.target))
|
|
489
|
+
handler(event);
|
|
490
|
+
};
|
|
491
|
+
this.host.addEventListener(type, listener);
|
|
492
|
+
this.listeners.push([type, listener]);
|
|
493
|
+
}
|
|
269
494
|
destroy() {
|
|
495
|
+
this.closeStory(false);
|
|
496
|
+
this.showFound(null);
|
|
497
|
+
this.controlChrome.destroy();
|
|
498
|
+
if (this.editor.storyView === this.stories)
|
|
499
|
+
this.editor.storyView = null;
|
|
270
500
|
this.destroyed = true;
|
|
271
501
|
this.unsubscribe();
|
|
272
502
|
this.host.ownerDocument.fonts?.removeEventListener("loadingdone", this.onFontsLoaded);
|
|
@@ -275,19 +505,10 @@ export class EditorView {
|
|
|
275
505
|
for (const style of this.printStyles)
|
|
276
506
|
style.remove();
|
|
277
507
|
const { host } = this;
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
host.removeEventListener("compositionstart", this.onCompositionStart);
|
|
283
|
-
host.removeEventListener("compositionend", this.onCompositionEnd);
|
|
284
|
-
host.removeEventListener("blur", this.onBlur);
|
|
285
|
-
host.removeEventListener("mousedown", this.onMouseDown);
|
|
286
|
-
host.removeEventListener("copy", this.onCopy);
|
|
287
|
-
host.removeEventListener("cut", this.onCut);
|
|
288
|
-
host.removeEventListener("paste", this.onPaste);
|
|
289
|
-
host.removeEventListener("click", this.onClick);
|
|
290
|
-
host.removeEventListener("auxclick", this.onClick);
|
|
508
|
+
for (const [type, listener] of this.listeners)
|
|
509
|
+
host.removeEventListener(type, listener);
|
|
510
|
+
this.endDrag();
|
|
511
|
+
this.endResize();
|
|
291
512
|
host.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
|
|
292
513
|
const owned = [
|
|
293
514
|
"contenteditable",
|
|
@@ -309,6 +530,10 @@ export class EditorView {
|
|
|
309
530
|
}
|
|
310
531
|
/** Focuses the host, shows the model selection in it and scrolls it into view. */
|
|
311
532
|
focus() {
|
|
533
|
+
if (this.mount) {
|
|
534
|
+
this.mount.view.focus();
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
312
537
|
this.host.focus();
|
|
313
538
|
this.writeSelection(true);
|
|
314
539
|
// The focus handler scrolls only when it writes the selection itself, and a DOM selection
|
|
@@ -323,12 +548,37 @@ export class EditorView {
|
|
|
323
548
|
if (!options.editable && this.composing)
|
|
324
549
|
this.onCompositionEnd();
|
|
325
550
|
this.editable = options.editable;
|
|
551
|
+
if (!this.editable)
|
|
552
|
+
this.closeStory(false);
|
|
553
|
+
// A selected picture's handle only while it can be resized.
|
|
554
|
+
this.endResize();
|
|
555
|
+
this.showSelectedPicture();
|
|
326
556
|
}
|
|
327
557
|
if (options.placeholder !== undefined)
|
|
328
558
|
this.placeholder = options.placeholder;
|
|
559
|
+
if (options.upload !== undefined)
|
|
560
|
+
this.upload = options.upload ?? undefined;
|
|
561
|
+
this.mount?.view.setOptions({
|
|
562
|
+
...(options.upload !== undefined ? { upload: options.upload } : {}),
|
|
563
|
+
...(options.resource !== undefined ? { resource: options.resource } : {}),
|
|
564
|
+
});
|
|
565
|
+
// null clears the resolver (stored as none): the same as none is no change.
|
|
566
|
+
const resource = options.resource ?? undefined;
|
|
567
|
+
if (options.resource !== undefined && resource !== this.resource) {
|
|
568
|
+
this.resource = resource;
|
|
569
|
+
// Every picture again, from the new URLs: after a running composition, keeping the
|
|
570
|
+
// selection.
|
|
571
|
+
if (this.word) {
|
|
572
|
+
if (this.composing)
|
|
573
|
+
this.onCompositionEnd();
|
|
574
|
+
this.word = null;
|
|
575
|
+
this.render();
|
|
576
|
+
this.writeSelection(false);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
329
579
|
// Read-only: no caret and no browser editing; the text stays selectable and copyable.
|
|
330
|
-
host.setAttribute("contenteditable", String(this.editable));
|
|
331
|
-
if (this.editable)
|
|
580
|
+
host.setAttribute("contenteditable", String(this.editable && !this.mount));
|
|
581
|
+
if (this.editable && !this.mount)
|
|
332
582
|
host.removeAttribute("aria-readonly");
|
|
333
583
|
else
|
|
334
584
|
host.setAttribute("aria-readonly", "true");
|
|
@@ -356,6 +606,9 @@ export class EditorView {
|
|
|
356
606
|
}
|
|
357
607
|
// ---------- rendering ----------
|
|
358
608
|
update(state) {
|
|
609
|
+
// A resize is of the picture at its position when it started: the document changed, over.
|
|
610
|
+
if (state.doc !== this.state.doc)
|
|
611
|
+
this.onResizeCancel();
|
|
359
612
|
const review = trackState(state)?.view ?? "markup";
|
|
360
613
|
// Another review view (`setReviewView`): every block drawn again, by a new renderer.
|
|
361
614
|
const reviewChanged = review !== this.review;
|
|
@@ -363,11 +616,34 @@ export class EditorView {
|
|
|
363
616
|
this.review = review;
|
|
364
617
|
this.word = null;
|
|
365
618
|
}
|
|
366
|
-
|
|
619
|
+
// Codes shown or hidden: every block and story drawn again.
|
|
620
|
+
const codes = fieldCodesShown(state);
|
|
621
|
+
const codesChanged = codes !== this.fieldCodes;
|
|
622
|
+
if (codesChanged) {
|
|
623
|
+
this.fieldCodes = codes;
|
|
624
|
+
this.word = null;
|
|
625
|
+
}
|
|
626
|
+
const before = wordContext(this.state)?.envelope;
|
|
627
|
+
const envelope = wordContext(state)?.envelope;
|
|
628
|
+
// The last section's setup and the settings live in the envelope: changing them leaves the
|
|
629
|
+
// tree as it is. So does a story's change, which only its occurrences show.
|
|
630
|
+
const docChanged = state.doc !== this.state.doc ||
|
|
631
|
+
reviewChanged ||
|
|
632
|
+
codesChanged ||
|
|
633
|
+
envelope?.section !== before?.section ||
|
|
634
|
+
envelope?.settings !== before?.settings;
|
|
635
|
+
const storiesChanged = envelope?.stories !== before?.stories;
|
|
367
636
|
const selectionChanged = !state.selection.eq(this.state.selection);
|
|
637
|
+
// Another document: the story being edited closes.
|
|
638
|
+
const lost = !!this.mount && wordContext(state)?.id !== wordContext(this.state)?.id;
|
|
368
639
|
this.state = state;
|
|
369
|
-
if (docChanged)
|
|
640
|
+
if (docChanged || (storiesChanged && !this.redrawRegions()))
|
|
370
641
|
this.render();
|
|
642
|
+
if (lost)
|
|
643
|
+
this.closeStory(true);
|
|
644
|
+
// The open story has its own editor, which hears nothing of this.
|
|
645
|
+
if (codesChanged)
|
|
646
|
+
this.mount?.view.update(this.mount.view.editor.state);
|
|
371
647
|
this.showSelectedNode();
|
|
372
648
|
this.writeSelection(docChanged);
|
|
373
649
|
// shortcut: scrolls for every change while focused; once remote or plugin changes exist, scroll only for local input (a transaction flag).
|
|
@@ -410,83 +686,212 @@ export class EditorView {
|
|
|
410
686
|
* Measurements are cached by node and the flow restarts at the first changed block (5.4).
|
|
411
687
|
*/
|
|
412
688
|
render() {
|
|
689
|
+
try {
|
|
690
|
+
this.renderPages();
|
|
691
|
+
}
|
|
692
|
+
catch (error) {
|
|
693
|
+
// What it had changed is not input: read back, it would render and fail again, for ever.
|
|
694
|
+
this.observer.takeRecords();
|
|
695
|
+
this.pending = [];
|
|
696
|
+
throw error;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
renderPages() {
|
|
413
700
|
const { doc } = this.state;
|
|
414
701
|
const ownerDocument = this.host.ownerDocument;
|
|
415
702
|
// A new document (envelope) gets its renderer; nothing rendered before is reused then. An
|
|
416
703
|
// editor's state always has one (`createEditor`).
|
|
417
704
|
const context = wordContext(this.state);
|
|
418
705
|
// Fonts loaded: a new renderer (new line heights), but not while a composition runs in a
|
|
419
|
-
// block it would redraw.
|
|
420
|
-
const
|
|
706
|
+
// block it would redraw. What only stories or the settings changed leaves blocks as they are.
|
|
707
|
+
const drawn = this.word?.context;
|
|
708
|
+
const renewed = !drawn ||
|
|
709
|
+
drawn.id !== context.id ||
|
|
710
|
+
drawn.resolver !== context.resolver ||
|
|
711
|
+
drawn.envelope.section !== context.envelope.section ||
|
|
712
|
+
drawn.envelope.resources !== context.envelope.resources ||
|
|
713
|
+
drawn.envelope.comments !== context.envelope.comments ||
|
|
714
|
+
(this.fontsChanged && !this.composing);
|
|
421
715
|
if (renewed)
|
|
422
716
|
this.fontsChanged = false;
|
|
423
717
|
let word = this.word;
|
|
718
|
+
if (!renewed)
|
|
719
|
+
word.context = context;
|
|
424
720
|
if (renewed) {
|
|
425
|
-
|
|
721
|
+
// A document with pictures: the mark of one without alt text is the view's stylesheet's.
|
|
722
|
+
if (context.envelope.resources)
|
|
723
|
+
injectStyles(this.host);
|
|
724
|
+
word = this.word = new WordRenderer(context, ownerDocument, this.lineRatio, false, this.review, imageSource(context.envelope.resources, this.resource ?? undefined), this.fieldCodes);
|
|
426
725
|
this.invalidateLayout();
|
|
427
726
|
}
|
|
428
|
-
|
|
429
|
-
|
|
727
|
+
const references = this.noteReferences();
|
|
728
|
+
word.setNotes(noteTexts(references), this.noteMark?.());
|
|
729
|
+
// The blocks the view renders (paragraphs in table cells among them) and the page flow's
|
|
730
|
+
// items (top-level paragraphs and opaque blocks, and tables).
|
|
731
|
+
const { units, items } = collect(doc, context.resolver);
|
|
732
|
+
word.prepare(units.map((unit) => unit.node), (i) => {
|
|
733
|
+
const unit = units[i];
|
|
734
|
+
const previous = units[i - 1];
|
|
735
|
+
// Siblings: one ends where the other starts.
|
|
736
|
+
return unit.cell && previous && previous.pos + previous.node.nodeSize === unit.pos
|
|
737
|
+
? { node: previous.node, cell: unit.cell }
|
|
738
|
+
: null;
|
|
739
|
+
});
|
|
740
|
+
// A story's view has none of the body's sections: its one flow is not a page's.
|
|
741
|
+
const spans = sectionSpans(doc, this.paged ? context.envelope.section : {});
|
|
742
|
+
const { regions } = this;
|
|
743
|
+
regions?.setDocument(context.envelope, spans.map((span) => span.setup), context.resolver);
|
|
744
|
+
const { notes } = this;
|
|
745
|
+
notes?.setDocument(context.envelope, spans.map((span) => span.setup), context.resolver, references);
|
|
746
|
+
const layout = sectionLayouts(spans, regions && ((section, page) => regions.boxHeight(section, page)));
|
|
430
747
|
doc.forEach((node, _, i) => {
|
|
431
|
-
const {
|
|
432
|
-
const key = `${
|
|
748
|
+
const { section, first } = layout[i];
|
|
749
|
+
const key = `${section.key}${first ? "|first" : ""}`;
|
|
433
750
|
const before = this.layoutKeys.get(node);
|
|
434
751
|
if (before !== undefined && before !== key)
|
|
435
752
|
this.stale.add(node);
|
|
436
753
|
this.layoutKeys.set(node, key);
|
|
437
754
|
});
|
|
438
755
|
const previous = new Map(this.blocks.filter((desc) => !this.dirty.has(desc)).map((desc) => [desc.node, desc]));
|
|
439
|
-
const previousPages = this.
|
|
756
|
+
const previousPages = this.itemPages;
|
|
757
|
+
const previousFrames = this.frames;
|
|
440
758
|
this.dirty.clear();
|
|
441
759
|
const dropLines = this.linesStale && !this.composing;
|
|
442
760
|
if (dropLines) {
|
|
443
761
|
this.linesStale = false;
|
|
444
762
|
this.flowed = null;
|
|
445
763
|
}
|
|
764
|
+
// What can be reused: a block whose list number, comment shading or cell formatting changed
|
|
765
|
+
// (an edit before it) is redrawn.
|
|
766
|
+
const reusable = units.map((unit, i) => {
|
|
767
|
+
const found = renewed ? undefined : previous.get(unit.node);
|
|
768
|
+
if (found && found.key === word.key(i, unit.cell))
|
|
769
|
+
return found;
|
|
770
|
+
if (found)
|
|
771
|
+
this.stale.add(unit.node);
|
|
772
|
+
return undefined;
|
|
773
|
+
});
|
|
774
|
+
this.staleAroundFloats(doc, previousPages, new Set(units.filter((_, i) => !reusable[i]).map((unit) => unit.node)));
|
|
775
|
+
// A table is measured again (drawn whole first) when it changed, went stale, or one of its
|
|
776
|
+
// blocks is redrawn or stale; its blocks with it.
|
|
777
|
+
const remeasureUnit = units.map(() => false);
|
|
778
|
+
for (const item of items) {
|
|
779
|
+
const frame = item.frame;
|
|
780
|
+
if (!frame)
|
|
781
|
+
continue;
|
|
782
|
+
let stale = dropLines || !this.measures.has(frame.node) || this.stale.has(frame.node);
|
|
783
|
+
for (let u = frame.first; !stale && u < frame.end; u++)
|
|
784
|
+
stale = !reusable[u] || this.stale.has(units[u].node);
|
|
785
|
+
if (!stale)
|
|
786
|
+
continue;
|
|
787
|
+
this.stale.add(frame.node);
|
|
788
|
+
for (let u = frame.first; u < frame.end; u++)
|
|
789
|
+
remeasureUnit[u] = true;
|
|
790
|
+
}
|
|
446
791
|
let blocks = [];
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
if (
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
}
|
|
792
|
+
// Nodes still in the document: an old block or table at an index is only taken over (during
|
|
793
|
+
// a composition) when its node is gone, never when an insertion moved it along.
|
|
794
|
+
const present = new Set(units.map((unit) => unit.node));
|
|
795
|
+
for (const item of items)
|
|
796
|
+
if (item.frame)
|
|
797
|
+
present.add(item.frame.node);
|
|
798
|
+
units.forEach((unit, i) => {
|
|
799
|
+
const { node } = unit;
|
|
800
|
+
let reused = reusable[i];
|
|
455
801
|
// A split block about to be measured again (fonts, CSS) is rendered whole first: each
|
|
456
802
|
// fragment's end breaks its line, so its lines would depend on where it was split before.
|
|
457
|
-
const remeasure = dropLines || !this.measures.has(node) || this.stale.has(node);
|
|
803
|
+
const remeasure = remeasureUnit[i] || dropLines || !this.measures.has(node) || this.stale.has(node);
|
|
458
804
|
if (reused && reused.fragments.length > 1 && remeasure && !this.composing)
|
|
459
805
|
reused = undefined;
|
|
460
806
|
if (reused)
|
|
461
807
|
previous.delete(node);
|
|
462
|
-
|
|
463
|
-
|
|
808
|
+
const desc = reused ?? word.render(node, i, [], unit.cell);
|
|
809
|
+
blocks.push(desc);
|
|
810
|
+
// Drawn again in a table cell: the new block takes the old one's place there, so a table
|
|
811
|
+
// kept as it is (during a composition, which moves nothing) still holds it. During a
|
|
812
|
+
// composition a block whose node changed takes the place of the block drawn at its index.
|
|
813
|
+
const atIndex = this.blocks[i];
|
|
814
|
+
const old = reused
|
|
815
|
+
? undefined
|
|
816
|
+
: (previous.get(node) ??
|
|
817
|
+
(this.composing &&
|
|
818
|
+
atIndex &&
|
|
819
|
+
!present.has(atIndex.node) &&
|
|
820
|
+
previous.get(atIndex.node) === atIndex
|
|
821
|
+
? atIndex
|
|
822
|
+
: undefined));
|
|
823
|
+
const first = old?.fragments[0];
|
|
824
|
+
if (old && first?.isConnected && first.parentElement?.closest(`[${FRAME_ATTR}]`)) {
|
|
825
|
+
first.replaceWith(...desc.fragments);
|
|
826
|
+
for (const fragment of old.fragments.slice(1))
|
|
827
|
+
fragment.remove();
|
|
828
|
+
for (const fragment of old.fragments)
|
|
829
|
+
this.viewRemoved.add(fragment);
|
|
830
|
+
previous.delete(old.node);
|
|
831
|
+
}
|
|
464
832
|
});
|
|
465
833
|
for (const stale of previous.values())
|
|
466
|
-
for (const fragment of stale.fragments)
|
|
834
|
+
for (const fragment of stale.fragments) {
|
|
467
835
|
fragment.remove();
|
|
836
|
+
this.viewRemoved.add(fragment);
|
|
837
|
+
}
|
|
468
838
|
this.applyPrintStyles(layout);
|
|
839
|
+
const doc_ = this.host.ownerDocument;
|
|
840
|
+
const frames = new Map();
|
|
841
|
+
/** A table drawn whole, on one page: what is measured. */
|
|
842
|
+
const whole = (frame) => {
|
|
843
|
+
const rows = frame.rows.map((_, r) => r);
|
|
844
|
+
const wrapper = frameElement(frame, rows, [], (r, c) => this.cellContent(frame, r, c, blocks, () => true), doc_);
|
|
845
|
+
return { wrappers: [wrapper], pages: [0], key: "" };
|
|
846
|
+
};
|
|
847
|
+
// Before the flow, each item where it was (a new one joins the page of the item before it);
|
|
848
|
+
// a table that changed is drawn whole on that page.
|
|
469
849
|
let last = 0;
|
|
470
|
-
let pages =
|
|
471
|
-
const
|
|
850
|
+
let pages = items.map((item, i) => {
|
|
851
|
+
const node = doc.child(i);
|
|
852
|
+
const before = previousPages.get(node);
|
|
853
|
+
if (item.frame) {
|
|
854
|
+
let state = previousFrames.get(node);
|
|
855
|
+
// During a composition nothing moves: a table that changed keeps the wrappers drawn at
|
|
856
|
+
// its place (its redrawn blocks took their old ones' places above).
|
|
857
|
+
const at = this.frameAt[i];
|
|
858
|
+
if (!state && this.composing && at && !present.has(at.node))
|
|
859
|
+
state = at.state;
|
|
860
|
+
if (!state || (this.stale.has(node) && !this.composing))
|
|
861
|
+
state = whole(item.frame);
|
|
862
|
+
frames.set(node, state);
|
|
863
|
+
const pagesBefore = before ?? (state === at?.state ? state.pages : undefined);
|
|
864
|
+
return state.wrappers.map((_, f) => (last = Math.max(last, pagesBefore?.[f] ?? last)));
|
|
865
|
+
}
|
|
866
|
+
const desc = blocks[item.unit];
|
|
472
867
|
return desc.fragments.map((_, f) => (last = Math.max(last, before?.[f] ?? last)));
|
|
473
868
|
});
|
|
474
|
-
|
|
475
|
-
|
|
869
|
+
const initial = initialPlaces(pages, layout, items.map((_, i) => this.itemSlots.get(doc.child(i))));
|
|
870
|
+
pages = initial.pages;
|
|
871
|
+
let slots = initial.slots;
|
|
872
|
+
const elementsOf = (item, i) => item.frame
|
|
873
|
+
? frames.get(doc.child(i)).wrappers
|
|
874
|
+
: blocks[item.unit].fragments;
|
|
875
|
+
this.place(items.map((item, i) => elementsOf(item, i)), pages, slots, layout);
|
|
476
876
|
if (!this.composing) {
|
|
477
877
|
// DOM reads only for blocks without a valid measurement (new, changed or stale ones).
|
|
478
878
|
let scale;
|
|
479
879
|
const layoutPx = () => {
|
|
480
|
-
scale ??=
|
|
880
|
+
scale ??= this.scale();
|
|
481
881
|
return scale;
|
|
482
882
|
};
|
|
883
|
+
// A header or footer of another height moves every page's text: no flow is reused.
|
|
884
|
+
if (regions && this.regionsChanged(regions, spans))
|
|
885
|
+
this.flowed = null;
|
|
483
886
|
if (dropLines)
|
|
484
887
|
for (const desc of blocks) {
|
|
485
888
|
const measure = this.measures.get(desc.node);
|
|
486
|
-
if (measure)
|
|
889
|
+
if (measure) {
|
|
487
890
|
delete measure.lines;
|
|
891
|
+
delete measure.widths;
|
|
892
|
+
}
|
|
488
893
|
}
|
|
489
|
-
const nodes =
|
|
894
|
+
const nodes = items.map((_, i) => doc.child(i));
|
|
490
895
|
// A block's spacing depends on its neighbours' styles: reuse stops a block earlier.
|
|
491
896
|
const reuse = this.flowed ? reuseOf(this.flowed, nodes, this.stale, 1) : undefined;
|
|
492
897
|
const measureOf = (desc) => {
|
|
@@ -503,30 +908,188 @@ export class EditorView {
|
|
|
503
908
|
found.lines ??= measureLines(desc, layoutPx());
|
|
504
909
|
return found.lines;
|
|
505
910
|
};
|
|
506
|
-
|
|
507
|
-
const
|
|
911
|
+
/** A block's height and lines at a column's width, wherever it is now. */
|
|
912
|
+
const atWidth = (desc, width, kept) => {
|
|
913
|
+
const measure = measureOf(desc);
|
|
914
|
+
const widths = measure.widths ?? new Map();
|
|
915
|
+
measure.widths = widths;
|
|
916
|
+
const known = widths.get(width);
|
|
917
|
+
if (known)
|
|
918
|
+
return known;
|
|
919
|
+
const read = (measure) => {
|
|
920
|
+
for (const { style } of desc.fragments) {
|
|
921
|
+
style.boxSizing = "border-box";
|
|
922
|
+
style.width = `${width}px`;
|
|
923
|
+
}
|
|
924
|
+
const value = measure();
|
|
925
|
+
for (const { style } of desc.fragments) {
|
|
926
|
+
style.boxSizing = "";
|
|
927
|
+
style.width = "";
|
|
928
|
+
}
|
|
929
|
+
return value;
|
|
930
|
+
};
|
|
931
|
+
const { height } = read(() => measureBox(desc, layoutPx()));
|
|
932
|
+
let all;
|
|
933
|
+
const found = {
|
|
934
|
+
height,
|
|
935
|
+
all: () => {
|
|
936
|
+
all ??= read(() => measureLines(desc, layoutPx()));
|
|
937
|
+
return all;
|
|
938
|
+
},
|
|
939
|
+
lines: () => (kept ? [height] : found.all().bottoms),
|
|
940
|
+
};
|
|
941
|
+
widths.set(width, found);
|
|
942
|
+
return found;
|
|
943
|
+
};
|
|
944
|
+
const tableOf = (frame, i) => {
|
|
945
|
+
let found = this.measures.get(frame.node);
|
|
946
|
+
if (!found?.table || this.stale.delete(frame.node)) {
|
|
947
|
+
const wrapper = frames.get(doc.child(i)).wrappers[0];
|
|
948
|
+
// Its blocks are measured with it (their heights, for a resize later).
|
|
949
|
+
for (let u = frame.first; u < frame.end; u++) {
|
|
950
|
+
const desc = blocks[u];
|
|
951
|
+
this.stale.delete(desc.node);
|
|
952
|
+
this.measures.set(desc.node, measureBox(desc, layoutPx()));
|
|
953
|
+
}
|
|
954
|
+
found = measureTable(frame, wrapper, blocks, layoutPx());
|
|
955
|
+
this.measures.set(frame.node, found);
|
|
956
|
+
}
|
|
957
|
+
return found;
|
|
958
|
+
};
|
|
959
|
+
const words = items.map((item) => item.frame ? TABLE_WORD : blocks[item.unit].word);
|
|
960
|
+
const endnotes = notes?.endnotes();
|
|
961
|
+
const boxes = items.map((item, i) => {
|
|
962
|
+
const own = layout[i];
|
|
963
|
+
const pageHeight = contentHeight(own.sheet.settings);
|
|
964
|
+
const index = own.section.flow.index ?? 0;
|
|
965
|
+
const noteOf = (story) => notes?.footnote(story, index) ?? null;
|
|
966
|
+
// Endnotes follow the last block of their section, or of the document.
|
|
967
|
+
const after = layout[i + 1]?.section !== own.section
|
|
968
|
+
? { endnotes: endnotes?.get(index) }
|
|
969
|
+
: {};
|
|
970
|
+
if (item.frame) {
|
|
971
|
+
const frame = item.frame;
|
|
972
|
+
const measure = tableOf(frame, i);
|
|
973
|
+
const breaks = () => breaksOf(frame, measure, blocks, pageHeight, lines);
|
|
974
|
+
// A page break before the next paragraph ends its page.
|
|
975
|
+
return {
|
|
976
|
+
...tableBox(frame, measure, pageHeight, !!words[i + 1]?.pageBreakBefore, breaks),
|
|
977
|
+
section: own.section.flow,
|
|
978
|
+
notes: tableNotes(frame, measure, blocks, lines, breaks, noteOf),
|
|
979
|
+
...after,
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
const desc = blocks[item.unit];
|
|
983
|
+
return {
|
|
984
|
+
...wordBox(words, i, desc, measureOf(desc), () => lines(desc), own, atWidth, context.resolver.addsParagraphSpacing, noteOf),
|
|
985
|
+
...after,
|
|
986
|
+
};
|
|
987
|
+
});
|
|
988
|
+
const rules = {
|
|
989
|
+
...WORD_RULES,
|
|
990
|
+
addSpacing: context.resolver.addsParagraphSpacing,
|
|
991
|
+
evenAndOddHeaders: context.envelope.settings?.evenAndOddHeaders === true,
|
|
992
|
+
notes: notes?.flowRules(),
|
|
993
|
+
};
|
|
994
|
+
const flowHeight = contentHeight(this.editor.settings);
|
|
995
|
+
let result = flowFrom(boxes, flowHeight, rules, reuse);
|
|
996
|
+
let facts = pagesOf(boxes, result);
|
|
997
|
+
// The page count is known once flowed; a header holding it can change what fits.
|
|
998
|
+
for (let pass = 0; regions && pass < 2 && regions.settle(facts); pass++) {
|
|
999
|
+
result = flowFrom(boxes, flowHeight, rules);
|
|
1000
|
+
facts = pagesOf(boxes, result);
|
|
1001
|
+
}
|
|
1002
|
+
this.facts = facts;
|
|
508
1003
|
this.flowed = { nodes, result };
|
|
1004
|
+
this.flowLayout = layout;
|
|
1005
|
+
this.flowBoxes = boxes;
|
|
509
1006
|
this.stale.clear();
|
|
510
1007
|
const flowed = result.fragments;
|
|
511
|
-
|
|
1008
|
+
slots = flowed.map((fragments) => fragments.map(slotOf));
|
|
1009
|
+
// Paragraphs: split where their fragments start. Tables: the rows each fragment shows,
|
|
1010
|
+
// and their blocks split where a row is.
|
|
1011
|
+
const splitsOf = new Map();
|
|
1012
|
+
const parts = new Map();
|
|
1013
|
+
items.forEach((item, i) => {
|
|
512
1014
|
const fragments = flowed[i] ?? [];
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
const
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
1015
|
+
if (item.unit !== undefined) {
|
|
1016
|
+
const desc = blocks[item.unit];
|
|
1017
|
+
const contentStart = units[item.unit].pos + 1;
|
|
1018
|
+
const { section } = layout[i];
|
|
1019
|
+
splitsOf.set(item.unit, fragments.slice(1).map((fragment) => {
|
|
1020
|
+
// Line numbers are those of the column the fragment is in.
|
|
1021
|
+
const measured = section.unequal
|
|
1022
|
+
? atWidth(desc, section.columns.widths[fragment.column ?? 0], false).all()
|
|
1023
|
+
: lines(desc);
|
|
1024
|
+
const offset = measured.starts[fragment.fromLine];
|
|
1025
|
+
// Never split a grapheme cluster across pages.
|
|
1026
|
+
return clusterBoundary(doc, contentStart + offset, false) - contentStart;
|
|
1027
|
+
}));
|
|
1028
|
+
return;
|
|
1029
|
+
}
|
|
1030
|
+
const frame = item.frame;
|
|
1031
|
+
const measure = this.measures.get(frame.node);
|
|
1032
|
+
const cut = cutTable(frame, measure, fragments, blocks, lines);
|
|
1033
|
+
parts.set(i, cut);
|
|
1034
|
+
for (const [u, at] of cut.splits) {
|
|
1035
|
+
const contentStart = units[u].pos + 1;
|
|
1036
|
+
splitsOf.set(u, at.map((offset) => clusterBoundary(doc, contentStart + offset, false) - contentStart));
|
|
1037
|
+
}
|
|
1038
|
+
});
|
|
1039
|
+
blocks = blocks.map((desc, u) => {
|
|
1040
|
+
const splits = splitsOf.get(u) ?? [];
|
|
519
1041
|
const same = splits.length === desc.splits.length && splits.every((at, k) => at === desc.splits[k]);
|
|
520
|
-
return same ? desc : word.render(desc.node,
|
|
1042
|
+
return same ? desc : word.render(desc.node, u, splits, units[u].cell);
|
|
1043
|
+
});
|
|
1044
|
+
pages = items.map((item, i) => {
|
|
1045
|
+
const fragments = flowed[i] ?? [];
|
|
1046
|
+
if (!item.frame)
|
|
1047
|
+
return fragments.map((fragment) => fragment.page);
|
|
1048
|
+
const node = doc.child(i);
|
|
1049
|
+
const cut = parts.get(i);
|
|
1050
|
+
const key = JSON.stringify([cut.parts, [...cut.partOf]]);
|
|
1051
|
+
const kept = frames.get(node);
|
|
1052
|
+
const pagesOf = fragments.map((fragment) => fragment.page);
|
|
1053
|
+
// The same cut of the same table, its blocks' elements all in it: its wrappers stay.
|
|
1054
|
+
if (kept.key === key && holdsAll(kept, item.frame, blocks)) {
|
|
1055
|
+
frames.set(node, { ...kept, pages: pagesOf });
|
|
1056
|
+
return pagesOf;
|
|
1057
|
+
}
|
|
1058
|
+
const wrappers = cut.parts.map((part, k) => frameElement(item.frame, part.rows, part.headers, (r, c) => this.cellContent(item.frame, r, c, blocks, (u, f) => cut.partOf.get(u)?.[f] === k), doc_));
|
|
1059
|
+
frames.set(node, { wrappers, pages: pagesOf, key });
|
|
1060
|
+
return pagesOf;
|
|
521
1061
|
});
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
1062
|
+
const firsts = items.map((item, i) => item.frame
|
|
1063
|
+
? frames.get(doc.child(i)).wrappers[0]
|
|
1064
|
+
: blocks[item.unit].dom);
|
|
1065
|
+
applyGaps(firsts, result.gaps);
|
|
1066
|
+
this.drawRegions();
|
|
1067
|
+
this.drawNotes();
|
|
1068
|
+
this.place(items.map((item, i) => elementsOf(item, i)), pages, slots, layout);
|
|
1069
|
+
this.afterPlace();
|
|
525
1070
|
}
|
|
1071
|
+
const placed = items.map((item, i) => elementsOf(item, i));
|
|
1072
|
+
const placedPages = pages;
|
|
1073
|
+
const placedSlots = slots;
|
|
1074
|
+
this.placeAgain = () => this.place(placed, placedPages, placedSlots, layout);
|
|
1075
|
+
// (Wrappers no longer drawn are not in a page: `place` removed them.)
|
|
1076
|
+
this.frames = frames;
|
|
1077
|
+
this.frameAt = items.map((item, i) => {
|
|
1078
|
+
const state = item.frame && frames.get(doc.child(i));
|
|
1079
|
+
return state ? { node: doc.child(i), state } : undefined;
|
|
1080
|
+
});
|
|
1081
|
+
this.frameOf = new Map();
|
|
1082
|
+
items.forEach((item, i) => {
|
|
1083
|
+
if (!item.frame)
|
|
1084
|
+
return;
|
|
1085
|
+
for (const wrapper of frames.get(doc.child(i)).wrappers)
|
|
1086
|
+
this.frameOf.set(wrapper, item.frame);
|
|
1087
|
+
});
|
|
526
1088
|
this.blocks = blocks;
|
|
527
|
-
this.starts =
|
|
1089
|
+
this.starts = units.map((unit) => unit.pos);
|
|
528
1090
|
this.indexOf = new Map(blocks.map((desc, i) => [desc, i]));
|
|
529
|
-
this.
|
|
1091
|
+
this.itemPages = new Map(items.map((_, i) => [doc.child(i), pages[i] ?? []]));
|
|
1092
|
+
this.itemSlots = new Map(items.map((_, i) => [doc.child(i), slots[i] ?? []]));
|
|
530
1093
|
this.owner = new Map(blocks.flatMap((desc) => desc.fragments.map((fragment) => [fragment, desc])));
|
|
531
1094
|
this.unflowed = this.composing;
|
|
532
1095
|
this.observeSizes();
|
|
@@ -537,6 +1100,1051 @@ export class EditorView {
|
|
|
537
1100
|
const records = this.observer.takeRecords();
|
|
538
1101
|
if (this.composing)
|
|
539
1102
|
this.pending.push(...records);
|
|
1103
|
+
this.renumberNotes();
|
|
1104
|
+
}
|
|
1105
|
+
/** The note references shown, with their numbers as the last flow's pages make them. */
|
|
1106
|
+
noteReferences() {
|
|
1107
|
+
if (!this.paged)
|
|
1108
|
+
return [];
|
|
1109
|
+
const { doc } = this.state;
|
|
1110
|
+
const { envelope } = wordContext(this.state);
|
|
1111
|
+
const hideDeleted = this.review !== "markup";
|
|
1112
|
+
const all = noteNumbers(doc, envelope, {
|
|
1113
|
+
hideDeleted,
|
|
1114
|
+
pageOf: (_pos, story) => this.notePages.get(story),
|
|
1115
|
+
});
|
|
1116
|
+
this.shownNotes = JSON.stringify(all.map((n) => n.text));
|
|
1117
|
+
return hideDeleted ? all.filter((n) => !n.deleted) : all;
|
|
1118
|
+
}
|
|
1119
|
+
/**
|
|
1120
|
+
* Numbers that restart on each page depend on the flow just made: when they came out otherwise,
|
|
1121
|
+
* once more with them (their width can move a line), at most twice.
|
|
1122
|
+
*/
|
|
1123
|
+
renumberNotes() {
|
|
1124
|
+
if (!this.notes || this.composing || this.renumbering > 1)
|
|
1125
|
+
return;
|
|
1126
|
+
const { envelope } = wordContext(this.state);
|
|
1127
|
+
const each = this.sections().some((section) => noteProperties(envelope, "footnote", section).restart === "eachPage");
|
|
1128
|
+
if (!each)
|
|
1129
|
+
return;
|
|
1130
|
+
const shown = this.shownNotes;
|
|
1131
|
+
this.noteReferences();
|
|
1132
|
+
if (this.shownNotes === shown)
|
|
1133
|
+
return;
|
|
1134
|
+
this.renumbering++;
|
|
1135
|
+
try {
|
|
1136
|
+
this.renderPages();
|
|
1137
|
+
}
|
|
1138
|
+
finally {
|
|
1139
|
+
this.renumbering = 0;
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
/** The section of each page's bands in the last flow, and each note's place on the pages. */
|
|
1143
|
+
drawNotes() {
|
|
1144
|
+
const { notes, flowed, facts, mount } = this;
|
|
1145
|
+
if (!notes)
|
|
1146
|
+
return;
|
|
1147
|
+
const pieces = flowed ? notePieces(flowed.result) : [];
|
|
1148
|
+
const notePages = new Map();
|
|
1149
|
+
for (const piece of pieces)
|
|
1150
|
+
if (!piece.fromLine && !notePages.has(piece.id))
|
|
1151
|
+
notePages.set(piece.id, piece.page);
|
|
1152
|
+
this.notePages = notePages;
|
|
1153
|
+
const bandSections = new Map();
|
|
1154
|
+
flowed?.result.fragments.forEach((fragments, i) => {
|
|
1155
|
+
const index = this.flowLayout[i]?.section.flow.index ?? 0;
|
|
1156
|
+
for (const f of fragments)
|
|
1157
|
+
bandSections.set(`${f.page}|${f.band ?? 0}`, index);
|
|
1158
|
+
});
|
|
1159
|
+
const groups = notes.groups(pieces, (page, band) => bandSections.get(`${page}|${band}`) ??
|
|
1160
|
+
bandSections.get(`${page}|0`) ??
|
|
1161
|
+
facts[page]?.section ??
|
|
1162
|
+
0);
|
|
1163
|
+
const foot = groups.filter((group) => !group.inFlow);
|
|
1164
|
+
const known = this.noteElements;
|
|
1165
|
+
const elements = new Map();
|
|
1166
|
+
const shown = [];
|
|
1167
|
+
const note = mount?.side === "note" ? mount : null;
|
|
1168
|
+
for (const group of groups) {
|
|
1169
|
+
const { settings } = this.sheetOfPage(group.page);
|
|
1170
|
+
const fact = facts[group.page];
|
|
1171
|
+
const bottom = fact?.sectionPages
|
|
1172
|
+
? this.regions.margins(fact.section, fact).bottom
|
|
1173
|
+
: settings.margins.bottom * PX_PER_MM;
|
|
1174
|
+
const place = group.inFlow
|
|
1175
|
+
? null
|
|
1176
|
+
: notes.footPlace({ left: settings.margins.left * PX_PER_MM, bottom }, notes.stacked(group, foot));
|
|
1177
|
+
// Footnotes beneath the text keep the space after the paragraph above them.
|
|
1178
|
+
const lead = group.inFlow && !group.pieces[0]?.end && flowed
|
|
1179
|
+
? spaceAfterText(this.flowBoxes, flowed.result, group.page, group.band, group.column)
|
|
1180
|
+
: 0;
|
|
1181
|
+
const key = `${group.page}|${group.band}|${group.column}|${group.inFlow}|${place?.left}|${place?.bottom}|${lead}|${notes.keyOf(group)}`;
|
|
1182
|
+
let element = known.get(key);
|
|
1183
|
+
if (!element) {
|
|
1184
|
+
element = notes.groupElement(group, place, (piece) => piece.id === note?.id && !piece.fromLine
|
|
1185
|
+
? note.region.element
|
|
1186
|
+
: notes.pieceElement(piece, group), lead);
|
|
1187
|
+
if (note && element.contains(note.wrapper))
|
|
1188
|
+
note.moved = true;
|
|
1189
|
+
}
|
|
1190
|
+
elements.set(key, element);
|
|
1191
|
+
const page = shown[group.page] ?? { foot: [], flow: new Map() };
|
|
1192
|
+
shown[group.page] = page;
|
|
1193
|
+
if (!group.inFlow)
|
|
1194
|
+
page.foot.push(element);
|
|
1195
|
+
else {
|
|
1196
|
+
const slot = `${group.band}|${group.column}`;
|
|
1197
|
+
page.flow.set(slot, [...(page.flow.get(slot) ?? []), element]);
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
this.noteElements = elements;
|
|
1201
|
+
this.pageNotes = Array.from({ length: shown.length }, (_, p) => shown[p] ?? { foot: [], flow: new Map() });
|
|
1202
|
+
if (!note)
|
|
1203
|
+
return;
|
|
1204
|
+
// Its reference went (undone, or hidden with the changes): the note closes.
|
|
1205
|
+
const page = notePages.get(note.id);
|
|
1206
|
+
if (page === undefined)
|
|
1207
|
+
queueMicrotask(() => this.closeStory(true));
|
|
1208
|
+
else
|
|
1209
|
+
note.page = page;
|
|
1210
|
+
}
|
|
1211
|
+
/** Layout px per px on screen: what a scaled ancestor (`transform`, `zoom`) multiplies by. */
|
|
1212
|
+
scale() {
|
|
1213
|
+
const page = this.pages[0];
|
|
1214
|
+
if (!page)
|
|
1215
|
+
return 1;
|
|
1216
|
+
return this.paged
|
|
1217
|
+
? layoutScale(page, this.sheets[0].settings)
|
|
1218
|
+
: page.getBoundingClientRect().width / page.offsetWidth || 1;
|
|
1219
|
+
}
|
|
1220
|
+
/** Whether the headers' and footers' heights differ from when the pages were last flowed. */
|
|
1221
|
+
regionsChanged(regions, spans) {
|
|
1222
|
+
const { stories, settings } = wordContext(this.state).envelope;
|
|
1223
|
+
const sections = spans.map((span) => span.setup);
|
|
1224
|
+
const known = this.regionsFor;
|
|
1225
|
+
if (known &&
|
|
1226
|
+
known.stories === stories &&
|
|
1227
|
+
known.settings === settings &&
|
|
1228
|
+
known.sections.length === sections.length &&
|
|
1229
|
+
known.sections.every((section, i) => section === sections[i]))
|
|
1230
|
+
return false;
|
|
1231
|
+
this.regionsFor = { stories, settings, sections };
|
|
1232
|
+
const key = `${regions.key()}|${this.notes?.key() ?? ""}`;
|
|
1233
|
+
// Even and odd headers also decide the blank pages: the flow depends on them.
|
|
1234
|
+
const changed = key !== this.regionsKey ||
|
|
1235
|
+
(known?.settings !== settings &&
|
|
1236
|
+
known?.settings?.evenAndOddHeaders !==
|
|
1237
|
+
settings?.evenAndOddHeaders);
|
|
1238
|
+
this.regionsKey = key;
|
|
1239
|
+
return changed;
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* Gives every page the header and footer the last flow says, redrawing those that changed. The
|
|
1243
|
+
* one holding the story being edited stays; it follows the story if its page no longer shows it.
|
|
1244
|
+
*/
|
|
1245
|
+
drawRegions() {
|
|
1246
|
+
const { regions, facts } = this;
|
|
1247
|
+
// A note open for editing is `drawNotes`' to look after.
|
|
1248
|
+
const mount = this.mount?.side === "note" ? null : this.mount;
|
|
1249
|
+
if (!regions)
|
|
1250
|
+
return;
|
|
1251
|
+
const sides = ["header", "footer"];
|
|
1252
|
+
const wanted = facts.map((page) =>
|
|
1253
|
+
// Word's blank page before an even or odd page section has neither.
|
|
1254
|
+
page.sectionPages
|
|
1255
|
+
? {
|
|
1256
|
+
header: regions.drawing(page.section, "header", page),
|
|
1257
|
+
footer: regions.drawing(page.section, "footer", page),
|
|
1258
|
+
}
|
|
1259
|
+
: { header: null, footer: null });
|
|
1260
|
+
const shows = (p) => !!mount && wanted[p]?.[mount.side]?.id === mount.id;
|
|
1261
|
+
// Its page, while it shows it. Replaced there (the section unlinked, another variant turned
|
|
1262
|
+
// on) it does not follow the old story to another page: the page's own opens.
|
|
1263
|
+
const replaced = !!mount && facts[mount.page]?.section === mount.section;
|
|
1264
|
+
const home = !mount
|
|
1265
|
+
? -1
|
|
1266
|
+
: shows(mount.page)
|
|
1267
|
+
? mount.page
|
|
1268
|
+
: replaced
|
|
1269
|
+
? -1
|
|
1270
|
+
: wanted.findIndex((_, p) => shows(p));
|
|
1271
|
+
this.pageRegions = facts.map((page, p) => {
|
|
1272
|
+
const own = {};
|
|
1273
|
+
for (const side of sides) {
|
|
1274
|
+
const drawing = wanted[p]?.[side];
|
|
1275
|
+
if (!drawing)
|
|
1276
|
+
continue;
|
|
1277
|
+
if (mount && p === home && side === mount.side) {
|
|
1278
|
+
own[side] = mount.region;
|
|
1279
|
+
if (mount.region.drawing !== drawing.content) {
|
|
1280
|
+
mount.region.drawing = drawing.content;
|
|
1281
|
+
const copy = drawing.content.content.cloneNode(true);
|
|
1282
|
+
copy.style.display = "none";
|
|
1283
|
+
mount.region.element
|
|
1284
|
+
.querySelector(`:scope > .${REGION_CONTENT_CLASS}`)
|
|
1285
|
+
?.replaceWith(copy);
|
|
1286
|
+
mount.wrapper.style.paddingBottom = copy.style.paddingBottom;
|
|
1287
|
+
}
|
|
1288
|
+
continue;
|
|
1289
|
+
}
|
|
1290
|
+
const known = this.pageRegions[p]?.[side];
|
|
1291
|
+
if (known?.drawing === drawing.content && known.section === page.section) {
|
|
1292
|
+
own[side] = known;
|
|
1293
|
+
continue;
|
|
1294
|
+
}
|
|
1295
|
+
const element = regions.element(page.section, side);
|
|
1296
|
+
element.append(drawing.content.content.cloneNode(true));
|
|
1297
|
+
own[side] = { element, drawing: drawing.content, section: page.section, id: drawing.id };
|
|
1298
|
+
}
|
|
1299
|
+
return own;
|
|
1300
|
+
});
|
|
1301
|
+
this.pageMargins = facts.map((page, p) => {
|
|
1302
|
+
if (!page.sectionPages)
|
|
1303
|
+
return { top: "", bottom: "" };
|
|
1304
|
+
const { top, bottom } = regions.margins(page.section, page);
|
|
1305
|
+
const { margins } = this.sheetOfPage(p).settings;
|
|
1306
|
+
return {
|
|
1307
|
+
top: Math.abs(top - margins.top * PX_PER_MM) < 0.01 ? "" : `${top}px`,
|
|
1308
|
+
bottom: Math.abs(bottom - margins.bottom * PX_PER_MM) < 0.01 ? "" : `${bottom}px`,
|
|
1309
|
+
};
|
|
1310
|
+
});
|
|
1311
|
+
if (!mount)
|
|
1312
|
+
return;
|
|
1313
|
+
// Not shown anywhere any more (a variant turned on or off): the page's own story opens.
|
|
1314
|
+
if (home < 0)
|
|
1315
|
+
queueMicrotask(this.reopenStory);
|
|
1316
|
+
else if (home !== mount.page) {
|
|
1317
|
+
mount.page = home;
|
|
1318
|
+
mount.moved = true;
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
/** The page setup page `p` has, or will have once placed. */
|
|
1322
|
+
sheetOfPage(p) {
|
|
1323
|
+
return this.sheets[p] ?? this.sheets[this.sheets.length - 1] ?? this.lastSheet();
|
|
1324
|
+
}
|
|
1325
|
+
/**
|
|
1326
|
+
* After a story changed: its occurrences redrawn. False when a height changed, which takes a
|
|
1327
|
+
* new flow (`render`), or during a composition.
|
|
1328
|
+
*/
|
|
1329
|
+
redrawRegions() {
|
|
1330
|
+
const { regions } = this;
|
|
1331
|
+
if (!regions)
|
|
1332
|
+
return true;
|
|
1333
|
+
if (this.composing)
|
|
1334
|
+
return true;
|
|
1335
|
+
const context = wordContext(this.state);
|
|
1336
|
+
const spans = sectionSpans(this.state.doc, context.envelope.section);
|
|
1337
|
+
regions.setDocument(context.envelope, spans.map((span) => span.setup), context.resolver);
|
|
1338
|
+
this.notes?.setDocument(context.envelope, spans.map((span) => span.setup), context.resolver, this.noteReferences());
|
|
1339
|
+
if (this.regionsChanged(regions, spans)) {
|
|
1340
|
+
this.flowed = null;
|
|
1341
|
+
return false;
|
|
1342
|
+
}
|
|
1343
|
+
this.drawRegions();
|
|
1344
|
+
this.drawNotes();
|
|
1345
|
+
this.placeAgain?.();
|
|
1346
|
+
this.afterPlace();
|
|
1347
|
+
this.observer.takeRecords();
|
|
1348
|
+
return true;
|
|
1349
|
+
}
|
|
1350
|
+
/** The story being edited, moved with its region: the focus goes back to it. */
|
|
1351
|
+
afterPlace() {
|
|
1352
|
+
this.drawControls();
|
|
1353
|
+
this.drawMatches();
|
|
1354
|
+
if (!this.mount?.moved)
|
|
1355
|
+
return;
|
|
1356
|
+
this.mount.moved = false;
|
|
1357
|
+
this.mount.view.focus();
|
|
1358
|
+
}
|
|
1359
|
+
// ---------- stories on their pages (ADR-0007) ----------
|
|
1360
|
+
/** What the toolbar and code open stories through (`Editor.storyView`). */
|
|
1361
|
+
stories = ((view) => ({
|
|
1362
|
+
get open() {
|
|
1363
|
+
const { mount } = view;
|
|
1364
|
+
return mount
|
|
1365
|
+
? { id: mount.id, side: mount.side, variant: mount.variant, section: mount.section }
|
|
1366
|
+
: null;
|
|
1367
|
+
},
|
|
1368
|
+
edit: (side, page) => view.openStory(side, page),
|
|
1369
|
+
editNote: (id) => view.openNote(id),
|
|
1370
|
+
toReference: () => view.toReference(),
|
|
1371
|
+
close: () => view.closeStory(),
|
|
1372
|
+
get fieldLayout() {
|
|
1373
|
+
return view.fieldLayout();
|
|
1374
|
+
},
|
|
1375
|
+
updateFields: (options, editor) => view.updateFields(options, editor),
|
|
1376
|
+
showMatches: (found) => view.showMatches(found),
|
|
1377
|
+
reveal: (target, options) => view.reveal(target, options),
|
|
1378
|
+
goToPage: (page, options) => view.goToPage(page, options),
|
|
1379
|
+
focus: () => view.focus(),
|
|
1380
|
+
}))(this);
|
|
1381
|
+
/** Makes this view the one `Editor.storyView` speaks for, telling listeners if it was not. */
|
|
1382
|
+
claimStories() {
|
|
1383
|
+
if (!this.paged || this.editor.storyView === this.stories)
|
|
1384
|
+
return;
|
|
1385
|
+
const first = !this.editor.storyView;
|
|
1386
|
+
this.editor.storyView = this.stories;
|
|
1387
|
+
if (!first)
|
|
1388
|
+
this.editor.storyChanged();
|
|
1389
|
+
}
|
|
1390
|
+
// ---------- find, and going places (11.11) ----------
|
|
1391
|
+
/**
|
|
1392
|
+
* Marks what find found: on the pages, in the story open, and in the drawn copies of the others.
|
|
1393
|
+
* Nothing of it is in the document or the pages' DOM, and it does not print. The current match is
|
|
1394
|
+
* scrolled to when it is where the view can show it.
|
|
1395
|
+
*/
|
|
1396
|
+
showMatches(found) {
|
|
1397
|
+
this.showFound(found);
|
|
1398
|
+
const { current, scroll } = found ?? {};
|
|
1399
|
+
if (!current || !scroll)
|
|
1400
|
+
return;
|
|
1401
|
+
if (current.story === this.matchStory)
|
|
1402
|
+
this.scrollToRange(current.from, current.to);
|
|
1403
|
+
else if (current.story === this.mount?.id)
|
|
1404
|
+
this.mount?.view.scrollToRange(current.from, current.to);
|
|
1405
|
+
}
|
|
1406
|
+
/** The screen ranges of `from..to` in one paragraph: one per text node it covers. */
|
|
1407
|
+
rangesOf(from, to) {
|
|
1408
|
+
const { doc } = this.state;
|
|
1409
|
+
if (to > doc.content.size)
|
|
1410
|
+
return [];
|
|
1411
|
+
const $from = doc.resolve(from);
|
|
1412
|
+
if (!$from.parent.isTextblock)
|
|
1413
|
+
return [];
|
|
1414
|
+
const desc = this.blocks[this.blockFrom($from.before())];
|
|
1415
|
+
if (!desc)
|
|
1416
|
+
return [];
|
|
1417
|
+
const start = $from.start();
|
|
1418
|
+
const out = [];
|
|
1419
|
+
for (const leaf of desc.leaves) {
|
|
1420
|
+
const at = start + leaf.offset;
|
|
1421
|
+
const a = Math.max(from, at);
|
|
1422
|
+
const b = Math.min(to, at + leaf.size);
|
|
1423
|
+
if (a >= b || hiddenIn(leaf.dom, desc.dom))
|
|
1424
|
+
continue;
|
|
1425
|
+
const range = this.host.ownerDocument.createRange();
|
|
1426
|
+
if (leaf.dom.nodeType === Node.TEXT_NODE) {
|
|
1427
|
+
range.setStart(leaf.dom, a - at);
|
|
1428
|
+
range.setEnd(leaf.dom, b - at);
|
|
1429
|
+
}
|
|
1430
|
+
else
|
|
1431
|
+
range.selectNodeContents(leaf.dom);
|
|
1432
|
+
out.push(range);
|
|
1433
|
+
}
|
|
1434
|
+
return out;
|
|
1435
|
+
}
|
|
1436
|
+
/** The pages on the screen and a screen around it: only these carry marks. */
|
|
1437
|
+
pagesNearView() {
|
|
1438
|
+
const height = this.host.ownerDocument.defaultView?.innerHeight ?? 0;
|
|
1439
|
+
const near = new Set();
|
|
1440
|
+
this.pages.forEach((page, i) => {
|
|
1441
|
+
const { top, bottom } = page.getBoundingClientRect();
|
|
1442
|
+
if (bottom >= -height && top <= 2 * height)
|
|
1443
|
+
near.add(i);
|
|
1444
|
+
});
|
|
1445
|
+
return near;
|
|
1446
|
+
}
|
|
1447
|
+
drawMatches() {
|
|
1448
|
+
const { found, mount } = this;
|
|
1449
|
+
if (mount) {
|
|
1450
|
+
mount.view.matchStory = mount.id;
|
|
1451
|
+
mount.view.showFound(found);
|
|
1452
|
+
}
|
|
1453
|
+
if (!found) {
|
|
1454
|
+
this.matchMarks.set([], []);
|
|
1455
|
+
this.matchPages = "";
|
|
1456
|
+
return;
|
|
1457
|
+
}
|
|
1458
|
+
injectStyles(this.host);
|
|
1459
|
+
const { doc } = this.state;
|
|
1460
|
+
const near = this.pagesNearView();
|
|
1461
|
+
this.matchPages = [...near].join();
|
|
1462
|
+
// What the near pages hold, as positions: of the body's top-level nodes on them.
|
|
1463
|
+
let low = 0;
|
|
1464
|
+
let high = doc.content.size;
|
|
1465
|
+
if (this.paged) {
|
|
1466
|
+
low = high + 1;
|
|
1467
|
+
high = -1;
|
|
1468
|
+
doc.forEach((node, offset) => {
|
|
1469
|
+
const pages = this.itemPages.get(node);
|
|
1470
|
+
if (pages && !pages.some((page) => near.has(page)))
|
|
1471
|
+
return;
|
|
1472
|
+
low = Math.min(low, offset);
|
|
1473
|
+
high = Math.max(high, offset + node.nodeSize);
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
// A tree's matches stand together, in order: those near are found by halving.
|
|
1477
|
+
const { matches } = found;
|
|
1478
|
+
let start = matches.findIndex((m) => m.story === this.matchStory);
|
|
1479
|
+
if (start < 0)
|
|
1480
|
+
start = matches.length;
|
|
1481
|
+
let end = start;
|
|
1482
|
+
while (end < matches.length && matches[end]?.story === this.matchStory)
|
|
1483
|
+
end++;
|
|
1484
|
+
let first = start;
|
|
1485
|
+
for (let last = end; first < last;) {
|
|
1486
|
+
const mid = (first + last) >> 1;
|
|
1487
|
+
if (matches[mid].to <= low)
|
|
1488
|
+
first = mid + 1;
|
|
1489
|
+
else
|
|
1490
|
+
last = mid;
|
|
1491
|
+
}
|
|
1492
|
+
const all = [];
|
|
1493
|
+
for (let i = first; i < end && matches[i].from < high; i++) {
|
|
1494
|
+
const { from, to } = matches[i];
|
|
1495
|
+
all.push(...this.rangesOf(from, to));
|
|
1496
|
+
}
|
|
1497
|
+
const others = new Set();
|
|
1498
|
+
for (const [i, { story }] of matches.entries())
|
|
1499
|
+
if ((i < start || i >= end) && story !== null && story !== mount?.id)
|
|
1500
|
+
others.add(story);
|
|
1501
|
+
const { current, query, matchCase, wholeWord } = found;
|
|
1502
|
+
const here = current?.story === this.matchStory ? current : null;
|
|
1503
|
+
if (others.size) {
|
|
1504
|
+
const options = { matchCase, wholeWord };
|
|
1505
|
+
const add = (root) => {
|
|
1506
|
+
if (root)
|
|
1507
|
+
all.push(...rangesInText(root, query, options));
|
|
1508
|
+
};
|
|
1509
|
+
for (const p of near) {
|
|
1510
|
+
const { header, footer } = this.pageRegions[p] ?? {};
|
|
1511
|
+
for (const region of [header, footer])
|
|
1512
|
+
if (region && others.has(region.id))
|
|
1513
|
+
add(region.element.querySelector(`:scope > .${REGION_CONTENT_CLASS}`));
|
|
1514
|
+
for (const note of this.pages[p]?.querySelectorAll(`[${NOTE_ATTR}]`) ?? [])
|
|
1515
|
+
if (others.has(note.getAttribute(NOTE_ATTR)))
|
|
1516
|
+
add(note);
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
this.matchMarks.set(all, here ? this.rangesOf(here.from, here.to) : []);
|
|
1520
|
+
}
|
|
1521
|
+
/** Scrolling brings other pages near: their marks are drawn, once per frame. */
|
|
1522
|
+
onMatchScroll = () => {
|
|
1523
|
+
const win = this.host.ownerDocument.defaultView;
|
|
1524
|
+
if (this.matchFrame || !win)
|
|
1525
|
+
return;
|
|
1526
|
+
this.matchFrame = win.requestAnimationFrame(() => {
|
|
1527
|
+
this.matchFrame = 0;
|
|
1528
|
+
if (this.found && [...this.pagesNearView()].join() !== this.matchPages)
|
|
1529
|
+
this.drawMatches();
|
|
1530
|
+
});
|
|
1531
|
+
};
|
|
1532
|
+
/** What find shows here, marked; a story's view is told by its page's view. */
|
|
1533
|
+
showFound(found) {
|
|
1534
|
+
const doc = this.host.ownerDocument;
|
|
1535
|
+
if (this.paged && !this.found !== !found) {
|
|
1536
|
+
if (found)
|
|
1537
|
+
doc.addEventListener("scroll", this.onMatchScroll, SCROLL_OPTIONS);
|
|
1538
|
+
else
|
|
1539
|
+
doc.removeEventListener("scroll", this.onMatchScroll, SCROLL_OPTIONS);
|
|
1540
|
+
}
|
|
1541
|
+
this.found = found;
|
|
1542
|
+
this.drawMatches();
|
|
1543
|
+
}
|
|
1544
|
+
scrollToRange(from, to) {
|
|
1545
|
+
let rect = this.rangesOf(from, to)[0]?.getClientRects?.()[0];
|
|
1546
|
+
if (!rect) {
|
|
1547
|
+
// A place, not a stretch of text: what holds it.
|
|
1548
|
+
const { node } = this.domFromPos(from);
|
|
1549
|
+
rect = (node instanceof Element ? node : node.parentElement)?.getBoundingClientRect();
|
|
1550
|
+
}
|
|
1551
|
+
// With room around it: a panel may float over the top of the window.
|
|
1552
|
+
if (rect)
|
|
1553
|
+
scrollRectIntoView(this.host, { top: rect.top - REVEAL_ABOVE, bottom: rect.bottom + 48 });
|
|
1554
|
+
}
|
|
1555
|
+
/** Opens story `id` where a page shows it, leaving the focus where it is. */
|
|
1556
|
+
openForReveal(id) {
|
|
1557
|
+
const kind = wordContext(this.state)?.stories.get(id)?.kind;
|
|
1558
|
+
if (kind === "footnote" || kind === "endnote")
|
|
1559
|
+
return this.openNote(id, false);
|
|
1560
|
+
if (kind !== "header" && kind !== "footer")
|
|
1561
|
+
return false;
|
|
1562
|
+
const page = this.pageRegions.findIndex((regions) => regions[kind]?.id === id);
|
|
1563
|
+
return page >= 0 && this.openStory(kind, page, false, false);
|
|
1564
|
+
}
|
|
1565
|
+
/**
|
|
1566
|
+
* Selects `target` and scrolls to it: in the body (leaving a story that is open), or in its story,
|
|
1567
|
+
* opened where it is. `focus`: the document takes the focus. False when no page shows it.
|
|
1568
|
+
*/
|
|
1569
|
+
reveal({ story, from, to }, { focus = false } = {}) {
|
|
1570
|
+
if (story === null) {
|
|
1571
|
+
this.closeStory(false);
|
|
1572
|
+
const { doc } = this.state;
|
|
1573
|
+
if (to > doc.content.size)
|
|
1574
|
+
return false;
|
|
1575
|
+
this.editor.dispatch(this.state.tr.setSelection(TextSelection.create(doc, from, to)));
|
|
1576
|
+
if (focus)
|
|
1577
|
+
this.focus();
|
|
1578
|
+
this.scrollToRange(from, to);
|
|
1579
|
+
return true;
|
|
1580
|
+
}
|
|
1581
|
+
if (this.mount?.id !== story && !this.openForReveal(story))
|
|
1582
|
+
return false;
|
|
1583
|
+
const { mount } = this;
|
|
1584
|
+
if (!mount)
|
|
1585
|
+
return false;
|
|
1586
|
+
mount.view.editor.select(from, to);
|
|
1587
|
+
if (focus)
|
|
1588
|
+
mount.view.focus();
|
|
1589
|
+
mount.view.scrollToRange(from, to);
|
|
1590
|
+
return true;
|
|
1591
|
+
}
|
|
1592
|
+
/** The caret to the start of page `page` (1-based) and the page into view. */
|
|
1593
|
+
goToPage(page, { focus = false } = {}) {
|
|
1594
|
+
const element = this.pages[page - 1];
|
|
1595
|
+
if (!element)
|
|
1596
|
+
return false;
|
|
1597
|
+
this.closeStory(false);
|
|
1598
|
+
search: for (const [i, desc] of this.blocks.entries()) {
|
|
1599
|
+
for (const [f, fragment] of desc.fragments.entries()) {
|
|
1600
|
+
if (fragment.closest(".foli-page") !== element)
|
|
1601
|
+
continue;
|
|
1602
|
+
const start = this.starts[i] + 1 + (f ? desc.splits[f - 1] : 0);
|
|
1603
|
+
const { doc } = this.state;
|
|
1604
|
+
this.editor.dispatch(this.state.tr.setSelection(Selection.near(doc.resolve(Math.min(start, doc.content.size)))));
|
|
1605
|
+
break search;
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
if (focus)
|
|
1609
|
+
this.focus();
|
|
1610
|
+
scrollRectIntoView(this.host, element.getBoundingClientRect());
|
|
1611
|
+
return true;
|
|
1612
|
+
}
|
|
1613
|
+
/** Word's keys for finding and going places, when the app shows something for them. */
|
|
1614
|
+
navigationKey(name) {
|
|
1615
|
+
const request = Object.hasOwn(NAVIGATION_KEYS, name) ? NAVIGATION_KEYS[name] : undefined;
|
|
1616
|
+
return !!request && this.editor.navigation?.(request) === true;
|
|
1617
|
+
}
|
|
1618
|
+
// ---------- content controls ----------
|
|
1619
|
+
/** The frames of content controls, drawn again (a render takes them off the pages). */
|
|
1620
|
+
drawControls() {
|
|
1621
|
+
if (!this.composing)
|
|
1622
|
+
this.controlChrome.draw(!this.mount);
|
|
1623
|
+
}
|
|
1624
|
+
/** Where a control's content is on the screen: its lines, or its blocks by page. */
|
|
1625
|
+
controlRects(range) {
|
|
1626
|
+
if (range.level !== "inline") {
|
|
1627
|
+
const byPage = new Map();
|
|
1628
|
+
for (let i = this.blockFrom(range.from); i < this.blocks.length; i++) {
|
|
1629
|
+
if (this.starts[i] >= range.to)
|
|
1630
|
+
break;
|
|
1631
|
+
for (const fragment of this.blocks[i].fragments) {
|
|
1632
|
+
if (!this.host.contains(fragment))
|
|
1633
|
+
continue;
|
|
1634
|
+
const rect = fragment.getBoundingClientRect();
|
|
1635
|
+
const page = fragment.closest(".foli-page,.foli-story-flow");
|
|
1636
|
+
const known = byPage.get(page);
|
|
1637
|
+
const left = Math.min(known?.left ?? rect.left, rect.left);
|
|
1638
|
+
const top = Math.min(known?.top ?? rect.top, rect.top);
|
|
1639
|
+
byPage.set(page, boxOf(left, top, Math.max(known?.right ?? rect.right, rect.right) - left, Math.max(known?.bottom ?? rect.bottom, rect.bottom) - top));
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
return [...byPage.values()];
|
|
1643
|
+
}
|
|
1644
|
+
return this.controlContentRects(range);
|
|
1645
|
+
}
|
|
1646
|
+
/** Where what a control's content shows is on the screen. */
|
|
1647
|
+
controlContentRects(range) {
|
|
1648
|
+
const dom = this.host.ownerDocument.createRange();
|
|
1649
|
+
const start = this.domFromPos(range.contentFrom);
|
|
1650
|
+
const end = this.domFromPos(range.contentTo);
|
|
1651
|
+
dom.setStart(start.node, start.offset);
|
|
1652
|
+
dom.setEnd(end.node, end.offset);
|
|
1653
|
+
const rects = [...(dom.getClientRects?.() ?? [])].filter((rect) => rect.width > 0);
|
|
1654
|
+
if (rects.length)
|
|
1655
|
+
return rects;
|
|
1656
|
+
// Nothing in it: a thin box where it is.
|
|
1657
|
+
const element = start.node.nodeType === Node.ELEMENT_NODE
|
|
1658
|
+
? start.node
|
|
1659
|
+
: start.node.parentElement;
|
|
1660
|
+
const rect = dom.getBoundingClientRect?.();
|
|
1661
|
+
const box = rect?.height ? rect : element?.getBoundingClientRect();
|
|
1662
|
+
return box ? [boxOf(box.left, box.top, 4, box.height)] : [];
|
|
1663
|
+
}
|
|
1664
|
+
/**
|
|
1665
|
+
* The keys of content controls: Alt+Down opens a list or date picker, and Left and Right stop on
|
|
1666
|
+
* each side of a control's edge, as Word's caret does (browsers cannot see the difference).
|
|
1667
|
+
*/
|
|
1668
|
+
controlKey(name) {
|
|
1669
|
+
if (name === "Alt-ArrowDown")
|
|
1670
|
+
return this.controlChrome.open();
|
|
1671
|
+
if (name !== "ArrowLeft" && name !== "ArrowRight")
|
|
1672
|
+
return false;
|
|
1673
|
+
const { selection, doc } = this.state;
|
|
1674
|
+
if (!(selection instanceof TextSelection) || !wordContext(this.state)?.envelope.controls)
|
|
1675
|
+
return false;
|
|
1676
|
+
const forward = name === "ArrowRight";
|
|
1677
|
+
const range = controlAt(doc, selection.from);
|
|
1678
|
+
if (!selection.empty) {
|
|
1679
|
+
// A placeholder is one thing: the arrows go past it.
|
|
1680
|
+
if (range?.level !== "inline" ||
|
|
1681
|
+
!controlProperties(this.state, range.id)?.placeholder?.showing ||
|
|
1682
|
+
selection.from !== range.contentFrom ||
|
|
1683
|
+
selection.to !== range.contentTo)
|
|
1684
|
+
return false;
|
|
1685
|
+
this.dispatch(this.state.tr.setSelection(TextSelection.create(doc, forward ? range.to : range.from)));
|
|
1686
|
+
return true;
|
|
1687
|
+
}
|
|
1688
|
+
const { $from } = selection;
|
|
1689
|
+
const next = forward ? $from.nodeAfter : $from.nodeBefore;
|
|
1690
|
+
if (next?.type.name !== "controlStart" && next?.type.name !== "controlEnd")
|
|
1691
|
+
return false;
|
|
1692
|
+
this.dispatch(this.state.tr.setSelection(TextSelection.create(doc, $from.pos + (forward ? 1 : -1))));
|
|
1693
|
+
return true;
|
|
1694
|
+
}
|
|
1695
|
+
// ---------- fields ----------
|
|
1696
|
+
/** The pages as last flowed, as fields need them; null without pages. */
|
|
1697
|
+
fieldLayout() {
|
|
1698
|
+
if (!this.regions || !this.facts.length)
|
|
1699
|
+
return null;
|
|
1700
|
+
return {
|
|
1701
|
+
pages: this.facts.length,
|
|
1702
|
+
pageAt: (pos) => {
|
|
1703
|
+
const { node } = this.domFromPos(Math.min(pos, this.state.doc.content.size));
|
|
1704
|
+
const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
|
|
1705
|
+
const page = this.facts[this.pages.indexOf(element?.closest(".foli-page"))];
|
|
1706
|
+
if (!page)
|
|
1707
|
+
return null;
|
|
1708
|
+
const format = this.sections()[page.section]?.pageNumbers?.format;
|
|
1709
|
+
return { number: page.number, sectionPages: page.sectionPages, format };
|
|
1710
|
+
},
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
/**
|
|
1714
|
+
* Updates fields from the pages shown: all of them, or those `options.only` says, of the body or
|
|
1715
|
+
* of `editor` (a story's). What that does to the pages is taken in by a second pass over what
|
|
1716
|
+
* depends on them, in the same undo step.
|
|
1717
|
+
*/
|
|
1718
|
+
updateFields(options = {}, editor = this.editor) {
|
|
1719
|
+
// A story's view has no pages: the view of the body has.
|
|
1720
|
+
const main = this.regions ? null : this.editor.storyView;
|
|
1721
|
+
if (main)
|
|
1722
|
+
return main.updateFields(options, editor);
|
|
1723
|
+
if (this.composing)
|
|
1724
|
+
this.onCompositionEnd();
|
|
1725
|
+
const report = updateFields(editor, { ...options, layout: this.fieldLayout() });
|
|
1726
|
+
const { only } = options;
|
|
1727
|
+
const range = !!only && typeof only !== "function";
|
|
1728
|
+
if (!report.updated || (range && !report.rebuilt))
|
|
1729
|
+
return report;
|
|
1730
|
+
const follows = (field) => range
|
|
1731
|
+
? field.parent?.name === "TOC"
|
|
1732
|
+
: PAGE_DEPENDENT.has(field.name) && (typeof only !== "function" || only(field));
|
|
1733
|
+
const again = updateFields(editor, {
|
|
1734
|
+
...options,
|
|
1735
|
+
layout: this.fieldLayout(),
|
|
1736
|
+
only: follows,
|
|
1737
|
+
continues: true,
|
|
1738
|
+
});
|
|
1739
|
+
return { ...report, updated: report.updated + again.updated };
|
|
1740
|
+
}
|
|
1741
|
+
/**
|
|
1742
|
+
* Prints what the document is now: fields updated (one undo step), then the browser's dialog.
|
|
1743
|
+
*/
|
|
1744
|
+
print() {
|
|
1745
|
+
try {
|
|
1746
|
+
this.updateFields();
|
|
1747
|
+
}
|
|
1748
|
+
finally {
|
|
1749
|
+
this.host.ownerDocument.defaultView?.print();
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
/**
|
|
1753
|
+
* Left and Right next to a field's markers: the browser's move starts where something can be
|
|
1754
|
+
* seen, or the markers (empty elements) cost WebKit a key press each. With codes shown the
|
|
1755
|
+
* view makes the move itself, over the whole field; whether it did.
|
|
1756
|
+
*/
|
|
1757
|
+
skipFieldParts(event) {
|
|
1758
|
+
const forward = event.key === "ArrowRight";
|
|
1759
|
+
if ((!forward && event.key !== "ArrowLeft") || event.ctrlKey || event.altKey || event.metaKey)
|
|
1760
|
+
return false;
|
|
1761
|
+
const { selection, doc } = this.state;
|
|
1762
|
+
// Shift extends by itself: an extended DOM selection would lose its anchor to the same spot.
|
|
1763
|
+
if (!(selection instanceof TextSelection) || event.shiftKey || !selection.empty)
|
|
1764
|
+
return false;
|
|
1765
|
+
const stop = caretStop(this.state, selection.head, forward);
|
|
1766
|
+
const sel = this.host.ownerDocument.getSelection();
|
|
1767
|
+
if (stop === selection.head || !sel)
|
|
1768
|
+
return false;
|
|
1769
|
+
if (this.fieldCodes) {
|
|
1770
|
+
this.dispatch(this.state.tr.setSelection(TextSelection.create(doc, stop)));
|
|
1771
|
+
return true;
|
|
1772
|
+
}
|
|
1773
|
+
const { node, offset } = this.domFromPos(stop);
|
|
1774
|
+
sel.collapse(node, offset);
|
|
1775
|
+
return false;
|
|
1776
|
+
}
|
|
1777
|
+
/** F9 and Alt+F9, as in Word. */
|
|
1778
|
+
fieldKey(name) {
|
|
1779
|
+
if (name === "Alt-F9") {
|
|
1780
|
+
this.run(toggleFieldCodes);
|
|
1781
|
+
return true;
|
|
1782
|
+
}
|
|
1783
|
+
if (name !== "F9")
|
|
1784
|
+
return false;
|
|
1785
|
+
if (!this.editable)
|
|
1786
|
+
return true;
|
|
1787
|
+
const { selection } = this.state;
|
|
1788
|
+
this.updateFields(selection instanceof AllSelection ? {} : { only: { from: selection.from, to: selection.to } });
|
|
1789
|
+
return true;
|
|
1790
|
+
}
|
|
1791
|
+
/** Shades what shows the fields the selection is in (not printed): the outermost of each. */
|
|
1792
|
+
showSelectedFields() {
|
|
1793
|
+
const { selection, doc } = this.state;
|
|
1794
|
+
const wanted = new Set();
|
|
1795
|
+
const fields = selection instanceof TextSelection ? fieldsIn(doc) : [];
|
|
1796
|
+
const touched = (field) => selection.empty
|
|
1797
|
+
? field.from < selection.from && selection.from < field.to
|
|
1798
|
+
: field.from < selection.to && field.to > selection.from;
|
|
1799
|
+
for (const field of fields) {
|
|
1800
|
+
if (!touched(field) || (field.parent && touched(field.parent)))
|
|
1801
|
+
continue;
|
|
1802
|
+
const [from, to] = this.fieldCodes
|
|
1803
|
+
? [field.from, field.codeEnd + 1]
|
|
1804
|
+
: [field.resultFrom, field.resultTo];
|
|
1805
|
+
const first = Math.max(this.blockFrom(from) - 1, 0);
|
|
1806
|
+
for (let i = first; i < this.blocks.length; i++) {
|
|
1807
|
+
const start = this.starts[i] + 1;
|
|
1808
|
+
if (start > to)
|
|
1809
|
+
break;
|
|
1810
|
+
const desc = this.blocks[i];
|
|
1811
|
+
for (const leaf of desc.leaves) {
|
|
1812
|
+
const at = start + leaf.offset;
|
|
1813
|
+
if (at + leaf.size <= from || at >= to || !leaf.size)
|
|
1814
|
+
continue;
|
|
1815
|
+
if (hiddenIn(leaf.dom, desc.dom))
|
|
1816
|
+
continue;
|
|
1817
|
+
const element = leaf.dom.nodeType === Node.TEXT_NODE ? leaf.dom.parentElement : leaf.dom;
|
|
1818
|
+
if (element instanceof Element && element.textContent)
|
|
1819
|
+
wanted.add(element);
|
|
1820
|
+
}
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
for (const element of this.shadedFields)
|
|
1824
|
+
if (!wanted.has(element))
|
|
1825
|
+
element.removeAttribute(FIELD_SELECTED_ATTR);
|
|
1826
|
+
if (wanted.size)
|
|
1827
|
+
injectStyles(this.host);
|
|
1828
|
+
for (const element of wanted)
|
|
1829
|
+
element.setAttribute(FIELD_SELECTED_ATTR, "");
|
|
1830
|
+
this.shadedFields = [...wanted];
|
|
1831
|
+
}
|
|
1832
|
+
/** The sections of the document, in order. */
|
|
1833
|
+
sections() {
|
|
1834
|
+
const { envelope } = wordContext(this.state);
|
|
1835
|
+
return sectionSpans(this.state.doc, envelope.section).map((span) => span.setup);
|
|
1836
|
+
}
|
|
1837
|
+
/** The page the selection's head is on. */
|
|
1838
|
+
selectionPage() {
|
|
1839
|
+
const { node } = this.domFromPos(this.state.selection.head);
|
|
1840
|
+
const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
|
|
1841
|
+
return Math.max(this.pages.indexOf(element?.closest(".foli-page")), 0);
|
|
1842
|
+
}
|
|
1843
|
+
/**
|
|
1844
|
+
* Opens the header or footer of page `at` (by default the selection's) for editing where it is;
|
|
1845
|
+
* made first when the page has none. Whether it is open now.
|
|
1846
|
+
*/
|
|
1847
|
+
openStory(side, at = this.selectionPage(), create = true, focus = true) {
|
|
1848
|
+
if (!this.regions || !this.editable || this.composing)
|
|
1849
|
+
return false;
|
|
1850
|
+
// Word's blank page has none: the next page's.
|
|
1851
|
+
let p = at;
|
|
1852
|
+
while (this.facts[p] && !this.facts[p]?.sectionPages)
|
|
1853
|
+
p++;
|
|
1854
|
+
const page = this.facts[p];
|
|
1855
|
+
if (!page)
|
|
1856
|
+
return false;
|
|
1857
|
+
const context = wordContext(this.state);
|
|
1858
|
+
const setup = this.sections()[page.section];
|
|
1859
|
+
const even = context.envelope.settings?.evenAndOddHeaders === true;
|
|
1860
|
+
const variant = pageVariant(setup, page, even);
|
|
1861
|
+
const before = storyOfSection(this.sections(), page.section, side, variant);
|
|
1862
|
+
if (this.mount?.id === before?.id && this.mount?.side === side && this.mount?.page === p) {
|
|
1863
|
+
if (focus)
|
|
1864
|
+
this.mount?.view.focus();
|
|
1865
|
+
return true;
|
|
1866
|
+
}
|
|
1867
|
+
this.closeStory(false);
|
|
1868
|
+
if (!before && (!create || !this.editor.run(ensureStory(side, variant, page.section))))
|
|
1869
|
+
return false;
|
|
1870
|
+
const found = storyOfSection(this.sections(), page.section, side, variant);
|
|
1871
|
+
const editor = found && this.editor.story(found.id);
|
|
1872
|
+
const region = this.pageRegions[p]?.[side];
|
|
1873
|
+
if (!found || !editor || !region)
|
|
1874
|
+
return false;
|
|
1875
|
+
this.mountStory(editor, { id: found.id, side, variant, section: page.section, page: p, region }, side === "header" ? "Header" : "Footer", undefined, focus);
|
|
1876
|
+
return true;
|
|
1877
|
+
}
|
|
1878
|
+
/**
|
|
1879
|
+
* Opens note `id`, or the one whose reference is at the selection, in place: shown whole at its
|
|
1880
|
+
* reference's page. Whether it is open now.
|
|
1881
|
+
*/
|
|
1882
|
+
openNote(id, focus = true) {
|
|
1883
|
+
const { notes } = this;
|
|
1884
|
+
if (!notes || !this.editable || this.composing)
|
|
1885
|
+
return false;
|
|
1886
|
+
const story = id ?? noteAtSelection(this.state)?.story;
|
|
1887
|
+
if (!story)
|
|
1888
|
+
return false;
|
|
1889
|
+
if (this.mount?.id === story) {
|
|
1890
|
+
if (focus)
|
|
1891
|
+
this.mount.view.focus();
|
|
1892
|
+
return true;
|
|
1893
|
+
}
|
|
1894
|
+
this.closeStory(false);
|
|
1895
|
+
const editor = this.editor.story(story);
|
|
1896
|
+
if (!editor)
|
|
1897
|
+
return false;
|
|
1898
|
+
notes.open = story;
|
|
1899
|
+
this.flowed = null;
|
|
1900
|
+
this.render();
|
|
1901
|
+
const element = this.host.querySelector(`[${NOTE_ATTR}="${CSS.escape(story)}"]`);
|
|
1902
|
+
const page = this.notePages.get(story);
|
|
1903
|
+
if (!element || page === undefined) {
|
|
1904
|
+
notes.open = null;
|
|
1905
|
+
this.flowed = null;
|
|
1906
|
+
this.render();
|
|
1907
|
+
return false;
|
|
1908
|
+
}
|
|
1909
|
+
const region = { element, drawing: {}, section: 0, id: story };
|
|
1910
|
+
const texts = () => noteTexts(noteNumbers(this.state.doc, wordContext(this.state).envelope));
|
|
1911
|
+
this.mountStory(editor, { id: story, side: "note", variant: "default", section: 0, page, region }, "Note", () => texts().get(story) ?? "", focus);
|
|
1912
|
+
editor.select(Selection.atEnd(editor.state.doc).from);
|
|
1913
|
+
return true;
|
|
1914
|
+
}
|
|
1915
|
+
/** From the note being edited back to its reference, the caret after it. */
|
|
1916
|
+
toReference() {
|
|
1917
|
+
const { mount } = this;
|
|
1918
|
+
if (mount?.side !== "note")
|
|
1919
|
+
return false;
|
|
1920
|
+
const reference = noteNumbers(this.state.doc, wordContext(this.state).envelope).find((n) => n.story === mount.id);
|
|
1921
|
+
this.closeStory(false);
|
|
1922
|
+
if (reference)
|
|
1923
|
+
this.dispatch(this.state.tr.setSelection(TextSelection.create(this.state.doc, reference.pos + 1)));
|
|
1924
|
+
this.focus();
|
|
1925
|
+
return true;
|
|
1926
|
+
}
|
|
1927
|
+
/** Puts `editor`'s story on its page, in `place`, the body read-only and dimmed around it. */
|
|
1928
|
+
mountStory(editor, place, label, noteMark, focus = true) {
|
|
1929
|
+
const { region } = place;
|
|
1930
|
+
injectStyles(this.host);
|
|
1931
|
+
this.observer.disconnect();
|
|
1932
|
+
this.host.setAttribute("contenteditable", "false");
|
|
1933
|
+
this.host.setAttribute("aria-readonly", "true");
|
|
1934
|
+
this.host.classList.add("foli-in-story");
|
|
1935
|
+
const doc = this.host.ownerDocument;
|
|
1936
|
+
const wrapper = doc.createElement("div");
|
|
1937
|
+
wrapper.className = "foli-story-mount";
|
|
1938
|
+
wrapper.setAttribute("contenteditable", "false");
|
|
1939
|
+
wrapper.style.userSelect = "text";
|
|
1940
|
+
wrapper.style.setProperty("-webkit-user-select", "text");
|
|
1941
|
+
const inner = doc.createElement("div");
|
|
1942
|
+
inner.setAttribute("aria-label", label);
|
|
1943
|
+
wrapper.append(inner);
|
|
1944
|
+
const shown = region.element.querySelector(`:scope > .${REGION_CONTENT_CLASS}`);
|
|
1945
|
+
if (shown) {
|
|
1946
|
+
shown.style.display = "none";
|
|
1947
|
+
wrapper.style.paddingBottom = shown.style.paddingBottom;
|
|
1948
|
+
}
|
|
1949
|
+
region.element.append(wrapper);
|
|
1950
|
+
const view = new EditorView(inner, editor, {
|
|
1951
|
+
paged: false,
|
|
1952
|
+
upload: this.upload ?? null,
|
|
1953
|
+
resource: this.resource ?? null,
|
|
1954
|
+
...(noteMark ? { noteMark } : {}),
|
|
1955
|
+
});
|
|
1956
|
+
wrapper.addEventListener("keydown", (event) => {
|
|
1957
|
+
if (event.isComposing || view.composing)
|
|
1958
|
+
return;
|
|
1959
|
+
if (isNoteKey(event) && this.toReference()) {
|
|
1960
|
+
// Not on to the body, which would open the note again.
|
|
1961
|
+
event.preventDefault();
|
|
1962
|
+
event.stopPropagation();
|
|
1963
|
+
return;
|
|
1964
|
+
}
|
|
1965
|
+
if (event.key !== "Escape")
|
|
1966
|
+
return;
|
|
1967
|
+
event.preventDefault();
|
|
1968
|
+
this.closeStory(true);
|
|
1969
|
+
});
|
|
1970
|
+
this.mount = { ...place, wrapper, view, moved: false };
|
|
1971
|
+
// With several views of the editor, the one in use answers for its story.
|
|
1972
|
+
wrapper.addEventListener("focusin", () => this.claimStories());
|
|
1973
|
+
this.claimStories();
|
|
1974
|
+
if (focus)
|
|
1975
|
+
view.focus();
|
|
1976
|
+
this.drawMatches();
|
|
1977
|
+
this.editor.storyChanged();
|
|
1978
|
+
}
|
|
1979
|
+
/** Finishes a running composition, its text going into the model. */
|
|
1980
|
+
endComposition() {
|
|
1981
|
+
if (this.composing)
|
|
1982
|
+
this.onCompositionEnd();
|
|
1983
|
+
}
|
|
1984
|
+
/** Leaves the story being edited; `focus`: the body takes the focus, with its selection back. */
|
|
1985
|
+
closeStory(focus = true) {
|
|
1986
|
+
const { mount } = this;
|
|
1987
|
+
if (!mount)
|
|
1988
|
+
return;
|
|
1989
|
+
mount.view.endComposition();
|
|
1990
|
+
this.mount = null;
|
|
1991
|
+
mount.view.destroy();
|
|
1992
|
+
mount.wrapper.remove();
|
|
1993
|
+
const shown = mount.region.element.querySelector(`:scope > .${REGION_CONTENT_CLASS}`);
|
|
1994
|
+
if (shown)
|
|
1995
|
+
shown.style.display = "";
|
|
1996
|
+
if (mount.side === "note" && this.notes) {
|
|
1997
|
+
this.notes.open = null;
|
|
1998
|
+
this.flowed = null;
|
|
1999
|
+
if (!this.destroyed)
|
|
2000
|
+
this.render();
|
|
2001
|
+
}
|
|
2002
|
+
this.host.classList.remove("foli-in-story");
|
|
2003
|
+
this.host.setAttribute("contenteditable", String(this.editable));
|
|
2004
|
+
if (this.editable)
|
|
2005
|
+
this.host.removeAttribute("aria-readonly");
|
|
2006
|
+
this.observer.takeRecords();
|
|
2007
|
+
this.observer.observe(this.host, { childList: true, characterData: true, subtree: true });
|
|
2008
|
+
if (focus && !this.destroyed)
|
|
2009
|
+
this.focus();
|
|
2010
|
+
if (!this.destroyed)
|
|
2011
|
+
this.drawMatches();
|
|
2012
|
+
this.editor.storyChanged();
|
|
2013
|
+
}
|
|
2014
|
+
/** The page's own story, after what was open is shown nowhere any more. */
|
|
2015
|
+
reopenStory = () => {
|
|
2016
|
+
const { mount } = this;
|
|
2017
|
+
if (!mount || mount.side === "note" || this.facts.length === 0)
|
|
2018
|
+
return;
|
|
2019
|
+
const { side, page, id } = mount;
|
|
2020
|
+
// A story that went (undone) is not made again.
|
|
2021
|
+
const create = !!wordContext(this.state)?.stories.has(id);
|
|
2022
|
+
this.closeStory(false);
|
|
2023
|
+
if (!this.openStory(side, Math.min(page, this.facts.length - 1), create))
|
|
2024
|
+
this.focus();
|
|
2025
|
+
};
|
|
2026
|
+
/** The margin of a page a mouse event is in, if it is on the page itself. */
|
|
2027
|
+
marginAt(event) {
|
|
2028
|
+
const element = event.target;
|
|
2029
|
+
const page = this.pages.indexOf(element);
|
|
2030
|
+
if (page < 0 || !this.regions)
|
|
2031
|
+
return null;
|
|
2032
|
+
const box = element.getBoundingClientRect();
|
|
2033
|
+
const scale = this.scale();
|
|
2034
|
+
const style = getComputedStyle(element);
|
|
2035
|
+
const y = (event.clientY - box.top) / scale;
|
|
2036
|
+
if (y < Number.parseFloat(style.paddingTop))
|
|
2037
|
+
return { side: "header", page };
|
|
2038
|
+
return y > box.height / scale - Number.parseFloat(style.paddingBottom)
|
|
2039
|
+
? { side: "footer", page }
|
|
2040
|
+
: null;
|
|
2041
|
+
}
|
|
2042
|
+
/**
|
|
2043
|
+
* A press outside the story being edited leaves it. The second press of a double click in a
|
|
2044
|
+
* page's margin opens its header or footer, the body's selection kept: on the press, since the
|
|
2045
|
+
* first click may have scrolled the page (Firefox) and the double click would land elsewhere.
|
|
2046
|
+
*/
|
|
2047
|
+
onPress = (event) => {
|
|
2048
|
+
this.closeStory(false);
|
|
2049
|
+
// A note on the page, or the number of its reference: the second press opens the note.
|
|
2050
|
+
const target = event.target instanceof Element ? event.target : null;
|
|
2051
|
+
const onNote = target?.closest(`[${NOTE_ATTR}]`);
|
|
2052
|
+
const number = target?.closest(`[${NOTE_REF_ATTR}]`);
|
|
2053
|
+
const story = onNote?.getAttribute(NOTE_ATTR) ?? number?.getAttribute(NOTE_REF_ATTR);
|
|
2054
|
+
if (story && event.button === 0 && !event.shiftKey) {
|
|
2055
|
+
const opens = event.detail === 2 && this.editable && isNoteStory(this.state, story);
|
|
2056
|
+
if (onNote || opens)
|
|
2057
|
+
event.preventDefault();
|
|
2058
|
+
if (opens) {
|
|
2059
|
+
if (this.openNote(story) && onNote)
|
|
2060
|
+
this.mount?.view.placeCaret(event.clientX, event.clientY);
|
|
2061
|
+
return;
|
|
2062
|
+
}
|
|
2063
|
+
if (onNote)
|
|
2064
|
+
return;
|
|
2065
|
+
}
|
|
2066
|
+
const margin = event.button === 0 && !event.shiftKey ? this.marginAt(event) : null;
|
|
2067
|
+
if (margin && event.detail > 1) {
|
|
2068
|
+
event.preventDefault();
|
|
2069
|
+
if (event.detail > 2 || !this.editable)
|
|
2070
|
+
return;
|
|
2071
|
+
const selection = this.pressSelection;
|
|
2072
|
+
this.pressSelection = null;
|
|
2073
|
+
if (selection && !selection.eq(this.state.selection))
|
|
2074
|
+
this.editor.dispatch(this.state.tr.setSelection(selection));
|
|
2075
|
+
if (this.openStory(margin.side, margin.page))
|
|
2076
|
+
this.mount?.view.placeCaret(event.clientX, event.clientY);
|
|
2077
|
+
return;
|
|
2078
|
+
}
|
|
2079
|
+
// What the body shows now is what leaving the story comes back to (`selectionchange` comes
|
|
2080
|
+
// late, and the browser may select something on the way to the second press).
|
|
2081
|
+
if (margin && this.hasFocus())
|
|
2082
|
+
this.syncSelection();
|
|
2083
|
+
this.pressSelection = margin ? this.state.selection : null;
|
|
2084
|
+
// On a header or footer a press is not for the body: it places no caret.
|
|
2085
|
+
if (margin && this.pageRegions[margin.page]?.[margin.side]) {
|
|
2086
|
+
event.preventDefault();
|
|
2087
|
+
if (!this.hasFocus()) {
|
|
2088
|
+
this.pointerFocus = true;
|
|
2089
|
+
this.host.focus({ preventScroll: true });
|
|
2090
|
+
this.writeSelection(true);
|
|
2091
|
+
}
|
|
2092
|
+
return;
|
|
2093
|
+
}
|
|
2094
|
+
this.onMouseDown(event);
|
|
2095
|
+
};
|
|
2096
|
+
/** Puts the caret at a point of the window, if it is on this view's content. */
|
|
2097
|
+
placeCaret(x, y) {
|
|
2098
|
+
const pos = this.posAtPoint(x, y);
|
|
2099
|
+
if (pos !== null)
|
|
2100
|
+
this.editor.dispatch(this.state.tr.setSelection(TextSelection.near(this.state.doc.resolve(pos))));
|
|
2101
|
+
}
|
|
2102
|
+
/** The model position at a point of the window, or null. */
|
|
2103
|
+
posAtPoint(x, y) {
|
|
2104
|
+
const doc = this.host.ownerDocument;
|
|
2105
|
+
const point = doc.caretPositionFromPoint?.(x, y);
|
|
2106
|
+
const range = point ? null : doc.caretRangeFromPoint?.(x, y);
|
|
2107
|
+
const node = point?.offsetNode ?? range?.startContainer;
|
|
2108
|
+
const offset = point?.offset ?? range?.startOffset ?? 0;
|
|
2109
|
+
return node && this.host.contains(node) ? this.posFromDOM(node, offset) : null;
|
|
2110
|
+
}
|
|
2111
|
+
/**
|
|
2112
|
+
* A floating picture reaches into the blocks after its paragraph (their lines go around it):
|
|
2113
|
+
* a block that changed (new, drawn again or stale) on a page holding one has the blocks after
|
|
2114
|
+
* it on that page and the next measured again. A new block counts on the page of the block
|
|
2115
|
+
* before it, where `place` first puts it, and the next (it may have been that page's first);
|
|
2116
|
+
* only blocks that changed reach on, not the ones this marks, so an edit re-measures three
|
|
2117
|
+
* pages at most.
|
|
2118
|
+
*/
|
|
2119
|
+
staleAroundFloats(doc, pagesOf, redrawn) {
|
|
2120
|
+
const blocks = [];
|
|
2121
|
+
let last = 0;
|
|
2122
|
+
doc.forEach((node) => {
|
|
2123
|
+
const known = pagesOf.get(node);
|
|
2124
|
+
const pages = known?.length ? known : [last, last + 1];
|
|
2125
|
+
last = known?.length ? known[known.length - 1] : last;
|
|
2126
|
+
blocks.push({ node, pages, changed: !known || redrawn.has(node) || this.stale.has(node) });
|
|
2127
|
+
});
|
|
2128
|
+
// The pages floats are on now, and were on before (a float deleted or made inline leaves
|
|
2129
|
+
// lines that went around it).
|
|
2130
|
+
const floatPages = new Set();
|
|
2131
|
+
for (const { node, pages } of blocks)
|
|
2132
|
+
if (holdsFloat(node))
|
|
2133
|
+
for (const p of pages)
|
|
2134
|
+
floatPages.add(p);
|
|
2135
|
+
for (const [node, pages] of pagesOf)
|
|
2136
|
+
if (holdsFloat(node))
|
|
2137
|
+
for (const p of pages)
|
|
2138
|
+
floatPages.add(p);
|
|
2139
|
+
if (!floatPages.size)
|
|
2140
|
+
return;
|
|
2141
|
+
let reach = -1;
|
|
2142
|
+
for (const { node, pages, changed } of blocks) {
|
|
2143
|
+
if (pages[0] <= reach)
|
|
2144
|
+
this.stale.add(node);
|
|
2145
|
+
if (changed && pages.some((p) => floatPages.has(p)))
|
|
2146
|
+
reach = Math.max(reach, pages[pages.length - 1] + 1);
|
|
2147
|
+
}
|
|
540
2148
|
}
|
|
541
2149
|
/** A font's normal line height ratio, measured outside the host (no input to read back). */
|
|
542
2150
|
lineRatio = (family) => {
|
|
@@ -550,20 +2158,30 @@ export class EditorView {
|
|
|
550
2158
|
};
|
|
551
2159
|
/**
|
|
552
2160
|
* Puts each fragment of each block into its page (pages are non-decreasing in document
|
|
553
|
-
* order)
|
|
554
|
-
*
|
|
555
|
-
* or a page (stray DOM) is removed.
|
|
2161
|
+
* order) and, on a page with several sections or columns, into its band's column, creating
|
|
2162
|
+
* and removing pages as needed, and gives each page the page setup of its first section.
|
|
2163
|
+
* Anything else in the host or a page (stray DOM) is removed.
|
|
556
2164
|
*/
|
|
557
|
-
place(
|
|
2165
|
+
place(elements, pages, slots, layout) {
|
|
558
2166
|
const { host } = this;
|
|
559
|
-
const items =
|
|
560
|
-
|
|
2167
|
+
const items = elements.flatMap((list, i) => list.map((dom, f) => ({
|
|
2168
|
+
dom,
|
|
2169
|
+
page: pages[i]?.[f] ?? 0,
|
|
2170
|
+
slot: slots[i]?.[f],
|
|
2171
|
+
section: layout[i].section,
|
|
2172
|
+
})));
|
|
2173
|
+
// A note can reach pages no text is on.
|
|
2174
|
+
const count = Math.max((items[items.length - 1]?.page ?? 0) + 1, this.pageNotes.length);
|
|
561
2175
|
const sheets = [];
|
|
562
2176
|
pages.forEach((list, i) => {
|
|
563
2177
|
for (const p of list)
|
|
564
2178
|
sheets[p] ??= layout[i].sheet;
|
|
565
2179
|
});
|
|
566
|
-
// A page no block
|
|
2180
|
+
// A page no block is on has the setup of the page after it (Word's blank page before an
|
|
2181
|
+
// even or odd page section); the last, one with no blocks yet, of the page before it.
|
|
2182
|
+
for (let p = count - 1; p >= 0; p--)
|
|
2183
|
+
if (sheets[p + 1])
|
|
2184
|
+
sheets[p] ??= sheets[p + 1];
|
|
567
2185
|
for (let p = 0; p < count; p++)
|
|
568
2186
|
sheets[p] ??=
|
|
569
2187
|
sheets[p - 1] ?? layout[0]?.sheet ?? this.lastSheet();
|
|
@@ -573,11 +2191,19 @@ export class EditorView {
|
|
|
573
2191
|
this.sheets.forEach((sheet, p) => {
|
|
574
2192
|
const page = this.pages[p];
|
|
575
2193
|
const key = `${sheet.index} ${sheet.css}`;
|
|
576
|
-
if (pageSheets.get(page)
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
2194
|
+
if (pageSheets.get(page) !== key) {
|
|
2195
|
+
pageSheets.set(page, key);
|
|
2196
|
+
pagePads.delete(page);
|
|
2197
|
+
page.style.cssText = sheet.css;
|
|
2198
|
+
page.setAttribute(SHEET_ATTR, String(sheet.index));
|
|
2199
|
+
}
|
|
2200
|
+
const { top = "", bottom = "" } = this.pageMargins[p] ?? {};
|
|
2201
|
+
const pads = `${top} ${bottom}`;
|
|
2202
|
+
if ((pagePads.get(page) ?? " ") !== pads) {
|
|
2203
|
+
pagePads.set(page, pads);
|
|
2204
|
+
page.style.paddingTop = top;
|
|
2205
|
+
page.style.paddingBottom = bottom;
|
|
2206
|
+
}
|
|
581
2207
|
});
|
|
582
2208
|
// Pages first, in order; anything else in the host ends up after them.
|
|
583
2209
|
let cursor = host.firstChild;
|
|
@@ -590,20 +2216,60 @@ export class EditorView {
|
|
|
590
2216
|
let i = 0;
|
|
591
2217
|
for (let p = 0; p < count; p++) {
|
|
592
2218
|
const page = this.pages[p];
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
2219
|
+
const first = i;
|
|
2220
|
+
while (i < items.length && items[i]?.page === p)
|
|
2221
|
+
i++;
|
|
2222
|
+
const onPage = items.slice(first, i);
|
|
2223
|
+
const { header, footer } = this.pageRegions[p] ?? {};
|
|
2224
|
+
const notes = this.pageNotes[p];
|
|
2225
|
+
/** What follows the text of a column: its endnotes. */
|
|
2226
|
+
const after = (band, column) => notes?.flow.get(`${band}|${column}`) ?? [];
|
|
2227
|
+
/** A page's children: its header, what it holds, its notes, its footer. */
|
|
2228
|
+
const framed = (list) => [
|
|
2229
|
+
...(header ? [header.element] : []),
|
|
2230
|
+
...list,
|
|
2231
|
+
...(notes?.foot ?? []),
|
|
2232
|
+
...(footer ? [footer.element] : []),
|
|
2233
|
+
];
|
|
2234
|
+
for (const { dom, slot } of onPage) {
|
|
2235
|
+
const position = slot.mark ? "absolute" : "";
|
|
2236
|
+
if (dom.style.position !== position)
|
|
2237
|
+
dom.style.position = position;
|
|
2238
|
+
}
|
|
2239
|
+
// One section in one column: the blocks are the page's children.
|
|
2240
|
+
const last = onPage[onPage.length - 1];
|
|
2241
|
+
if (!last || (!last.slot.band && last.section.columns.widths.length === 1)) {
|
|
2242
|
+
fillElement(page, framed([...onPage.map((item) => item.dom), ...after(0, 0)]), this.viewRemoved);
|
|
2243
|
+
this.bands.delete(page);
|
|
2244
|
+
continue;
|
|
600
2245
|
}
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
2246
|
+
const known = this.bands.get(page) ?? [];
|
|
2247
|
+
const bands = [];
|
|
2248
|
+
for (const { section, slot } of onPage) {
|
|
2249
|
+
if (bands[slot.band])
|
|
2250
|
+
continue;
|
|
2251
|
+
const key = columnsKey(section.columns);
|
|
2252
|
+
const reused = known[slot.band];
|
|
2253
|
+
bands[slot.band] =
|
|
2254
|
+
reused?.key === key
|
|
2255
|
+
? reused
|
|
2256
|
+
: { key, ...bandElement(host.ownerDocument, section.columns) };
|
|
606
2257
|
}
|
|
2258
|
+
this.bands.set(page, bands);
|
|
2259
|
+
fillElement(page, framed(bands.map((b) => b.band)), this.viewRemoved);
|
|
2260
|
+
bands.forEach((band, b) => {
|
|
2261
|
+
const inBand = onPage.filter((item) => item.slot.band === b);
|
|
2262
|
+
const lead = inBand[0]?.slot.lead;
|
|
2263
|
+
const margin = lead ? `${lead}px` : "";
|
|
2264
|
+
if (band.band.style.marginTop !== margin)
|
|
2265
|
+
band.band.style.marginTop = margin;
|
|
2266
|
+
band.columns.forEach((column, c) => {
|
|
2267
|
+
fillElement(column, [
|
|
2268
|
+
...inBand.filter((item) => item.slot.column === c).map((item) => item.dom),
|
|
2269
|
+
...after(b, c),
|
|
2270
|
+
], this.viewRemoved);
|
|
2271
|
+
});
|
|
2272
|
+
});
|
|
607
2273
|
}
|
|
608
2274
|
// Pages no longer needed and stray DOM in the host: all after the last page by now.
|
|
609
2275
|
let rest = this.pages[count - 1].nextSibling;
|
|
@@ -614,9 +2280,30 @@ export class EditorView {
|
|
|
614
2280
|
}
|
|
615
2281
|
this.pages.length = count;
|
|
616
2282
|
}
|
|
2283
|
+
/**
|
|
2284
|
+
* What a table's cell shows in one of its fragments: its blocks' elements that `takes` puts
|
|
2285
|
+
* there, and nested tables whole (where their first block goes).
|
|
2286
|
+
*/
|
|
2287
|
+
cellContent(frame, r, c, blocks, takes) {
|
|
2288
|
+
const out = [];
|
|
2289
|
+
for (const item of frame.rows[r]?.cells[c]?.items ?? []) {
|
|
2290
|
+
if ("frame" in item) {
|
|
2291
|
+
const nested = item.frame;
|
|
2292
|
+
if (!takes(nested.first, 0))
|
|
2293
|
+
continue;
|
|
2294
|
+
out.push(frameElement(nested, nested.rows.map((_, i) => i), [], (rr, cc) => this.cellContent(nested, rr, cc, blocks, () => true), this.host.ownerDocument));
|
|
2295
|
+
continue;
|
|
2296
|
+
}
|
|
2297
|
+
blocks[item.unit].fragments.forEach((fragment, f) => {
|
|
2298
|
+
if (takes(item.unit, f))
|
|
2299
|
+
out.push(fragment);
|
|
2300
|
+
});
|
|
2301
|
+
}
|
|
2302
|
+
return out;
|
|
2303
|
+
}
|
|
617
2304
|
createPage() {
|
|
618
2305
|
const page = this.host.ownerDocument.createElement("section");
|
|
619
|
-
page.className = "foli-page";
|
|
2306
|
+
page.className = this.paged ? "foli-page" : "foli-story-flow";
|
|
620
2307
|
return page;
|
|
621
2308
|
}
|
|
622
2309
|
/** The last section's page setup (the envelope's), for an empty document. */
|
|
@@ -625,6 +2312,8 @@ export class EditorView {
|
|
|
625
2312
|
}
|
|
626
2313
|
/** The print rules for the document's page setups, written when they change. */
|
|
627
2314
|
applyPrintStyles(layout) {
|
|
2315
|
+
if (!this.paged)
|
|
2316
|
+
return;
|
|
628
2317
|
const sheets = [...new Set(layout.map((block) => block.sheet))];
|
|
629
2318
|
const key = [this.lastSheet(), ...sheets].map((sheet) => sheet.css).join("\n");
|
|
630
2319
|
if (key === this.printKey)
|
|
@@ -641,7 +2330,7 @@ export class EditorView {
|
|
|
641
2330
|
this.printStyles = parents.map((parent) => {
|
|
642
2331
|
const style = doc.createElement("style");
|
|
643
2332
|
style.setAttribute("data-foli-print", "");
|
|
644
|
-
style.textContent =
|
|
2333
|
+
style.textContent = viewPrintStyles(this.editor.settings, sheets, this.id);
|
|
645
2334
|
parent.append(style);
|
|
646
2335
|
return style;
|
|
647
2336
|
});
|
|
@@ -650,6 +2339,11 @@ export class EditorView {
|
|
|
650
2339
|
invalidateLayout() {
|
|
651
2340
|
this.measures = new WeakMap();
|
|
652
2341
|
this.flowed = null;
|
|
2342
|
+
this.regionsFor = null;
|
|
2343
|
+
if (this.regions)
|
|
2344
|
+
this.regions.cache = new WeakMap();
|
|
2345
|
+
if (this.notes)
|
|
2346
|
+
this.notes.cache = new WeakMap();
|
|
653
2347
|
}
|
|
654
2348
|
/** Re-flows the pages once web fonts have loaded: line heights and wrapping change. */
|
|
655
2349
|
onFontsLoaded = () => {
|
|
@@ -690,7 +2384,7 @@ export class EditorView {
|
|
|
690
2384
|
// A hidden host (display: none) reports every block as 0x0: nothing to re-flow.
|
|
691
2385
|
if (!entry.contentRect.width)
|
|
692
2386
|
continue;
|
|
693
|
-
scale ??=
|
|
2387
|
+
scale ??= this.scale();
|
|
694
2388
|
let height = 0;
|
|
695
2389
|
for (const fragment of desc.fragments)
|
|
696
2390
|
height += fragment.getBoundingClientRect().height;
|
|
@@ -719,7 +2413,7 @@ export class EditorView {
|
|
|
719
2413
|
if (this.destroyed)
|
|
720
2414
|
return;
|
|
721
2415
|
// compositionend flows what a composition kept from moving.
|
|
722
|
-
if (this.composing) {
|
|
2416
|
+
if (this.composing || this.mount?.view.composing) {
|
|
723
2417
|
this.unflowed = true;
|
|
724
2418
|
return;
|
|
725
2419
|
}
|
|
@@ -737,9 +2431,19 @@ export class EditorView {
|
|
|
737
2431
|
}
|
|
738
2432
|
return null;
|
|
739
2433
|
}
|
|
740
|
-
/**
|
|
2434
|
+
/**
|
|
2435
|
+
* Whether `node` holds blocks rather than content: the host, a page, a band or column of one,
|
|
2436
|
+
* or a table's wrapper, table, rows and cells.
|
|
2437
|
+
*/
|
|
741
2438
|
holdsBlocks(node) {
|
|
742
|
-
|
|
2439
|
+
if (node === this.host || this.pages.includes(node))
|
|
2440
|
+
return true;
|
|
2441
|
+
if (node.nodeType !== Node.ELEMENT_NODE)
|
|
2442
|
+
return false;
|
|
2443
|
+
const element = node;
|
|
2444
|
+
return (element.classList.contains(BAND_CLASS) ||
|
|
2445
|
+
element.classList.contains(COLUMN_CLASS) ||
|
|
2446
|
+
(element.hasAttribute(FRAME_ATTR) && !element.closest(`[${REPEATED_ATTR}]`)));
|
|
743
2447
|
}
|
|
744
2448
|
/** Index of the first block that starts at or after `pos` (the block count if none). */
|
|
745
2449
|
blockFrom(pos) {
|
|
@@ -757,19 +2461,37 @@ export class EditorView {
|
|
|
757
2461
|
/** Model position of a DOM point inside the host, or null if it is outside. */
|
|
758
2462
|
posFromDOM(node, offset) {
|
|
759
2463
|
const { host } = this;
|
|
2464
|
+
// In a header row drawn again (not document content): the first position below it.
|
|
2465
|
+
const at = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
|
|
2466
|
+
const repeated = at?.closest(`[${REPEATED_ATTR}]`);
|
|
2467
|
+
if (repeated?.parentNode && host.contains(repeated)) {
|
|
2468
|
+
const parent = repeated.parentNode;
|
|
2469
|
+
return this.posFromDOM(parent, [...parent.childNodes].indexOf(repeated) + 1);
|
|
2470
|
+
}
|
|
760
2471
|
if (this.holdsBlocks(node)) {
|
|
761
2472
|
// Between fragments: the start of the first one after the point (a block start, or
|
|
762
2473
|
// where a continuation starts), else the document end.
|
|
763
2474
|
const range = host.ownerDocument.createRange();
|
|
764
2475
|
range.setStart(node, offset);
|
|
2476
|
+
const posOf = (i, f) => f === 0
|
|
2477
|
+
? this.starts[i]
|
|
2478
|
+
: this.starts[i] +
|
|
2479
|
+
1 +
|
|
2480
|
+
this.blocks[i].splits[f - 1];
|
|
2481
|
+
// Without tables, blocks are in DOM order: the first one after the point. In a row split
|
|
2482
|
+
// across pages, a cell's continuation comes after the next cell: the earliest in the DOM.
|
|
2483
|
+
let best = null;
|
|
765
2484
|
for (const [i, desc] of this.blocks.entries()) {
|
|
766
2485
|
const f = desc.fragments.findIndex((fragment) => range.comparePoint(fragment, 0) >= 0);
|
|
767
|
-
if (f
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
2486
|
+
if (f < 0)
|
|
2487
|
+
continue;
|
|
2488
|
+
const dom = desc.fragments[f];
|
|
2489
|
+
if (!this.frames.size)
|
|
2490
|
+
return posOf(i, f);
|
|
2491
|
+
if (!best || dom.compareDocumentPosition(best.dom) & Node.DOCUMENT_POSITION_FOLLOWING)
|
|
2492
|
+
best = { i, f, dom };
|
|
771
2493
|
}
|
|
772
|
-
return this.state.doc.content.size;
|
|
2494
|
+
return best ? posOf(best.i, best.f) : this.state.doc.content.size;
|
|
773
2495
|
}
|
|
774
2496
|
const element = this.blockElement(node);
|
|
775
2497
|
const owner = element ? this.owner.get(element) : undefined;
|
|
@@ -850,25 +2572,49 @@ export class EditorView {
|
|
|
850
2572
|
const sel = this.host.ownerDocument.getSelection();
|
|
851
2573
|
if (!sel?.anchorNode || !sel.focusNode)
|
|
852
2574
|
return null;
|
|
2575
|
+
if (this.mount?.wrapper.contains(sel.anchorNode))
|
|
2576
|
+
return null;
|
|
853
2577
|
// A range around exactly one block leaf element (a rule): the node selection that wrote it.
|
|
854
2578
|
// (Its end, mapped alone, would be the start of the next block, not the end of the rule.)
|
|
855
2579
|
if (sel.anchorNode === sel.focusNode && Math.abs(sel.anchorOffset - sel.focusOffset) === 1) {
|
|
856
2580
|
const child = sel.anchorNode.childNodes[Math.min(sel.anchorOffset, sel.focusOffset)];
|
|
2581
|
+
// Around a table's (first) wrapper: the table selected whole.
|
|
2582
|
+
const table = child && this.frameOf.get(child);
|
|
2583
|
+
if (table)
|
|
2584
|
+
return NodeSelection.create(this.state.doc, table.pos);
|
|
857
2585
|
const owner = child && this.owner.get(child);
|
|
858
2586
|
const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
|
|
859
2587
|
if (owner && !owner.node.isTextblock && NodeSelection.isSelectable(owner.node))
|
|
860
2588
|
return NodeSelection.create(this.state.doc, this.starts[index]);
|
|
861
2589
|
}
|
|
862
|
-
|
|
863
|
-
|
|
2590
|
+
// Several ranges (Firefox selects table cells so, one range per cell): from the first cell
|
|
2591
|
+
// to the last (a range's start is in its cell; its end is after it).
|
|
2592
|
+
const many = sel.rangeCount > 1;
|
|
2593
|
+
const first = many ? sel.getRangeAt(0) : null;
|
|
2594
|
+
const lastRange = many ? sel.getRangeAt(sel.rangeCount - 1) : null;
|
|
2595
|
+
const anchor = first
|
|
2596
|
+
? this.posFromDOM(first.startContainer, first.startOffset)
|
|
2597
|
+
: this.posFromDOM(sel.anchorNode, sel.anchorOffset);
|
|
2598
|
+
const head = lastRange
|
|
2599
|
+
? this.posFromDOM(lastRange.startContainer, lastRange.startOffset)
|
|
2600
|
+
: this.posFromDOM(sel.focusNode, sel.focusOffset);
|
|
864
2601
|
if (anchor === null || head === null)
|
|
865
2602
|
return null;
|
|
866
2603
|
const { doc } = this.state;
|
|
2604
|
+
// The caret the view wrote for a cell selection (in its head cell): that selection.
|
|
2605
|
+
const current = this.state.selection;
|
|
2606
|
+
if (current instanceof CellSelection && anchor === head && anchor === this.cellCaret)
|
|
2607
|
+
return current;
|
|
2608
|
+
// Ends in two cells of one table: the cells between them.
|
|
2609
|
+
const a = cellAround(doc, anchor);
|
|
2610
|
+
const h = cellAround(doc, head);
|
|
2611
|
+
if (a && h && a.cell !== h.cell && a.table === h.table)
|
|
2612
|
+
return CellSelection.create(doc, a.cell, h.cell);
|
|
867
2613
|
// Exactly around a selectable block leaf (a rule): the node selection that wrote it.
|
|
868
2614
|
const from = Math.min(anchor, head);
|
|
869
2615
|
const node = doc.nodeAt(from);
|
|
870
2616
|
if (node &&
|
|
871
|
-
node.isBlock &&
|
|
2617
|
+
(node.isBlock || node.type.name === "picture") &&
|
|
872
2618
|
node.isAtom &&
|
|
873
2619
|
Math.max(anchor, head) === from + node.nodeSize &&
|
|
874
2620
|
NodeSelection.isSelectable(node))
|
|
@@ -883,9 +2629,77 @@ export class EditorView {
|
|
|
883
2629
|
const desc = this.blocks[this.blockFrom(selection.from)];
|
|
884
2630
|
return desc && this.starts[this.indexOf.get(desc) ?? -1] === selection.from ? desc : null;
|
|
885
2631
|
}
|
|
2632
|
+
/** The span of the picture a node selection selects, if it selects one. */
|
|
2633
|
+
pictureSpan(pos) {
|
|
2634
|
+
for (const img of this.host.querySelectorAll(`[${PICTURE_ATTR}]`)) {
|
|
2635
|
+
const span = img.parentElement;
|
|
2636
|
+
// A floating picture's place in the text is its anchor.
|
|
2637
|
+
if (span && this.posFromDOM(FLOAT_ANCHORS.get(span) ?? span, 0) === pos)
|
|
2638
|
+
return span;
|
|
2639
|
+
}
|
|
2640
|
+
return null;
|
|
2641
|
+
}
|
|
2642
|
+
/** Marks the selected picture and gives it a resize handle (when the document is editable). */
|
|
2643
|
+
showSelectedPicture() {
|
|
2644
|
+
const { selection } = this.state;
|
|
2645
|
+
const span = selection instanceof NodeSelection && selection.node.type.name === "picture"
|
|
2646
|
+
? this.pictureSpan(selection.from)
|
|
2647
|
+
: null;
|
|
2648
|
+
const handled = !!span?.querySelector("[data-foli-resize]");
|
|
2649
|
+
if (span === this.selectedPicture && (!span || handled === this.editable))
|
|
2650
|
+
return;
|
|
2651
|
+
this.selectedPicture?.removeAttribute(PICTURE_SELECTED_ATTR);
|
|
2652
|
+
this.selectedPicture?.querySelector("[data-foli-resize]")?.remove();
|
|
2653
|
+
this.selectedPicture = span;
|
|
2654
|
+
if (!span)
|
|
2655
|
+
return;
|
|
2656
|
+
injectStyles(this.host);
|
|
2657
|
+
span.setAttribute(PICTURE_SELECTED_ATTR, "");
|
|
2658
|
+
if (!this.editable)
|
|
2659
|
+
return;
|
|
2660
|
+
const handle = this.host.ownerDocument.createElement("span");
|
|
2661
|
+
handle.setAttribute("data-foli-resize", "");
|
|
2662
|
+
handle.setAttribute("aria-hidden", "true");
|
|
2663
|
+
span.append(handle);
|
|
2664
|
+
}
|
|
2665
|
+
/** Marks the cells of a cell selection (their table cell elements, on every page). */
|
|
2666
|
+
showSelectedCells() {
|
|
2667
|
+
const { selection } = this.state;
|
|
2668
|
+
const cells = [];
|
|
2669
|
+
if (selection instanceof CellSelection) {
|
|
2670
|
+
for (const pos of selection.cells) {
|
|
2671
|
+
const caret = Selection.near(this.state.doc.resolve(pos + 1), 1).from;
|
|
2672
|
+
const { node } = this.domFromPos(caret);
|
|
2673
|
+
const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
|
|
2674
|
+
const td = element?.closest("td");
|
|
2675
|
+
if (td instanceof HTMLElement)
|
|
2676
|
+
cells.push(td);
|
|
2677
|
+
}
|
|
2678
|
+
}
|
|
2679
|
+
for (const td of this.selectedCells)
|
|
2680
|
+
if (!cells.includes(td))
|
|
2681
|
+
td.classList.remove(CELL_CLASS);
|
|
2682
|
+
for (const td of cells)
|
|
2683
|
+
td.classList.add(CELL_CLASS);
|
|
2684
|
+
this.selectedCells = cells;
|
|
2685
|
+
this.host.toggleAttribute(CELLS_ATTR, cells.length > 0);
|
|
2686
|
+
if (cells.length)
|
|
2687
|
+
injectStyles(this.host);
|
|
2688
|
+
}
|
|
2689
|
+
/** The first wrapper of a node-selected table, if a table is selected. */
|
|
2690
|
+
selectedTable() {
|
|
2691
|
+
const { selection } = this.state;
|
|
2692
|
+
if (!(selection instanceof NodeSelection) || selection.node.type.name !== "table")
|
|
2693
|
+
return null;
|
|
2694
|
+
return this.frames.get(selection.node)?.wrappers[0] ?? null;
|
|
2695
|
+
}
|
|
886
2696
|
/** Marks the element of a node-selected block, for styling (the DOM selection is around it). */
|
|
887
2697
|
showSelectedNode() {
|
|
888
|
-
|
|
2698
|
+
this.showSelectedCells();
|
|
2699
|
+
this.showSelectedPicture();
|
|
2700
|
+
this.showSelectedFields();
|
|
2701
|
+
this.drawControls();
|
|
2702
|
+
const dom = this.selectedBlock()?.dom ?? this.selectedTable();
|
|
889
2703
|
if (dom === this.selectedDom)
|
|
890
2704
|
return;
|
|
891
2705
|
this.selectedDom?.classList.remove(SELECTED_CLASS);
|
|
@@ -912,11 +2726,19 @@ export class EditorView {
|
|
|
912
2726
|
const shown = selection instanceof AllSelection
|
|
913
2727
|
? TextSelection.between(selection.$anchor, selection.$head)
|
|
914
2728
|
: selection;
|
|
915
|
-
|
|
2729
|
+
if (dom.anchor === shown.anchor && dom.head === shown.head)
|
|
2730
|
+
return true;
|
|
2731
|
+
// Field markers take no room, and a control's edge is one place to the browser: the DOM
|
|
2732
|
+
// cannot tell their two sides apart.
|
|
2733
|
+
const { doc } = this.state;
|
|
2734
|
+
const texts = shown instanceof TextSelection && dom instanceof TextSelection;
|
|
2735
|
+
const same = (a, b) => controlSpot(doc, a, b) ||
|
|
2736
|
+
(texts && doc.resolve(a).parent.inlineContent && sameSpot(doc, a, b));
|
|
2737
|
+
return same(dom.anchor, shown.anchor) && same(dom.head, shown.head);
|
|
916
2738
|
}
|
|
917
2739
|
hasFocus() {
|
|
918
2740
|
const active = this.host.ownerDocument.activeElement;
|
|
919
|
-
return active === this.host || this.host.contains(active);
|
|
2741
|
+
return ((active === this.host || this.host.contains(active)) && !this.mount?.wrapper.contains(active));
|
|
920
2742
|
}
|
|
921
2743
|
/** Writes the model selection to the DOM unless the DOM already shows it (keeps native affinity). */
|
|
922
2744
|
writeSelection(force) {
|
|
@@ -931,12 +2753,20 @@ export class EditorView {
|
|
|
931
2753
|
if (current && this.shows(current))
|
|
932
2754
|
return;
|
|
933
2755
|
}
|
|
934
|
-
const selected = this.selectedBlock();
|
|
2756
|
+
const selected = this.selectedBlock()?.dom ?? this.selectedTable();
|
|
935
2757
|
if (selected) {
|
|
936
|
-
const point = before(selected
|
|
2758
|
+
const point = before(selected);
|
|
937
2759
|
sel.setBaseAndExtent(point.node, point.offset, point.node, point.offset + 1);
|
|
938
2760
|
return;
|
|
939
2761
|
}
|
|
2762
|
+
// Cells: drawn by their class; the native caret stays in the head cell (ADR-0006).
|
|
2763
|
+
if (selection instanceof CellSelection) {
|
|
2764
|
+
const caret = Selection.near(doc.resolve(selection.head + 1), 1).from;
|
|
2765
|
+
this.cellCaret = caret;
|
|
2766
|
+
const point = this.domFromPos(caret);
|
|
2767
|
+
sel.collapse(point.node, point.offset);
|
|
2768
|
+
return;
|
|
2769
|
+
}
|
|
940
2770
|
// Never show a caret inside a grapheme cluster (the core snaps only out of surrogate pairs).
|
|
941
2771
|
// The model takes the snapped selection back on its next read of the DOM.
|
|
942
2772
|
const from = clusterBoundary(doc, selection.from, false);
|
|
@@ -957,7 +2787,7 @@ export class EditorView {
|
|
|
957
2787
|
*/
|
|
958
2788
|
dispatch(tr) {
|
|
959
2789
|
const marksAdded = tr.storedMarks !== null && tr.storedMarks !== this.state.storedMarks;
|
|
960
|
-
if (!this.editable && (tr.docChanged || marksAdded))
|
|
2790
|
+
if ((!this.editable || this.mount) && (tr.docChanged || marksAdded))
|
|
961
2791
|
return false;
|
|
962
2792
|
this.editor.dispatch(tr);
|
|
963
2793
|
return true;
|
|
@@ -1052,6 +2882,399 @@ export class EditorView {
|
|
|
1052
2882
|
return command ? this.run(command) : false;
|
|
1053
2883
|
});
|
|
1054
2884
|
}
|
|
2885
|
+
// ---------- column borders (10.7c) ----------
|
|
2886
|
+
/** A column border being dragged: its table and column, the column's width, the press, the guide. */
|
|
2887
|
+
drag = null;
|
|
2888
|
+
/** Whether this view set the host's cursor (an embedder's own cursor is left alone). */
|
|
2889
|
+
resizeCursor = false;
|
|
2890
|
+
/**
|
|
2891
|
+
* The column border of a top-level table near the pointer (within 4 px): an edge of the cell
|
|
2892
|
+
* under it (a grid line through a merged cell is no border), or the table's right edge from
|
|
2893
|
+
* outside; as the grid column left of it, with the table's px per twip. None in read-only
|
|
2894
|
+
* mode, during a composition, or while tracking (column widths do not change then).
|
|
2895
|
+
*/
|
|
2896
|
+
columnBorder(event) {
|
|
2897
|
+
if (!this.editable || this.composing || trackState(this.state)?.on)
|
|
2898
|
+
return null;
|
|
2899
|
+
const target = event.target;
|
|
2900
|
+
const wrapper = target?.closest?.(`[${FRAME_ATTR}="table"]`);
|
|
2901
|
+
const element = wrapper?.querySelector(`:scope > table[${FRAME_ATTR}]`);
|
|
2902
|
+
if (!wrapper || !element || !this.host.contains(wrapper))
|
|
2903
|
+
return null;
|
|
2904
|
+
let table;
|
|
2905
|
+
for (const [node, frame] of this.frames)
|
|
2906
|
+
if (frame.wrappers.includes(wrapper))
|
|
2907
|
+
table = node;
|
|
2908
|
+
const grid = table?.attrs.grid ?? [];
|
|
2909
|
+
const total = grid.reduce((a, b) => a + b, 0);
|
|
2910
|
+
if (!table || !total)
|
|
2911
|
+
return null;
|
|
2912
|
+
const rect = element.getBoundingClientRect();
|
|
2913
|
+
const perTwip = rect.width / total;
|
|
2914
|
+
const edges = [];
|
|
2915
|
+
let x = rect.left;
|
|
2916
|
+
for (const width of grid) {
|
|
2917
|
+
x += width * perTwip;
|
|
2918
|
+
edges.push(x);
|
|
2919
|
+
}
|
|
2920
|
+
const near = (column) => Math.abs(event.clientX - edges[column]) <= 4;
|
|
2921
|
+
// The grid lines that are borders here: the cell's own edges, the table's right edge from
|
|
2922
|
+
// outside it, any line on the table's own border area (none in a row's empty places).
|
|
2923
|
+
const cell = target?.closest("td");
|
|
2924
|
+
let columns;
|
|
2925
|
+
if (cell && element.contains(cell)) {
|
|
2926
|
+
const box = cell.getBoundingClientRect();
|
|
2927
|
+
const at = (line) => edges.findIndex((edge) => Math.abs(edge - line) <= 3);
|
|
2928
|
+
columns = [at(box.left), at(box.right)].filter((c) => c >= 0);
|
|
2929
|
+
}
|
|
2930
|
+
else if (target === element)
|
|
2931
|
+
columns = grid.map((_w, i) => i);
|
|
2932
|
+
else if (element.contains(target))
|
|
2933
|
+
columns = [];
|
|
2934
|
+
else
|
|
2935
|
+
columns = [grid.length - 1];
|
|
2936
|
+
const column = columns.find(near);
|
|
2937
|
+
return column === undefined ? null : { table, column, perTwip, rect };
|
|
2938
|
+
}
|
|
2939
|
+
/** The pointer over a column border shows that it can be dragged. */
|
|
2940
|
+
onMouseMove = (event) => {
|
|
2941
|
+
if (this.drag)
|
|
2942
|
+
return;
|
|
2943
|
+
if (event.buttons === 0)
|
|
2944
|
+
this.controlChrome.hover(event.target);
|
|
2945
|
+
const near = event.buttons === 0 && this.columnBorder(event) !== null;
|
|
2946
|
+
if (near === this.resizeCursor)
|
|
2947
|
+
return;
|
|
2948
|
+
this.resizeCursor = near;
|
|
2949
|
+
this.host.style.cursor = near ? "col-resize" : "";
|
|
2950
|
+
};
|
|
2951
|
+
/**
|
|
2952
|
+
* A press on a column border (no Shift: Shift-click extends the selection) starts dragging it:
|
|
2953
|
+
* a guide line follows the pointer and the release moves the border by as much as the pointer
|
|
2954
|
+
* moved (`setColumnWidth`); a press without a move changes nothing; Escape, the button let go
|
|
2955
|
+
* elsewhere or the window losing the focus cancel.
|
|
2956
|
+
*/
|
|
2957
|
+
startColumnDrag(event) {
|
|
2958
|
+
this.endDrag();
|
|
2959
|
+
if (event.shiftKey)
|
|
2960
|
+
return false;
|
|
2961
|
+
const border = this.columnBorder(event);
|
|
2962
|
+
if (!border)
|
|
2963
|
+
return false;
|
|
2964
|
+
// No caret or text selection from this press. Focus taken by it keeps the selection the
|
|
2965
|
+
// model has (the press places none).
|
|
2966
|
+
event.preventDefault();
|
|
2967
|
+
if (!this.hasFocus()) {
|
|
2968
|
+
this.host.focus({ preventScroll: true });
|
|
2969
|
+
this.writeSelection(true);
|
|
2970
|
+
}
|
|
2971
|
+
const doc = this.host.ownerDocument;
|
|
2972
|
+
const guide = doc.createElement("div");
|
|
2973
|
+
guide.setAttribute("aria-hidden", "true");
|
|
2974
|
+
Object.assign(guide.style, {
|
|
2975
|
+
position: "fixed",
|
|
2976
|
+
top: `${border.rect.top}px`,
|
|
2977
|
+
height: `${border.rect.height}px`,
|
|
2978
|
+
left: `${event.clientX}px`,
|
|
2979
|
+
width: "0",
|
|
2980
|
+
borderLeft: "1px dashed GrayText",
|
|
2981
|
+
pointerEvents: "none",
|
|
2982
|
+
zIndex: "2147483647",
|
|
2983
|
+
});
|
|
2984
|
+
doc.body.append(guide);
|
|
2985
|
+
const width = border.table.attrs.grid[border.column];
|
|
2986
|
+
this.drag = { ...border, width, startX: event.clientX, guide };
|
|
2987
|
+
doc.addEventListener("mousemove", this.onDragMove);
|
|
2988
|
+
doc.addEventListener("mouseup", this.onDragEnd);
|
|
2989
|
+
doc.addEventListener("keydown", this.onDragKey, true);
|
|
2990
|
+
doc.defaultView?.addEventListener("blur", this.onDragBlur);
|
|
2991
|
+
return true;
|
|
2992
|
+
}
|
|
2993
|
+
onDragMove = (event) => {
|
|
2994
|
+
if (!this.drag)
|
|
2995
|
+
return;
|
|
2996
|
+
// The button let go where no mouseup reached the page (another window, a menu): cancelled.
|
|
2997
|
+
if ((event.buttons & 1) === 0)
|
|
2998
|
+
this.endDrag();
|
|
2999
|
+
else
|
|
3000
|
+
this.drag.guide.style.left = `${event.clientX}px`;
|
|
3001
|
+
};
|
|
3002
|
+
onDragEnd = (event) => {
|
|
3003
|
+
const drag = this.endDrag();
|
|
3004
|
+
if (!drag)
|
|
3005
|
+
return;
|
|
3006
|
+
const moved = event.clientX - drag.startX;
|
|
3007
|
+
// A click on a border (no real move) is no resize.
|
|
3008
|
+
if (Math.abs(moved) < 2)
|
|
3009
|
+
return;
|
|
3010
|
+
// The table's position: a top-level block's.
|
|
3011
|
+
let pos = -1;
|
|
3012
|
+
this.state.doc.forEach((node, offset) => {
|
|
3013
|
+
if (node === drag.table)
|
|
3014
|
+
pos = offset;
|
|
3015
|
+
});
|
|
3016
|
+
if (pos >= 0)
|
|
3017
|
+
this.run(setColumnWidth(pos, drag.column, drag.width + moved / drag.perTwip));
|
|
3018
|
+
};
|
|
3019
|
+
onDragKey = (event) => {
|
|
3020
|
+
if (event.key !== "Escape")
|
|
3021
|
+
return;
|
|
3022
|
+
event.preventDefault();
|
|
3023
|
+
event.stopPropagation();
|
|
3024
|
+
this.endDrag();
|
|
3025
|
+
};
|
|
3026
|
+
onDragBlur = () => {
|
|
3027
|
+
this.endDrag();
|
|
3028
|
+
};
|
|
3029
|
+
/** Ends a drag (its guide and listeners gone) and returns it. */
|
|
3030
|
+
endDrag() {
|
|
3031
|
+
const { drag } = this;
|
|
3032
|
+
if (!drag)
|
|
3033
|
+
return null;
|
|
3034
|
+
this.drag = null;
|
|
3035
|
+
drag.guide.remove();
|
|
3036
|
+
const doc = this.host.ownerDocument;
|
|
3037
|
+
doc.removeEventListener("mousemove", this.onDragMove);
|
|
3038
|
+
doc.removeEventListener("mouseup", this.onDragEnd);
|
|
3039
|
+
doc.removeEventListener("keydown", this.onDragKey, true);
|
|
3040
|
+
doc.defaultView?.removeEventListener("blur", this.onDragBlur);
|
|
3041
|
+
if (this.resizeCursor) {
|
|
3042
|
+
this.resizeCursor = false;
|
|
3043
|
+
this.host.style.cursor = "";
|
|
3044
|
+
}
|
|
3045
|
+
return drag;
|
|
3046
|
+
}
|
|
3047
|
+
// ---------- pictures (10.8d) ----------
|
|
3048
|
+
/**
|
|
3049
|
+
* A press on a picture selects it (a node selection); on the selected picture's handle it
|
|
3050
|
+
* starts a resize that keeps its aspect ratio (`setPictureSize` on release, Escape cancels).
|
|
3051
|
+
*/
|
|
3052
|
+
pictureMouseDown(event) {
|
|
3053
|
+
this.endResize();
|
|
3054
|
+
if (event.shiftKey || this.composing)
|
|
3055
|
+
return false;
|
|
3056
|
+
const target = event.target;
|
|
3057
|
+
const span = target?.closest?.(`[${PICTURE_ATTR}], [data-foli-resize]`)?.parentElement ?? null;
|
|
3058
|
+
if (!span || !this.host.contains(span))
|
|
3059
|
+
return false;
|
|
3060
|
+
const pos = this.posFromDOM(FLOAT_ANCHORS.get(span) ?? span, 0);
|
|
3061
|
+
if (pos === null)
|
|
3062
|
+
return false;
|
|
3063
|
+
event.preventDefault();
|
|
3064
|
+
if (!this.hasFocus())
|
|
3065
|
+
this.host.focus({ preventScroll: true });
|
|
3066
|
+
if (!(this.state.selection instanceof NodeSelection && this.state.selection.from === pos))
|
|
3067
|
+
this.dispatch(this.state.tr.setSelection(NodeSelection.create(this.state.doc, pos)));
|
|
3068
|
+
// Already selected: written again (the focus may have put a caret in the host).
|
|
3069
|
+
else
|
|
3070
|
+
this.writeSelection(true);
|
|
3071
|
+
const img = span.querySelector(`[${PICTURE_ATTR}]`);
|
|
3072
|
+
if (!img || !target?.closest("[data-foli-resize]") || !this.editable)
|
|
3073
|
+
return true;
|
|
3074
|
+
const rect = img.getBoundingClientRect();
|
|
3075
|
+
const width = Number.parseFloat(img.style.width) || rect.width;
|
|
3076
|
+
const scale = rect.width / width || 1;
|
|
3077
|
+
this.resize = {
|
|
3078
|
+
pos,
|
|
3079
|
+
img,
|
|
3080
|
+
width: rect.width,
|
|
3081
|
+
height: rect.height,
|
|
3082
|
+
scale,
|
|
3083
|
+
// No wider than the page's text (layout px).
|
|
3084
|
+
max: Math.max(this.textWidthEmu() / EMU_PER_PX, MIN_PICTURE),
|
|
3085
|
+
x: event.clientX,
|
|
3086
|
+
y: event.clientY,
|
|
3087
|
+
style: img.getAttribute("style") ?? "",
|
|
3088
|
+
};
|
|
3089
|
+
const doc = this.host.ownerDocument;
|
|
3090
|
+
doc.addEventListener("mousemove", this.onResizeMove);
|
|
3091
|
+
doc.addEventListener("mouseup", this.onResizeEnd);
|
|
3092
|
+
doc.addEventListener("keydown", this.onResizeKey, true);
|
|
3093
|
+
doc.defaultView?.addEventListener("blur", this.onResizeCancel);
|
|
3094
|
+
return true;
|
|
3095
|
+
}
|
|
3096
|
+
/** The size (layout px) a resize gives at the pointer: the larger move, the ratio kept. */
|
|
3097
|
+
resizedTo(event) {
|
|
3098
|
+
const r = this.resize;
|
|
3099
|
+
const ratio = r.height / r.width;
|
|
3100
|
+
const dx = event.clientX - r.x;
|
|
3101
|
+
const dy = (event.clientY - r.y) / ratio;
|
|
3102
|
+
const width = Math.min(Math.max((r.width + (Math.abs(dx) > Math.abs(dy) ? dx : dy)) / r.scale, MIN_PICTURE), r.max);
|
|
3103
|
+
return { width, height: width * ratio };
|
|
3104
|
+
}
|
|
3105
|
+
onResizeMove = (event) => {
|
|
3106
|
+
if (!this.resize)
|
|
3107
|
+
return;
|
|
3108
|
+
if ((event.buttons & 1) === 0) {
|
|
3109
|
+
this.onResizeCancel();
|
|
3110
|
+
return;
|
|
3111
|
+
}
|
|
3112
|
+
const { width, height } = this.resizedTo(event);
|
|
3113
|
+
this.resize.img.style.width = `${width}px`;
|
|
3114
|
+
this.resize.img.style.height = `${height}px`;
|
|
3115
|
+
};
|
|
3116
|
+
onResizeEnd = (event) => {
|
|
3117
|
+
if (!this.resize)
|
|
3118
|
+
return;
|
|
3119
|
+
const { width, height } = this.resizedTo(event);
|
|
3120
|
+
const r = this.endResize();
|
|
3121
|
+
if (!r)
|
|
3122
|
+
return;
|
|
3123
|
+
// No real move: nothing changes (a jiggle drawn while moving goes back).
|
|
3124
|
+
const moved = Math.abs(event.clientX - r.x) >= 2 || Math.abs(event.clientY - r.y) >= 2;
|
|
3125
|
+
const applied = moved &&
|
|
3126
|
+
this.run(setPictureSize(r.pos, Math.round(width * EMU_PER_PX), Math.round(height * EMU_PER_PX)));
|
|
3127
|
+
// Not applied (no move, tracking, the picture gone): as it was.
|
|
3128
|
+
if (!applied)
|
|
3129
|
+
r.img.setAttribute("style", r.style);
|
|
3130
|
+
};
|
|
3131
|
+
onResizeKey = (event) => {
|
|
3132
|
+
if (event.key !== "Escape")
|
|
3133
|
+
return;
|
|
3134
|
+
event.preventDefault();
|
|
3135
|
+
event.stopPropagation();
|
|
3136
|
+
this.onResizeCancel();
|
|
3137
|
+
};
|
|
3138
|
+
onResizeCancel = () => {
|
|
3139
|
+
const r = this.endResize();
|
|
3140
|
+
if (r)
|
|
3141
|
+
r.img.setAttribute("style", r.style);
|
|
3142
|
+
};
|
|
3143
|
+
/** Ends a resize (its listeners gone) and returns it. */
|
|
3144
|
+
endResize() {
|
|
3145
|
+
const r = this.resize;
|
|
3146
|
+
if (!r)
|
|
3147
|
+
return null;
|
|
3148
|
+
this.resize = null;
|
|
3149
|
+
const doc = this.host.ownerDocument;
|
|
3150
|
+
doc.removeEventListener("mousemove", this.onResizeMove);
|
|
3151
|
+
doc.removeEventListener("mouseup", this.onResizeEnd);
|
|
3152
|
+
doc.removeEventListener("keydown", this.onResizeKey, true);
|
|
3153
|
+
doc.defaultView?.removeEventListener("blur", this.onResizeCancel);
|
|
3154
|
+
return r;
|
|
3155
|
+
}
|
|
3156
|
+
textWidthEmu() {
|
|
3157
|
+
return textWidthEmu(this.state);
|
|
3158
|
+
}
|
|
3159
|
+
/** Image files in a transfer (paste or drop), when the app takes uploads. */
|
|
3160
|
+
imageFiles(data) {
|
|
3161
|
+
if (!this.upload || !this.editable || !data)
|
|
3162
|
+
return [];
|
|
3163
|
+
// A clipboard object from code may have no files.
|
|
3164
|
+
return [...(data.files ?? [])].filter((file) => file.type.startsWith("image/"));
|
|
3165
|
+
}
|
|
3166
|
+
/** Whether a drag carries files (from outside the page). */
|
|
3167
|
+
static carriesFiles = (event) => [...(event.dataTransfer?.types ?? [])].includes("Files");
|
|
3168
|
+
onDragOver = (event) => {
|
|
3169
|
+
if (!EditorView.carriesFiles(event))
|
|
3170
|
+
return;
|
|
3171
|
+
// Files dropped here never open in the page (unsaved work would be lost).
|
|
3172
|
+
event.preventDefault();
|
|
3173
|
+
const images = [...(event.dataTransfer?.items ?? [])].some((i) => i.type.startsWith("image/"));
|
|
3174
|
+
if (event.dataTransfer)
|
|
3175
|
+
event.dataTransfer.dropEffect = images && this.upload && this.editable ? "copy" : "none";
|
|
3176
|
+
};
|
|
3177
|
+
onDrop = (event) => {
|
|
3178
|
+
if (!EditorView.carriesFiles(event))
|
|
3179
|
+
return;
|
|
3180
|
+
event.preventDefault();
|
|
3181
|
+
const files = this.imageFiles(event.dataTransfer);
|
|
3182
|
+
if (!files.length || this.composing)
|
|
3183
|
+
return;
|
|
3184
|
+
// The place the files were dropped.
|
|
3185
|
+
const pos = this.posAtPoint(event.clientX, event.clientY);
|
|
3186
|
+
if (pos !== null)
|
|
3187
|
+
this.dispatch(this.state.tr.setSelection(TextSelection.near(this.state.doc.resolve(pos))));
|
|
3188
|
+
void this.insertFiles(files);
|
|
3189
|
+
};
|
|
3190
|
+
/**
|
|
3191
|
+
* Inserts image files where the selection is now, one picture each, in order: each measured
|
|
3192
|
+
* first (one the browser cannot show is skipped, not uploaded), then given to the `upload`
|
|
3193
|
+
* option, then inserted at its natural size (96 px per inch) no wider than the page's text,
|
|
3194
|
+
* where the selection was, however the document changed meanwhile (after a composition that
|
|
3195
|
+
* runs then). A file whose upload fails is skipped (reported on the console). Resolves to
|
|
3196
|
+
* the number inserted (none without `upload`); never rejects.
|
|
3197
|
+
*/
|
|
3198
|
+
async insertFiles(files) {
|
|
3199
|
+
const upload = this.upload;
|
|
3200
|
+
if (!upload || !this.editable)
|
|
3201
|
+
return 0;
|
|
3202
|
+
// The insertion point, mapped through every change until the pictures go in.
|
|
3203
|
+
let at = this.state.selection.from;
|
|
3204
|
+
const replace = !this.state.selection.empty;
|
|
3205
|
+
// Another document (`setDocument` notifies with no transaction): the files are not for it.
|
|
3206
|
+
let lost = false;
|
|
3207
|
+
let mapped = this.state.doc;
|
|
3208
|
+
// The user's own selection while a picture goes in, mapped, to give back after it.
|
|
3209
|
+
let user = null;
|
|
3210
|
+
const unsubscribe = this.editor.subscribe((state, transactions) => {
|
|
3211
|
+
for (const tr of transactions) {
|
|
3212
|
+
at = tr.mapping.map(at);
|
|
3213
|
+
if (user)
|
|
3214
|
+
user = user.map(tr.doc, tr.mapping);
|
|
3215
|
+
}
|
|
3216
|
+
if (!transactions.length && state.doc !== mapped)
|
|
3217
|
+
lost = true;
|
|
3218
|
+
mapped = state.doc;
|
|
3219
|
+
});
|
|
3220
|
+
let inserted = 0;
|
|
3221
|
+
try {
|
|
3222
|
+
for (const file of files) {
|
|
3223
|
+
if (!file.type.startsWith("image/"))
|
|
3224
|
+
continue;
|
|
3225
|
+
const size = await measureImageFile(file, this.host.ownerDocument);
|
|
3226
|
+
if (this.destroyed)
|
|
3227
|
+
return inserted;
|
|
3228
|
+
if (!size)
|
|
3229
|
+
continue;
|
|
3230
|
+
let answer;
|
|
3231
|
+
try {
|
|
3232
|
+
answer = await upload(file);
|
|
3233
|
+
}
|
|
3234
|
+
catch (error) {
|
|
3235
|
+
console.warn(`Foli: the upload of ${file.name} failed`, error);
|
|
3236
|
+
continue;
|
|
3237
|
+
}
|
|
3238
|
+
const { src, alt, decorative } = typeof answer === "string" ? { src: answer } : (answer ?? { src: "" });
|
|
3239
|
+
if (typeof src !== "string" || !src)
|
|
3240
|
+
continue;
|
|
3241
|
+
// The browser owns the DOM during a composition: the picture goes in after it.
|
|
3242
|
+
while (this.composing && !this.destroyed)
|
|
3243
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
3244
|
+
if (this.destroyed || !this.editable || lost)
|
|
3245
|
+
return inserted;
|
|
3246
|
+
const scale = Math.min(1, this.textWidthEmu() / (size.width * EMU_PER_PX));
|
|
3247
|
+
// A `data:` URL says its own type (an app may have converted the file).
|
|
3248
|
+
const type = /^data:([^;,]+)/i.exec(src)?.[1]?.toLowerCase() ?? file.type;
|
|
3249
|
+
const picture = {
|
|
3250
|
+
contentType: type,
|
|
3251
|
+
...(src.startsWith("data:") ? { data: src } : { url: src }),
|
|
3252
|
+
width: Math.max(1, Math.round(size.width * EMU_PER_PX * scale)),
|
|
3253
|
+
height: Math.max(1, Math.round(size.height * EMU_PER_PX * scale)),
|
|
3254
|
+
...(typeof alt === "string" && alt.trim() ? { alt } : {}),
|
|
3255
|
+
...(decorative === true ? { decorative } : {}),
|
|
3256
|
+
};
|
|
3257
|
+
const { doc, selection } = this.state;
|
|
3258
|
+
const pos = Math.min(at, doc.content.size);
|
|
3259
|
+
// The first picture replaces what was selected at the paste (still selected there).
|
|
3260
|
+
const here = replace && inserted === 0 && selection.from === pos;
|
|
3261
|
+
// A caret the user moved elsewhere meanwhile stays there.
|
|
3262
|
+
const elsewhere = !here && !(selection.empty && selection.from === pos);
|
|
3263
|
+
user = elsewhere ? selection : null;
|
|
3264
|
+
if (!here)
|
|
3265
|
+
this.dispatch(this.state.tr.setSelection(TextSelection.near(doc.resolve(pos))));
|
|
3266
|
+
if (this.run(insertPicture(picture, { requireAlt: false })))
|
|
3267
|
+
inserted++;
|
|
3268
|
+
if (user)
|
|
3269
|
+
this.dispatch(this.state.tr.setSelection(user));
|
|
3270
|
+
user = null;
|
|
3271
|
+
}
|
|
3272
|
+
return inserted;
|
|
3273
|
+
}
|
|
3274
|
+
finally {
|
|
3275
|
+
unsubscribe();
|
|
3276
|
+
}
|
|
3277
|
+
}
|
|
1055
3278
|
/**
|
|
1056
3279
|
* Triple-click selects the clicked block's content. Chromium and WebKit natively extend the
|
|
1057
3280
|
* selection to the start of the next block, so typing over it would merge the two blocks.
|
|
@@ -1064,6 +3287,40 @@ export class EditorView {
|
|
|
1064
3287
|
setTimeout(() => (this.pointerFocus = false));
|
|
1065
3288
|
if (event.button !== 0)
|
|
1066
3289
|
return;
|
|
3290
|
+
if (this.startColumnDrag(event))
|
|
3291
|
+
return;
|
|
3292
|
+
if (this.pictureMouseDown(event))
|
|
3293
|
+
return;
|
|
3294
|
+
// A click puts a caret where it lands, even on the one a cell selection wrote.
|
|
3295
|
+
if (!event.shiftKey)
|
|
3296
|
+
this.cellCaret = null;
|
|
3297
|
+
// A header row drawn again is not document content: the caret goes below it.
|
|
3298
|
+
const repeated = event.target?.closest?.(`[${REPEATED_ATTR}]`);
|
|
3299
|
+
if (repeated && this.host.contains(repeated) && !event.shiftKey) {
|
|
3300
|
+
const pos = this.posFromDOM(repeated, 0);
|
|
3301
|
+
if (pos !== null) {
|
|
3302
|
+
event.preventDefault();
|
|
3303
|
+
if (!this.hasFocus())
|
|
3304
|
+
this.host.focus({ preventScroll: true });
|
|
3305
|
+
const $pos = this.state.doc.resolve(pos);
|
|
3306
|
+
this.dispatch(this.state.tr.setSelection(Selection.near($pos)));
|
|
3307
|
+
}
|
|
3308
|
+
return;
|
|
3309
|
+
}
|
|
3310
|
+
// Word's blank page before an even or odd page section holds nothing: the caret goes to the
|
|
3311
|
+
// section after it (the browser would put it at the document's start).
|
|
3312
|
+
const blank = event.target;
|
|
3313
|
+
if (!event.shiftKey && this.pages.includes(blank) && !blank.firstChild) {
|
|
3314
|
+
const pos = this.posFromDOM(blank, 0);
|
|
3315
|
+
if (pos !== null) {
|
|
3316
|
+
event.preventDefault();
|
|
3317
|
+
if (!this.hasFocus())
|
|
3318
|
+
this.host.focus({ preventScroll: true });
|
|
3319
|
+
this.dispatch(this.state.tr.setSelection(Selection.near(this.state.doc.resolve(pos))));
|
|
3320
|
+
this.writeSelection(true);
|
|
3321
|
+
}
|
|
3322
|
+
return;
|
|
3323
|
+
}
|
|
1067
3324
|
const element = this.blockElement(event.target);
|
|
1068
3325
|
const owner = element ? this.owner.get(element) : undefined;
|
|
1069
3326
|
const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
|
|
@@ -1096,6 +3353,8 @@ export class EditorView {
|
|
|
1096
3353
|
*/
|
|
1097
3354
|
onClick = (event) => {
|
|
1098
3355
|
const target = event.target;
|
|
3356
|
+
if (event.type === "click" && !event.shiftKey && this.controlChrome.click(event))
|
|
3357
|
+
return;
|
|
1099
3358
|
const element = target instanceof Element ? target.closest("a") : null;
|
|
1100
3359
|
if (!element || !this.host.contains(element))
|
|
1101
3360
|
return;
|
|
@@ -1118,6 +3377,15 @@ export class EditorView {
|
|
|
1118
3377
|
return isSafeHref(href) ? href : null;
|
|
1119
3378
|
}
|
|
1120
3379
|
onKeyDown = (event) => {
|
|
3380
|
+
// The host itself focused while a story is open (Shift+Tab): it is read-only, and its selection
|
|
3381
|
+
// is what leaving the story comes back to.
|
|
3382
|
+
if (this.mount) {
|
|
3383
|
+
if (event.key === "Escape") {
|
|
3384
|
+
event.preventDefault();
|
|
3385
|
+
this.closeStory(true);
|
|
3386
|
+
}
|
|
3387
|
+
return;
|
|
3388
|
+
}
|
|
1121
3389
|
if (event.isComposing || this.composing)
|
|
1122
3390
|
return;
|
|
1123
3391
|
this.syncSelection();
|
|
@@ -1125,7 +3393,19 @@ export class EditorView {
|
|
|
1125
3393
|
event.preventDefault();
|
|
1126
3394
|
return;
|
|
1127
3395
|
}
|
|
3396
|
+
if (this.skipFieldParts(event)) {
|
|
3397
|
+
event.preventDefault();
|
|
3398
|
+
return;
|
|
3399
|
+
}
|
|
1128
3400
|
const name = keyName(event);
|
|
3401
|
+
if (this.documentEdgeKey(name) ||
|
|
3402
|
+
this.fieldKey(name) ||
|
|
3403
|
+
this.controlKey(name) ||
|
|
3404
|
+
this.noteKey(event, name) ||
|
|
3405
|
+
this.navigationKey(name)) {
|
|
3406
|
+
event.preventDefault();
|
|
3407
|
+
return;
|
|
3408
|
+
}
|
|
1129
3409
|
// Ctrl/Cmd+Shift+V: the paste event that follows uses only the plain text.
|
|
1130
3410
|
this.plainPaste = name === "Mod-Shift-v";
|
|
1131
3411
|
// Tab and Shift+Tab move the focus on in read-only mode, and right after Escape where Tab
|
|
@@ -1144,19 +3424,74 @@ export class EditorView {
|
|
|
1144
3424
|
}
|
|
1145
3425
|
// Up/Down on a textblock's first/last line next to a rule select it (only the view knows
|
|
1146
3426
|
// lines; measured only when a rule is beside the block); else the browser moves the caret.
|
|
3427
|
+
// Shift+arrows in a table: cells selected grow by a cell; from text in a cell, Shift+Up or
|
|
3428
|
+
// Down starts a cell selection once the head is on the cell's first or last line.
|
|
3429
|
+
const shift = {
|
|
3430
|
+
"Shift-ArrowUp": ["row", -1],
|
|
3431
|
+
"Shift-ArrowDown": ["row", 1],
|
|
3432
|
+
"Shift-ArrowLeft": ["column", -1],
|
|
3433
|
+
"Shift-ArrowRight": ["column", 1],
|
|
3434
|
+
};
|
|
3435
|
+
const growing = Object.hasOwn(shift, name) ? shift[name] : undefined;
|
|
3436
|
+
if (growing) {
|
|
3437
|
+
const [axis, dir] = growing;
|
|
3438
|
+
const grow = extendCellSelection(axis, dir);
|
|
3439
|
+
const leaving = this.state.selection instanceof CellSelection ||
|
|
3440
|
+
(axis === "row" && this.caretOnEdgeLine(dir, true));
|
|
3441
|
+
if (leaving && grow(this.state) && this.run(grow)) {
|
|
3442
|
+
event.preventDefault();
|
|
3443
|
+
return;
|
|
3444
|
+
}
|
|
3445
|
+
}
|
|
1147
3446
|
const vertical = name === "ArrowUp" ? -1 : name === "ArrowDown" ? 1 : 0;
|
|
3447
|
+
// In a table, from a cell's first or last line: the cell above or below, or out of the
|
|
3448
|
+
// table (browsers go to the next cell in the DOM, or across pages to the wrong row).
|
|
3449
|
+
const cells = vertical ? goToCellVertically(vertical) : null;
|
|
3450
|
+
// (A selection of a cell's whole content, Tab's, moves as the cell: no line to measure.)
|
|
3451
|
+
const onEdge = () => !this.state.selection.empty || this.caretOnEdgeLine(vertical);
|
|
3452
|
+
if (cells?.(this.state) && onEdge() && this.run(cells)) {
|
|
3453
|
+
event.preventDefault();
|
|
3454
|
+
return;
|
|
3455
|
+
}
|
|
1148
3456
|
const across = vertical ? arrowAcrossLeaf(vertical, "line") : null;
|
|
1149
3457
|
if (across?.(this.state) && this.caretOnEdgeLine(vertical) && this.run(across)) {
|
|
1150
3458
|
event.preventDefault();
|
|
1151
3459
|
}
|
|
1152
3460
|
};
|
|
3461
|
+
/** Word's keys for notes, and Shift+Alt+N from a reference to its note. */
|
|
3462
|
+
noteKey(event, name) {
|
|
3463
|
+
if (isNoteKey(event))
|
|
3464
|
+
return this.openNote();
|
|
3465
|
+
const kind = name === "Mod-Alt-f" ? "footnote" : name === "Mod-Alt-d" ? "endnote" : null;
|
|
3466
|
+
if (!kind || !this.editable || !this.notes)
|
|
3467
|
+
return false;
|
|
3468
|
+
return this.run(insertNote(kind)) && this.openNote();
|
|
3469
|
+
}
|
|
3470
|
+
/**
|
|
3471
|
+
* Ctrl+Home and Ctrl+End (with Shift, extending) on pages with headers and footers: the browser
|
|
3472
|
+
* stops at the first or last place before what it cannot edit, so the model says where.
|
|
3473
|
+
*/
|
|
3474
|
+
documentEdgeKey(name) {
|
|
3475
|
+
const shift = name.startsWith("Mod-Shift-");
|
|
3476
|
+
const key = name.replace("Mod-Shift-", "Mod-");
|
|
3477
|
+
if ((key !== "Mod-Home" && key !== "Mod-End") || !this.editable)
|
|
3478
|
+
return false;
|
|
3479
|
+
if (!this.pageRegions.some((page) => page.header || page.footer))
|
|
3480
|
+
return false;
|
|
3481
|
+
const { doc, selection } = this.state;
|
|
3482
|
+
const edge = key === "Mod-Home" ? Selection.atStart(doc) : Selection.atEnd(doc);
|
|
3483
|
+
const next = shift ? TextSelection.between(selection.$anchor, edge.$head) : edge;
|
|
3484
|
+
this.dispatch(this.state.tr.setSelection(next).setStoredMarks(null));
|
|
3485
|
+
return true;
|
|
3486
|
+
}
|
|
1153
3487
|
/**
|
|
1154
3488
|
* Whether the caret is on the first (`dir` -1) or last (1) line of its textblock, in the
|
|
1155
3489
|
* block's first or last fragment (a block split across pages has several).
|
|
1156
3490
|
*/
|
|
1157
|
-
caretOnEdgeLine(dir) {
|
|
3491
|
+
caretOnEdgeLine(dir, focusOnly = false) {
|
|
1158
3492
|
const sel = this.host.ownerDocument.getSelection();
|
|
1159
|
-
|
|
3493
|
+
// `focusOnly`: a range's head (Shift+arrows), else only a caret.
|
|
3494
|
+
if (!sel?.rangeCount || (!focusOnly && !sel.isCollapsed) || !sel.focusNode)
|
|
1160
3495
|
return false;
|
|
1161
3496
|
const element = this.blockElement(sel.focusNode);
|
|
1162
3497
|
const desc = element ? this.owner.get(element) : undefined;
|
|
@@ -1167,7 +3502,10 @@ export class EditorView {
|
|
|
1167
3502
|
return false;
|
|
1168
3503
|
if (!desc.node.content.size)
|
|
1169
3504
|
return true;
|
|
1170
|
-
const
|
|
3505
|
+
const at = this.host.ownerDocument.createRange();
|
|
3506
|
+
at.setStart(sel.focusNode, sel.focusOffset);
|
|
3507
|
+
at.collapse(true);
|
|
3508
|
+
const caret = at.getClientRects()[0];
|
|
1171
3509
|
const lines = this.host.ownerDocument.createRange();
|
|
1172
3510
|
lines.selectNodeContents(fragment);
|
|
1173
3511
|
const rects = lines.getClientRects();
|
|
@@ -1289,9 +3627,10 @@ export class EditorView {
|
|
|
1289
3627
|
* and so is the scroll position.
|
|
1290
3628
|
*/
|
|
1291
3629
|
onFocus = () => {
|
|
3630
|
+
this.claimStories();
|
|
1292
3631
|
const pointer = this.pointerFocus;
|
|
1293
3632
|
this.pointerFocus = false;
|
|
1294
|
-
if (pointer)
|
|
3633
|
+
if (pointer || this.mount)
|
|
1295
3634
|
return;
|
|
1296
3635
|
const current = this.readSelection();
|
|
1297
3636
|
if (current && this.shows(current))
|
|
@@ -1306,13 +3645,13 @@ export class EditorView {
|
|
|
1306
3645
|
this.onCompositionEnd();
|
|
1307
3646
|
};
|
|
1308
3647
|
onMutations = (records) => {
|
|
1309
|
-
this.pending.push(...records);
|
|
1310
|
-
if (!this.composing)
|
|
3648
|
+
this.pending.push(...records.filter((r) => !handleOnly(r)));
|
|
3649
|
+
if (!this.composing && this.pending.length)
|
|
1311
3650
|
this.flush();
|
|
1312
3651
|
};
|
|
1313
3652
|
/** Reads back every DOM change recorded so far. */
|
|
1314
3653
|
flush() {
|
|
1315
|
-
const records = [...this.pending, ...this.observer.takeRecords()];
|
|
3654
|
+
const records = [...this.pending, ...this.observer.takeRecords().filter((r) => !handleOnly(r))];
|
|
1316
3655
|
this.pending = [];
|
|
1317
3656
|
if (records.length)
|
|
1318
3657
|
this.readBack(records);
|
|
@@ -1355,30 +3694,59 @@ export class EditorView {
|
|
|
1355
3694
|
else
|
|
1356
3695
|
node.childNodes.forEach(walk);
|
|
1357
3696
|
};
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
const blockLevel = [];
|
|
3697
|
+
// Block-level nodes: inside pages and tables, and anything else in the host.
|
|
3698
|
+
let stray = false;
|
|
1361
3699
|
const collect = (parent) => {
|
|
1362
3700
|
for (const child of parent.childNodes) {
|
|
3701
|
+
if (this.owner.has(child))
|
|
3702
|
+
continue;
|
|
3703
|
+
// Drawn, not document content (a repeated header row): no text of the model.
|
|
3704
|
+
if (child.getAttribute?.("contenteditable") === "false")
|
|
3705
|
+
continue;
|
|
1363
3706
|
if (this.holdsBlocks(child))
|
|
1364
3707
|
collect(child);
|
|
1365
|
-
|
|
1366
|
-
|
|
3708
|
+
// Text outside every block (an element the browser added): a block the model does not
|
|
3709
|
+
// have. An empty stray node (an extension's marker) holds none; the re-render removes it.
|
|
3710
|
+
else if (child.textContent)
|
|
3711
|
+
stray = true;
|
|
1367
3712
|
}
|
|
1368
3713
|
};
|
|
1369
3714
|
collect(this.host);
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
3715
|
+
if (stray) {
|
|
3716
|
+
// shortcut: a change that adds blocks cannot be read back yet; it is dropped.
|
|
3717
|
+
console.warn("Foli: discarded a DOM change that adds blocks or line breaks");
|
|
3718
|
+
this.rerender();
|
|
3719
|
+
return;
|
|
3720
|
+
}
|
|
3721
|
+
// Each block's fragments are one text, blocks in document order (a row split across pages
|
|
3722
|
+
// has its cells' fragments on two pages).
|
|
3723
|
+
// A block whose elements the browser removed (merging it into another) has no text there.
|
|
3724
|
+
// One missing without a recorded removal was never placed (drawn during a composition):
|
|
3725
|
+
// its text counts as unchanged, never as deleted.
|
|
3726
|
+
const removed = new Set(records.flatMap((record) => [...record.removedNodes]).filter((n) => !this.viewRemoved.has(n)));
|
|
3727
|
+
const removedByInput = (node) => {
|
|
3728
|
+
for (let at = node; at; at = at.parentNode)
|
|
3729
|
+
if (removed.has(at))
|
|
3730
|
+
return true;
|
|
3731
|
+
return false;
|
|
3732
|
+
};
|
|
3733
|
+
let first = true;
|
|
3734
|
+
for (const desc of this.blocks) {
|
|
3735
|
+
const shown = desc.fragments.filter((fragment) => this.host.contains(fragment));
|
|
3736
|
+
if (!shown.length && !desc.fragments.some(removedByInput)) {
|
|
3737
|
+
if (!first)
|
|
3738
|
+
domText += BLOCK_SEPARATOR;
|
|
3739
|
+
first = false;
|
|
3740
|
+
domText += textOfBlock(desc.node);
|
|
1375
3741
|
continue;
|
|
1376
|
-
|
|
1377
|
-
if (!
|
|
3742
|
+
}
|
|
3743
|
+
if (!shown.length)
|
|
3744
|
+
continue;
|
|
3745
|
+
if (!first)
|
|
1378
3746
|
domText += BLOCK_SEPARATOR;
|
|
1379
3747
|
first = false;
|
|
1380
|
-
|
|
1381
|
-
|
|
3748
|
+
for (const fragment of shown)
|
|
3749
|
+
walk(fragment);
|
|
1382
3750
|
}
|
|
1383
3751
|
const { doc } = this.state;
|
|
1384
3752
|
const lineStarts = [];
|
|
@@ -1387,14 +3755,7 @@ export class EditorView {
|
|
|
1387
3755
|
if (i > 0)
|
|
1388
3756
|
modelText += BLOCK_SEPARATOR;
|
|
1389
3757
|
lineStarts.push(modelText.length);
|
|
1390
|
-
block
|
|
1391
|
-
// A tab is text in the DOM (a "\t" text node).
|
|
1392
|
-
modelText += child.isText
|
|
1393
|
-
? (child.text ?? "")
|
|
1394
|
-
: child.type.name === "tab"
|
|
1395
|
-
? "\t"
|
|
1396
|
-
: HARD_BREAK;
|
|
1397
|
-
});
|
|
3758
|
+
modelText += textOfBlock(block);
|
|
1398
3759
|
});
|
|
1399
3760
|
/** Model position of an offset in `modelText`. */
|
|
1400
3761
|
const posAt = (offset) => {
|
|
@@ -1470,8 +3831,11 @@ export class EditorView {
|
|
|
1470
3831
|
return;
|
|
1471
3832
|
event.preventDefault();
|
|
1472
3833
|
const context = wordContext(this.state);
|
|
1473
|
-
|
|
1474
|
-
|
|
3834
|
+
// Selected cells are copied as a table of their own (ADR-0006).
|
|
3835
|
+
const table = selection instanceof CellSelection ? cellsAsTable(selection) : null;
|
|
3836
|
+
const source = table ? doc.type.create(null, table) : doc;
|
|
3837
|
+
const { text, html, json } = serializeRange(source, table ? 0 : selection.from, table ? source.content.size : selection.to, this.host.ownerDocument, { context, ratio: this.lineRatio });
|
|
3838
|
+
event.clipboardData.setData("text/plain", table ? cellsText(table) : text);
|
|
1475
3839
|
event.clipboardData.setData("text/html", html);
|
|
1476
3840
|
event.clipboardData.setData(FOLI_MIME, json);
|
|
1477
3841
|
};
|
|
@@ -1493,6 +3857,12 @@ export class EditorView {
|
|
|
1493
3857
|
return;
|
|
1494
3858
|
this.syncSelection();
|
|
1495
3859
|
const data = event.clipboardData;
|
|
3860
|
+
// An image alone (a screenshot, an image copied from a page): a picture.
|
|
3861
|
+
const files = plain ? [] : this.imageFiles(data);
|
|
3862
|
+
if (files.length && !data.getData(FOLI_MIME) && !data.getData("text/plain").trim()) {
|
|
3863
|
+
void this.insertFiles(files);
|
|
3864
|
+
return;
|
|
3865
|
+
}
|
|
1496
3866
|
this.paste(plain ? { getData: (type) => (type === "text/plain" ? data.getData(type) : "") } : data, !plain);
|
|
1497
3867
|
};
|
|
1498
3868
|
/**
|
|
@@ -1506,6 +3876,10 @@ export class EditorView {
|
|
|
1506
3876
|
*/
|
|
1507
3877
|
paste(data, autolink = true) {
|
|
1508
3878
|
const { state } = this;
|
|
3879
|
+
// A text control takes the text alone.
|
|
3880
|
+
const plainText = data.getData("text/plain");
|
|
3881
|
+
if (plainText && this.run(insertControlText(plainText)))
|
|
3882
|
+
return true;
|
|
1509
3883
|
const text = autolink && !data.getData(FOLI_MIME) ? data.getData("text/plain") : "";
|
|
1510
3884
|
const href = text ? autolinkHref(text) : null;
|
|
1511
3885
|
if (href) {
|
|
@@ -1531,7 +3905,7 @@ export class EditorView {
|
|
|
1531
3905
|
const only = pasted?.doc.childCount === 1 ? pasted.doc.firstChild : null;
|
|
1532
3906
|
if (!pasted || (only?.isTextblock && !only.content.size))
|
|
1533
3907
|
return false;
|
|
1534
|
-
const { doc, open, envelope } = pasted;
|
|
3908
|
+
const { doc, open, envelope, notes } = pasted;
|
|
1535
3909
|
// As a slice (text joins the text around the caret); where that cannot be (an opaque block
|
|
1536
3910
|
// at an end), as whole blocks at the caret.
|
|
1537
3911
|
const asSlice = (tr) => {
|
|
@@ -1554,17 +3928,29 @@ export class EditorView {
|
|
|
1554
3928
|
throw new TransformError("Open content is pasted as a slice");
|
|
1555
3929
|
insertBlocks(tr, doc);
|
|
1556
3930
|
};
|
|
1557
|
-
|
|
3931
|
+
// Rows (a table alone) into a table fill its cells from the selected one (ADR-0006).
|
|
3932
|
+
const intoCells = (tr) => {
|
|
3933
|
+
if (only?.type.name !== "table" || !pasteCells(tr, only))
|
|
3934
|
+
throw new TransformError("Only rows are pasted into cells");
|
|
3935
|
+
};
|
|
3936
|
+
const strategies = [intoCells, asSlice, asBlocks];
|
|
1558
3937
|
for (const strategy of strategies) {
|
|
1559
3938
|
const tr = state.tr;
|
|
1560
3939
|
try {
|
|
1561
|
-
|
|
3940
|
+
// Other content over selected cells goes into the anchor cell; across a table's edge,
|
|
3941
|
+
// whole rows go (`deleteSelectionKeepingTables`).
|
|
3942
|
+
if (strategy !== intoCells && !tr.selection.empty)
|
|
3943
|
+
deleteSelectionKeepingTables(tr, true);
|
|
1562
3944
|
strategy(tr);
|
|
3945
|
+
// A pasted table never ends the body nor touches another table (Word's rules).
|
|
3946
|
+
keepTablesApart(tr);
|
|
1563
3947
|
const current = wordContext(state)?.envelope;
|
|
1564
3948
|
if (envelope && current && envelope !== current) {
|
|
1565
3949
|
withEnvelope(tr, envelope);
|
|
1566
3950
|
setComments(tr, current.comments, envelope.comments);
|
|
1567
3951
|
}
|
|
3952
|
+
for (const { id, story } of notes ?? [])
|
|
3953
|
+
tr.step(new StoryStep(id, null, story));
|
|
1568
3954
|
}
|
|
1569
3955
|
catch (error) {
|
|
1570
3956
|
if (error instanceof TransformError)
|
|
@@ -1576,10 +3962,22 @@ export class EditorView {
|
|
|
1576
3962
|
return false;
|
|
1577
3963
|
}
|
|
1578
3964
|
onSelectionChange = () => {
|
|
1579
|
-
if (!this.composing && this.hasFocus())
|
|
3965
|
+
if (!this.composing && !this.mount && this.hasFocus())
|
|
1580
3966
|
this.syncSelection();
|
|
1581
3967
|
};
|
|
1582
3968
|
}
|
|
3969
|
+
/** Copied cells as text, as spreadsheets read it: a tab between cells, a line per row. */
|
|
3970
|
+
function cellsText(table) {
|
|
3971
|
+
const rows = [];
|
|
3972
|
+
table.forEach((row) => {
|
|
3973
|
+
const cells = [];
|
|
3974
|
+
row.forEach((cell) => {
|
|
3975
|
+
cells.push(cell.textBetween(0, cell.content.size, " "));
|
|
3976
|
+
});
|
|
3977
|
+
rows.push(cells.join("\t"));
|
|
3978
|
+
});
|
|
3979
|
+
return rows.join("\n");
|
|
3980
|
+
}
|
|
1583
3981
|
/**
|
|
1584
3982
|
* Pastes whole blocks at the caret (after deleting the selection): before or after the caret's
|
|
1585
3983
|
* paragraph, else between its two halves (an empty one is replaced as a slice first).
|
|
@@ -1610,6 +4008,170 @@ function insertBlocks(tr, doc) {
|
|
|
1610
4008
|
function layoutScale(page, settings) {
|
|
1611
4009
|
return page.getBoundingClientRect().width / (settings.pageSize.width * PX_PER_MM) || 1;
|
|
1612
4010
|
}
|
|
4011
|
+
/** The innermost cell around pos (the position before it) and its table's, or null. */
|
|
4012
|
+
function cellAround(doc, pos) {
|
|
4013
|
+
const $pos = doc.resolve(pos);
|
|
4014
|
+
for (let d = $pos.depth; d > 2; d--)
|
|
4015
|
+
if ($pos.node(d).type.name === "tableCell")
|
|
4016
|
+
return { cell: $pos.before(d), table: $pos.before(d - 2) };
|
|
4017
|
+
return null;
|
|
4018
|
+
}
|
|
4019
|
+
/** A block's text as the read-back compares it: a tab "\t", other inline leaves one character. */
|
|
4020
|
+
function textOfBlock(block) {
|
|
4021
|
+
let text = "";
|
|
4022
|
+
block.forEach((child) => {
|
|
4023
|
+
// A tab is text in the DOM (a "\t" text node).
|
|
4024
|
+
text += child.isText ? (child.text ?? "") : child.type.name === "tab" ? "\t" : HARD_BREAK;
|
|
4025
|
+
});
|
|
4026
|
+
return text;
|
|
4027
|
+
}
|
|
4028
|
+
/** Whether a table's wrappers hold every element of its blocks (none was drawn anew). */
|
|
4029
|
+
function holdsAll(state, frame, blocks) {
|
|
4030
|
+
for (let u = frame.first; u < frame.end; u++)
|
|
4031
|
+
for (const fragment of blocks[u].fragments)
|
|
4032
|
+
if (!state.wrappers.some((wrapper) => wrapper.contains(fragment)))
|
|
4033
|
+
return false;
|
|
4034
|
+
return true;
|
|
4035
|
+
}
|
|
4036
|
+
/** Measures a table drawn whole: its height, its rows and where its blocks start. */
|
|
4037
|
+
function measureTable(frame, wrapper, blocks, scale) {
|
|
4038
|
+
const box = wrapper.getBoundingClientRect();
|
|
4039
|
+
const rows = [...wrapper.querySelectorAll(":scope > table > tbody > tr")].map((tr) => {
|
|
4040
|
+
const rect = tr.getBoundingClientRect();
|
|
4041
|
+
return { top: (rect.top - box.top) / scale, bottom: (rect.bottom - box.top) / scale };
|
|
4042
|
+
});
|
|
4043
|
+
const tops = new Map();
|
|
4044
|
+
for (let u = frame.first; u < frame.end; u++) {
|
|
4045
|
+
const dom = blocks[u].dom;
|
|
4046
|
+
// A block of a cell a merge covers is not shown: it goes with its row.
|
|
4047
|
+
const hidden = !!dom.closest(`[${FRAME_ATTR}="covered"]`);
|
|
4048
|
+
tops.set(u, hidden ? null : (dom.getBoundingClientRect().top - box.top) / scale);
|
|
4049
|
+
}
|
|
4050
|
+
return {
|
|
4051
|
+
height: box.height / scale,
|
|
4052
|
+
marginTop: 0,
|
|
4053
|
+
marginBottom: 0,
|
|
4054
|
+
box: 0,
|
|
4055
|
+
table: { rows, tops },
|
|
4056
|
+
};
|
|
4057
|
+
}
|
|
4058
|
+
/**
|
|
4059
|
+
* Where a table may break across pages (from its top, sorted): after each row, and inside a row
|
|
4060
|
+
* at its cells' line ends, unless the row may not split (`cantSplit`, unless taller than a
|
|
4061
|
+
* page), is part of a vertical merge or holds a nested table (shortcut: those split only
|
|
4062
|
+
* between rows; a nested table stays whole within its row).
|
|
4063
|
+
*/
|
|
4064
|
+
export function breaksOf(frame, measure, blocks, pageHeight, lines) {
|
|
4065
|
+
const t = measure.table;
|
|
4066
|
+
if (t.breaks)
|
|
4067
|
+
return t.breaks;
|
|
4068
|
+
const out = [];
|
|
4069
|
+
frame.rows.forEach((row, r) => {
|
|
4070
|
+
const { top, bottom } = t.rows[r] ?? { top: 0, bottom: 0 };
|
|
4071
|
+
const merged = row.cells.some((cell) => cell.vMerge !== null);
|
|
4072
|
+
const nested = row.cells.some((cell) => cell.items.some((item) => "frame" in item));
|
|
4073
|
+
const splits = (!row.cantSplit || bottom - top > pageHeight) && !merged && !nested;
|
|
4074
|
+
if (splits)
|
|
4075
|
+
for (const cell of row.cells)
|
|
4076
|
+
for (const item of cell.items) {
|
|
4077
|
+
if ("frame" in item)
|
|
4078
|
+
continue;
|
|
4079
|
+
const unitTop = t.tops.get(item.unit);
|
|
4080
|
+
if (unitTop === null || unitTop === undefined)
|
|
4081
|
+
continue;
|
|
4082
|
+
for (const b of lines(blocks[item.unit]).bottoms) {
|
|
4083
|
+
const y = unitTop + b;
|
|
4084
|
+
if (y > top + 0.5 && y < bottom - 0.5)
|
|
4085
|
+
out.push(y);
|
|
4086
|
+
}
|
|
4087
|
+
}
|
|
4088
|
+
out.push(r === frame.rows.length - 1 ? Math.max(bottom, measure.height) : bottom);
|
|
4089
|
+
});
|
|
4090
|
+
out.sort((a, b) => a - b);
|
|
4091
|
+
t.breaks = out.filter((y, k) => k === 0 || y - out[k - 1] > 0.5);
|
|
4092
|
+
return t.breaks;
|
|
4093
|
+
}
|
|
4094
|
+
/** What the flow needs of a table: its height, where it may break, its header rows' height. */
|
|
4095
|
+
function tableBox(frame, measure, pageHeight, breakAfter, breaks) {
|
|
4096
|
+
const t = measure.table;
|
|
4097
|
+
const header = frame.headers ? (t.rows[frame.headers - 1]?.bottom ?? 0) : 0;
|
|
4098
|
+
return {
|
|
4099
|
+
height: measure.height,
|
|
4100
|
+
marginTop: 0,
|
|
4101
|
+
marginBottom: 0,
|
|
4102
|
+
pageHeight,
|
|
4103
|
+
repeat: header,
|
|
4104
|
+
// Word keeps no lines together across a table's rows (a cell's paragraph splits anywhere).
|
|
4105
|
+
anyLine: true,
|
|
4106
|
+
lines: breaks,
|
|
4107
|
+
breaksAfter: () => (breakAfter ? [breaks().length - 1] : []),
|
|
4108
|
+
};
|
|
4109
|
+
}
|
|
4110
|
+
/**
|
|
4111
|
+
* A flowed table cut into its fragments: the rows each shows (a row split across pages in
|
|
4112
|
+
* both), the header rows drawn again above a continuation, the fragment of the table each
|
|
4113
|
+
* block's fragments go in, and where a block of a split row splits (content offsets).
|
|
4114
|
+
*/
|
|
4115
|
+
export function cutTable(frame, measure, fragments, blocks, lines) {
|
|
4116
|
+
const t = measure.table;
|
|
4117
|
+
const all = frame.rows.map((_, r) => r);
|
|
4118
|
+
const partOf = new Map();
|
|
4119
|
+
const splits = new Map();
|
|
4120
|
+
if (fragments.length <= 1 || !t.breaks) {
|
|
4121
|
+
for (let u = frame.first; u < frame.end; u++)
|
|
4122
|
+
partOf.set(u, [0]);
|
|
4123
|
+
return { parts: [{ rows: all, headers: [] }], partOf, splits };
|
|
4124
|
+
}
|
|
4125
|
+
const breaks = t.breaks;
|
|
4126
|
+
const bounds = fragments.map((f) => [
|
|
4127
|
+
f.fromLine ? breaks[f.fromLine - 1] : 0,
|
|
4128
|
+
f.toLine === Number.POSITIVE_INFINITY ? measure.height : breaks[f.toLine - 1],
|
|
4129
|
+
]);
|
|
4130
|
+
const parts = bounds.map(([y0, y1], k) => {
|
|
4131
|
+
const rows = all.filter((r) => {
|
|
4132
|
+
const row = t.rows[r] ?? { top: 0, bottom: 0 };
|
|
4133
|
+
return row.top < y1 - 0.5 && row.bottom > y0 + 0.5;
|
|
4134
|
+
});
|
|
4135
|
+
const repeat = k > 0 && frame.headers > 0 && (rows[0] ?? 0) >= frame.headers;
|
|
4136
|
+
return { rows, headers: repeat ? all.slice(0, frame.headers) : [] };
|
|
4137
|
+
});
|
|
4138
|
+
frame.rows.forEach((row, r) => {
|
|
4139
|
+
const ks = parts.flatMap((part, k) => (part.rows.includes(r) ? [k] : []));
|
|
4140
|
+
const firstPart = ks[0] ?? 0;
|
|
4141
|
+
for (const cell of row.cells)
|
|
4142
|
+
for (const item of cell.items) {
|
|
4143
|
+
if ("frame" in item) {
|
|
4144
|
+
for (let u = item.frame.first; u < item.frame.end; u++)
|
|
4145
|
+
partOf.set(u, [firstPart]);
|
|
4146
|
+
continue;
|
|
4147
|
+
}
|
|
4148
|
+
const u = item.unit;
|
|
4149
|
+
const top = t.tops.get(u);
|
|
4150
|
+
if (ks.length < 2 || top === null || top === undefined) {
|
|
4151
|
+
partOf.set(u, [firstPart]);
|
|
4152
|
+
continue;
|
|
4153
|
+
}
|
|
4154
|
+
// Each line on the page its bottom fits; consecutive lines on one page are a fragment.
|
|
4155
|
+
const { starts, bottoms } = lines(blocks[u]);
|
|
4156
|
+
const runs = [];
|
|
4157
|
+
const at = [];
|
|
4158
|
+
bottoms.forEach((b, i) => {
|
|
4159
|
+
const y = top + b;
|
|
4160
|
+
const k = ks.find((part) => y <= bounds[part][1] + 0.5) ??
|
|
4161
|
+
ks.at(-1);
|
|
4162
|
+
if (runs.at(-1) !== k) {
|
|
4163
|
+
if (runs.length)
|
|
4164
|
+
at.push(starts[i]);
|
|
4165
|
+
runs.push(k);
|
|
4166
|
+
}
|
|
4167
|
+
});
|
|
4168
|
+
partOf.set(u, runs.length ? runs : [firstPart]);
|
|
4169
|
+
if (at.length)
|
|
4170
|
+
splits.set(u, at);
|
|
4171
|
+
}
|
|
4172
|
+
});
|
|
4173
|
+
return { parts, partOf, splits };
|
|
4174
|
+
}
|
|
1613
4175
|
/** Reads a block's height (in layout px) and vertical margins from the DOM. */
|
|
1614
4176
|
function measureBox(desc, scale) {
|
|
1615
4177
|
let height = 0;
|
|
@@ -1633,64 +4195,112 @@ function measureBox(desc, scale) {
|
|
|
1633
4195
|
/**
|
|
1634
4196
|
* What the flow needs of a block: its measurement, its lines (on demand), Word's spacing before
|
|
1635
4197
|
* and after (next to its neighbours), keep with next, keep lines together (not for a block
|
|
1636
|
-
* taller than a page, or one with a
|
|
1637
|
-
* and a page break before the next block ending this one's page.
|
|
4198
|
+
* taller than a page, or one with a break in it), page and column breaks ending their line's
|
|
4199
|
+
* page or column, and a page break before the next block ending this one's page.
|
|
1638
4200
|
*/
|
|
1639
|
-
function wordBox(
|
|
4201
|
+
function wordBox(words, i, desc, measure, lines, layout, atWidth, adds, noteOf) {
|
|
1640
4202
|
const pageHeight = contentHeight(layout.sheet.settings);
|
|
1641
|
-
const
|
|
1642
|
-
|
|
1643
|
-
const
|
|
1644
|
-
const
|
|
1645
|
-
const
|
|
1646
|
-
const
|
|
4203
|
+
const { section } = layout;
|
|
4204
|
+
// Without pages nothing is kept off the next one, and a page break ends nothing.
|
|
4205
|
+
const paged = layout.sheet.css !== UNPAGED_CSS;
|
|
4206
|
+
const next = words[i + 1] ? { word: words[i + 1] } : undefined;
|
|
4207
|
+
const { before, after } = spacing(words[i - 1], desc.word, next?.word, adds);
|
|
4208
|
+
const leavesWith = (attr) => desc.leaves.filter((leaf) => leaf.dom.nodeType !== Node.TEXT_NODE && leaf.dom.hasAttribute(attr));
|
|
4209
|
+
const pageBreaks = leavesWith(PAGE_BREAK_ATTR);
|
|
4210
|
+
const columnBreaks = leavesWith(WORD_COLUMN_BREAK_ATTR);
|
|
4211
|
+
const hasBreak = pageBreaks.length + columnBreaks.length > 0;
|
|
4212
|
+
const keep = desc.word.keepLines && !hasBreak;
|
|
4213
|
+
const kept = keep && measure.height <= pageHeight;
|
|
1647
4214
|
const bottoms = () => (kept ? [measure.height] : lines().bottoms);
|
|
4215
|
+
/** The block as it is in `column`, when the columns' widths differ. */
|
|
4216
|
+
const inColumn = (column) => atWidth(desc, section.columns.widths[column], keep);
|
|
4217
|
+
// The line holding a break, among the column's lines: the last starting at or before it.
|
|
4218
|
+
const linesOf = (leaves, column = 0) => {
|
|
4219
|
+
if (!leaves.length)
|
|
4220
|
+
return [];
|
|
4221
|
+
const { starts } = section.unequal ? inColumn(column).all() : lines();
|
|
4222
|
+
return leaves.map((leaf) => {
|
|
4223
|
+
let line = starts.length - 1;
|
|
4224
|
+
while (line > 0 && starts[line] > leaf.offset)
|
|
4225
|
+
line--;
|
|
4226
|
+
return line;
|
|
4227
|
+
});
|
|
4228
|
+
};
|
|
4229
|
+
const references = referencesIn(desc.node);
|
|
4230
|
+
const notes = references.flatMap((ref) => {
|
|
4231
|
+
const note = noteOf(ref.story);
|
|
4232
|
+
return note ? [{ note, offset: ref.offset - 1 }] : [];
|
|
4233
|
+
});
|
|
1648
4234
|
return {
|
|
4235
|
+
notes: notes.length
|
|
4236
|
+
? (column) => {
|
|
4237
|
+
if (kept)
|
|
4238
|
+
return notes.map(({ note }) => ({ line: 0, note }));
|
|
4239
|
+
const { starts } = section.unequal ? inColumn(column).all() : lines();
|
|
4240
|
+
return notes.map(({ note, offset }) => {
|
|
4241
|
+
let line = starts.length - 1;
|
|
4242
|
+
while (line > 0 && starts[line] > offset)
|
|
4243
|
+
line--;
|
|
4244
|
+
return { line, note };
|
|
4245
|
+
});
|
|
4246
|
+
}
|
|
4247
|
+
: undefined,
|
|
1649
4248
|
height: measure.height,
|
|
1650
4249
|
marginTop: before,
|
|
1651
4250
|
marginBottom: after,
|
|
1652
4251
|
keepWithNext: desc.word.keepNext,
|
|
1653
4252
|
pageHeight,
|
|
4253
|
+
section: section.flow,
|
|
4254
|
+
sectionMark: !!desc.node.attrs.section && desc.word.empty,
|
|
4255
|
+
inColumn: section.unequal ? inColumn : undefined,
|
|
1654
4256
|
lines: bottoms,
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
return line;
|
|
1663
|
-
});
|
|
1664
|
-
if (next?.word.pageBreakBefore || layout.breakAfter)
|
|
1665
|
-
breaks.push(bottoms().length - 1);
|
|
4257
|
+
columnBreaksAfter: (column) => linesOf(columnBreaks, column),
|
|
4258
|
+
breaksAfter: (column = 0) => {
|
|
4259
|
+
if (!paged)
|
|
4260
|
+
return [];
|
|
4261
|
+
const breaks = linesOf(pageBreaks, column);
|
|
4262
|
+
if (next?.word.pageBreakBefore)
|
|
4263
|
+
breaks.push((section.unequal ? inColumn(column).lines() : bottoms()).length - 1);
|
|
1666
4264
|
return breaks;
|
|
1667
4265
|
},
|
|
1668
4266
|
};
|
|
1669
4267
|
}
|
|
4268
|
+
/** The footnotes a table refers to, each on the break at or after its reference's line. */
|
|
4269
|
+
function tableNotes(frame, measure, blocks, lines, breaks, noteOf) {
|
|
4270
|
+
const t = measure.table;
|
|
4271
|
+
const found = [];
|
|
4272
|
+
for (let unit = frame.first; unit < frame.end; unit++)
|
|
4273
|
+
for (const ref of referencesIn(blocks[unit].node)) {
|
|
4274
|
+
const note = noteOf(ref.story);
|
|
4275
|
+
if (note && t.tops.get(unit) != null)
|
|
4276
|
+
found.push({ note, unit, offset: ref.offset - 1 });
|
|
4277
|
+
}
|
|
4278
|
+
if (!found.length)
|
|
4279
|
+
return undefined;
|
|
4280
|
+
return () => {
|
|
4281
|
+
const list = breaks();
|
|
4282
|
+
return found.map(({ note, unit, offset }) => {
|
|
4283
|
+
const { starts, bottoms } = lines(blocks[unit]);
|
|
4284
|
+
let k = starts.length - 1;
|
|
4285
|
+
while (k > 0 && starts[k] > offset)
|
|
4286
|
+
k--;
|
|
4287
|
+
const y = t.tops.get(unit) + bottoms[k];
|
|
4288
|
+
const line = list.findIndex((b) => b >= y - 0.5);
|
|
4289
|
+
return { line: line < 0 ? list.length - 1 : line, note };
|
|
4290
|
+
});
|
|
4291
|
+
};
|
|
4292
|
+
}
|
|
1670
4293
|
/**
|
|
1671
|
-
* Writes Word's space above each v3 block as
|
|
1672
|
-
*
|
|
1673
|
-
* and only on the first page or after an explicit break (a page the text flowed onto drops it).
|
|
1674
|
-
* Written only when it changes.
|
|
4294
|
+
* Writes Word's space above each v3 block, as the flow worked it out, as its top margin. Written
|
|
4295
|
+
* only when it changes.
|
|
1675
4296
|
*/
|
|
1676
|
-
function applyGaps(
|
|
1677
|
-
|
|
1678
|
-
const
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
gap = boxes[i - 1].marginBottom + box.marginTop;
|
|
1684
|
-
else {
|
|
1685
|
-
const prior = boxes[i - 1];
|
|
1686
|
-
const breaks = prior?.breaksAfter?.() ?? [];
|
|
1687
|
-
const forced = page === 0 || (!!prior && breaks.length > 0 && breaks.includes(prior.lines().length - 1));
|
|
1688
|
-
gap = forced ? box.marginTop : 0;
|
|
1689
|
-
}
|
|
1690
|
-
if (gaps.get(desc.dom) === gap)
|
|
1691
|
-
return;
|
|
1692
|
-
gaps.set(desc.dom, gap);
|
|
1693
|
-
desc.dom.style.marginTop = `${gap}px`;
|
|
4297
|
+
function applyGaps(firsts, spaces) {
|
|
4298
|
+
firsts.forEach((dom, i) => {
|
|
4299
|
+
const gap = spaces[i] ?? 0;
|
|
4300
|
+
if (gaps.get(dom) === gap)
|
|
4301
|
+
return;
|
|
4302
|
+
gaps.set(dom, gap);
|
|
4303
|
+
dom.style.marginTop = `${gap}px`;
|
|
1694
4304
|
});
|
|
1695
4305
|
}
|
|
1696
4306
|
/** The gap `applyGaps` last wrote on each block element (the style serializes it rounded). */
|
|
@@ -1743,6 +4353,9 @@ function measureLines(desc, scale) {
|
|
|
1743
4353
|
continue;
|
|
1744
4354
|
if (leaf.dom.nodeType !== Node.TEXT_NODE) {
|
|
1745
4355
|
const br = leaf.dom;
|
|
4356
|
+
// A raised number says nothing about where its line is.
|
|
4357
|
+
if (br.hasAttribute(NOTE_NUMBER_ATTR))
|
|
4358
|
+
continue;
|
|
1746
4359
|
items.push({ offset: leaf.offset, rect: () => br.getBoundingClientRect() });
|
|
1747
4360
|
continue;
|
|
1748
4361
|
}
|
|
@@ -1871,6 +4484,22 @@ function scrollRectIntoView(from, rect) {
|
|
|
1871
4484
|
if (move)
|
|
1872
4485
|
win.scrollBy(0, move);
|
|
1873
4486
|
}
|
|
4487
|
+
const SCROLL_OPTIONS = { capture: true, passive: true };
|
|
4488
|
+
/** Room kept above what is scrolled to for find, in px. */
|
|
4489
|
+
const REVEAL_ABOVE = 200;
|
|
4490
|
+
/** Word's keys for finding and going places. */
|
|
4491
|
+
const NAVIGATION_KEYS = {
|
|
4492
|
+
"Mod-f": "find",
|
|
4493
|
+
"Mod-h": "replace",
|
|
4494
|
+
"Mod-g": "goTo",
|
|
4495
|
+
F3: "next",
|
|
4496
|
+
"Shift-F3": "previous",
|
|
4497
|
+
"Mod-Shift-F5": "bookmarks",
|
|
4498
|
+
};
|
|
4499
|
+
/** Shift+Alt+N: from a note's reference to the note, and back. */
|
|
4500
|
+
const isNoteKey = (event) => event.altKey && event.shiftKey && !event.ctrlKey && !event.metaKey && event.code === "KeyN";
|
|
4501
|
+
/** Whether story `id` of `state`'s document exists (a number can outlive its note on screen). */
|
|
4502
|
+
const isNoteStory = (state, id) => !!wordContext(state)?.stories.has(id);
|
|
1874
4503
|
function before(node) {
|
|
1875
4504
|
const parent = node.parentNode;
|
|
1876
4505
|
return { node: parent, offset: Array.prototype.indexOf.call(parent.childNodes, node) };
|
|
@@ -1909,4 +4538,68 @@ export function keyName(event) {
|
|
|
1909
4538
|
name = `Mod-${name}`;
|
|
1910
4539
|
return name;
|
|
1911
4540
|
}
|
|
4541
|
+
/**
|
|
4542
|
+
* The text width of a document's (last) section in EMU (635 per twip; Word's Letter page and
|
|
4543
|
+
* margins where it does not say): the widest a picture is inserted or resized.
|
|
4544
|
+
* shortcut: the last section's, not the caret's section or table cell; use the caret's when
|
|
4545
|
+
* documents mix page sizes.
|
|
4546
|
+
*/
|
|
4547
|
+
export function textWidthEmu(state) {
|
|
4548
|
+
const section = wordContext(state)?.envelope.section;
|
|
4549
|
+
return (((section?.pageSize?.width ?? 12_240) -
|
|
4550
|
+
(section?.margins?.left ?? 1440) -
|
|
4551
|
+
(section?.margins?.right ?? 1440)) *
|
|
4552
|
+
635);
|
|
4553
|
+
}
|
|
4554
|
+
/** A file's image's natural size (CSS px) from a local object URL, before any upload. */
|
|
4555
|
+
export async function measureImageFile(file, doc) {
|
|
4556
|
+
if (typeof URL.createObjectURL !== "function")
|
|
4557
|
+
return null;
|
|
4558
|
+
const url = URL.createObjectURL(file);
|
|
4559
|
+
try {
|
|
4560
|
+
return await naturalSize(url, doc);
|
|
4561
|
+
}
|
|
4562
|
+
finally {
|
|
4563
|
+
URL.revokeObjectURL(url);
|
|
4564
|
+
}
|
|
4565
|
+
}
|
|
4566
|
+
/** An image's natural size (CSS px), or null when it does not load. */
|
|
4567
|
+
async function naturalSize(src, doc) {
|
|
4568
|
+
const img = doc.createElement("img");
|
|
4569
|
+
// Load events, not decode(): WebKit rejects decode() for an image outside the document.
|
|
4570
|
+
const loaded = new Promise((resolve) => {
|
|
4571
|
+
img.onload = () => resolve(true);
|
|
4572
|
+
img.onerror = () => resolve(false);
|
|
4573
|
+
});
|
|
4574
|
+
img.src = src;
|
|
4575
|
+
if (!(await loaded))
|
|
4576
|
+
return null;
|
|
4577
|
+
return img.naturalWidth && img.naturalHeight
|
|
4578
|
+
? { width: img.naturalWidth, height: img.naturalHeight }
|
|
4579
|
+
: null;
|
|
4580
|
+
}
|
|
4581
|
+
/** Whether a block holds a floating picture (cached per node: nodes do not change). */
|
|
4582
|
+
const floats = new WeakMap();
|
|
4583
|
+
function holdsFloat(node) {
|
|
4584
|
+
let found = floats.get(node);
|
|
4585
|
+
if (found === undefined) {
|
|
4586
|
+
found = false;
|
|
4587
|
+
node.descendants((child) => {
|
|
4588
|
+
if (child.type.name === "picture" && child.attrs.float)
|
|
4589
|
+
found = true;
|
|
4590
|
+
return !found;
|
|
4591
|
+
});
|
|
4592
|
+
floats.set(node, found);
|
|
4593
|
+
}
|
|
4594
|
+
return found;
|
|
4595
|
+
}
|
|
4596
|
+
/** A change that only adds or removes the view's own marks (a resize handle, a control's frame). */
|
|
4597
|
+
function handleOnly(record) {
|
|
4598
|
+
const nodes = [...record.addedNodes, ...record.removedNodes];
|
|
4599
|
+
return (record.type === "childList" &&
|
|
4600
|
+
nodes.length > 0 &&
|
|
4601
|
+
nodes.every((n) => n.nodeType === 1 &&
|
|
4602
|
+
(n.hasAttribute("data-foli-resize") ||
|
|
4603
|
+
n.hasAttribute(CONTROL_UI_ATTR))));
|
|
4604
|
+
}
|
|
1912
4605
|
//# sourceMappingURL=view.js.map
|