@folijs/view 0.5.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +194 -0
- package/README.md +1 -1
- package/dist/clipboard.d.ts +1 -49
- package/dist/clipboard.d.ts.map +1 -1
- package/dist/clipboard.js +65 -13
- package/dist/clipboard.js.map +1 -1
- package/dist/extension.d.ts +90 -0
- package/dist/extension.d.ts.map +1 -0
- package/dist/extension.js +152 -0
- package/dist/extension.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/layout/flow.d.ts +1 -109
- package/dist/layout/flow.d.ts.map +1 -1
- package/dist/layout/flow.js +808 -103
- package/dist/layout/flow.js.map +1 -1
- package/dist/print.d.ts +6 -0
- package/dist/print.d.ts.map +1 -0
- package/dist/print.js +35 -0
- package/dist/print.js.map +1 -0
- package/dist/render.d.ts +1 -24
- package/dist/render.d.ts.map +1 -1
- package/dist/render.js +4 -1
- package/dist/render.js.map +1 -1
- package/dist/view.d.ts +244 -64
- package/dist/view.d.ts.map +1 -1
- package/dist/view.js +1945 -215
- package/dist/view.js.map +1 -1
- package/dist/word/blocks.d.ts +0 -146
- package/dist/word/blocks.d.ts.map +1 -1
- package/dist/word/blocks.js +294 -59
- package/dist/word/blocks.js.map +1 -1
- package/dist/word/columns.d.ts +2 -0
- package/dist/word/columns.d.ts.map +1 -0
- package/dist/word/columns.js +63 -0
- package/dist/word/columns.js.map +1 -0
- package/dist/word/controls.d.ts +2 -0
- package/dist/word/controls.d.ts.map +1 -0
- package/dist/word/controls.js +416 -0
- package/dist/word/controls.js.map +1 -0
- package/dist/word/edit.d.ts +1 -71
- package/dist/word/edit.d.ts.map +1 -1
- package/dist/word/edit.js +338 -29
- package/dist/word/edit.js.map +1 -1
- package/dist/word/matches.d.ts +2 -0
- package/dist/word/matches.d.ts.map +1 -0
- package/dist/word/matches.js +102 -0
- package/dist/word/matches.js.map +1 -0
- package/dist/word/notes.d.ts +2 -0
- package/dist/word/notes.d.ts.map +1 -0
- package/dist/word/notes.js +403 -0
- package/dist/word/notes.js.map +1 -0
- package/dist/word/pages.d.ts +30 -20
- package/dist/word/pages.d.ts.map +1 -1
- package/dist/word/pages.js +421 -229
- package/dist/word/pages.js.map +1 -1
- package/dist/word/regions.d.ts +2 -0
- package/dist/word/regions.d.ts.map +1 -0
- package/dist/word/regions.js +388 -0
- package/dist/word/regions.js.map +1 -0
- package/dist/word/table.d.ts +1 -78
- package/dist/word/table.d.ts.map +1 -1
- package/dist/word/table.js +13 -3
- package/dist/word/table.js.map +1 -1
- package/package.json +6 -3
- package/src/clipboard.ts +93 -20
- package/src/extension.ts +267 -0
- package/src/index.ts +10 -0
- package/src/layout/flow.ts +997 -116
- package/src/print.ts +55 -0
- package/src/render.ts +6 -1
- package/src/view.ts +2178 -245
- package/src/word/blocks.ts +339 -62
- package/src/word/columns.ts +81 -0
- package/src/word/controls.ts +457 -0
- package/src/word/edit.ts +381 -31
- package/src/word/matches.ts +104 -0
- package/src/word/notes.ts +464 -0
- package/src/word/pages.ts +518 -221
- package/src/word/regions.ts +488 -0
- package/src/word/table.ts +33 -8
package/src/view.ts
CHANGED
|
@@ -4,28 +4,46 @@ import {
|
|
|
4
4
|
autolinkHref,
|
|
5
5
|
CellSelection,
|
|
6
6
|
type Command,
|
|
7
|
+
type ControlRange,
|
|
7
8
|
cellsAsTable,
|
|
8
9
|
closeHistory,
|
|
10
|
+
controlAt,
|
|
11
|
+
controlProperties,
|
|
9
12
|
type DocumentSettings,
|
|
13
|
+
type DocumentTarget,
|
|
10
14
|
deleteBackward,
|
|
11
15
|
deleteForward,
|
|
12
16
|
deleteSelection,
|
|
13
|
-
deleteSelectionKeepingTables,
|
|
14
17
|
type Editor,
|
|
15
18
|
type EditorState,
|
|
19
|
+
ensureStory,
|
|
16
20
|
extendCellSelection,
|
|
17
|
-
|
|
18
|
-
|
|
21
|
+
type Field,
|
|
22
|
+
type FieldLayout,
|
|
23
|
+
type FieldsReport,
|
|
24
|
+
type FindMatch,
|
|
25
|
+
type FoundMatches,
|
|
26
|
+
fieldCodesShown,
|
|
27
|
+
fieldsIn,
|
|
19
28
|
goToCellVertically,
|
|
29
|
+
insertControlText,
|
|
20
30
|
insertHardBreak,
|
|
21
31
|
insertLink,
|
|
32
|
+
insertNote,
|
|
22
33
|
insertPicture,
|
|
23
34
|
insertText,
|
|
24
35
|
isSafeHref,
|
|
25
|
-
keepTablesApart,
|
|
26
36
|
type Node as ModelNode,
|
|
27
37
|
marksAt,
|
|
38
|
+
type NavigationRequest,
|
|
28
39
|
NodeSelection,
|
|
40
|
+
type NoteNumber,
|
|
41
|
+
noteAtSelection,
|
|
42
|
+
noteNumbers,
|
|
43
|
+
noteProperties,
|
|
44
|
+
noteTexts,
|
|
45
|
+
type OpenStory,
|
|
46
|
+
pageVariant,
|
|
29
47
|
parseContentV2,
|
|
30
48
|
pasteCells,
|
|
31
49
|
type ResourceJSON,
|
|
@@ -34,37 +52,97 @@ import {
|
|
|
34
52
|
type SectionJSON,
|
|
35
53
|
Selection,
|
|
36
54
|
Slice,
|
|
55
|
+
type StorySide,
|
|
56
|
+
type StoryView,
|
|
37
57
|
sectionSettings,
|
|
38
58
|
setColumnWidth,
|
|
39
|
-
setComments,
|
|
40
59
|
setLink,
|
|
41
60
|
setPictureSize,
|
|
42
61
|
splitBlock,
|
|
62
|
+
storyOfSection,
|
|
43
63
|
TextSelection,
|
|
44
64
|
type Transaction,
|
|
45
65
|
TransformError,
|
|
66
|
+
toggleFieldCodes,
|
|
46
67
|
toggleMark,
|
|
47
68
|
trackState,
|
|
48
|
-
|
|
69
|
+
type UpdateFieldsOptions,
|
|
49
70
|
undo,
|
|
71
|
+
updateFields,
|
|
72
|
+
type WordSettingsJSON,
|
|
73
|
+
} from "@folijs/core";
|
|
74
|
+
import {
|
|
75
|
+
caretStop,
|
|
76
|
+
controlSpot,
|
|
77
|
+
deleteSelectionKeepingTables,
|
|
78
|
+
fitPaste,
|
|
79
|
+
fitPastedV2,
|
|
80
|
+
keepTablesApart,
|
|
81
|
+
referencesIn,
|
|
82
|
+
StoryStep,
|
|
83
|
+
sameSpot,
|
|
84
|
+
setComments,
|
|
85
|
+
typedMarks,
|
|
86
|
+
viewKeys,
|
|
50
87
|
type WordContext,
|
|
51
88
|
withEnvelope,
|
|
52
89
|
wordContext,
|
|
53
|
-
} from "@folijs/core";
|
|
90
|
+
} from "@folijs/core/internal";
|
|
54
91
|
import { docFromClipboard, FOLI_MIME, serializeRange } from "./clipboard.js";
|
|
92
|
+
import {
|
|
93
|
+
checkAttrs,
|
|
94
|
+
type Decoration,
|
|
95
|
+
type Drawn,
|
|
96
|
+
decorationsByBlock,
|
|
97
|
+
type PluginView,
|
|
98
|
+
reportError,
|
|
99
|
+
type ViewExtension,
|
|
100
|
+
type Views,
|
|
101
|
+
viewsOf,
|
|
102
|
+
} from "./extension.js";
|
|
55
103
|
import {
|
|
56
104
|
type BlockBox,
|
|
57
105
|
contentHeight,
|
|
58
106
|
DEFAULT_RULES,
|
|
107
|
+
type FlowNote,
|
|
108
|
+
type FlowPage,
|
|
59
109
|
type FlowResult,
|
|
60
110
|
type FlowRules,
|
|
111
|
+
type FlowSection,
|
|
112
|
+
type Fragment,
|
|
61
113
|
flowFrom,
|
|
114
|
+
notePieces,
|
|
115
|
+
type PageFacts,
|
|
62
116
|
PX_PER_MM,
|
|
117
|
+
pagesOf,
|
|
63
118
|
type Reuse,
|
|
119
|
+
spaceAfterText,
|
|
64
120
|
} from "./layout/flow.js";
|
|
65
|
-
import {
|
|
66
|
-
|
|
67
|
-
import {
|
|
121
|
+
import { printStyles, SHEET_ATTR } from "./print.js";
|
|
122
|
+
import { type BlockDesc, type LeafDesc, PAGE_BREAK_ATTR } from "./render.js";
|
|
123
|
+
import {
|
|
124
|
+
EMU_PER_PX,
|
|
125
|
+
imageSource,
|
|
126
|
+
NOTE_NUMBER_ATTR,
|
|
127
|
+
NOTE_REF_ATTR,
|
|
128
|
+
PICTURE_ATTR,
|
|
129
|
+
WORD_COLUMN_BREAK_ATTR,
|
|
130
|
+
} from "./word/blocks.js";
|
|
131
|
+
import {
|
|
132
|
+
BAND_CLASS,
|
|
133
|
+
bandElement,
|
|
134
|
+
COLUMN_CLASS,
|
|
135
|
+
type ColumnsPx,
|
|
136
|
+
columnsKey,
|
|
137
|
+
columnsPx,
|
|
138
|
+
} from "./word/columns.js";
|
|
139
|
+
import {
|
|
140
|
+
type Box,
|
|
141
|
+
boxOf,
|
|
142
|
+
CONTROL_STYLES,
|
|
143
|
+
CONTROL_UI_ATTR,
|
|
144
|
+
ControlChrome,
|
|
145
|
+
} from "./word/controls.js";
|
|
68
146
|
import {
|
|
69
147
|
FLOAT_ANCHORS,
|
|
70
148
|
spacing,
|
|
@@ -72,7 +150,10 @@ import {
|
|
|
72
150
|
type WordInfo,
|
|
73
151
|
WordRenderer,
|
|
74
152
|
} from "./word/edit.js";
|
|
153
|
+
import { MATCH_STYLES, MatchMarks, rangesInText } from "./word/matches.js";
|
|
154
|
+
import { NOTE_ATTR, type NoteGroup, PageNotes } from "./word/notes.js";
|
|
75
155
|
import { measureLineRatio } from "./word/pages.js";
|
|
156
|
+
import { PageRegions, REGION_CONTENT_CLASS } from "./word/regions.js";
|
|
76
157
|
import {
|
|
77
158
|
collect,
|
|
78
159
|
type FlowItem,
|
|
@@ -92,6 +173,7 @@ const TABLE_WORD: WordInfo = {
|
|
|
92
173
|
pageBreakBefore: false,
|
|
93
174
|
style: null,
|
|
94
175
|
contextual: false,
|
|
176
|
+
empty: false,
|
|
95
177
|
};
|
|
96
178
|
|
|
97
179
|
/** Where a table's fragment is: the rows it shows, the header rows drawn again above them. */
|
|
@@ -108,7 +190,10 @@ interface FrameState {
|
|
|
108
190
|
key: string;
|
|
109
191
|
}
|
|
110
192
|
|
|
111
|
-
/**
|
|
193
|
+
/**
|
|
194
|
+
* A table's measurement, in layout px from the table's top (drawn whole).
|
|
195
|
+
* @internal
|
|
196
|
+
*/
|
|
112
197
|
export interface TableMeasure {
|
|
113
198
|
rows: { top: number; bottom: number }[];
|
|
114
199
|
/** The top of each of its units (by index into the units), null for one not shown (covered). */
|
|
@@ -154,16 +239,25 @@ export interface EditorViewOptions {
|
|
|
154
239
|
upload?:
|
|
155
240
|
| ((file: File) => Promise<string | { src: string; alt?: string; decorative?: boolean }>)
|
|
156
241
|
| null;
|
|
242
|
+
/**
|
|
243
|
+
* `false`: the content in one flow, without pages, headers or print rules (a story being edited
|
|
244
|
+
* on its page, ADR-0007). Set when the view is made. Default true.
|
|
245
|
+
*/
|
|
246
|
+
paged?: boolean;
|
|
247
|
+
/** What a note's own mark shows, for the view of a note being edited. */
|
|
248
|
+
noteMark?: () => string;
|
|
157
249
|
}
|
|
158
250
|
|
|
159
251
|
const PLACEHOLDER_ATTR = "data-foli-placeholder";
|
|
160
252
|
/** On the span of a selected picture (it holds the resize handle). */
|
|
161
253
|
const PICTURE_SELECTED_ATTR = "data-foli-picture-selected";
|
|
254
|
+
/** On what shows a field the selection is in: Word shades it. */
|
|
255
|
+
const FIELD_SELECTED_ATTR = "data-foli-field-selected";
|
|
162
256
|
/** The smallest a picture gets by dragging its handle, in px. */
|
|
163
257
|
const MIN_PICTURE = 8;
|
|
164
258
|
// Generated content is not document text: no caret stops inside it, a zero-height float keeps
|
|
165
259
|
// the caret at the line start, and the empty alt text keeps screen readers on aria-placeholder.
|
|
166
|
-
const STYLES =
|
|
260
|
+
const STYLES = `[${FIELD_SELECTED_ATTR}]{background-color:rgba(0,0,0,.14)}@media print{[${FIELD_SELECTED_ATTR}]{background-color:transparent}}.foli-in-story>.foli-page>:not(.foli-region){opacity:.45}.foli-story-mount{pointer-events:auto;outline:1px dashed GrayText;outline-offset:2px}.foli-story-mount>[contenteditable=true]:focus{outline:none}@media print{.foli-in-story>.foli-page>:not(.foli-region){opacity:1}.foli-story-mount{outline:none}}.${CELL_CLASS}{box-shadow:inset 0 0 0 9999px rgba(0,120,215,.22)}[${CELLS_ATTR}] ::selection{background:transparent}[data-foli-no-alt]{outline:2px dashed #b45309;outline-offset:-2px}@media print{[data-foli-no-alt]{outline:none}}[${PICTURE_SELECTED_ATTR}]{position:relative;outline:2px solid Highlight}[${PICTURE_SELECTED_ATTR}] [data-foli-resize]{position:absolute;right:-5px;bottom:-5px;width:10px;height:10px;box-sizing:border-box;border:1px solid Canvas;background:Highlight;cursor:nwse-resize;forced-color-adjust:none}@media print{[${PICTURE_SELECTED_ATTR}]{outline:none}[${PICTURE_SELECTED_ATTR}] [data-foli-resize]{display:none}}[${PLACEHOLDER_ATTR}]::before{content:attr(${PLACEHOLDER_ATTR});content:attr(${PLACEHOLDER_ATTR}) / "";float:inline-start;height:0;pointer-events:none;color:GrayText}${CONTROL_STYLES}${MATCH_STYLES}`;
|
|
167
261
|
|
|
168
262
|
/**
|
|
169
263
|
* Adds the view's stylesheet once per document or shadow root, when a placeholder is first shown
|
|
@@ -188,34 +282,20 @@ const VIEW_ATTR = "data-foli-view";
|
|
|
188
282
|
let viewCount = 0;
|
|
189
283
|
|
|
190
284
|
/**
|
|
191
|
-
* Print rules for the page settings of the view whose host has `VIEW_ATTR` = `id
|
|
192
|
-
*
|
|
193
|
-
* margins (the page's padding holds them). A page is exactly as tall as a sheet (the flow keeps content inside it; the exact height absorbs its
|
|
194
|
-
* half-pixel slack), with no gap after it. Content taller than a page (a line taller than a
|
|
195
|
-
* page) is not cut: it prints over the next sheet.
|
|
285
|
+
* Print rules for the page settings of the view whose host has `VIEW_ATTR` = `id` (`print.ts`,
|
|
286
|
+
* shared with the read-only renderer and so with `@folijs/pdf`).
|
|
196
287
|
* shortcut: `@page` is per document: with several editors of different page sizes on one web page, the last one's sheet size wins (each keeps its own page rules); print one editor per document until that is needed.
|
|
197
288
|
*/
|
|
198
|
-
function
|
|
199
|
-
const { width, height }
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
:
|
|
207
|
-
|
|
208
|
-
const name = `foli-${id}-${index}`;
|
|
209
|
-
return (
|
|
210
|
-
`@page ${name}{size:${size.width}mm ${size.height}mm;margin:0}` +
|
|
211
|
-
`${pages}[${SHEET_ATTR}="${index}"]{page:${name};height:${size.height}mm!important}`
|
|
212
|
-
);
|
|
213
|
-
})
|
|
214
|
-
.join("");
|
|
215
|
-
return (
|
|
216
|
-
`@media print{@page{size:${width}mm ${height}mm;margin:0}` +
|
|
217
|
-
`${pages}{height:${height}mm!important;margin-block:0!important;` +
|
|
218
|
-
`break-after:page;break-inside:avoid}${pages}:last-child{break-after:auto}${named}}`
|
|
289
|
+
function viewPrintStyles(settings: DocumentSettings, sheets: readonly Sheet[], id: string): string {
|
|
290
|
+
const mm = ({ width, height }: { width: number; height: number }) => ({
|
|
291
|
+
width: `${width}mm`,
|
|
292
|
+
height: `${height}mm`,
|
|
293
|
+
});
|
|
294
|
+
return printStyles(
|
|
295
|
+
`[${VIEW_ATTR}="${id}"]>.foli-page`,
|
|
296
|
+
mm(settings.pageSize),
|
|
297
|
+
sheets.map(({ settings: { pageSize }, index }) => ({ ...mm(pageSize), index })),
|
|
298
|
+
id,
|
|
219
299
|
);
|
|
220
300
|
}
|
|
221
301
|
|
|
@@ -226,8 +306,8 @@ function hiddenIn(node: Node, stop: Node): boolean {
|
|
|
226
306
|
return false;
|
|
227
307
|
}
|
|
228
308
|
|
|
229
|
-
/** The
|
|
230
|
-
const
|
|
309
|
+
/** The fields whose results depend on where things fall on the pages. */
|
|
310
|
+
const PAGE_DEPENDENT = new Set(["PAGE", "NUMPAGES", "SECTIONPAGES", "PAGEREF"]);
|
|
231
311
|
|
|
232
312
|
/** A page setup: its settings (mm), the page style it gives, its index among the document's. */
|
|
233
313
|
interface Sheet {
|
|
@@ -249,73 +329,208 @@ function sheetOf(settings: DocumentSettings, index: number): Sheet {
|
|
|
249
329
|
|
|
250
330
|
/** The style each page element was last given (its `cssText` reads back normalized). */
|
|
251
331
|
const pageSheets = new WeakMap<HTMLElement, string>();
|
|
332
|
+
/** The margins a header or footer gave each page element, as last written. */
|
|
333
|
+
const pagePads = new WeakMap<HTMLElement, string>();
|
|
334
|
+
/** What a view without pages gives its one flow of content. */
|
|
335
|
+
const UNPAGED_CSS = "display: flow-root; position: relative;";
|
|
252
336
|
|
|
253
|
-
/** A
|
|
337
|
+
/** A section as laid out: its page setup, its columns, what the flow needs of it. */
|
|
338
|
+
interface SectionLayout {
|
|
339
|
+
readonly sheet: Sheet;
|
|
340
|
+
readonly columns: ColumnsPx;
|
|
341
|
+
/** Columns of different widths: a block is measured in the one it lands in. */
|
|
342
|
+
readonly unequal: boolean;
|
|
343
|
+
readonly flow: FlowSection;
|
|
344
|
+
/** What a block's place depends on, besides its own content. */
|
|
345
|
+
readonly key: string;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** A block's section, and whether it is the section's first block. */
|
|
254
349
|
interface BlockLayout {
|
|
255
350
|
readonly sheet: Sheet;
|
|
256
|
-
readonly
|
|
351
|
+
readonly section: SectionLayout;
|
|
352
|
+
readonly first: boolean;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** A page's header or footer as drawn. */
|
|
356
|
+
interface RegionElement {
|
|
357
|
+
element: HTMLElement;
|
|
358
|
+
/** What it shows: the same object, the same drawing. */
|
|
359
|
+
drawing: object;
|
|
360
|
+
section: number;
|
|
361
|
+
/** Its story. */
|
|
362
|
+
id: string;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** What a page shows of notes: at its feet, and after the text of each column. */
|
|
366
|
+
interface PageNoteElements {
|
|
367
|
+
foot: HTMLElement[];
|
|
368
|
+
flow: Map<string, HTMLElement[]>;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** A story being edited on its page. */
|
|
372
|
+
interface StoryMount extends OpenStory {
|
|
373
|
+
/** The page and the region it is open in. */
|
|
374
|
+
page: number;
|
|
375
|
+
region: RegionElement;
|
|
376
|
+
wrapper: HTMLElement;
|
|
377
|
+
view: EditorView;
|
|
378
|
+
/** Moved to another page by a new layout: the focus went with the DOM. */
|
|
379
|
+
moved: boolean;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** A header or footer being edited. */
|
|
383
|
+
type HeaderMount = StoryMount & { side: StorySide };
|
|
384
|
+
|
|
385
|
+
/** A fragment's place on its page. */
|
|
386
|
+
interface Slot {
|
|
387
|
+
band: number;
|
|
388
|
+
column: number;
|
|
389
|
+
/** The space above its band, when it opens one. */
|
|
390
|
+
lead: number | undefined;
|
|
391
|
+
/** A section's empty last paragraph: on the page, taking no room. */
|
|
392
|
+
mark: boolean;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
const slotOf = (fragment: Fragment): Slot => ({
|
|
396
|
+
band: fragment.band ?? 0,
|
|
397
|
+
column: fragment.column ?? 0,
|
|
398
|
+
lead: fragment.lead,
|
|
399
|
+
mark: !!fragment.mark,
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
/** The document's sections and the blocks of each. */
|
|
403
|
+
function sectionSpans(doc: ModelNode, last: SectionJSON) {
|
|
404
|
+
const spans: { setup: SectionJSON; from: number; to: number }[] = [];
|
|
405
|
+
let from = 0;
|
|
406
|
+
doc.forEach((node, _, i) => {
|
|
407
|
+
const own = node.attrs.section as SectionJSON | null | undefined;
|
|
408
|
+
if (!own) return;
|
|
409
|
+
spans.push({ setup: own, from, to: i + 1 });
|
|
410
|
+
from = i + 1;
|
|
411
|
+
});
|
|
412
|
+
if (from < doc.childCount || !spans.length) spans.push({ setup: last, from, to: doc.childCount });
|
|
413
|
+
return spans;
|
|
257
414
|
}
|
|
258
415
|
|
|
259
416
|
/**
|
|
260
417
|
* The section of each top-level block (the section a paragraph's `section` ends; the
|
|
261
|
-
* envelope's for the blocks after the last such paragraph)
|
|
262
|
-
*
|
|
263
|
-
*
|
|
264
|
-
* add a blank page), as `renderDocument` lays sections out.
|
|
418
|
+
* envelope's for the blocks after the last such paragraph), as `renderDocument` lays sections
|
|
419
|
+
* out. By position: two paragraphs may end sections with one object. `box` gives a page's text
|
|
420
|
+
* height: null for a view without pages.
|
|
265
421
|
*/
|
|
266
|
-
function sectionLayouts(
|
|
422
|
+
function sectionLayouts(
|
|
423
|
+
spans: ReturnType<typeof sectionSpans>,
|
|
424
|
+
box: ((section: number, page: FlowPage) => number) | null,
|
|
425
|
+
): BlockLayout[] {
|
|
267
426
|
const sheets = new Map<string, Sheet>();
|
|
268
427
|
const bySection = new Map<SectionJSON, Sheet>();
|
|
269
428
|
const sheet = (section: SectionJSON) => {
|
|
270
429
|
let found = bySection.get(section);
|
|
271
430
|
if (!found) {
|
|
272
431
|
const settings = sectionSettings(section);
|
|
273
|
-
const css = sheetOf(settings, 0).css;
|
|
274
|
-
found = sheets.get(css) ?? sheetOf(settings, sheets.size);
|
|
432
|
+
const css = box ? sheetOf(settings, 0).css : UNPAGED_CSS;
|
|
433
|
+
found = sheets.get(css) ?? { ...sheetOf(settings, sheets.size), css };
|
|
275
434
|
sheets.set(css, found);
|
|
276
435
|
bySection.set(section, found);
|
|
277
436
|
}
|
|
278
437
|
return found;
|
|
279
438
|
};
|
|
280
|
-
const
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
const
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
439
|
+
const sheetByFlow = new Map<FlowSection, Sheet>();
|
|
440
|
+
const out: BlockLayout[] = [];
|
|
441
|
+
spans.forEach(({ setup, from: start, to }, s) => {
|
|
442
|
+
// Indexes in document order: the first page setup is 0.
|
|
443
|
+
const own = sheet(setup);
|
|
444
|
+
const next = spans[s + 1]?.setup;
|
|
445
|
+
const columns = columnsPx(setup);
|
|
446
|
+
const count = columns.widths.length;
|
|
447
|
+
const balanced =
|
|
448
|
+
!!next && count > 1 && next.type === "continuous" && sheet(next).css === own.css;
|
|
449
|
+
const flow: FlowSection = {
|
|
450
|
+
index: s,
|
|
451
|
+
start: setup.type ?? "nextPage",
|
|
452
|
+
columns: count,
|
|
453
|
+
balanced,
|
|
454
|
+
pageStart: setup.pageNumbers?.start,
|
|
455
|
+
box: (page) => ({ height: box ? box(s, page) : Number.POSITIVE_INFINITY }),
|
|
456
|
+
samePage: (other) => sheetByFlow.get(other)?.css === own.css,
|
|
457
|
+
};
|
|
458
|
+
sheetByFlow.set(flow, own);
|
|
459
|
+
const section: SectionLayout = {
|
|
460
|
+
sheet: own,
|
|
461
|
+
columns,
|
|
462
|
+
unequal: new Set(columns.widths).size > 1,
|
|
463
|
+
flow,
|
|
464
|
+
key: `${own.css}|${flow.start}|${flow.pageStart ?? ""}|${balanced}|${columnsKey(columns)}`,
|
|
465
|
+
};
|
|
466
|
+
for (let i = start; i < to; i++) out[i] = { sheet: own, section, first: i === start };
|
|
295
467
|
});
|
|
468
|
+
return out;
|
|
296
469
|
}
|
|
297
470
|
|
|
298
471
|
/**
|
|
299
|
-
*
|
|
300
|
-
* page setup
|
|
472
|
+
* Where blocks are before a flow: where they were (`known`), moved where needed so that each
|
|
473
|
+
* page holds blocks of one page setup and each section has a band of its own: a block is
|
|
474
|
+
* measured in a column of its own section's width.
|
|
301
475
|
*/
|
|
302
|
-
function
|
|
476
|
+
function initialPlaces(
|
|
303
477
|
pages: readonly (readonly number[])[],
|
|
304
478
|
layout: readonly BlockLayout[],
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
let
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
479
|
+
known: readonly (readonly Slot[] | undefined)[],
|
|
480
|
+
): { pages: number[][]; slots: Slot[][] } {
|
|
481
|
+
let page = 0;
|
|
482
|
+
let band = 0;
|
|
483
|
+
let column = 0;
|
|
484
|
+
let section: SectionLayout | undefined;
|
|
485
|
+
const slots: Slot[][] = [];
|
|
486
|
+
const placed = pages.map((list, i) => {
|
|
487
|
+
const own = (layout[i] as BlockLayout).section;
|
|
488
|
+
const out: Slot[] = [];
|
|
489
|
+
slots[i] = out;
|
|
490
|
+
return list.map((p, f) => {
|
|
491
|
+
let target = Math.max(p, page);
|
|
492
|
+
if (target === page && section && section !== own) {
|
|
493
|
+
// Only the last page used so far has a setup: the next one is free.
|
|
494
|
+
if (section.sheet.css !== own.sheet.css) target++;
|
|
495
|
+
else {
|
|
496
|
+
band++;
|
|
497
|
+
column = 0;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
if (target > page) {
|
|
501
|
+
page = target;
|
|
502
|
+
band = 0;
|
|
503
|
+
column = 0;
|
|
504
|
+
}
|
|
505
|
+
section = own;
|
|
506
|
+
const was = known[i]?.[f];
|
|
507
|
+
column = Math.min(Math.max(column, was?.column ?? 0), own.columns.widths.length - 1);
|
|
508
|
+
out.push({
|
|
509
|
+
band,
|
|
510
|
+
column,
|
|
511
|
+
lead: was?.band === band ? was.lead : undefined,
|
|
512
|
+
mark: was?.mark ?? false,
|
|
513
|
+
});
|
|
316
514
|
return page;
|
|
317
|
-
})
|
|
318
|
-
);
|
|
515
|
+
});
|
|
516
|
+
});
|
|
517
|
+
return { pages: placed, slots };
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/** Makes `list` the children of `parent`, moving as little as possible; returns what it removed. */
|
|
521
|
+
function fillElement(parent: HTMLElement, list: readonly HTMLElement[], removed: WeakSet<Node>) {
|
|
522
|
+
let at = parent.firstChild;
|
|
523
|
+
for (const dom of list) {
|
|
524
|
+
if (dom === at) at = at.nextSibling;
|
|
525
|
+
else parent.insertBefore(dom, at);
|
|
526
|
+
}
|
|
527
|
+
// What is left after the last placed one: strays, and blocks of later pages.
|
|
528
|
+
while (at) {
|
|
529
|
+
const next: ChildNode | null = at.nextSibling;
|
|
530
|
+
at.remove();
|
|
531
|
+
removed.add(at);
|
|
532
|
+
at = next;
|
|
533
|
+
}
|
|
319
534
|
}
|
|
320
535
|
|
|
321
536
|
/**
|
|
@@ -344,6 +559,13 @@ export class EditorView {
|
|
|
344
559
|
private cellCaret: number | null = null;
|
|
345
560
|
/** The pages of each top-level item (a paragraph's fragments, a table's wrappers), by node. */
|
|
346
561
|
private itemPages = new Map<ModelNode, readonly number[]>();
|
|
562
|
+
/** Where on its page each of those is (band and column). */
|
|
563
|
+
private itemSlots = new Map<ModelNode, readonly Slot[]>();
|
|
564
|
+
/** Each page's band elements, as last placed. */
|
|
565
|
+
private bands = new WeakMap<
|
|
566
|
+
HTMLElement,
|
|
567
|
+
{ key: string; band: HTMLElement; columns: HTMLElement[] }[]
|
|
568
|
+
>();
|
|
347
569
|
/** Each table as last rendered, by node. */
|
|
348
570
|
private frames = new Map<ModelNode, FrameState>();
|
|
349
571
|
/** The table each wrapper element draws (part of). */
|
|
@@ -395,9 +617,12 @@ export class EditorView {
|
|
|
395
617
|
private readonly resizeObserver: ResizeObserver | null;
|
|
396
618
|
private readonly observed = new Set<Element>();
|
|
397
619
|
private relayoutPending = false;
|
|
398
|
-
|
|
620
|
+
/** A composition runs in this view. */
|
|
621
|
+
composing = false;
|
|
399
622
|
/** Set by Ctrl/Cmd+Shift+V for the paste event it triggers. */
|
|
400
623
|
private plainPaste = false;
|
|
624
|
+
/** How deep `renumberNotes` has rendered again. */
|
|
625
|
+
private renumbering = 0;
|
|
401
626
|
/** Blocks whose DOM the browser changed: the next render rebuilds them. */
|
|
402
627
|
private readonly dirty = new Set<BlockDesc>();
|
|
403
628
|
/** DOM mutations not yet read back (kept while a composition is running). */
|
|
@@ -437,10 +662,69 @@ export class EditorView {
|
|
|
437
662
|
private resource: EditorViewOptions["resource"];
|
|
438
663
|
/** How tracked changes show. */
|
|
439
664
|
private review: ReviewView = "markup";
|
|
665
|
+
/** Whether fields show their codes (`toggleFieldCodes`). */
|
|
666
|
+
private fieldCodes = false;
|
|
667
|
+
/** The elements shaded for the fields the selection is in. */
|
|
668
|
+
private shadedFields: Element[] = [];
|
|
440
669
|
/** Fonts' normal line height ratios, measured once per family (Word's single spacing). */
|
|
441
670
|
private readonly ratios = new Map<string, number>();
|
|
442
671
|
/** Web fonts loaded since the v3 blocks were drawn: the next render draws them again. */
|
|
443
672
|
private fontsChanged = false;
|
|
673
|
+
/** Whether content goes on pages (`EditorViewOptions.paged`). */
|
|
674
|
+
private readonly paged: boolean;
|
|
675
|
+
/** The headers and footers of the pages; none without pages. */
|
|
676
|
+
private readonly regions: PageRegions | null;
|
|
677
|
+
/** Each page as last flowed. */
|
|
678
|
+
private facts: PageFacts[] = [];
|
|
679
|
+
/** The header and footer element of each page, as last drawn. */
|
|
680
|
+
private pageRegions: { header?: RegionElement; footer?: RegionElement }[] = [];
|
|
681
|
+
/** Each page's margins, when a header or footer pushes them. */
|
|
682
|
+
private pageMargins: { top: string; bottom: string }[] = [];
|
|
683
|
+
/** What the header and footer heights were when last laid out (`PageRegions.key`). */
|
|
684
|
+
private regionsKey = "";
|
|
685
|
+
/** What `regionsKey` was computed from. */
|
|
686
|
+
private regionsFor: { stories: unknown; settings: unknown; sections: SectionJSON[] } | null =
|
|
687
|
+
null;
|
|
688
|
+
/** Footnotes and endnotes on the pages; none without pages. */
|
|
689
|
+
private readonly notes: PageNotes | null;
|
|
690
|
+
/** What each page shows of them. */
|
|
691
|
+
private pageNotes: PageNoteElements[] = [];
|
|
692
|
+
/** Their elements by what they show. */
|
|
693
|
+
private noteElements = new Map<string, HTMLElement>();
|
|
694
|
+
/** The page each note starts on, as last flowed: numbers can restart on each. */
|
|
695
|
+
private notePages = new Map<string, number>();
|
|
696
|
+
/** What the note references showed when last drawn. */
|
|
697
|
+
private shownNotes = "";
|
|
698
|
+
/** The layout and boxes of the last flow, to draw notes again from. */
|
|
699
|
+
private flowLayout: readonly BlockLayout[] = [];
|
|
700
|
+
private flowBoxes: readonly BlockBox[] = [];
|
|
701
|
+
/** What this view's note mark shows (`EditorViewOptions.noteMark`). */
|
|
702
|
+
private readonly noteMark: (() => string) | undefined;
|
|
703
|
+
/** Puts everything on its page again, as the last render left it. */
|
|
704
|
+
private placeAgain: (() => void) | null = null;
|
|
705
|
+
/** The story being edited on its page, if any (ADR-0007). */
|
|
706
|
+
private mount: StoryMount | null = null;
|
|
707
|
+
/** What find shows, and which tree this view draws of it (a mounted story's view: its own). */
|
|
708
|
+
private found: FoundMatches | null = null;
|
|
709
|
+
private matchStory: string | null = null;
|
|
710
|
+
private readonly matchMarks: MatchMarks;
|
|
711
|
+
/** The pages marked, as a key; the frame waiting to look again. */
|
|
712
|
+
private matchPages = "";
|
|
713
|
+
private matchFrame = 0;
|
|
714
|
+
/** The body's selection before the press of a double click in a page's margin. */
|
|
715
|
+
private pressSelection: Selection | null = null;
|
|
716
|
+
/** The listeners on the host, to remove them. */
|
|
717
|
+
private readonly listeners: [string, EventListener][] = [];
|
|
718
|
+
/** The frames, titles and pop-ups of content controls. */
|
|
719
|
+
private readonly controlChrome: ControlChrome;
|
|
720
|
+
/** The editor's view extensions' node and mark views, decorations and plugin views. */
|
|
721
|
+
private readonly views: Views;
|
|
722
|
+
private readonly decorators: ViewExtension["decorations"][];
|
|
723
|
+
private decorations: readonly Decoration[] = [];
|
|
724
|
+
private decorationKey = "";
|
|
725
|
+
private pluginViews: PluginView[] = [];
|
|
726
|
+
/** What node views drew and the view still shows (their `destroy` when it no longer does). */
|
|
727
|
+
private readonly drawn: Drawn[] = [];
|
|
444
728
|
|
|
445
729
|
constructor(
|
|
446
730
|
readonly host: HTMLElement,
|
|
@@ -448,6 +732,39 @@ export class EditorView {
|
|
|
448
732
|
options: EditorViewOptions = {},
|
|
449
733
|
) {
|
|
450
734
|
this.state = editor.state;
|
|
735
|
+
this.matchMarks = new MatchMarks(host.ownerDocument);
|
|
736
|
+
this.paged = options.paged !== false;
|
|
737
|
+
this.noteMark = options.noteMark;
|
|
738
|
+
const view = this;
|
|
739
|
+
this.controlChrome = new ControlChrome({
|
|
740
|
+
host,
|
|
741
|
+
editor,
|
|
742
|
+
state: () => view.state,
|
|
743
|
+
editable: () => view.editable && !view.mount,
|
|
744
|
+
pages: () => view.pages,
|
|
745
|
+
scale: () => view.scale(),
|
|
746
|
+
rects: (range) => view.controlRects(range),
|
|
747
|
+
contentRects: (range) => view.controlContentRects(range),
|
|
748
|
+
posFromDOM: (node, offset) => view.posFromDOM(node, offset),
|
|
749
|
+
focus: () => view.focus(),
|
|
750
|
+
injectStyles: () => injectStyles(host),
|
|
751
|
+
});
|
|
752
|
+
const storyOptions = {
|
|
753
|
+
get review() {
|
|
754
|
+
return view.review;
|
|
755
|
+
},
|
|
756
|
+
get fieldCodes() {
|
|
757
|
+
return view.fieldCodes;
|
|
758
|
+
},
|
|
759
|
+
lineRatio: (family: string) => this.lineRatio(family),
|
|
760
|
+
resource: (key: string, resource: ResourceJSON) => this.resource?.(key, resource),
|
|
761
|
+
measureIn: () => this.pages[0] ?? host,
|
|
762
|
+
scale: () => this.scale(),
|
|
763
|
+
};
|
|
764
|
+
this.regions = this.paged
|
|
765
|
+
? new PageRegions(host.ownerDocument, storyOptions, new WeakMap())
|
|
766
|
+
: null;
|
|
767
|
+
this.notes = this.paged ? new PageNotes(host.ownerDocument, storyOptions, new WeakMap()) : null;
|
|
451
768
|
host.setAttribute("role", "textbox");
|
|
452
769
|
host.setAttribute("aria-multiline", "true");
|
|
453
770
|
host.setAttribute(VIEW_ATTR, this.id);
|
|
@@ -458,37 +775,121 @@ export class EditorView {
|
|
|
458
775
|
host.style.overflowWrap = "break-word";
|
|
459
776
|
host.replaceChildren();
|
|
460
777
|
this.review = trackState(this.state)?.view ?? "markup";
|
|
778
|
+
this.fieldCodes = fieldCodesShown(this.state);
|
|
461
779
|
this.resizeObserver =
|
|
462
780
|
typeof ResizeObserver === "undefined" ? null : new ResizeObserver(this.onResize);
|
|
463
781
|
this.observer = new MutationObserver(this.onMutations);
|
|
464
782
|
this.observer.observe(host, { childList: true, characterData: true, subtree: true });
|
|
465
783
|
// The picture resolver before the first render: no image drawn from a URL the app refuses.
|
|
466
784
|
this.resource = options.resource ?? undefined;
|
|
785
|
+
const extensions = editor.extensions as readonly ViewExtension[];
|
|
786
|
+
this.views = viewsOf(extensions);
|
|
787
|
+
this.decorators = extensions.flatMap((e) => (e.decorations ? [e.decorations.bind(e)] : []));
|
|
788
|
+
this.decorate(this.state);
|
|
467
789
|
this.render();
|
|
468
790
|
this.setOptions(options);
|
|
469
791
|
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
792
|
+
this.listen("beforeinput", this.onBeforeInput);
|
|
793
|
+
this.listen("focus", this.onFocus);
|
|
794
|
+
this.listen("keydown", this.onKeyDown);
|
|
795
|
+
this.listen("input", this.onInput);
|
|
796
|
+
this.listen("compositionstart", this.onCompositionStart);
|
|
797
|
+
this.listen("compositionend", this.onCompositionEnd);
|
|
798
|
+
this.listen("blur", this.onBlur);
|
|
799
|
+
this.listen("mousedown", this.onPress);
|
|
800
|
+
this.listen("mousemove", this.onMouseMove);
|
|
801
|
+
this.listen("mouseleave", () => this.controlChrome.hover(null));
|
|
802
|
+
this.listen("copy", this.onCopy);
|
|
803
|
+
this.listen("cut", this.onCut);
|
|
804
|
+
this.listen("paste", this.onPaste);
|
|
805
|
+
this.listen("dragover", this.onDragOver);
|
|
806
|
+
this.listen("drop", this.onDrop);
|
|
807
|
+
this.listen("click", this.onClick);
|
|
808
|
+
this.listen("auxclick", this.onClick);
|
|
809
|
+
this.claimStories();
|
|
486
810
|
host.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
|
|
487
811
|
host.ownerDocument.fonts?.addEventListener("loadingdone", this.onFontsLoaded);
|
|
488
812
|
this.unsubscribe = editor.subscribe((state) => this.update(state));
|
|
813
|
+
for (const extension of extensions) {
|
|
814
|
+
try {
|
|
815
|
+
if (extension.view) this.pluginViews.push(extension.view(this));
|
|
816
|
+
} catch (error) {
|
|
817
|
+
reportError(error);
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
/** Calls `hook` for each plugin view, reporting what throws. */
|
|
823
|
+
private eachPluginView(hook: (view: PluginView) => void): void {
|
|
824
|
+
for (const view of this.pluginViews) {
|
|
825
|
+
try {
|
|
826
|
+
hook(view);
|
|
827
|
+
} catch (error) {
|
|
828
|
+
reportError(error);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/** Destroys node views' drawings the host no longer holds (all of them: `all`). */
|
|
834
|
+
private dropDrawn(all: boolean): void {
|
|
835
|
+
let kept = 0;
|
|
836
|
+
for (const drawn of this.drawn) {
|
|
837
|
+
if (!all && this.host.contains(drawn.box)) {
|
|
838
|
+
this.drawn[kept++] = drawn;
|
|
839
|
+
continue;
|
|
840
|
+
}
|
|
841
|
+
try {
|
|
842
|
+
drawn.view.destroy?.(drawn.root);
|
|
843
|
+
} catch (error) {
|
|
844
|
+
reportError(error);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
this.drawn.length = kept;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/** Asks the extensions for `state`'s decorations; whether they changed. */
|
|
851
|
+
private decorate(state: EditorState): boolean {
|
|
852
|
+
if (!this.decorators.length) return false;
|
|
853
|
+
// A failing extension, or a decoration with a refused attribute, is reported and left out.
|
|
854
|
+
const decorations = this.decorators.flatMap((decorate) => {
|
|
855
|
+
try {
|
|
856
|
+
return (decorate?.(state) ?? []).filter((decoration) => {
|
|
857
|
+
try {
|
|
858
|
+
checkAttrs(decoration.attrs);
|
|
859
|
+
return true;
|
|
860
|
+
} catch (error) {
|
|
861
|
+
reportError(error);
|
|
862
|
+
return false;
|
|
863
|
+
}
|
|
864
|
+
});
|
|
865
|
+
} catch (error) {
|
|
866
|
+
reportError(error);
|
|
867
|
+
return [];
|
|
868
|
+
}
|
|
869
|
+
});
|
|
870
|
+
const key = JSON.stringify(decorations);
|
|
871
|
+
if (key === this.decorationKey) return false;
|
|
872
|
+
this.decorations = decorations;
|
|
873
|
+
this.decorationKey = key;
|
|
874
|
+
return true;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/** Adds a listener for the body's events: a story open on a page has its own view. */
|
|
878
|
+
private listen<E extends Event>(type: string, handler: (event: E) => void): void {
|
|
879
|
+
const listener: EventListener = (event) => {
|
|
880
|
+
if (!this.mount?.wrapper.contains(event.target as Node | null)) handler(event as E);
|
|
881
|
+
};
|
|
882
|
+
this.host.addEventListener(type, listener);
|
|
883
|
+
this.listeners.push([type, listener]);
|
|
489
884
|
}
|
|
490
885
|
|
|
491
886
|
destroy(): void {
|
|
887
|
+
this.eachPluginView((view) => view.destroy?.());
|
|
888
|
+
this.pluginViews = [];
|
|
889
|
+
this.closeStory(false);
|
|
890
|
+
this.showFound(null);
|
|
891
|
+
this.controlChrome.destroy();
|
|
892
|
+
if (this.editor.storyView === this.stories) this.editor.storyView = null;
|
|
492
893
|
this.destroyed = true;
|
|
493
894
|
this.unsubscribe();
|
|
494
895
|
this.host.ownerDocument.fonts?.removeEventListener("loadingdone", this.onFontsLoaded);
|
|
@@ -496,24 +897,9 @@ export class EditorView {
|
|
|
496
897
|
this.resizeObserver?.disconnect();
|
|
497
898
|
for (const style of this.printStyles) style.remove();
|
|
498
899
|
const { host } = this;
|
|
499
|
-
host.removeEventListener(
|
|
500
|
-
host.removeEventListener("focus", this.onFocus);
|
|
501
|
-
host.removeEventListener("keydown", this.onKeyDown);
|
|
502
|
-
host.removeEventListener("input", this.onInput);
|
|
503
|
-
host.removeEventListener("compositionstart", this.onCompositionStart);
|
|
504
|
-
host.removeEventListener("compositionend", this.onCompositionEnd);
|
|
505
|
-
host.removeEventListener("blur", this.onBlur);
|
|
506
|
-
host.removeEventListener("mousedown", this.onMouseDown);
|
|
507
|
-
host.removeEventListener("mousemove", this.onMouseMove);
|
|
900
|
+
for (const [type, listener] of this.listeners) host.removeEventListener(type, listener);
|
|
508
901
|
this.endDrag();
|
|
509
|
-
host.removeEventListener("copy", this.onCopy);
|
|
510
|
-
host.removeEventListener("cut", this.onCut);
|
|
511
|
-
host.removeEventListener("paste", this.onPaste);
|
|
512
|
-
host.removeEventListener("dragover", this.onDragOver);
|
|
513
|
-
host.removeEventListener("drop", this.onDrop);
|
|
514
902
|
this.endResize();
|
|
515
|
-
host.removeEventListener("click", this.onClick);
|
|
516
|
-
host.removeEventListener("auxclick", this.onClick);
|
|
517
903
|
host.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
|
|
518
904
|
const owned = [
|
|
519
905
|
"contenteditable",
|
|
@@ -529,10 +915,15 @@ export class EditorView {
|
|
|
529
915
|
host.style.removeProperty("overflow-wrap");
|
|
530
916
|
if (!host.getAttribute("style")) host.removeAttribute("style");
|
|
531
917
|
host.replaceChildren();
|
|
918
|
+
this.dropDrawn(true);
|
|
532
919
|
}
|
|
533
920
|
|
|
534
921
|
/** Focuses the host, shows the model selection in it and scrolls it into view. */
|
|
535
922
|
focus(): void {
|
|
923
|
+
if (this.mount) {
|
|
924
|
+
this.mount.view.focus();
|
|
925
|
+
return;
|
|
926
|
+
}
|
|
536
927
|
this.host.focus();
|
|
537
928
|
this.writeSelection(true);
|
|
538
929
|
// The focus handler scrolls only when it writes the selection itself, and a DOM selection
|
|
@@ -547,12 +938,17 @@ export class EditorView {
|
|
|
547
938
|
// Finish a running composition while its text can still go into the model.
|
|
548
939
|
if (!options.editable && this.composing) this.onCompositionEnd();
|
|
549
940
|
this.editable = options.editable;
|
|
941
|
+
if (!this.editable) this.closeStory(false);
|
|
550
942
|
// A selected picture's handle only while it can be resized.
|
|
551
943
|
this.endResize();
|
|
552
944
|
this.showSelectedPicture();
|
|
553
945
|
}
|
|
554
946
|
if (options.placeholder !== undefined) this.placeholder = options.placeholder;
|
|
555
947
|
if (options.upload !== undefined) this.upload = options.upload ?? undefined;
|
|
948
|
+
this.mount?.view.setOptions({
|
|
949
|
+
...(options.upload !== undefined ? { upload: options.upload } : {}),
|
|
950
|
+
...(options.resource !== undefined ? { resource: options.resource } : {}),
|
|
951
|
+
});
|
|
556
952
|
// null clears the resolver (stored as none): the same as none is no change.
|
|
557
953
|
const resource = options.resource ?? undefined;
|
|
558
954
|
if (options.resource !== undefined && resource !== this.resource) {
|
|
@@ -568,8 +964,8 @@ export class EditorView {
|
|
|
568
964
|
}
|
|
569
965
|
|
|
570
966
|
// Read-only: no caret and no browser editing; the text stays selectable and copyable.
|
|
571
|
-
host.setAttribute("contenteditable", String(this.editable));
|
|
572
|
-
if (this.editable) host.removeAttribute("aria-readonly");
|
|
967
|
+
host.setAttribute("contenteditable", String(this.editable && !this.mount));
|
|
968
|
+
if (this.editable && !this.mount) host.removeAttribute("aria-readonly");
|
|
573
969
|
else host.setAttribute("aria-readonly", "true");
|
|
574
970
|
if (this.placeholder) host.setAttribute("aria-placeholder", this.placeholder);
|
|
575
971
|
else host.removeAttribute("aria-placeholder");
|
|
@@ -606,14 +1002,41 @@ export class EditorView {
|
|
|
606
1002
|
this.review = review;
|
|
607
1003
|
this.word = null;
|
|
608
1004
|
}
|
|
609
|
-
|
|
1005
|
+
// Codes shown or hidden: every block and story drawn again.
|
|
1006
|
+
const codes = fieldCodesShown(state);
|
|
1007
|
+
const codesChanged = codes !== this.fieldCodes;
|
|
1008
|
+
if (codesChanged) {
|
|
1009
|
+
this.fieldCodes = codes;
|
|
1010
|
+
this.word = null;
|
|
1011
|
+
}
|
|
1012
|
+
const before = wordContext(this.state)?.envelope;
|
|
1013
|
+
const envelope = wordContext(state)?.envelope;
|
|
1014
|
+
// The last section's setup and the settings live in the envelope: changing them leaves the
|
|
1015
|
+
// tree as it is. So does a story's change, which only its occurrences show.
|
|
1016
|
+
const docChanged =
|
|
1017
|
+
state.doc !== this.state.doc ||
|
|
1018
|
+
reviewChanged ||
|
|
1019
|
+
codesChanged ||
|
|
1020
|
+
envelope?.section !== before?.section ||
|
|
1021
|
+
envelope?.settings !== before?.settings;
|
|
1022
|
+
const storiesChanged = envelope?.stories !== before?.stories;
|
|
610
1023
|
const selectionChanged = !state.selection.eq(this.state.selection);
|
|
1024
|
+
// Another document: the story being edited closes.
|
|
1025
|
+
const lost = !!this.mount && wordContext(state)?.id !== wordContext(this.state)?.id;
|
|
1026
|
+
const previous = this.state;
|
|
611
1027
|
this.state = state;
|
|
612
|
-
|
|
1028
|
+
// Decorations that changed redraw their blocks (the others are reused).
|
|
1029
|
+
const decorated = this.decorate(state);
|
|
1030
|
+
if (docChanged || decorated || (storiesChanged && !this.redrawRegions())) this.render();
|
|
1031
|
+
if (lost) this.closeStory(true);
|
|
1032
|
+
// The open story has its own editor, which hears nothing of this.
|
|
1033
|
+
if (codesChanged) this.mount?.view.update(this.mount.view.editor.state);
|
|
613
1034
|
this.showSelectedNode();
|
|
614
|
-
|
|
1035
|
+
// Redrawn blocks may have held the DOM selection.
|
|
1036
|
+
this.writeSelection(docChanged || decorated);
|
|
615
1037
|
// shortcut: scrolls for every change while focused; once remote or plugin changes exist, scroll only for local input (a transaction flag).
|
|
616
1038
|
if (docChanged || selectionChanged) this.scrollToSelection();
|
|
1039
|
+
this.eachPluginView((view) => view.update?.(this, previous));
|
|
617
1040
|
}
|
|
618
1041
|
|
|
619
1042
|
/**
|
|
@@ -651,17 +1074,37 @@ export class EditorView {
|
|
|
651
1074
|
* Measurements are cached by node and the flow restarts at the first changed block (5.4).
|
|
652
1075
|
*/
|
|
653
1076
|
private render(): void {
|
|
1077
|
+
try {
|
|
1078
|
+
this.renderPages();
|
|
1079
|
+
if (this.drawn.length) this.dropDrawn(false);
|
|
1080
|
+
} catch (error) {
|
|
1081
|
+
// What it had changed is not input: read back, it would render and fail again, for ever.
|
|
1082
|
+
this.observer.takeRecords();
|
|
1083
|
+
this.pending = [];
|
|
1084
|
+
throw error;
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
private renderPages(): void {
|
|
654
1089
|
const { doc } = this.state;
|
|
655
1090
|
const ownerDocument = this.host.ownerDocument;
|
|
656
1091
|
// A new document (envelope) gets its renderer; nothing rendered before is reused then. An
|
|
657
1092
|
// editor's state always has one (`createEditor`).
|
|
658
1093
|
const context = wordContext(this.state) as WordContext;
|
|
659
1094
|
// Fonts loaded: a new renderer (new line heights), but not while a composition runs in a
|
|
660
|
-
// block it would redraw.
|
|
1095
|
+
// block it would redraw. What only stories or the settings changed leaves blocks as they are.
|
|
1096
|
+
const drawn = this.word?.context;
|
|
661
1097
|
const renewed =
|
|
662
|
-
|
|
1098
|
+
!drawn ||
|
|
1099
|
+
drawn.id !== context.id ||
|
|
1100
|
+
drawn.resolver !== context.resolver ||
|
|
1101
|
+
drawn.envelope.section !== context.envelope.section ||
|
|
1102
|
+
drawn.envelope.resources !== context.envelope.resources ||
|
|
1103
|
+
drawn.envelope.comments !== context.envelope.comments ||
|
|
1104
|
+
(this.fontsChanged && !this.composing);
|
|
663
1105
|
if (renewed) this.fontsChanged = false;
|
|
664
1106
|
let word = this.word as WordRenderer;
|
|
1107
|
+
if (!renewed) word.context = context;
|
|
665
1108
|
if (renewed) {
|
|
666
1109
|
// A document with pictures: the mark of one without alt text is the view's stylesheet's.
|
|
667
1110
|
if (context.envelope.resources) injectStyles(this.host);
|
|
@@ -672,17 +1115,51 @@ export class EditorView {
|
|
|
672
1115
|
false,
|
|
673
1116
|
this.review,
|
|
674
1117
|
imageSource(context.envelope.resources, this.resource ?? undefined),
|
|
1118
|
+
this.fieldCodes,
|
|
675
1119
|
);
|
|
1120
|
+
word.views = this.views;
|
|
1121
|
+
word.drawn = this.drawn;
|
|
676
1122
|
this.invalidateLayout();
|
|
677
1123
|
}
|
|
1124
|
+
const references = this.noteReferences();
|
|
1125
|
+
word.setNotes(noteTexts(references), this.noteMark?.());
|
|
678
1126
|
// The blocks the view renders (paragraphs in table cells among them) and the page flow's
|
|
679
1127
|
// items (top-level paragraphs and opaque blocks, and tables).
|
|
680
1128
|
const { units, items } = collect(doc, context.resolver);
|
|
681
|
-
word.
|
|
682
|
-
|
|
1129
|
+
word.decorations = this.decorations.length ? decorationsByBlock(units, this.decorations) : [];
|
|
1130
|
+
word.prepare(
|
|
1131
|
+
units.map((unit) => unit.node),
|
|
1132
|
+
(i) => {
|
|
1133
|
+
const unit = units[i] as Unit;
|
|
1134
|
+
const previous = units[i - 1];
|
|
1135
|
+
// Siblings: one ends where the other starts.
|
|
1136
|
+
return unit.cell && previous && previous.pos + previous.node.nodeSize === unit.pos
|
|
1137
|
+
? { node: previous.node, cell: unit.cell }
|
|
1138
|
+
: null;
|
|
1139
|
+
},
|
|
1140
|
+
);
|
|
1141
|
+
// A story's view has none of the body's sections: its one flow is not a page's.
|
|
1142
|
+
const spans = sectionSpans(doc, this.paged ? context.envelope.section : {});
|
|
1143
|
+
const { regions } = this;
|
|
1144
|
+
regions?.setDocument(
|
|
1145
|
+
context.envelope,
|
|
1146
|
+
spans.map((span) => span.setup),
|
|
1147
|
+
context.resolver,
|
|
1148
|
+
);
|
|
1149
|
+
const { notes } = this;
|
|
1150
|
+
notes?.setDocument(
|
|
1151
|
+
context.envelope,
|
|
1152
|
+
spans.map((span) => span.setup),
|
|
1153
|
+
context.resolver,
|
|
1154
|
+
references,
|
|
1155
|
+
);
|
|
1156
|
+
const layout = sectionLayouts(
|
|
1157
|
+
spans,
|
|
1158
|
+
regions && ((section, page) => regions.boxHeight(section, page)),
|
|
1159
|
+
);
|
|
683
1160
|
doc.forEach((node, _, i) => {
|
|
684
|
-
const {
|
|
685
|
-
const key = `${
|
|
1161
|
+
const { section, first } = layout[i] as BlockLayout;
|
|
1162
|
+
const key = `${section.key}${first ? "|first" : ""}`;
|
|
686
1163
|
const before = this.layoutKeys.get(node);
|
|
687
1164
|
if (before !== undefined && before !== key) this.stale.add(node);
|
|
688
1165
|
this.layoutKeys.set(node, key);
|
|
@@ -801,7 +1278,13 @@ export class EditorView {
|
|
|
801
1278
|
const desc = blocks[item.unit] as WordBlockDesc;
|
|
802
1279
|
return desc.fragments.map((_, f) => (last = Math.max(last, before?.[f] ?? last)));
|
|
803
1280
|
});
|
|
804
|
-
|
|
1281
|
+
const initial = initialPlaces(
|
|
1282
|
+
pages,
|
|
1283
|
+
layout,
|
|
1284
|
+
items.map((_, i) => this.itemSlots.get(doc.child(i))),
|
|
1285
|
+
);
|
|
1286
|
+
pages = initial.pages;
|
|
1287
|
+
let slots = initial.slots;
|
|
805
1288
|
const elementsOf = (item: FlowItem, i: number): readonly HTMLElement[] =>
|
|
806
1289
|
item.frame
|
|
807
1290
|
? (frames.get(doc.child(i)) as FrameState).wrappers
|
|
@@ -809,19 +1292,25 @@ export class EditorView {
|
|
|
809
1292
|
this.place(
|
|
810
1293
|
items.map((item, i) => elementsOf(item, i)),
|
|
811
1294
|
pages,
|
|
1295
|
+
slots,
|
|
812
1296
|
layout,
|
|
813
1297
|
);
|
|
814
1298
|
if (!this.composing) {
|
|
815
1299
|
// DOM reads only for blocks without a valid measurement (new, changed or stale ones).
|
|
816
1300
|
let scale: number | undefined;
|
|
817
1301
|
const layoutPx = () => {
|
|
818
|
-
scale ??=
|
|
1302
|
+
scale ??= this.scale();
|
|
819
1303
|
return scale;
|
|
820
1304
|
};
|
|
1305
|
+
// A header or footer of another height moves every page's text: no flow is reused.
|
|
1306
|
+
if (regions && this.regionsChanged(regions, spans)) this.flowed = null;
|
|
821
1307
|
if (dropLines)
|
|
822
1308
|
for (const desc of blocks) {
|
|
823
1309
|
const measure = this.measures.get(desc.node);
|
|
824
|
-
if (measure)
|
|
1310
|
+
if (measure) {
|
|
1311
|
+
delete measure.lines;
|
|
1312
|
+
delete measure.widths;
|
|
1313
|
+
}
|
|
825
1314
|
}
|
|
826
1315
|
const nodes = items.map((_, i) => doc.child(i));
|
|
827
1316
|
// A block's spacing depends on its neighbours' styles: reuse stops a block earlier.
|
|
@@ -840,6 +1329,38 @@ export class EditorView {
|
|
|
840
1329
|
found.lines ??= measureLines(desc, layoutPx());
|
|
841
1330
|
return found.lines;
|
|
842
1331
|
};
|
|
1332
|
+
/** A block's height and lines at a column's width, wherever it is now. */
|
|
1333
|
+
const atWidth = (desc: BlockDesc, width: number, kept: boolean): WidthMeasure => {
|
|
1334
|
+
const measure = measureOf(desc);
|
|
1335
|
+
const widths = measure.widths ?? new Map<number, WidthMeasure>();
|
|
1336
|
+
measure.widths = widths;
|
|
1337
|
+
const known = widths.get(width);
|
|
1338
|
+
if (known) return known;
|
|
1339
|
+
const read = <T>(measure: () => T): T => {
|
|
1340
|
+
for (const { style } of desc.fragments) {
|
|
1341
|
+
style.boxSizing = "border-box";
|
|
1342
|
+
style.width = `${width}px`;
|
|
1343
|
+
}
|
|
1344
|
+
const value = measure();
|
|
1345
|
+
for (const { style } of desc.fragments) {
|
|
1346
|
+
style.boxSizing = "";
|
|
1347
|
+
style.width = "";
|
|
1348
|
+
}
|
|
1349
|
+
return value;
|
|
1350
|
+
};
|
|
1351
|
+
const { height } = read(() => measureBox(desc, layoutPx()));
|
|
1352
|
+
let all: Lines | undefined;
|
|
1353
|
+
const found: WidthMeasure = {
|
|
1354
|
+
height,
|
|
1355
|
+
all: () => {
|
|
1356
|
+
all ??= read(() => measureLines(desc, layoutPx()));
|
|
1357
|
+
return all;
|
|
1358
|
+
},
|
|
1359
|
+
lines: () => (kept ? [height] : found.all().bottoms),
|
|
1360
|
+
};
|
|
1361
|
+
widths.set(width, found);
|
|
1362
|
+
return found;
|
|
1363
|
+
};
|
|
843
1364
|
const tableOf = (frame: Frame, i: number) => {
|
|
844
1365
|
let found = this.measures.get(frame.node);
|
|
845
1366
|
if (!found?.table || this.stale.delete(frame.node)) {
|
|
@@ -858,32 +1379,66 @@ export class EditorView {
|
|
|
858
1379
|
const words = items.map((item) =>
|
|
859
1380
|
item.frame ? TABLE_WORD : (blocks[item.unit] as WordBlockDesc).word,
|
|
860
1381
|
);
|
|
1382
|
+
const endnotes = notes?.endnotes();
|
|
861
1383
|
const boxes = items.map((item, i) => {
|
|
862
|
-
const
|
|
1384
|
+
const own = layout[i] as BlockLayout;
|
|
1385
|
+
const pageHeight = contentHeight(own.sheet.settings);
|
|
1386
|
+
const index = own.section.flow.index ?? 0;
|
|
1387
|
+
const noteOf = (story: string) => notes?.footnote(story, index) ?? null;
|
|
1388
|
+
// Endnotes follow the last block of their section, or of the document.
|
|
1389
|
+
const after =
|
|
1390
|
+
(layout[i + 1] as BlockLayout | undefined)?.section !== own.section
|
|
1391
|
+
? { endnotes: endnotes?.get(index) }
|
|
1392
|
+
: {};
|
|
863
1393
|
if (item.frame) {
|
|
864
1394
|
const frame = item.frame;
|
|
865
1395
|
const measure = tableOf(frame, i);
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
1396
|
+
const breaks = () => breaksOf(frame, measure, blocks, pageHeight, lines);
|
|
1397
|
+
// A page break before the next paragraph ends its page.
|
|
1398
|
+
return {
|
|
1399
|
+
...tableBox(frame, measure, pageHeight, !!words[i + 1]?.pageBreakBefore, breaks),
|
|
1400
|
+
section: own.section.flow,
|
|
1401
|
+
notes: tableNotes(frame, measure, blocks, lines, breaks, noteOf),
|
|
1402
|
+
...after,
|
|
1403
|
+
};
|
|
872
1404
|
}
|
|
873
1405
|
const desc = blocks[item.unit] as WordBlockDesc;
|
|
874
|
-
return
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
1406
|
+
return {
|
|
1407
|
+
...wordBox(
|
|
1408
|
+
words,
|
|
1409
|
+
i,
|
|
1410
|
+
desc,
|
|
1411
|
+
measureOf(desc),
|
|
1412
|
+
() => lines(desc),
|
|
1413
|
+
own,
|
|
1414
|
+
atWidth,
|
|
1415
|
+
context.resolver.addsParagraphSpacing,
|
|
1416
|
+
noteOf,
|
|
1417
|
+
),
|
|
1418
|
+
...after,
|
|
1419
|
+
};
|
|
882
1420
|
});
|
|
883
|
-
const
|
|
1421
|
+
const rules = {
|
|
1422
|
+
...WORD_RULES,
|
|
1423
|
+
addSpacing: context.resolver.addsParagraphSpacing,
|
|
1424
|
+
evenAndOddHeaders: context.envelope.settings?.evenAndOddHeaders === true,
|
|
1425
|
+
notes: notes?.flowRules(),
|
|
1426
|
+
};
|
|
1427
|
+
const flowHeight = contentHeight(this.editor.settings);
|
|
1428
|
+
let result = flowFrom(boxes, flowHeight, rules, reuse);
|
|
1429
|
+
let facts = pagesOf(boxes, result);
|
|
1430
|
+
// The page count is known once flowed; a header holding it can change what fits.
|
|
1431
|
+
for (let pass = 0; regions && pass < 2 && regions.settle(facts); pass++) {
|
|
1432
|
+
result = flowFrom(boxes, flowHeight, rules);
|
|
1433
|
+
facts = pagesOf(boxes, result);
|
|
1434
|
+
}
|
|
1435
|
+
this.facts = facts;
|
|
884
1436
|
this.flowed = { nodes, result };
|
|
1437
|
+
this.flowLayout = layout;
|
|
1438
|
+
this.flowBoxes = boxes;
|
|
885
1439
|
this.stale.clear();
|
|
886
1440
|
const flowed = result.fragments;
|
|
1441
|
+
slots = flowed.map((fragments) => fragments.map(slotOf));
|
|
887
1442
|
// Paragraphs: split where their fragments start. Tables: the rows each fragment shows,
|
|
888
1443
|
// and their blocks split where a row is.
|
|
889
1444
|
const splitsOf = new Map<number, number[]>();
|
|
@@ -893,10 +1448,24 @@ export class EditorView {
|
|
|
893
1448
|
if (item.unit !== undefined) {
|
|
894
1449
|
const desc = blocks[item.unit] as WordBlockDesc;
|
|
895
1450
|
const contentStart = ((units[item.unit] as Unit).pos as number) + 1;
|
|
1451
|
+
const { section } = layout[i] as BlockLayout;
|
|
1452
|
+
// A node view splits where its part's line ends (layout px).
|
|
1453
|
+
if (desc.parts) {
|
|
1454
|
+
const { bottoms } = lines(desc);
|
|
1455
|
+
splitsOf.set(
|
|
1456
|
+
item.unit,
|
|
1457
|
+
fragments.slice(1).map((fragment) => bottoms[fragment.fromLine - 1] as number),
|
|
1458
|
+
);
|
|
1459
|
+
return;
|
|
1460
|
+
}
|
|
896
1461
|
splitsOf.set(
|
|
897
1462
|
item.unit,
|
|
898
1463
|
fragments.slice(1).map((fragment) => {
|
|
899
|
-
|
|
1464
|
+
// Line numbers are those of the column the fragment is in.
|
|
1465
|
+
const measured = section.unequal
|
|
1466
|
+
? atWidth(desc, section.columns.widths[fragment.column ?? 0] as number, false).all()
|
|
1467
|
+
: lines(desc);
|
|
1468
|
+
const offset = measured.starts[fragment.fromLine] as number;
|
|
900
1469
|
// Never split a grapheme cluster across pages.
|
|
901
1470
|
return clusterBoundary(doc, contentStart + offset, false) - contentStart;
|
|
902
1471
|
}),
|
|
@@ -952,13 +1521,21 @@ export class EditorView {
|
|
|
952
1521
|
? ((frames.get(doc.child(i)) as FrameState).wrappers[0] as HTMLElement)
|
|
953
1522
|
: (blocks[item.unit] as WordBlockDesc).dom,
|
|
954
1523
|
);
|
|
955
|
-
applyGaps(firsts,
|
|
1524
|
+
applyGaps(firsts, result.gaps);
|
|
1525
|
+
this.drawRegions();
|
|
1526
|
+
this.drawNotes();
|
|
956
1527
|
this.place(
|
|
957
1528
|
items.map((item, i) => elementsOf(item, i)),
|
|
958
1529
|
pages,
|
|
1530
|
+
slots,
|
|
959
1531
|
layout,
|
|
960
1532
|
);
|
|
1533
|
+
this.afterPlace();
|
|
961
1534
|
}
|
|
1535
|
+
const placed = items.map((item, i) => elementsOf(item, i));
|
|
1536
|
+
const placedPages = pages;
|
|
1537
|
+
const placedSlots = slots;
|
|
1538
|
+
this.placeAgain = () => this.place(placed, placedPages, placedSlots, layout);
|
|
962
1539
|
// (Wrappers no longer drawn are not in a page: `place` removed them.)
|
|
963
1540
|
this.frames = frames;
|
|
964
1541
|
this.frameAt = items.map((item, i) => {
|
|
@@ -975,6 +1552,7 @@ export class EditorView {
|
|
|
975
1552
|
this.starts = units.map((unit) => unit.pos);
|
|
976
1553
|
this.indexOf = new Map(blocks.map((desc, i) => [desc, i]));
|
|
977
1554
|
this.itemPages = new Map(items.map((_, i) => [doc.child(i), pages[i] ?? []]));
|
|
1555
|
+
this.itemSlots = new Map(items.map((_, i) => [doc.child(i), slots[i] ?? []]));
|
|
978
1556
|
this.owner = new Map(
|
|
979
1557
|
blocks.flatMap((desc) => desc.fragments.map((fragment) => [fragment, desc] as const)),
|
|
980
1558
|
);
|
|
@@ -986,6 +1564,1047 @@ export class EditorView {
|
|
|
986
1564
|
// changed before this render: the touched blocks are read back at compositionend.
|
|
987
1565
|
const records = this.observer.takeRecords();
|
|
988
1566
|
if (this.composing) this.pending.push(...records);
|
|
1567
|
+
this.renumberNotes();
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
/** The note references shown, with their numbers as the last flow's pages make them. */
|
|
1571
|
+
private noteReferences(): NoteNumber[] {
|
|
1572
|
+
if (!this.paged) return [];
|
|
1573
|
+
const { doc } = this.state;
|
|
1574
|
+
const { envelope } = wordContext(this.state) as WordContext;
|
|
1575
|
+
const hideDeleted = this.review !== "markup";
|
|
1576
|
+
const all = noteNumbers(doc, envelope, {
|
|
1577
|
+
hideDeleted,
|
|
1578
|
+
pageOf: (_pos, story) => this.notePages.get(story),
|
|
1579
|
+
});
|
|
1580
|
+
this.shownNotes = JSON.stringify(all.map((n) => n.text));
|
|
1581
|
+
return hideDeleted ? all.filter((n) => !n.deleted) : all;
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
/**
|
|
1585
|
+
* Numbers that restart on each page depend on the flow just made: when they came out otherwise,
|
|
1586
|
+
* once more with them (their width can move a line), at most twice.
|
|
1587
|
+
*/
|
|
1588
|
+
private renumberNotes(): void {
|
|
1589
|
+
if (!this.notes || this.composing || this.renumbering > 1) return;
|
|
1590
|
+
const { envelope } = wordContext(this.state) as WordContext;
|
|
1591
|
+
const each = this.sections().some(
|
|
1592
|
+
(section) => noteProperties(envelope, "footnote", section).restart === "eachPage",
|
|
1593
|
+
);
|
|
1594
|
+
if (!each) return;
|
|
1595
|
+
const shown = this.shownNotes;
|
|
1596
|
+
this.noteReferences();
|
|
1597
|
+
if (this.shownNotes === shown) return;
|
|
1598
|
+
this.renumbering++;
|
|
1599
|
+
try {
|
|
1600
|
+
this.renderPages();
|
|
1601
|
+
} finally {
|
|
1602
|
+
this.renumbering = 0;
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
/** The section of each page's bands in the last flow, and each note's place on the pages. */
|
|
1607
|
+
private drawNotes(): void {
|
|
1608
|
+
const { notes, flowed, facts, mount } = this;
|
|
1609
|
+
if (!notes) return;
|
|
1610
|
+
const pieces = flowed ? notePieces(flowed.result) : [];
|
|
1611
|
+
const notePages = new Map<string, number>();
|
|
1612
|
+
for (const piece of pieces)
|
|
1613
|
+
if (!piece.fromLine && !notePages.has(piece.id)) notePages.set(piece.id, piece.page);
|
|
1614
|
+
this.notePages = notePages;
|
|
1615
|
+
const bandSections = new Map<string, number>();
|
|
1616
|
+
flowed?.result.fragments.forEach((fragments, i) => {
|
|
1617
|
+
const index = (this.flowLayout[i] as BlockLayout | undefined)?.section.flow.index ?? 0;
|
|
1618
|
+
for (const f of fragments) bandSections.set(`${f.page}|${f.band ?? 0}`, index);
|
|
1619
|
+
});
|
|
1620
|
+
const groups: NoteGroup[] = notes.groups(
|
|
1621
|
+
pieces,
|
|
1622
|
+
(page, band) =>
|
|
1623
|
+
bandSections.get(`${page}|${band}`) ??
|
|
1624
|
+
bandSections.get(`${page}|0`) ??
|
|
1625
|
+
facts[page]?.section ??
|
|
1626
|
+
0,
|
|
1627
|
+
);
|
|
1628
|
+
const foot = groups.filter((group) => !group.inFlow);
|
|
1629
|
+
const known = this.noteElements;
|
|
1630
|
+
const elements = new Map<string, HTMLElement>();
|
|
1631
|
+
const shown: PageNoteElements[] = [];
|
|
1632
|
+
const note = mount?.side === "note" ? mount : null;
|
|
1633
|
+
for (const group of groups) {
|
|
1634
|
+
const { settings } = this.sheetOfPage(group.page);
|
|
1635
|
+
const fact = facts[group.page];
|
|
1636
|
+
const bottom = fact?.sectionPages
|
|
1637
|
+
? (this.regions as PageRegions).margins(fact.section, fact).bottom
|
|
1638
|
+
: settings.margins.bottom * PX_PER_MM;
|
|
1639
|
+
const place = group.inFlow
|
|
1640
|
+
? null
|
|
1641
|
+
: notes.footPlace(
|
|
1642
|
+
{ left: settings.margins.left * PX_PER_MM, bottom },
|
|
1643
|
+
notes.stacked(group, foot),
|
|
1644
|
+
);
|
|
1645
|
+
// Footnotes beneath the text keep the space after the paragraph above them.
|
|
1646
|
+
const lead =
|
|
1647
|
+
group.inFlow && !group.pieces[0]?.end && flowed
|
|
1648
|
+
? spaceAfterText(this.flowBoxes, flowed.result, group.page, group.band, group.column)
|
|
1649
|
+
: 0;
|
|
1650
|
+
const key = `${group.page}|${group.band}|${group.column}|${group.inFlow}|${place?.left}|${place?.bottom}|${lead}|${notes.keyOf(group)}`;
|
|
1651
|
+
let element = known.get(key);
|
|
1652
|
+
if (!element) {
|
|
1653
|
+
element = notes.groupElement(
|
|
1654
|
+
group,
|
|
1655
|
+
place,
|
|
1656
|
+
(piece) =>
|
|
1657
|
+
piece.id === note?.id && !piece.fromLine
|
|
1658
|
+
? note.region.element
|
|
1659
|
+
: notes.pieceElement(piece, group),
|
|
1660
|
+
lead,
|
|
1661
|
+
);
|
|
1662
|
+
if (note && element.contains(note.wrapper)) note.moved = true;
|
|
1663
|
+
}
|
|
1664
|
+
elements.set(key, element);
|
|
1665
|
+
const page = shown[group.page] ?? { foot: [], flow: new Map<string, HTMLElement[]>() };
|
|
1666
|
+
shown[group.page] = page;
|
|
1667
|
+
if (!group.inFlow) page.foot.push(element);
|
|
1668
|
+
else {
|
|
1669
|
+
const slot = `${group.band}|${group.column}`;
|
|
1670
|
+
page.flow.set(slot, [...(page.flow.get(slot) ?? []), element]);
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
this.noteElements = elements;
|
|
1674
|
+
this.pageNotes = Array.from(
|
|
1675
|
+
{ length: shown.length },
|
|
1676
|
+
(_, p) => shown[p] ?? { foot: [], flow: new Map() },
|
|
1677
|
+
);
|
|
1678
|
+
if (!note) return;
|
|
1679
|
+
// Its reference went (undone, or hidden with the changes): the note closes.
|
|
1680
|
+
const page = notePages.get(note.id);
|
|
1681
|
+
if (page === undefined) queueMicrotask(() => this.closeStory(true));
|
|
1682
|
+
else note.page = page;
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
/** Layout px per px on screen: what a scaled ancestor (`transform`, `zoom`) multiplies by. */
|
|
1686
|
+
private scale(): number {
|
|
1687
|
+
const page = this.pages[0];
|
|
1688
|
+
if (!page) return 1;
|
|
1689
|
+
return this.paged
|
|
1690
|
+
? layoutScale(page, (this.sheets[0] as Sheet).settings)
|
|
1691
|
+
: page.getBoundingClientRect().width / page.offsetWidth || 1;
|
|
1692
|
+
}
|
|
1693
|
+
|
|
1694
|
+
/** Whether the headers' and footers' heights differ from when the pages were last flowed. */
|
|
1695
|
+
private regionsChanged(regions: PageRegions, spans: readonly { setup: SectionJSON }[]): boolean {
|
|
1696
|
+
const { stories, settings } = (wordContext(this.state) as WordContext).envelope;
|
|
1697
|
+
const sections = spans.map((span) => span.setup);
|
|
1698
|
+
const known = this.regionsFor;
|
|
1699
|
+
if (
|
|
1700
|
+
known &&
|
|
1701
|
+
known.stories === stories &&
|
|
1702
|
+
known.settings === settings &&
|
|
1703
|
+
known.sections.length === sections.length &&
|
|
1704
|
+
known.sections.every((section, i) => section === sections[i])
|
|
1705
|
+
)
|
|
1706
|
+
return false;
|
|
1707
|
+
this.regionsFor = { stories, settings, sections };
|
|
1708
|
+
const key = `${regions.key()}|${this.notes?.key() ?? ""}`;
|
|
1709
|
+
// Even and odd headers also decide the blank pages: the flow depends on them.
|
|
1710
|
+
const changed =
|
|
1711
|
+
key !== this.regionsKey ||
|
|
1712
|
+
(known?.settings !== settings &&
|
|
1713
|
+
(known?.settings as WordSettingsJSON | undefined)?.evenAndOddHeaders !==
|
|
1714
|
+
settings?.evenAndOddHeaders);
|
|
1715
|
+
this.regionsKey = key;
|
|
1716
|
+
return changed;
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
/**
|
|
1720
|
+
* Gives every page the header and footer the last flow says, redrawing those that changed. The
|
|
1721
|
+
* one holding the story being edited stays; it follows the story if its page no longer shows it.
|
|
1722
|
+
*/
|
|
1723
|
+
private drawRegions(): void {
|
|
1724
|
+
const { regions, facts } = this;
|
|
1725
|
+
// A note open for editing is `drawNotes`' to look after.
|
|
1726
|
+
const mount = this.mount?.side === "note" ? null : (this.mount as HeaderMount | null);
|
|
1727
|
+
if (!regions) return;
|
|
1728
|
+
const sides = ["header", "footer"] as const;
|
|
1729
|
+
const wanted = facts.map((page) =>
|
|
1730
|
+
// Word's blank page before an even or odd page section has neither.
|
|
1731
|
+
page.sectionPages
|
|
1732
|
+
? {
|
|
1733
|
+
header: regions.drawing(page.section, "header", page),
|
|
1734
|
+
footer: regions.drawing(page.section, "footer", page),
|
|
1735
|
+
}
|
|
1736
|
+
: { header: null, footer: null },
|
|
1737
|
+
);
|
|
1738
|
+
const shows = (p: number) => !!mount && wanted[p]?.[mount.side]?.id === mount.id;
|
|
1739
|
+
// Its page, while it shows it. Replaced there (the section unlinked, another variant turned
|
|
1740
|
+
// on) it does not follow the old story to another page: the page's own opens.
|
|
1741
|
+
const replaced = !!mount && facts[mount.page]?.section === mount.section;
|
|
1742
|
+
const home = !mount
|
|
1743
|
+
? -1
|
|
1744
|
+
: shows(mount.page)
|
|
1745
|
+
? mount.page
|
|
1746
|
+
: replaced
|
|
1747
|
+
? -1
|
|
1748
|
+
: wanted.findIndex((_, p) => shows(p));
|
|
1749
|
+
this.pageRegions = facts.map((page, p) => {
|
|
1750
|
+
const own: EditorView["pageRegions"][number] = {};
|
|
1751
|
+
for (const side of sides) {
|
|
1752
|
+
const drawing = wanted[p]?.[side];
|
|
1753
|
+
if (!drawing) continue;
|
|
1754
|
+
if (mount && p === home && side === mount.side) {
|
|
1755
|
+
own[side] = mount.region;
|
|
1756
|
+
if (mount.region.drawing !== drawing.content) {
|
|
1757
|
+
mount.region.drawing = drawing.content;
|
|
1758
|
+
const copy = drawing.content.content.cloneNode(true) as HTMLElement;
|
|
1759
|
+
copy.style.display = "none";
|
|
1760
|
+
mount.region.element
|
|
1761
|
+
.querySelector(`:scope > .${REGION_CONTENT_CLASS}`)
|
|
1762
|
+
?.replaceWith(copy);
|
|
1763
|
+
mount.wrapper.style.paddingBottom = copy.style.paddingBottom;
|
|
1764
|
+
}
|
|
1765
|
+
continue;
|
|
1766
|
+
}
|
|
1767
|
+
const known = this.pageRegions[p]?.[side];
|
|
1768
|
+
if (known?.drawing === drawing.content && known.section === page.section) {
|
|
1769
|
+
own[side] = known;
|
|
1770
|
+
continue;
|
|
1771
|
+
}
|
|
1772
|
+
const element = regions.element(page.section, side);
|
|
1773
|
+
element.append(drawing.content.content.cloneNode(true));
|
|
1774
|
+
own[side] = { element, drawing: drawing.content, section: page.section, id: drawing.id };
|
|
1775
|
+
}
|
|
1776
|
+
return own;
|
|
1777
|
+
});
|
|
1778
|
+
this.pageMargins = facts.map((page, p) => {
|
|
1779
|
+
if (!page.sectionPages) return { top: "", bottom: "" };
|
|
1780
|
+
const { top, bottom } = regions.margins(page.section, page);
|
|
1781
|
+
const { margins } = this.sheetOfPage(p).settings;
|
|
1782
|
+
return {
|
|
1783
|
+
top: Math.abs(top - margins.top * PX_PER_MM) < 0.01 ? "" : `${top}px`,
|
|
1784
|
+
bottom: Math.abs(bottom - margins.bottom * PX_PER_MM) < 0.01 ? "" : `${bottom}px`,
|
|
1785
|
+
};
|
|
1786
|
+
});
|
|
1787
|
+
if (!mount) return;
|
|
1788
|
+
// Not shown anywhere any more (a variant turned on or off): the page's own story opens.
|
|
1789
|
+
if (home < 0) queueMicrotask(this.reopenStory);
|
|
1790
|
+
else if (home !== mount.page) {
|
|
1791
|
+
mount.page = home;
|
|
1792
|
+
mount.moved = true;
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1796
|
+
/** The page setup page `p` has, or will have once placed. */
|
|
1797
|
+
private sheetOfPage(p: number): Sheet {
|
|
1798
|
+
return this.sheets[p] ?? this.sheets[this.sheets.length - 1] ?? this.lastSheet();
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
/**
|
|
1802
|
+
* After a story changed: its occurrences redrawn. False when a height changed, which takes a
|
|
1803
|
+
* new flow (`render`), or during a composition.
|
|
1804
|
+
*/
|
|
1805
|
+
private redrawRegions(): boolean {
|
|
1806
|
+
const { regions } = this;
|
|
1807
|
+
if (!regions) return true;
|
|
1808
|
+
if (this.composing) return true;
|
|
1809
|
+
const context = wordContext(this.state) as WordContext;
|
|
1810
|
+
const spans = sectionSpans(this.state.doc, context.envelope.section);
|
|
1811
|
+
regions.setDocument(
|
|
1812
|
+
context.envelope,
|
|
1813
|
+
spans.map((span) => span.setup),
|
|
1814
|
+
context.resolver,
|
|
1815
|
+
);
|
|
1816
|
+
this.notes?.setDocument(
|
|
1817
|
+
context.envelope,
|
|
1818
|
+
spans.map((span) => span.setup),
|
|
1819
|
+
context.resolver,
|
|
1820
|
+
this.noteReferences(),
|
|
1821
|
+
);
|
|
1822
|
+
if (this.regionsChanged(regions, spans)) {
|
|
1823
|
+
this.flowed = null;
|
|
1824
|
+
return false;
|
|
1825
|
+
}
|
|
1826
|
+
this.drawRegions();
|
|
1827
|
+
this.drawNotes();
|
|
1828
|
+
this.placeAgain?.();
|
|
1829
|
+
this.afterPlace();
|
|
1830
|
+
this.observer.takeRecords();
|
|
1831
|
+
return true;
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
/** The story being edited, moved with its region: the focus goes back to it. */
|
|
1835
|
+
private afterPlace(): void {
|
|
1836
|
+
this.drawControls();
|
|
1837
|
+
this.drawMatches();
|
|
1838
|
+
if (!this.mount?.moved) return;
|
|
1839
|
+
this.mount.moved = false;
|
|
1840
|
+
this.mount.view.focus();
|
|
1841
|
+
}
|
|
1842
|
+
|
|
1843
|
+
// ---------- stories on their pages (ADR-0007) ----------
|
|
1844
|
+
|
|
1845
|
+
/** What the toolbar and code open stories through (`Editor.storyView`). */
|
|
1846
|
+
private readonly stories: StoryView = ((view: EditorView) => ({
|
|
1847
|
+
get open(): OpenStory | null {
|
|
1848
|
+
const { mount } = view;
|
|
1849
|
+
return mount
|
|
1850
|
+
? { id: mount.id, side: mount.side, variant: mount.variant, section: mount.section }
|
|
1851
|
+
: null;
|
|
1852
|
+
},
|
|
1853
|
+
edit: (side, page) => view.openStory(side, page),
|
|
1854
|
+
editNote: (id) => view.openNote(id),
|
|
1855
|
+
toReference: () => view.toReference(),
|
|
1856
|
+
close: () => view.closeStory(),
|
|
1857
|
+
get fieldLayout() {
|
|
1858
|
+
return view.fieldLayout();
|
|
1859
|
+
},
|
|
1860
|
+
updateFields: (options, editor) => view.updateFields(options, editor),
|
|
1861
|
+
showMatches: (found) => view.showMatches(found),
|
|
1862
|
+
reveal: (target, options) => view.reveal(target, options),
|
|
1863
|
+
goToPage: (page, options) => view.goToPage(page, options),
|
|
1864
|
+
focus: () => view.focus(),
|
|
1865
|
+
}))(this);
|
|
1866
|
+
|
|
1867
|
+
/** Makes this view the one `Editor.storyView` speaks for, telling listeners if it was not. */
|
|
1868
|
+
private claimStories(): void {
|
|
1869
|
+
if (!this.paged || this.editor.storyView === this.stories) return;
|
|
1870
|
+
const first = !this.editor.storyView;
|
|
1871
|
+
this.editor.storyView = this.stories;
|
|
1872
|
+
if (!first) this.editor.storyChanged();
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
// ---------- find, and going places (11.11) ----------
|
|
1876
|
+
|
|
1877
|
+
/**
|
|
1878
|
+
* Marks what find found: on the pages, in the story open, and in the drawn copies of the others.
|
|
1879
|
+
* Nothing of it is in the document or the pages' DOM, and it does not print. The current match is
|
|
1880
|
+
* scrolled to when it is where the view can show it.
|
|
1881
|
+
*/
|
|
1882
|
+
showMatches(found: FoundMatches | null): void {
|
|
1883
|
+
this.showFound(found);
|
|
1884
|
+
const { current, scroll } = found ?? {};
|
|
1885
|
+
if (!current || !scroll) return;
|
|
1886
|
+
if (current.story === this.matchStory) this.scrollToRange(current.from, current.to);
|
|
1887
|
+
else if (current.story === this.mount?.id)
|
|
1888
|
+
this.mount?.view.scrollToRange(current.from, current.to);
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
/** The screen ranges of `from..to` in one paragraph: one per text node it covers. */
|
|
1892
|
+
private rangesOf(from: number, to: number): Range[] {
|
|
1893
|
+
const { doc } = this.state;
|
|
1894
|
+
if (to > doc.content.size) return [];
|
|
1895
|
+
const $from = doc.resolve(from);
|
|
1896
|
+
if (!$from.parent.isTextblock) return [];
|
|
1897
|
+
const desc = this.blocks[this.blockFrom($from.before())];
|
|
1898
|
+
if (!desc) return [];
|
|
1899
|
+
const start = $from.start();
|
|
1900
|
+
const out: Range[] = [];
|
|
1901
|
+
for (const leaf of desc.leaves) {
|
|
1902
|
+
const at = start + leaf.offset;
|
|
1903
|
+
const a = Math.max(from, at);
|
|
1904
|
+
const b = Math.min(to, at + leaf.size);
|
|
1905
|
+
if (a >= b || hiddenIn(leaf.dom, desc.dom)) continue;
|
|
1906
|
+
const range = this.host.ownerDocument.createRange();
|
|
1907
|
+
if (leaf.dom.nodeType === Node.TEXT_NODE) {
|
|
1908
|
+
range.setStart(leaf.dom, a - at);
|
|
1909
|
+
range.setEnd(leaf.dom, b - at);
|
|
1910
|
+
} else range.selectNodeContents(leaf.dom);
|
|
1911
|
+
out.push(range);
|
|
1912
|
+
}
|
|
1913
|
+
return out;
|
|
1914
|
+
}
|
|
1915
|
+
|
|
1916
|
+
/** The pages on the screen and a screen around it: only these carry marks. */
|
|
1917
|
+
private pagesNearView(): Set<number> {
|
|
1918
|
+
const height = this.host.ownerDocument.defaultView?.innerHeight ?? 0;
|
|
1919
|
+
const near = new Set<number>();
|
|
1920
|
+
this.pages.forEach((page, i) => {
|
|
1921
|
+
const { top, bottom } = page.getBoundingClientRect();
|
|
1922
|
+
if (bottom >= -height && top <= 2 * height) near.add(i);
|
|
1923
|
+
});
|
|
1924
|
+
return near;
|
|
1925
|
+
}
|
|
1926
|
+
|
|
1927
|
+
private drawMatches(): void {
|
|
1928
|
+
const { found, mount } = this;
|
|
1929
|
+
if (mount) {
|
|
1930
|
+
mount.view.matchStory = mount.id;
|
|
1931
|
+
mount.view.showFound(found);
|
|
1932
|
+
}
|
|
1933
|
+
if (!found) {
|
|
1934
|
+
this.matchMarks.set([], []);
|
|
1935
|
+
this.matchPages = "";
|
|
1936
|
+
return;
|
|
1937
|
+
}
|
|
1938
|
+
injectStyles(this.host);
|
|
1939
|
+
const { doc } = this.state;
|
|
1940
|
+
const near = this.pagesNearView();
|
|
1941
|
+
this.matchPages = [...near].join();
|
|
1942
|
+
// What the near pages hold, as positions: of the body's top-level nodes on them.
|
|
1943
|
+
let low = 0;
|
|
1944
|
+
let high = doc.content.size;
|
|
1945
|
+
if (this.paged) {
|
|
1946
|
+
low = high + 1;
|
|
1947
|
+
high = -1;
|
|
1948
|
+
doc.forEach((node, offset) => {
|
|
1949
|
+
const pages = this.itemPages.get(node);
|
|
1950
|
+
if (pages && !pages.some((page) => near.has(page))) return;
|
|
1951
|
+
low = Math.min(low, offset);
|
|
1952
|
+
high = Math.max(high, offset + node.nodeSize);
|
|
1953
|
+
});
|
|
1954
|
+
}
|
|
1955
|
+
// A tree's matches stand together, in order: those near are found by halving.
|
|
1956
|
+
const { matches } = found;
|
|
1957
|
+
let start = matches.findIndex((m) => m.story === this.matchStory);
|
|
1958
|
+
if (start < 0) start = matches.length;
|
|
1959
|
+
let end = start;
|
|
1960
|
+
while (end < matches.length && matches[end]?.story === this.matchStory) end++;
|
|
1961
|
+
let first = start;
|
|
1962
|
+
for (let last = end; first < last; ) {
|
|
1963
|
+
const mid = (first + last) >> 1;
|
|
1964
|
+
if ((matches[mid] as FindMatch).to <= low) first = mid + 1;
|
|
1965
|
+
else last = mid;
|
|
1966
|
+
}
|
|
1967
|
+
const all: Range[] = [];
|
|
1968
|
+
for (let i = first; i < end && (matches[i] as FindMatch).from < high; i++) {
|
|
1969
|
+
const { from, to } = matches[i] as FindMatch;
|
|
1970
|
+
all.push(...this.rangesOf(from, to));
|
|
1971
|
+
}
|
|
1972
|
+
const others = new Set<string>();
|
|
1973
|
+
for (const [i, { story }] of matches.entries())
|
|
1974
|
+
if ((i < start || i >= end) && story !== null && story !== mount?.id) others.add(story);
|
|
1975
|
+
const { current, query, matchCase, wholeWord } = found;
|
|
1976
|
+
const here = current?.story === this.matchStory ? current : null;
|
|
1977
|
+
if (others.size) {
|
|
1978
|
+
const options = { matchCase, wholeWord };
|
|
1979
|
+
const add = (root: Element | null | undefined) => {
|
|
1980
|
+
if (root) all.push(...rangesInText(root, query, options));
|
|
1981
|
+
};
|
|
1982
|
+
for (const p of near) {
|
|
1983
|
+
const { header, footer } = this.pageRegions[p] ?? {};
|
|
1984
|
+
for (const region of [header, footer])
|
|
1985
|
+
if (region && others.has(region.id))
|
|
1986
|
+
add(region.element.querySelector(`:scope > .${REGION_CONTENT_CLASS}`));
|
|
1987
|
+
for (const note of this.pages[p]?.querySelectorAll(`[${NOTE_ATTR}]`) ?? [])
|
|
1988
|
+
if (others.has(note.getAttribute(NOTE_ATTR) as string)) add(note);
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
this.matchMarks.set(all, here ? this.rangesOf(here.from, here.to) : []);
|
|
1992
|
+
}
|
|
1993
|
+
|
|
1994
|
+
/** Scrolling brings other pages near: their marks are drawn, once per frame. */
|
|
1995
|
+
private readonly onMatchScroll = (): void => {
|
|
1996
|
+
const win = this.host.ownerDocument.defaultView;
|
|
1997
|
+
if (this.matchFrame || !win) return;
|
|
1998
|
+
this.matchFrame = win.requestAnimationFrame(() => {
|
|
1999
|
+
this.matchFrame = 0;
|
|
2000
|
+
if (this.found && [...this.pagesNearView()].join() !== this.matchPages) this.drawMatches();
|
|
2001
|
+
});
|
|
2002
|
+
};
|
|
2003
|
+
|
|
2004
|
+
/** What find shows here, marked; a story's view is told by its page's view. */
|
|
2005
|
+
private showFound(found: FoundMatches | null): void {
|
|
2006
|
+
const doc = this.host.ownerDocument;
|
|
2007
|
+
if (this.paged && !this.found !== !found) {
|
|
2008
|
+
if (found) doc.addEventListener("scroll", this.onMatchScroll, SCROLL_OPTIONS);
|
|
2009
|
+
else doc.removeEventListener("scroll", this.onMatchScroll, SCROLL_OPTIONS);
|
|
2010
|
+
}
|
|
2011
|
+
this.found = found;
|
|
2012
|
+
this.drawMatches();
|
|
2013
|
+
}
|
|
2014
|
+
|
|
2015
|
+
private scrollToRange(from: number, to: number): void {
|
|
2016
|
+
let rect = this.rangesOf(from, to)[0]?.getClientRects?.()[0];
|
|
2017
|
+
if (!rect) {
|
|
2018
|
+
// A place, not a stretch of text: what holds it.
|
|
2019
|
+
const { node } = this.domFromPos(from);
|
|
2020
|
+
rect = (node instanceof Element ? node : node.parentElement)?.getBoundingClientRect();
|
|
2021
|
+
}
|
|
2022
|
+
// With room around it: a panel may float over the top of the window.
|
|
2023
|
+
if (rect)
|
|
2024
|
+
scrollRectIntoView(this.host, { top: rect.top - REVEAL_ABOVE, bottom: rect.bottom + 48 });
|
|
2025
|
+
}
|
|
2026
|
+
|
|
2027
|
+
/** Opens story `id` where a page shows it, leaving the focus where it is. */
|
|
2028
|
+
private openForReveal(id: string): boolean {
|
|
2029
|
+
const kind = wordContext(this.state)?.stories.get(id)?.kind;
|
|
2030
|
+
if (kind === "footnote" || kind === "endnote") return this.openNote(id, false);
|
|
2031
|
+
if (kind !== "header" && kind !== "footer") return false;
|
|
2032
|
+
const page = this.pageRegions.findIndex((regions) => regions[kind]?.id === id);
|
|
2033
|
+
return page >= 0 && this.openStory(kind, page, false, false);
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
/**
|
|
2037
|
+
* Selects `target` and scrolls to it: in the body (leaving a story that is open), or in its story,
|
|
2038
|
+
* opened where it is. `focus`: the document takes the focus. False when no page shows it.
|
|
2039
|
+
*/
|
|
2040
|
+
reveal({ story, from, to }: DocumentTarget, { focus = false } = {}): boolean {
|
|
2041
|
+
if (story === null) {
|
|
2042
|
+
this.closeStory(false);
|
|
2043
|
+
const { doc } = this.state;
|
|
2044
|
+
if (to > doc.content.size) return false;
|
|
2045
|
+
this.editor.dispatch(this.state.tr.setSelection(TextSelection.create(doc, from, to)));
|
|
2046
|
+
if (focus) this.focus();
|
|
2047
|
+
this.scrollToRange(from, to);
|
|
2048
|
+
return true;
|
|
2049
|
+
}
|
|
2050
|
+
if (this.mount?.id !== story && !this.openForReveal(story)) return false;
|
|
2051
|
+
const { mount } = this;
|
|
2052
|
+
if (!mount) return false;
|
|
2053
|
+
mount.view.editor.select(from, to);
|
|
2054
|
+
if (focus) mount.view.focus();
|
|
2055
|
+
mount.view.scrollToRange(from, to);
|
|
2056
|
+
return true;
|
|
2057
|
+
}
|
|
2058
|
+
|
|
2059
|
+
/** The caret to the start of page `page` (1-based) and the page into view. */
|
|
2060
|
+
goToPage(page: number, { focus = false } = {}): boolean {
|
|
2061
|
+
const element = this.pages[page - 1];
|
|
2062
|
+
if (!element) return false;
|
|
2063
|
+
this.closeStory(false);
|
|
2064
|
+
search: for (const [i, desc] of this.blocks.entries()) {
|
|
2065
|
+
for (const [f, fragment] of desc.fragments.entries()) {
|
|
2066
|
+
if (fragment.closest(".foli-page") !== element) continue;
|
|
2067
|
+
// A block leaf's parts (a node view split across pages) are all before it.
|
|
2068
|
+
const start = desc.node.isTextblock
|
|
2069
|
+
? (this.starts[i] as number) + 1 + (f ? (desc.splits[f - 1] as number) : 0)
|
|
2070
|
+
: (this.starts[i] as number);
|
|
2071
|
+
const { doc } = this.state;
|
|
2072
|
+
this.editor.dispatch(
|
|
2073
|
+
this.state.tr.setSelection(
|
|
2074
|
+
Selection.near(doc.resolve(Math.min(start, doc.content.size))),
|
|
2075
|
+
),
|
|
2076
|
+
);
|
|
2077
|
+
break search;
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
if (focus) this.focus();
|
|
2081
|
+
scrollRectIntoView(this.host, element.getBoundingClientRect());
|
|
2082
|
+
return true;
|
|
2083
|
+
}
|
|
2084
|
+
|
|
2085
|
+
/** Word's keys for finding and going places, when the app shows something for them. */
|
|
2086
|
+
private navigationKey(name: string): boolean {
|
|
2087
|
+
const request = Object.hasOwn(NAVIGATION_KEYS, name) ? NAVIGATION_KEYS[name] : undefined;
|
|
2088
|
+
return !!request && this.editor.navigation?.(request) === true;
|
|
2089
|
+
}
|
|
2090
|
+
|
|
2091
|
+
// ---------- content controls ----------
|
|
2092
|
+
|
|
2093
|
+
/** The frames of content controls, drawn again (a render takes them off the pages). */
|
|
2094
|
+
private drawControls(): void {
|
|
2095
|
+
if (!this.composing) this.controlChrome.draw(!this.mount);
|
|
2096
|
+
}
|
|
2097
|
+
|
|
2098
|
+
/** Where a control's content is on the screen: its lines, or its blocks by page. */
|
|
2099
|
+
private controlRects(range: ControlRange): Box[] {
|
|
2100
|
+
if (range.level !== "inline") {
|
|
2101
|
+
const byPage = new Map<Element | null, Box>();
|
|
2102
|
+
for (let i = this.blockFrom(range.from); i < this.blocks.length; i++) {
|
|
2103
|
+
if ((this.starts[i] as number) >= range.to) break;
|
|
2104
|
+
for (const fragment of (this.blocks[i] as WordBlockDesc).fragments) {
|
|
2105
|
+
if (!this.host.contains(fragment)) continue;
|
|
2106
|
+
const rect = fragment.getBoundingClientRect();
|
|
2107
|
+
const page = fragment.closest(".foli-page,.foli-story-flow");
|
|
2108
|
+
const known = byPage.get(page);
|
|
2109
|
+
const left = Math.min(known?.left ?? rect.left, rect.left);
|
|
2110
|
+
const top = Math.min(known?.top ?? rect.top, rect.top);
|
|
2111
|
+
byPage.set(
|
|
2112
|
+
page,
|
|
2113
|
+
boxOf(
|
|
2114
|
+
left,
|
|
2115
|
+
top,
|
|
2116
|
+
Math.max(known?.right ?? rect.right, rect.right) - left,
|
|
2117
|
+
Math.max(known?.bottom ?? rect.bottom, rect.bottom) - top,
|
|
2118
|
+
),
|
|
2119
|
+
);
|
|
2120
|
+
}
|
|
2121
|
+
}
|
|
2122
|
+
return [...byPage.values()];
|
|
2123
|
+
}
|
|
2124
|
+
return this.controlContentRects(range);
|
|
2125
|
+
}
|
|
2126
|
+
|
|
2127
|
+
/** Where what a control's content shows is on the screen. */
|
|
2128
|
+
private controlContentRects(range: ControlRange): Box[] {
|
|
2129
|
+
const dom = this.host.ownerDocument.createRange();
|
|
2130
|
+
const start = this.domFromPos(range.contentFrom);
|
|
2131
|
+
const end = this.domFromPos(range.contentTo);
|
|
2132
|
+
dom.setStart(start.node, start.offset);
|
|
2133
|
+
dom.setEnd(end.node, end.offset);
|
|
2134
|
+
const rects = [...(dom.getClientRects?.() ?? [])].filter((rect) => rect.width > 0);
|
|
2135
|
+
if (rects.length) return rects;
|
|
2136
|
+
// Nothing in it: a thin box where it is.
|
|
2137
|
+
const element =
|
|
2138
|
+
start.node.nodeType === Node.ELEMENT_NODE
|
|
2139
|
+
? (start.node as Element)
|
|
2140
|
+
: start.node.parentElement;
|
|
2141
|
+
const rect = dom.getBoundingClientRect?.();
|
|
2142
|
+
const box = rect?.height ? rect : element?.getBoundingClientRect();
|
|
2143
|
+
return box ? [boxOf(box.left, box.top, 4, box.height)] : [];
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
/**
|
|
2147
|
+
* Left and Right stop on each side of a content control's edge, as Word's caret does (browsers
|
|
2148
|
+
* cannot see the difference). Alt+Down, which opens a list or date picker, is in `viewKey`.
|
|
2149
|
+
*/
|
|
2150
|
+
private controlKey(name: string): boolean {
|
|
2151
|
+
if (name !== "ArrowLeft" && name !== "ArrowRight") return false;
|
|
2152
|
+
const { selection, doc } = this.state;
|
|
2153
|
+
if (!(selection instanceof TextSelection) || !wordContext(this.state)?.envelope.controls)
|
|
2154
|
+
return false;
|
|
2155
|
+
const forward = name === "ArrowRight";
|
|
2156
|
+
const range = controlAt(doc, selection.from);
|
|
2157
|
+
if (!selection.empty) {
|
|
2158
|
+
// A placeholder is one thing: the arrows go past it.
|
|
2159
|
+
if (
|
|
2160
|
+
range?.level !== "inline" ||
|
|
2161
|
+
!controlProperties(this.state, range.id)?.placeholder?.showing ||
|
|
2162
|
+
selection.from !== range.contentFrom ||
|
|
2163
|
+
selection.to !== range.contentTo
|
|
2164
|
+
)
|
|
2165
|
+
return false;
|
|
2166
|
+
this.dispatch(
|
|
2167
|
+
this.state.tr.setSelection(TextSelection.create(doc, forward ? range.to : range.from)),
|
|
2168
|
+
);
|
|
2169
|
+
return true;
|
|
2170
|
+
}
|
|
2171
|
+
const { $from } = selection;
|
|
2172
|
+
const next = forward ? $from.nodeAfter : $from.nodeBefore;
|
|
2173
|
+
if (next?.type.name !== "controlStart" && next?.type.name !== "controlEnd") return false;
|
|
2174
|
+
this.dispatch(
|
|
2175
|
+
this.state.tr.setSelection(TextSelection.create(doc, $from.pos + (forward ? 1 : -1))),
|
|
2176
|
+
);
|
|
2177
|
+
return true;
|
|
2178
|
+
}
|
|
2179
|
+
|
|
2180
|
+
// ---------- fields ----------
|
|
2181
|
+
|
|
2182
|
+
/** The pages as last flowed, as fields need them; null without pages. */
|
|
2183
|
+
private fieldLayout(): FieldLayout | null {
|
|
2184
|
+
if (!this.regions || !this.facts.length) return null;
|
|
2185
|
+
return {
|
|
2186
|
+
pages: this.facts.length,
|
|
2187
|
+
pageAt: (pos) => {
|
|
2188
|
+
const { node } = this.domFromPos(Math.min(pos, this.state.doc.content.size));
|
|
2189
|
+
const element =
|
|
2190
|
+
node.nodeType === Node.ELEMENT_NODE ? (node as Element) : node.parentElement;
|
|
2191
|
+
const page = this.facts[this.pages.indexOf(element?.closest(".foli-page") as HTMLElement)];
|
|
2192
|
+
if (!page) return null;
|
|
2193
|
+
const format = this.sections()[page.section]?.pageNumbers?.format;
|
|
2194
|
+
return { number: page.number, sectionPages: page.sectionPages, format };
|
|
2195
|
+
},
|
|
2196
|
+
};
|
|
2197
|
+
}
|
|
2198
|
+
|
|
2199
|
+
/**
|
|
2200
|
+
* Updates fields from the pages shown: all of them, or those `options.only` says, of the body or
|
|
2201
|
+
* of `editor` (a story's). What that does to the pages is taken in by a second pass over what
|
|
2202
|
+
* depends on them, in the same undo step.
|
|
2203
|
+
*/
|
|
2204
|
+
updateFields(options: UpdateFieldsOptions = {}, editor: Editor = this.editor): FieldsReport {
|
|
2205
|
+
// A story's view has no pages: the view of the body has.
|
|
2206
|
+
const main = this.regions ? null : this.editor.storyView;
|
|
2207
|
+
if (main) return main.updateFields(options, editor);
|
|
2208
|
+
if (this.composing) this.onCompositionEnd();
|
|
2209
|
+
const report = updateFields(editor, { ...options, layout: this.fieldLayout() });
|
|
2210
|
+
const { only } = options;
|
|
2211
|
+
const range = !!only && typeof only !== "function";
|
|
2212
|
+
if (!report.updated || (range && !report.rebuilt)) return report;
|
|
2213
|
+
const follows = (field: Field) =>
|
|
2214
|
+
range
|
|
2215
|
+
? field.parent?.name === "TOC"
|
|
2216
|
+
: PAGE_DEPENDENT.has(field.name) && (typeof only !== "function" || only(field));
|
|
2217
|
+
const again = updateFields(editor, {
|
|
2218
|
+
...options,
|
|
2219
|
+
layout: this.fieldLayout(),
|
|
2220
|
+
only: follows,
|
|
2221
|
+
continues: true,
|
|
2222
|
+
});
|
|
2223
|
+
return { ...report, updated: report.updated + again.updated };
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
/**
|
|
2227
|
+
* Prints what the document is now: fields updated (one undo step), then the browser's dialog.
|
|
2228
|
+
*/
|
|
2229
|
+
print(): void {
|
|
2230
|
+
try {
|
|
2231
|
+
this.updateFields();
|
|
2232
|
+
} finally {
|
|
2233
|
+
this.host.ownerDocument.defaultView?.print();
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
|
|
2237
|
+
/**
|
|
2238
|
+
* Left and Right next to a field's markers: the browser's move starts where something can be
|
|
2239
|
+
* seen, or the markers (empty elements) cost WebKit a key press each. With codes shown the
|
|
2240
|
+
* view makes the move itself, over the whole field; whether it did.
|
|
2241
|
+
*/
|
|
2242
|
+
private skipFieldParts(event: KeyboardEvent): boolean {
|
|
2243
|
+
const forward = event.key === "ArrowRight";
|
|
2244
|
+
if ((!forward && event.key !== "ArrowLeft") || event.ctrlKey || event.altKey || event.metaKey)
|
|
2245
|
+
return false;
|
|
2246
|
+
const { selection, doc } = this.state;
|
|
2247
|
+
// Shift extends by itself: an extended DOM selection would lose its anchor to the same spot.
|
|
2248
|
+
if (!(selection instanceof TextSelection) || event.shiftKey || !selection.empty) return false;
|
|
2249
|
+
const stop = caretStop(this.state, selection.head, forward);
|
|
2250
|
+
const sel = this.host.ownerDocument.getSelection();
|
|
2251
|
+
if (stop === selection.head || !sel) return false;
|
|
2252
|
+
if (this.fieldCodes) {
|
|
2253
|
+
this.dispatch(this.state.tr.setSelection(TextSelection.create(doc, stop)));
|
|
2254
|
+
return true;
|
|
2255
|
+
}
|
|
2256
|
+
const { node, offset } = this.domFromPos(stop);
|
|
2257
|
+
sel.collapse(node, offset);
|
|
2258
|
+
return false;
|
|
2259
|
+
}
|
|
2260
|
+
|
|
2261
|
+
/** F9 and Alt+F9, as in Word. */
|
|
2262
|
+
private fieldKey(name: string): boolean {
|
|
2263
|
+
if (name === "Alt-F9") {
|
|
2264
|
+
this.run(toggleFieldCodes);
|
|
2265
|
+
return true;
|
|
2266
|
+
}
|
|
2267
|
+
if (name !== "F9") return false;
|
|
2268
|
+
if (!this.editable) return true;
|
|
2269
|
+
const { selection } = this.state;
|
|
2270
|
+
this.updateFields(
|
|
2271
|
+
selection instanceof AllSelection ? {} : { only: { from: selection.from, to: selection.to } },
|
|
2272
|
+
);
|
|
2273
|
+
return true;
|
|
2274
|
+
}
|
|
2275
|
+
|
|
2276
|
+
/** Shades what shows the fields the selection is in (not printed): the outermost of each. */
|
|
2277
|
+
private showSelectedFields(): void {
|
|
2278
|
+
const { selection, doc } = this.state;
|
|
2279
|
+
const wanted = new Set<Element>();
|
|
2280
|
+
const fields = selection instanceof TextSelection ? fieldsIn(doc) : [];
|
|
2281
|
+
const touched = (field: Field) =>
|
|
2282
|
+
selection.empty
|
|
2283
|
+
? field.from < selection.from && selection.from < field.to
|
|
2284
|
+
: field.from < selection.to && field.to > selection.from;
|
|
2285
|
+
for (const field of fields) {
|
|
2286
|
+
if (!touched(field) || (field.parent && touched(field.parent))) continue;
|
|
2287
|
+
const [from, to] = this.fieldCodes
|
|
2288
|
+
? [field.from, field.codeEnd + 1]
|
|
2289
|
+
: [field.resultFrom, field.resultTo];
|
|
2290
|
+
const first = Math.max(this.blockFrom(from) - 1, 0);
|
|
2291
|
+
for (let i = first; i < this.blocks.length; i++) {
|
|
2292
|
+
const start = (this.starts[i] as number) + 1;
|
|
2293
|
+
if (start > to) break;
|
|
2294
|
+
const desc = this.blocks[i] as WordBlockDesc;
|
|
2295
|
+
for (const leaf of desc.leaves) {
|
|
2296
|
+
const at = start + leaf.offset;
|
|
2297
|
+
if (at + leaf.size <= from || at >= to || !leaf.size) continue;
|
|
2298
|
+
if (hiddenIn(leaf.dom, desc.dom)) continue;
|
|
2299
|
+
const element = leaf.dom.nodeType === Node.TEXT_NODE ? leaf.dom.parentElement : leaf.dom;
|
|
2300
|
+
if (element instanceof Element && element.textContent) wanted.add(element);
|
|
2301
|
+
}
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
for (const element of this.shadedFields)
|
|
2305
|
+
if (!wanted.has(element)) element.removeAttribute(FIELD_SELECTED_ATTR);
|
|
2306
|
+
if (wanted.size) injectStyles(this.host);
|
|
2307
|
+
for (const element of wanted) element.setAttribute(FIELD_SELECTED_ATTR, "");
|
|
2308
|
+
this.shadedFields = [...wanted];
|
|
2309
|
+
}
|
|
2310
|
+
|
|
2311
|
+
/** The sections of the document, in order. */
|
|
2312
|
+
private sections(): SectionJSON[] {
|
|
2313
|
+
const { envelope } = wordContext(this.state) as WordContext;
|
|
2314
|
+
return sectionSpans(this.state.doc, envelope.section).map((span) => span.setup);
|
|
2315
|
+
}
|
|
2316
|
+
|
|
2317
|
+
/** The page the selection's head is on. */
|
|
2318
|
+
private selectionPage(): number {
|
|
2319
|
+
const { node } = this.domFromPos(this.state.selection.head);
|
|
2320
|
+
const element = node.nodeType === Node.ELEMENT_NODE ? (node as Element) : node.parentElement;
|
|
2321
|
+
return Math.max(this.pages.indexOf(element?.closest(".foli-page") as HTMLElement), 0);
|
|
2322
|
+
}
|
|
2323
|
+
|
|
2324
|
+
/**
|
|
2325
|
+
* Opens the header or footer of page `at` (by default the selection's) for editing where it is;
|
|
2326
|
+
* made first when the page has none. Whether it is open now.
|
|
2327
|
+
*/
|
|
2328
|
+
openStory(side: StorySide, at = this.selectionPage(), create = true, focus = true): boolean {
|
|
2329
|
+
if (!this.regions || !this.editable || this.composing) return false;
|
|
2330
|
+
// Word's blank page has none: the next page's.
|
|
2331
|
+
let p = at;
|
|
2332
|
+
while (this.facts[p] && !this.facts[p]?.sectionPages) p++;
|
|
2333
|
+
const page = this.facts[p];
|
|
2334
|
+
if (!page) return false;
|
|
2335
|
+
const context = wordContext(this.state) as WordContext;
|
|
2336
|
+
const setup = this.sections()[page.section] as SectionJSON;
|
|
2337
|
+
const even = context.envelope.settings?.evenAndOddHeaders === true;
|
|
2338
|
+
const variant = pageVariant(setup, page, even);
|
|
2339
|
+
const before = storyOfSection(this.sections(), page.section, side, variant);
|
|
2340
|
+
if (this.mount?.id === before?.id && this.mount?.side === side && this.mount?.page === p) {
|
|
2341
|
+
if (focus) this.mount?.view.focus();
|
|
2342
|
+
return true;
|
|
2343
|
+
}
|
|
2344
|
+
this.closeStory(false);
|
|
2345
|
+
if (!before && (!create || !this.editor.run(ensureStory(side, variant, page.section))))
|
|
2346
|
+
return false;
|
|
2347
|
+
const found = storyOfSection(this.sections(), page.section, side, variant);
|
|
2348
|
+
const editor = found && this.editor.story(found.id);
|
|
2349
|
+
const region = this.pageRegions[p]?.[side];
|
|
2350
|
+
if (!found || !editor || !region) return false;
|
|
2351
|
+
this.mountStory(
|
|
2352
|
+
editor,
|
|
2353
|
+
{ id: found.id, side, variant, section: page.section, page: p, region },
|
|
2354
|
+
side === "header" ? "Header" : "Footer",
|
|
2355
|
+
undefined,
|
|
2356
|
+
focus,
|
|
2357
|
+
);
|
|
2358
|
+
return true;
|
|
2359
|
+
}
|
|
2360
|
+
|
|
2361
|
+
/**
|
|
2362
|
+
* Opens note `id`, or the one whose reference is at the selection, in place: shown whole at its
|
|
2363
|
+
* reference's page. Whether it is open now.
|
|
2364
|
+
*/
|
|
2365
|
+
openNote(id?: string, focus = true): boolean {
|
|
2366
|
+
const { notes } = this;
|
|
2367
|
+
if (!notes || !this.editable || this.composing) return false;
|
|
2368
|
+
const story = id ?? noteAtSelection(this.state)?.story;
|
|
2369
|
+
if (!story) return false;
|
|
2370
|
+
if (this.mount?.id === story) {
|
|
2371
|
+
if (focus) this.mount.view.focus();
|
|
2372
|
+
return true;
|
|
2373
|
+
}
|
|
2374
|
+
this.closeStory(false);
|
|
2375
|
+
const editor = this.editor.story(story);
|
|
2376
|
+
if (!editor) return false;
|
|
2377
|
+
notes.open = story;
|
|
2378
|
+
this.flowed = null;
|
|
2379
|
+
this.render();
|
|
2380
|
+
const element = this.host.querySelector<HTMLElement>(`[${NOTE_ATTR}="${CSS.escape(story)}"]`);
|
|
2381
|
+
const page = this.notePages.get(story);
|
|
2382
|
+
if (!element || page === undefined) {
|
|
2383
|
+
notes.open = null;
|
|
2384
|
+
this.flowed = null;
|
|
2385
|
+
this.render();
|
|
2386
|
+
return false;
|
|
2387
|
+
}
|
|
2388
|
+
const region = { element, drawing: {}, section: 0, id: story };
|
|
2389
|
+
const texts = () =>
|
|
2390
|
+
noteTexts(noteNumbers(this.state.doc, (wordContext(this.state) as WordContext).envelope));
|
|
2391
|
+
this.mountStory(
|
|
2392
|
+
editor,
|
|
2393
|
+
{ id: story, side: "note", variant: "default", section: 0, page, region },
|
|
2394
|
+
"Note",
|
|
2395
|
+
() => texts().get(story) ?? "",
|
|
2396
|
+
focus,
|
|
2397
|
+
);
|
|
2398
|
+
editor.select(Selection.atEnd(editor.state.doc).from);
|
|
2399
|
+
return true;
|
|
2400
|
+
}
|
|
2401
|
+
|
|
2402
|
+
/** From the note being edited back to its reference, the caret after it. */
|
|
2403
|
+
private toReference(): boolean {
|
|
2404
|
+
const { mount } = this;
|
|
2405
|
+
if (mount?.side !== "note") return false;
|
|
2406
|
+
const reference = noteNumbers(
|
|
2407
|
+
this.state.doc,
|
|
2408
|
+
(wordContext(this.state) as WordContext).envelope,
|
|
2409
|
+
).find((n) => n.story === mount.id);
|
|
2410
|
+
this.closeStory(false);
|
|
2411
|
+
if (reference)
|
|
2412
|
+
this.dispatch(
|
|
2413
|
+
this.state.tr.setSelection(TextSelection.create(this.state.doc, reference.pos + 1)),
|
|
2414
|
+
);
|
|
2415
|
+
this.focus();
|
|
2416
|
+
return true;
|
|
2417
|
+
}
|
|
2418
|
+
|
|
2419
|
+
/** Puts `editor`'s story on its page, in `place`, the body read-only and dimmed around it. */
|
|
2420
|
+
private mountStory(
|
|
2421
|
+
editor: Editor,
|
|
2422
|
+
place: Omit<StoryMount, "wrapper" | "view" | "moved">,
|
|
2423
|
+
label: string,
|
|
2424
|
+
noteMark?: () => string,
|
|
2425
|
+
focus = true,
|
|
2426
|
+
): void {
|
|
2427
|
+
const { region } = place;
|
|
2428
|
+
injectStyles(this.host);
|
|
2429
|
+
this.observer.disconnect();
|
|
2430
|
+
this.host.setAttribute("contenteditable", "false");
|
|
2431
|
+
this.host.setAttribute("aria-readonly", "true");
|
|
2432
|
+
this.host.classList.add("foli-in-story");
|
|
2433
|
+
const doc = this.host.ownerDocument;
|
|
2434
|
+
const wrapper = doc.createElement("div");
|
|
2435
|
+
wrapper.className = "foli-story-mount";
|
|
2436
|
+
wrapper.setAttribute("contenteditable", "false");
|
|
2437
|
+
wrapper.style.userSelect = "text";
|
|
2438
|
+
wrapper.style.setProperty("-webkit-user-select", "text");
|
|
2439
|
+
const inner = doc.createElement("div");
|
|
2440
|
+
inner.setAttribute("aria-label", label);
|
|
2441
|
+
wrapper.append(inner);
|
|
2442
|
+
const shown = region.element.querySelector<HTMLElement>(`:scope > .${REGION_CONTENT_CLASS}`);
|
|
2443
|
+
if (shown) {
|
|
2444
|
+
shown.style.display = "none";
|
|
2445
|
+
wrapper.style.paddingBottom = shown.style.paddingBottom;
|
|
2446
|
+
}
|
|
2447
|
+
region.element.append(wrapper);
|
|
2448
|
+
const view = new EditorView(inner, editor, {
|
|
2449
|
+
paged: false,
|
|
2450
|
+
upload: this.upload ?? null,
|
|
2451
|
+
resource: this.resource ?? null,
|
|
2452
|
+
...(noteMark ? { noteMark } : {}),
|
|
2453
|
+
});
|
|
2454
|
+
wrapper.addEventListener("keydown", (event) => {
|
|
2455
|
+
if (event.isComposing || view.composing) return;
|
|
2456
|
+
// Unless the story's view ran a user's binding of the key.
|
|
2457
|
+
if (!event.defaultPrevented && keyName(event) === NOTE_KEY && this.toReference()) {
|
|
2458
|
+
// Not on to the body, which would open the note again.
|
|
2459
|
+
event.preventDefault();
|
|
2460
|
+
event.stopPropagation();
|
|
2461
|
+
return;
|
|
2462
|
+
}
|
|
2463
|
+
if (event.key !== "Escape") return;
|
|
2464
|
+
event.preventDefault();
|
|
2465
|
+
this.closeStory(true);
|
|
2466
|
+
});
|
|
2467
|
+
this.mount = { ...place, wrapper, view, moved: false };
|
|
2468
|
+
// With several views of the editor, the one in use answers for its story.
|
|
2469
|
+
wrapper.addEventListener("focusin", () => this.claimStories());
|
|
2470
|
+
this.claimStories();
|
|
2471
|
+
if (focus) view.focus();
|
|
2472
|
+
this.drawMatches();
|
|
2473
|
+
this.editor.storyChanged();
|
|
2474
|
+
}
|
|
2475
|
+
|
|
2476
|
+
/** Finishes a running composition, its text going into the model. */
|
|
2477
|
+
endComposition(): void {
|
|
2478
|
+
if (this.composing) this.onCompositionEnd();
|
|
2479
|
+
}
|
|
2480
|
+
|
|
2481
|
+
/** Leaves the story being edited; `focus`: the body takes the focus, with its selection back. */
|
|
2482
|
+
closeStory(focus = true): void {
|
|
2483
|
+
const { mount } = this;
|
|
2484
|
+
if (!mount) return;
|
|
2485
|
+
mount.view.endComposition();
|
|
2486
|
+
this.mount = null;
|
|
2487
|
+
mount.view.destroy();
|
|
2488
|
+
mount.wrapper.remove();
|
|
2489
|
+
const shown = mount.region.element.querySelector<HTMLElement>(
|
|
2490
|
+
`:scope > .${REGION_CONTENT_CLASS}`,
|
|
2491
|
+
);
|
|
2492
|
+
if (shown) shown.style.display = "";
|
|
2493
|
+
if (mount.side === "note" && this.notes) {
|
|
2494
|
+
this.notes.open = null;
|
|
2495
|
+
this.flowed = null;
|
|
2496
|
+
if (!this.destroyed) this.render();
|
|
2497
|
+
}
|
|
2498
|
+
this.host.classList.remove("foli-in-story");
|
|
2499
|
+
this.host.setAttribute("contenteditable", String(this.editable));
|
|
2500
|
+
if (this.editable) this.host.removeAttribute("aria-readonly");
|
|
2501
|
+
this.observer.takeRecords();
|
|
2502
|
+
this.observer.observe(this.host, { childList: true, characterData: true, subtree: true });
|
|
2503
|
+
if (focus && !this.destroyed) this.focus();
|
|
2504
|
+
if (!this.destroyed) this.drawMatches();
|
|
2505
|
+
this.editor.storyChanged();
|
|
2506
|
+
}
|
|
2507
|
+
|
|
2508
|
+
/** The page's own story, after what was open is shown nowhere any more. */
|
|
2509
|
+
private reopenStory = (): void => {
|
|
2510
|
+
const { mount } = this;
|
|
2511
|
+
if (!mount || mount.side === "note" || this.facts.length === 0) return;
|
|
2512
|
+
const { side, page, id } = mount;
|
|
2513
|
+
// A story that went (undone) is not made again.
|
|
2514
|
+
const create = !!wordContext(this.state)?.stories.has(id);
|
|
2515
|
+
this.closeStory(false);
|
|
2516
|
+
if (!this.openStory(side, Math.min(page, this.facts.length - 1), create)) this.focus();
|
|
2517
|
+
};
|
|
2518
|
+
|
|
2519
|
+
/** The margin of a page a mouse event is in, if it is on the page itself. */
|
|
2520
|
+
private marginAt(event: MouseEvent): { side: StorySide; page: number } | null {
|
|
2521
|
+
const element = event.target as Element | null;
|
|
2522
|
+
const page = this.pages.indexOf(element as HTMLElement);
|
|
2523
|
+
if (page < 0 || !this.regions) return null;
|
|
2524
|
+
const box = (element as Element).getBoundingClientRect();
|
|
2525
|
+
const scale = this.scale();
|
|
2526
|
+
const style = getComputedStyle(element as Element);
|
|
2527
|
+
const y = (event.clientY - box.top) / scale;
|
|
2528
|
+
if (y < Number.parseFloat(style.paddingTop)) return { side: "header", page };
|
|
2529
|
+
return y > box.height / scale - Number.parseFloat(style.paddingBottom)
|
|
2530
|
+
? { side: "footer", page }
|
|
2531
|
+
: null;
|
|
2532
|
+
}
|
|
2533
|
+
|
|
2534
|
+
/**
|
|
2535
|
+
* A press outside the story being edited leaves it. The second press of a double click in a
|
|
2536
|
+
* page's margin opens its header or footer, the body's selection kept: on the press, since the
|
|
2537
|
+
* first click may have scrolled the page (Firefox) and the double click would land elsewhere.
|
|
2538
|
+
*/
|
|
2539
|
+
private onPress = (event: MouseEvent): void => {
|
|
2540
|
+
this.closeStory(false);
|
|
2541
|
+
// A note on the page, or the number of its reference: the second press opens the note.
|
|
2542
|
+
const target = event.target instanceof Element ? event.target : null;
|
|
2543
|
+
const onNote = target?.closest(`[${NOTE_ATTR}]`);
|
|
2544
|
+
const number = target?.closest(`[${NOTE_REF_ATTR}]`);
|
|
2545
|
+
const story = onNote?.getAttribute(NOTE_ATTR) ?? number?.getAttribute(NOTE_REF_ATTR);
|
|
2546
|
+
if (story && event.button === 0 && !event.shiftKey) {
|
|
2547
|
+
const opens = event.detail === 2 && this.editable && isNoteStory(this.state, story);
|
|
2548
|
+
if (onNote || opens) event.preventDefault();
|
|
2549
|
+
if (opens) {
|
|
2550
|
+
if (this.openNote(story) && onNote)
|
|
2551
|
+
this.mount?.view.placeCaret(event.clientX, event.clientY);
|
|
2552
|
+
return;
|
|
2553
|
+
}
|
|
2554
|
+
if (onNote) return;
|
|
2555
|
+
}
|
|
2556
|
+
const margin = event.button === 0 && !event.shiftKey ? this.marginAt(event) : null;
|
|
2557
|
+
if (margin && event.detail > 1) {
|
|
2558
|
+
event.preventDefault();
|
|
2559
|
+
if (event.detail > 2 || !this.editable) return;
|
|
2560
|
+
const selection = this.pressSelection;
|
|
2561
|
+
this.pressSelection = null;
|
|
2562
|
+
if (selection && !selection.eq(this.state.selection))
|
|
2563
|
+
this.editor.dispatch(this.state.tr.setSelection(selection));
|
|
2564
|
+
if (this.openStory(margin.side, margin.page))
|
|
2565
|
+
this.mount?.view.placeCaret(event.clientX, event.clientY);
|
|
2566
|
+
return;
|
|
2567
|
+
}
|
|
2568
|
+
// What the body shows now is what leaving the story comes back to (`selectionchange` comes
|
|
2569
|
+
// late, and the browser may select something on the way to the second press).
|
|
2570
|
+
if (margin && this.hasFocus()) this.syncSelection();
|
|
2571
|
+
this.pressSelection = margin ? this.state.selection : null;
|
|
2572
|
+
// On a header or footer a press is not for the body: it places no caret.
|
|
2573
|
+
if (margin && this.pageRegions[margin.page]?.[margin.side]) {
|
|
2574
|
+
event.preventDefault();
|
|
2575
|
+
if (!this.hasFocus()) {
|
|
2576
|
+
this.pointerFocus = true;
|
|
2577
|
+
this.host.focus({ preventScroll: true });
|
|
2578
|
+
this.writeSelection(true);
|
|
2579
|
+
}
|
|
2580
|
+
return;
|
|
2581
|
+
}
|
|
2582
|
+
this.onMouseDown(event);
|
|
2583
|
+
};
|
|
2584
|
+
|
|
2585
|
+
/** Puts the caret at a point of the window, if it is on this view's content. */
|
|
2586
|
+
placeCaret(x: number, y: number): void {
|
|
2587
|
+
const pos = this.posAtPoint(x, y);
|
|
2588
|
+
if (pos !== null)
|
|
2589
|
+
this.editor.dispatch(
|
|
2590
|
+
this.state.tr.setSelection(TextSelection.near(this.state.doc.resolve(pos))),
|
|
2591
|
+
);
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2594
|
+
/** The model position at a point of the window, or null. */
|
|
2595
|
+
private posAtPoint(x: number, y: number): number | null {
|
|
2596
|
+
const doc = this.host.ownerDocument as Document & {
|
|
2597
|
+
caretPositionFromPoint?: (
|
|
2598
|
+
x: number,
|
|
2599
|
+
y: number,
|
|
2600
|
+
) => { offsetNode: Node; offset: number } | null;
|
|
2601
|
+
caretRangeFromPoint?: (x: number, y: number) => Range | null;
|
|
2602
|
+
};
|
|
2603
|
+
const point = doc.caretPositionFromPoint?.(x, y);
|
|
2604
|
+
const range = point ? null : doc.caretRangeFromPoint?.(x, y);
|
|
2605
|
+
const node = point?.offsetNode ?? range?.startContainer;
|
|
2606
|
+
const offset = point?.offset ?? range?.startOffset ?? 0;
|
|
2607
|
+
return node && this.host.contains(node) ? this.posFromDOM(node, offset) : null;
|
|
989
2608
|
}
|
|
990
2609
|
|
|
991
2610
|
/**
|
|
@@ -1038,25 +2657,34 @@ export class EditorView {
|
|
|
1038
2657
|
|
|
1039
2658
|
/**
|
|
1040
2659
|
* Puts each fragment of each block into its page (pages are non-decreasing in document
|
|
1041
|
-
* order)
|
|
1042
|
-
*
|
|
1043
|
-
* or a page (stray DOM) is removed.
|
|
2660
|
+
* order) and, on a page with several sections or columns, into its band's column, creating
|
|
2661
|
+
* and removing pages as needed, and gives each page the page setup of its first section.
|
|
2662
|
+
* Anything else in the host or a page (stray DOM) is removed.
|
|
1044
2663
|
*/
|
|
1045
2664
|
private place(
|
|
1046
2665
|
elements: readonly (readonly HTMLElement[])[],
|
|
1047
2666
|
pages: readonly (readonly number[])[],
|
|
2667
|
+
slots: readonly (readonly Slot[])[],
|
|
1048
2668
|
layout: readonly BlockLayout[],
|
|
1049
2669
|
): void {
|
|
1050
2670
|
const { host } = this;
|
|
1051
2671
|
const items = elements.flatMap((list, i) =>
|
|
1052
|
-
list.map((dom, f) => ({
|
|
2672
|
+
list.map((dom, f) => ({
|
|
2673
|
+
dom,
|
|
2674
|
+
page: pages[i]?.[f] ?? 0,
|
|
2675
|
+
slot: slots[i]?.[f] as Slot,
|
|
2676
|
+
section: (layout[i] as BlockLayout).section,
|
|
2677
|
+
})),
|
|
1053
2678
|
);
|
|
1054
|
-
|
|
2679
|
+
// A note can reach pages no text is on.
|
|
2680
|
+
const count = Math.max((items[items.length - 1]?.page ?? 0) + 1, this.pageNotes.length);
|
|
1055
2681
|
const sheets: Sheet[] = [];
|
|
1056
2682
|
pages.forEach((list, i) => {
|
|
1057
2683
|
for (const p of list) sheets[p] ??= (layout[i] as BlockLayout).sheet;
|
|
1058
2684
|
});
|
|
1059
|
-
// A page no block
|
|
2685
|
+
// A page no block is on has the setup of the page after it (Word's blank page before an
|
|
2686
|
+
// even or odd page section); the last, one with no blocks yet, of the page before it.
|
|
2687
|
+
for (let p = count - 1; p >= 0; p--) if (sheets[p + 1]) sheets[p] ??= sheets[p + 1] as Sheet;
|
|
1060
2688
|
for (let p = 0; p < count; p++)
|
|
1061
2689
|
sheets[p] ??=
|
|
1062
2690
|
sheets[p - 1] ?? (layout[0] as BlockLayout | undefined)?.sheet ?? this.lastSheet();
|
|
@@ -1065,10 +2693,19 @@ export class EditorView {
|
|
|
1065
2693
|
this.sheets.forEach((sheet, p) => {
|
|
1066
2694
|
const page = this.pages[p] as HTMLElement;
|
|
1067
2695
|
const key = `${sheet.index} ${sheet.css}`;
|
|
1068
|
-
if (pageSheets.get(page)
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
2696
|
+
if (pageSheets.get(page) !== key) {
|
|
2697
|
+
pageSheets.set(page, key);
|
|
2698
|
+
pagePads.delete(page);
|
|
2699
|
+
page.style.cssText = sheet.css;
|
|
2700
|
+
page.setAttribute(SHEET_ATTR, String(sheet.index));
|
|
2701
|
+
}
|
|
2702
|
+
const { top = "", bottom = "" } = this.pageMargins[p] ?? {};
|
|
2703
|
+
const pads = `${top} ${bottom}`;
|
|
2704
|
+
if ((pagePads.get(page) ?? " ") !== pads) {
|
|
2705
|
+
pagePads.set(page, pads);
|
|
2706
|
+
page.style.paddingTop = top;
|
|
2707
|
+
page.style.paddingBottom = bottom;
|
|
2708
|
+
}
|
|
1072
2709
|
});
|
|
1073
2710
|
// Pages first, in order; anything else in the host ends up after them.
|
|
1074
2711
|
let cursor = host.firstChild;
|
|
@@ -1079,19 +2716,64 @@ export class EditorView {
|
|
|
1079
2716
|
let i = 0;
|
|
1080
2717
|
for (let p = 0; p < count; p++) {
|
|
1081
2718
|
const page = this.pages[p] as HTMLElement;
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
2719
|
+
const first = i;
|
|
2720
|
+
while (i < items.length && items[i]?.page === p) i++;
|
|
2721
|
+
const onPage = items.slice(first, i);
|
|
2722
|
+
const { header, footer } = this.pageRegions[p] ?? {};
|
|
2723
|
+
const notes = this.pageNotes[p];
|
|
2724
|
+
/** What follows the text of a column: its endnotes. */
|
|
2725
|
+
const after = (band: number, column: number) => notes?.flow.get(`${band}|${column}`) ?? [];
|
|
2726
|
+
/** A page's children: its header, what it holds, its notes, its footer. */
|
|
2727
|
+
const framed = (list: readonly HTMLElement[]) => [
|
|
2728
|
+
...(header ? [header.element] : []),
|
|
2729
|
+
...list,
|
|
2730
|
+
...(notes?.foot ?? []),
|
|
2731
|
+
...(footer ? [footer.element] : []),
|
|
2732
|
+
];
|
|
2733
|
+
for (const { dom, slot } of onPage) {
|
|
2734
|
+
const position = slot.mark ? "absolute" : "";
|
|
2735
|
+
if (dom.style.position !== position) dom.style.position = position;
|
|
1087
2736
|
}
|
|
1088
|
-
//
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
2737
|
+
// One section in one column: the blocks are the page's children.
|
|
2738
|
+
const last = onPage[onPage.length - 1];
|
|
2739
|
+
if (!last || (!last.slot.band && last.section.columns.widths.length === 1)) {
|
|
2740
|
+
fillElement(
|
|
2741
|
+
page,
|
|
2742
|
+
framed([...onPage.map((item) => item.dom), ...after(0, 0)]),
|
|
2743
|
+
this.viewRemoved,
|
|
2744
|
+
);
|
|
2745
|
+
this.bands.delete(page);
|
|
2746
|
+
continue;
|
|
1094
2747
|
}
|
|
2748
|
+
const known = this.bands.get(page) ?? [];
|
|
2749
|
+
const bands: typeof known = [];
|
|
2750
|
+
for (const { section, slot } of onPage) {
|
|
2751
|
+
if (bands[slot.band]) continue;
|
|
2752
|
+
const key = columnsKey(section.columns);
|
|
2753
|
+
const reused = known[slot.band];
|
|
2754
|
+
bands[slot.band] =
|
|
2755
|
+
reused?.key === key
|
|
2756
|
+
? reused
|
|
2757
|
+
: { key, ...bandElement(host.ownerDocument, section.columns) };
|
|
2758
|
+
}
|
|
2759
|
+
this.bands.set(page, bands);
|
|
2760
|
+
fillElement(page, framed(bands.map((b) => b.band)), this.viewRemoved);
|
|
2761
|
+
bands.forEach((band, b) => {
|
|
2762
|
+
const inBand = onPage.filter((item) => item.slot.band === b);
|
|
2763
|
+
const lead = inBand[0]?.slot.lead;
|
|
2764
|
+
const margin = lead ? `${lead}px` : "";
|
|
2765
|
+
if (band.band.style.marginTop !== margin) band.band.style.marginTop = margin;
|
|
2766
|
+
band.columns.forEach((column, c) => {
|
|
2767
|
+
fillElement(
|
|
2768
|
+
column,
|
|
2769
|
+
[
|
|
2770
|
+
...inBand.filter((item) => item.slot.column === c).map((item) => item.dom),
|
|
2771
|
+
...after(b, c),
|
|
2772
|
+
],
|
|
2773
|
+
this.viewRemoved,
|
|
2774
|
+
);
|
|
2775
|
+
});
|
|
2776
|
+
});
|
|
1095
2777
|
}
|
|
1096
2778
|
// Pages no longer needed and stray DOM in the host: all after the last page by now.
|
|
1097
2779
|
let rest = (this.pages[count - 1] as HTMLElement).nextSibling;
|
|
@@ -1139,7 +2821,7 @@ export class EditorView {
|
|
|
1139
2821
|
|
|
1140
2822
|
private createPage(): HTMLElement {
|
|
1141
2823
|
const page = this.host.ownerDocument.createElement("section");
|
|
1142
|
-
page.className = "foli-page";
|
|
2824
|
+
page.className = this.paged ? "foli-page" : "foli-story-flow";
|
|
1143
2825
|
return page;
|
|
1144
2826
|
}
|
|
1145
2827
|
|
|
@@ -1150,6 +2832,7 @@ export class EditorView {
|
|
|
1150
2832
|
|
|
1151
2833
|
/** The print rules for the document's page setups, written when they change. */
|
|
1152
2834
|
private applyPrintStyles(layout: readonly BlockLayout[]): void {
|
|
2835
|
+
if (!this.paged) return;
|
|
1153
2836
|
const sheets = [...new Set(layout.map((block) => block.sheet))];
|
|
1154
2837
|
const key = [this.lastSheet(), ...sheets].map((sheet) => sheet.css).join("\n");
|
|
1155
2838
|
if (key === this.printKey) return;
|
|
@@ -1163,7 +2846,7 @@ export class EditorView {
|
|
|
1163
2846
|
this.printStyles = parents.map((parent) => {
|
|
1164
2847
|
const style = doc.createElement("style");
|
|
1165
2848
|
style.setAttribute("data-foli-print", "");
|
|
1166
|
-
style.textContent =
|
|
2849
|
+
style.textContent = viewPrintStyles(this.editor.settings, sheets, this.id);
|
|
1167
2850
|
parent.append(style);
|
|
1168
2851
|
return style;
|
|
1169
2852
|
});
|
|
@@ -1173,6 +2856,9 @@ export class EditorView {
|
|
|
1173
2856
|
private invalidateLayout(): void {
|
|
1174
2857
|
this.measures = new WeakMap();
|
|
1175
2858
|
this.flowed = null;
|
|
2859
|
+
this.regionsFor = null;
|
|
2860
|
+
if (this.regions) this.regions.cache = new WeakMap();
|
|
2861
|
+
if (this.notes) this.notes.cache = new WeakMap();
|
|
1176
2862
|
}
|
|
1177
2863
|
|
|
1178
2864
|
/** Re-flows the pages once web fonts have loaded: line heights and wrapping change. */
|
|
@@ -1211,7 +2897,7 @@ export class EditorView {
|
|
|
1211
2897
|
if (!desc || !measured || this.stale.has(desc.node)) continue;
|
|
1212
2898
|
// A hidden host (display: none) reports every block as 0x0: nothing to re-flow.
|
|
1213
2899
|
if (!entry.contentRect.width) continue;
|
|
1214
|
-
scale ??=
|
|
2900
|
+
scale ??= this.scale();
|
|
1215
2901
|
let height = 0;
|
|
1216
2902
|
for (const fragment of desc.fragments) height += fragment.getBoundingClientRect().height;
|
|
1217
2903
|
// A block is measured whole; each fragment of a split one keeps its padding and border,
|
|
@@ -1238,7 +2924,7 @@ export class EditorView {
|
|
|
1238
2924
|
this.relayoutPending = false;
|
|
1239
2925
|
if (this.destroyed) return;
|
|
1240
2926
|
// compositionend flows what a composition kept from moving.
|
|
1241
|
-
if (this.composing) {
|
|
2927
|
+
if (this.composing || this.mount?.view.composing) {
|
|
1242
2928
|
this.unflowed = true;
|
|
1243
2929
|
return;
|
|
1244
2930
|
}
|
|
@@ -1259,16 +2945,17 @@ export class EditorView {
|
|
|
1259
2945
|
}
|
|
1260
2946
|
|
|
1261
2947
|
/**
|
|
1262
|
-
* Whether `node` holds blocks rather than content: the host, a page, or
|
|
1263
|
-
* table, rows and cells.
|
|
2948
|
+
* Whether `node` holds blocks rather than content: the host, a page, a band or column of one,
|
|
2949
|
+
* or a table's wrapper, table, rows and cells.
|
|
1264
2950
|
*/
|
|
1265
2951
|
private holdsBlocks(node: Node): boolean {
|
|
2952
|
+
if (node === this.host || this.pages.includes(node as HTMLElement)) return true;
|
|
2953
|
+
if (node.nodeType !== Node.ELEMENT_NODE) return false;
|
|
2954
|
+
const element = node as Element;
|
|
1266
2955
|
return (
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
(
|
|
1270
|
-
(node as Element).hasAttribute(FRAME_ATTR) &&
|
|
1271
|
-
!(node as Element).closest(`[${REPEATED_ATTR}]`))
|
|
2956
|
+
element.classList.contains(BAND_CLASS) ||
|
|
2957
|
+
element.classList.contains(COLUMN_CLASS) ||
|
|
2958
|
+
(element.hasAttribute(FRAME_ATTR) && !element.closest(`[${REPEATED_ATTR}]`))
|
|
1272
2959
|
);
|
|
1273
2960
|
}
|
|
1274
2961
|
|
|
@@ -1300,7 +2987,7 @@ export class EditorView {
|
|
|
1300
2987
|
const range = host.ownerDocument.createRange();
|
|
1301
2988
|
range.setStart(node, offset);
|
|
1302
2989
|
const posOf = (i: number, f: number) =>
|
|
1303
|
-
f === 0
|
|
2990
|
+
f === 0 || !(this.blocks[i] as BlockDesc).node.isTextblock
|
|
1304
2991
|
? (this.starts[i] as number)
|
|
1305
2992
|
: (this.starts[i] as number) +
|
|
1306
2993
|
1 +
|
|
@@ -1396,6 +3083,7 @@ export class EditorView {
|
|
|
1396
3083
|
private readSelection(): Selection | null {
|
|
1397
3084
|
const sel = this.host.ownerDocument.getSelection();
|
|
1398
3085
|
if (!sel?.anchorNode || !sel.focusNode) return null;
|
|
3086
|
+
if (this.mount?.wrapper.contains(sel.anchorNode)) return null;
|
|
1399
3087
|
// A range around exactly one block leaf element (a rule): the node selection that wrote it.
|
|
1400
3088
|
// (Its end, mapped alone, would be the start of the next block, not the end of the rule.)
|
|
1401
3089
|
if (sel.anchorNode === sel.focusNode && Math.abs(sel.anchorOffset - sel.focusOffset) === 1) {
|
|
@@ -1516,6 +3204,8 @@ export class EditorView {
|
|
|
1516
3204
|
private showSelectedNode(): void {
|
|
1517
3205
|
this.showSelectedCells();
|
|
1518
3206
|
this.showSelectedPicture();
|
|
3207
|
+
this.showSelectedFields();
|
|
3208
|
+
this.drawControls();
|
|
1519
3209
|
const dom = this.selectedBlock()?.dom ?? this.selectedTable();
|
|
1520
3210
|
if (dom === this.selectedDom) return;
|
|
1521
3211
|
this.selectedDom?.classList.remove(SELECTED_CLASS);
|
|
@@ -1544,12 +3234,22 @@ export class EditorView {
|
|
|
1544
3234
|
selection instanceof AllSelection
|
|
1545
3235
|
? TextSelection.between(selection.$anchor, selection.$head)
|
|
1546
3236
|
: selection;
|
|
1547
|
-
|
|
3237
|
+
if (dom.anchor === shown.anchor && dom.head === shown.head) return true;
|
|
3238
|
+
// Field markers take no room, and a control's edge is one place to the browser: the DOM
|
|
3239
|
+
// cannot tell their two sides apart.
|
|
3240
|
+
const { doc } = this.state;
|
|
3241
|
+
const texts = shown instanceof TextSelection && dom instanceof TextSelection;
|
|
3242
|
+
const same = (a: number, b: number) =>
|
|
3243
|
+
controlSpot(doc, a, b) ||
|
|
3244
|
+
(texts && doc.resolve(a).parent.inlineContent && sameSpot(doc, a, b));
|
|
3245
|
+
return same(dom.anchor, shown.anchor) && same(dom.head, shown.head);
|
|
1548
3246
|
}
|
|
1549
3247
|
|
|
1550
3248
|
private hasFocus(): boolean {
|
|
1551
3249
|
const active = this.host.ownerDocument.activeElement;
|
|
1552
|
-
return
|
|
3250
|
+
return (
|
|
3251
|
+
(active === this.host || this.host.contains(active)) && !this.mount?.wrapper.contains(active)
|
|
3252
|
+
);
|
|
1553
3253
|
}
|
|
1554
3254
|
|
|
1555
3255
|
/** Writes the model selection to the DOM unless the DOM already shows it (keeps native affinity). */
|
|
@@ -1599,7 +3299,7 @@ export class EditorView {
|
|
|
1599
3299
|
*/
|
|
1600
3300
|
private dispatch(tr: Transaction): boolean {
|
|
1601
3301
|
const marksAdded = tr.storedMarks !== null && tr.storedMarks !== this.state.storedMarks;
|
|
1602
|
-
if (!this.editable && (tr.docChanged || marksAdded)) return false;
|
|
3302
|
+
if ((!this.editable || this.mount) && (tr.docChanged || marksAdded)) return false;
|
|
1603
3303
|
this.editor.dispatch(tr);
|
|
1604
3304
|
return true;
|
|
1605
3305
|
}
|
|
@@ -1681,14 +3381,34 @@ export class EditorView {
|
|
|
1681
3381
|
this.run(type.endsWith("Forward") ? deleteForward(unit) : deleteBackward(unit));
|
|
1682
3382
|
};
|
|
1683
3383
|
|
|
1684
|
-
/**
|
|
3384
|
+
/**
|
|
3385
|
+
* Runs the first command bound to `name` that applies, through the view's dispatch; the view's
|
|
3386
|
+
* own keys where core's `viewKeys` plugin stands (after the user's plugins, before the
|
|
3387
|
+
* built-in keymaps).
|
|
3388
|
+
*/
|
|
1685
3389
|
private runKey(name: string): boolean {
|
|
1686
3390
|
return this.state.plugins.some((plugin) => {
|
|
3391
|
+
if (plugin.key === viewKeys) return this.viewKey(name);
|
|
1687
3392
|
const command = plugin.spec.keymap?.[name];
|
|
1688
3393
|
return command ? this.run(command) : false;
|
|
1689
3394
|
});
|
|
1690
3395
|
}
|
|
1691
3396
|
|
|
3397
|
+
/**
|
|
3398
|
+
* The view's own overridable keys (ADR-0008, `docs/keyboard.md`): they need the pages, the
|
|
3399
|
+
* stories or the app's navigation UI, so they are not core commands. A user keymap binding the
|
|
3400
|
+
* same name runs first.
|
|
3401
|
+
*/
|
|
3402
|
+
private viewKey(name: string): boolean {
|
|
3403
|
+
return (
|
|
3404
|
+
this.documentEdgeKey(name) ||
|
|
3405
|
+
this.fieldKey(name) ||
|
|
3406
|
+
(name === "Alt-ArrowDown" && this.controlChrome.open()) ||
|
|
3407
|
+
this.noteKey(name) ||
|
|
3408
|
+
this.navigationKey(name)
|
|
3409
|
+
);
|
|
3410
|
+
}
|
|
3411
|
+
|
|
1692
3412
|
// ---------- column borders (10.7c) ----------
|
|
1693
3413
|
|
|
1694
3414
|
/** A column border being dragged: its table and column, the column's width, the press, the guide. */
|
|
@@ -1750,6 +3470,7 @@ export class EditorView {
|
|
|
1750
3470
|
/** The pointer over a column border shows that it can be dragged. */
|
|
1751
3471
|
private onMouseMove = (event: MouseEvent): void => {
|
|
1752
3472
|
if (this.drag) return;
|
|
3473
|
+
if (event.buttons === 0) this.controlChrome.hover(event.target);
|
|
1753
3474
|
const near = event.buttons === 0 && this.columnBorder(event) !== null;
|
|
1754
3475
|
if (near === this.resizeCursor) return;
|
|
1755
3476
|
this.resizeCursor = near;
|
|
@@ -1987,18 +3708,7 @@ export class EditorView {
|
|
|
1987
3708
|
const files = this.imageFiles(event.dataTransfer);
|
|
1988
3709
|
if (!files.length || this.composing) return;
|
|
1989
3710
|
// The place the files were dropped.
|
|
1990
|
-
const
|
|
1991
|
-
caretPositionFromPoint?: (
|
|
1992
|
-
x: number,
|
|
1993
|
-
y: number,
|
|
1994
|
-
) => { offsetNode: Node; offset: number } | null;
|
|
1995
|
-
caretRangeFromPoint?: (x: number, y: number) => Range | null;
|
|
1996
|
-
};
|
|
1997
|
-
const point = doc.caretPositionFromPoint?.(event.clientX, event.clientY);
|
|
1998
|
-
const range = point ? null : doc.caretRangeFromPoint?.(event.clientX, event.clientY);
|
|
1999
|
-
const node = point?.offsetNode ?? range?.startContainer;
|
|
2000
|
-
const offset = point?.offset ?? range?.startOffset ?? 0;
|
|
2001
|
-
const pos = node ? this.posFromDOM(node, offset) : null;
|
|
3711
|
+
const pos = this.posAtPoint(event.clientX, event.clientY);
|
|
2002
3712
|
if (pos !== null)
|
|
2003
3713
|
this.dispatch(this.state.tr.setSelection(TextSelection.near(this.state.doc.resolve(pos))));
|
|
2004
3714
|
void this.insertFiles(files);
|
|
@@ -2106,6 +3816,19 @@ export class EditorView {
|
|
|
2106
3816
|
}
|
|
2107
3817
|
return;
|
|
2108
3818
|
}
|
|
3819
|
+
// Word's blank page before an even or odd page section holds nothing: the caret goes to the
|
|
3820
|
+
// section after it (the browser would put it at the document's start).
|
|
3821
|
+
const blank = event.target as HTMLElement;
|
|
3822
|
+
if (!event.shiftKey && this.pages.includes(blank) && !blank.firstChild) {
|
|
3823
|
+
const pos = this.posFromDOM(blank, 0);
|
|
3824
|
+
if (pos !== null) {
|
|
3825
|
+
event.preventDefault();
|
|
3826
|
+
if (!this.hasFocus()) this.host.focus({ preventScroll: true });
|
|
3827
|
+
this.dispatch(this.state.tr.setSelection(Selection.near(this.state.doc.resolve(pos))));
|
|
3828
|
+
this.writeSelection(true);
|
|
3829
|
+
}
|
|
3830
|
+
return;
|
|
3831
|
+
}
|
|
2109
3832
|
const element = this.blockElement(event.target as Node | null);
|
|
2110
3833
|
const owner = element ? this.owner.get(element) : undefined;
|
|
2111
3834
|
const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
|
|
@@ -2134,6 +3857,7 @@ export class EditorView {
|
|
|
2134
3857
|
*/
|
|
2135
3858
|
private onClick = (event: MouseEvent): void => {
|
|
2136
3859
|
const target = event.target;
|
|
3860
|
+
if (event.type === "click" && !event.shiftKey && this.controlChrome.click(event)) return;
|
|
2137
3861
|
const element = target instanceof Element ? target.closest("a") : null;
|
|
2138
3862
|
if (!element || !this.host.contains(element)) return;
|
|
2139
3863
|
event.preventDefault();
|
|
@@ -2154,13 +3878,30 @@ export class EditorView {
|
|
|
2154
3878
|
}
|
|
2155
3879
|
|
|
2156
3880
|
private onKeyDown = (event: KeyboardEvent): void => {
|
|
3881
|
+
// The host itself focused while a story is open (Shift+Tab): it is read-only, and its selection
|
|
3882
|
+
// is what leaving the story comes back to.
|
|
3883
|
+
if (this.mount) {
|
|
3884
|
+
if (event.key === "Escape") {
|
|
3885
|
+
event.preventDefault();
|
|
3886
|
+
this.closeStory(true);
|
|
3887
|
+
}
|
|
3888
|
+
return;
|
|
3889
|
+
}
|
|
2157
3890
|
if (event.isComposing || this.composing) return;
|
|
2158
3891
|
this.syncSelection();
|
|
2159
3892
|
if (this.crossFragmentEdge(event) || this.crossListNumber(event)) {
|
|
2160
3893
|
event.preventDefault();
|
|
2161
3894
|
return;
|
|
2162
3895
|
}
|
|
3896
|
+
if (this.skipFieldParts(event)) {
|
|
3897
|
+
event.preventDefault();
|
|
3898
|
+
return;
|
|
3899
|
+
}
|
|
2163
3900
|
const name = keyName(event);
|
|
3901
|
+
if (this.controlKey(name)) {
|
|
3902
|
+
event.preventDefault();
|
|
3903
|
+
return;
|
|
3904
|
+
}
|
|
2164
3905
|
// Ctrl/Cmd+Shift+V: the paste event that follows uses only the plain text.
|
|
2165
3906
|
this.plainPaste = name === "Mod-Shift-v";
|
|
2166
3907
|
// Tab and Shift+Tab move the focus on in read-only mode, and right after Escape where Tab
|
|
@@ -2213,6 +3954,30 @@ export class EditorView {
|
|
|
2213
3954
|
}
|
|
2214
3955
|
};
|
|
2215
3956
|
|
|
3957
|
+
/** Word's keys for notes, and Shift+Alt+N from a reference to its note. */
|
|
3958
|
+
private noteKey(name: string): boolean {
|
|
3959
|
+
if (name === NOTE_KEY) return this.openNote();
|
|
3960
|
+
const kind = name === "Mod-Alt-f" ? "footnote" : name === "Mod-Alt-d" ? "endnote" : null;
|
|
3961
|
+
if (!kind || !this.editable || !this.notes) return false;
|
|
3962
|
+
return this.run(insertNote(kind)) && this.openNote();
|
|
3963
|
+
}
|
|
3964
|
+
|
|
3965
|
+
/**
|
|
3966
|
+
* Ctrl+Home and Ctrl+End (with Shift, extending) on pages with headers and footers: the browser
|
|
3967
|
+
* stops at the first or last place before what it cannot edit, so the model says where.
|
|
3968
|
+
*/
|
|
3969
|
+
private documentEdgeKey(name: string): boolean {
|
|
3970
|
+
const shift = name.startsWith("Mod-Shift-");
|
|
3971
|
+
const key = name.replace("Mod-Shift-", "Mod-");
|
|
3972
|
+
if ((key !== "Mod-Home" && key !== "Mod-End") || !this.editable) return false;
|
|
3973
|
+
if (!this.pageRegions.some((page) => page.header || page.footer)) return false;
|
|
3974
|
+
const { doc, selection } = this.state;
|
|
3975
|
+
const edge = key === "Mod-Home" ? Selection.atStart(doc) : Selection.atEnd(doc);
|
|
3976
|
+
const next = shift ? TextSelection.between(selection.$anchor, edge.$head) : edge;
|
|
3977
|
+
this.dispatch(this.state.tr.setSelection(next).setStoredMarks(null));
|
|
3978
|
+
return true;
|
|
3979
|
+
}
|
|
3980
|
+
|
|
2216
3981
|
/**
|
|
2217
3982
|
* Whether the caret is on the first (`dir` -1) or last (1) line of its textblock, in the
|
|
2218
3983
|
* block's first or last fragment (a block split across pages has several).
|
|
@@ -2347,9 +4112,10 @@ export class EditorView {
|
|
|
2347
4112
|
* and so is the scroll position.
|
|
2348
4113
|
*/
|
|
2349
4114
|
private onFocus = (): void => {
|
|
4115
|
+
this.claimStories();
|
|
2350
4116
|
const pointer = this.pointerFocus;
|
|
2351
4117
|
this.pointerFocus = false;
|
|
2352
|
-
if (pointer) return;
|
|
4118
|
+
if (pointer || this.mount) return;
|
|
2353
4119
|
const current = this.readSelection();
|
|
2354
4120
|
if (current && this.shows(current)) return;
|
|
2355
4121
|
this.writeSelection(true);
|
|
@@ -2363,13 +4129,16 @@ export class EditorView {
|
|
|
2363
4129
|
};
|
|
2364
4130
|
|
|
2365
4131
|
private onMutations = (records: MutationRecord[]): void => {
|
|
2366
|
-
this.pending.push(...records.filter((r) => !handleOnly(r)));
|
|
4132
|
+
this.pending.push(...records.filter((r) => !handleOnly(r) && !inNodeView(r)));
|
|
2367
4133
|
if (!this.composing && this.pending.length) this.flush();
|
|
2368
4134
|
};
|
|
2369
4135
|
|
|
2370
4136
|
/** Reads back every DOM change recorded so far. */
|
|
2371
4137
|
private flush(): void {
|
|
2372
|
-
const records = [
|
|
4138
|
+
const records = [
|
|
4139
|
+
...this.pending,
|
|
4140
|
+
...this.observer.takeRecords().filter((r) => !handleOnly(r) && !inNodeView(r)),
|
|
4141
|
+
];
|
|
2373
4142
|
this.pending = [];
|
|
2374
4143
|
if (records.length) this.readBack(records);
|
|
2375
4144
|
}
|
|
@@ -2529,6 +4298,37 @@ export class EditorView {
|
|
|
2529
4298
|
|
|
2530
4299
|
// ---------- clipboard ----------
|
|
2531
4300
|
|
|
4301
|
+
/**
|
|
4302
|
+
* A copied picture's image as another document can show and save it: its own `data:` or web
|
|
4303
|
+
* URL, else the image this view shows, as a `data:` URL (read from the drawn image when it is
|
|
4304
|
+
* an object URL: its bytes live in this page only). Nothing lasting known (an image not loaded
|
|
4305
|
+
* yet): as it is, and the paste brings the picture without its image.
|
|
4306
|
+
*/
|
|
4307
|
+
private portableResource(context: WordContext) {
|
|
4308
|
+
const shown = imageSource(context.envelope.resources, this.resource ?? undefined);
|
|
4309
|
+
return (key: string, resource: ResourceJSON): ResourceJSON => {
|
|
4310
|
+
if (resource.data !== undefined || /^https?:/i.test(resource.url ?? "")) return resource;
|
|
4311
|
+
const url = shown(key);
|
|
4312
|
+
if (url?.startsWith("data:image/")) return { contentType: resource.contentType, data: url };
|
|
4313
|
+
const img = [...this.host.querySelectorAll(`img[${PICTURE_ATTR}]`)].find(
|
|
4314
|
+
(element) => element.getAttribute(PICTURE_ATTR) === key,
|
|
4315
|
+
) as HTMLImageElement | undefined;
|
|
4316
|
+
if (img?.complete && img.naturalWidth > 0) {
|
|
4317
|
+
try {
|
|
4318
|
+
const canvas = this.host.ownerDocument.createElement("canvas");
|
|
4319
|
+
canvas.width = img.naturalWidth;
|
|
4320
|
+
canvas.height = img.naturalHeight;
|
|
4321
|
+
canvas.getContext("2d")?.drawImage(img, 0, 0);
|
|
4322
|
+
// PNG: the browser's encoding, the same pixels (JPEG's own bytes cannot be read here).
|
|
4323
|
+
return { contentType: "image/png", data: canvas.toDataURL("image/png") };
|
|
4324
|
+
} catch {} // a cross-origin image taints the canvas: keep what is known
|
|
4325
|
+
}
|
|
4326
|
+
// An image the page shows over the web lasts; an object URL does not (the paste then comes
|
|
4327
|
+
// without its image).
|
|
4328
|
+
return url && /^https?:/i.test(url) ? { contentType: resource.contentType, url } : resource;
|
|
4329
|
+
};
|
|
4330
|
+
}
|
|
4331
|
+
|
|
2532
4332
|
/** Copy writes the model's content (plain text, HTML, Foli JSON), never the browser's DOM. */
|
|
2533
4333
|
private onCopy = (event: ClipboardEvent): void => {
|
|
2534
4334
|
this.syncSelection();
|
|
@@ -2544,7 +4344,7 @@ export class EditorView {
|
|
|
2544
4344
|
table ? 0 : selection.from,
|
|
2545
4345
|
table ? source.content.size : selection.to,
|
|
2546
4346
|
this.host.ownerDocument,
|
|
2547
|
-
{ context, ratio: this.lineRatio },
|
|
4347
|
+
{ context, ratio: this.lineRatio, portable: this.portableResource(context) },
|
|
2548
4348
|
);
|
|
2549
4349
|
event.clipboardData.setData("text/plain", table ? cellsText(table) : text);
|
|
2550
4350
|
event.clipboardData.setData("text/html", html);
|
|
@@ -2590,6 +4390,9 @@ export class EditorView {
|
|
|
2590
4390
|
*/
|
|
2591
4391
|
paste(data: Pick<DataTransfer, "getData">, autolink = true): boolean {
|
|
2592
4392
|
const { state } = this;
|
|
4393
|
+
// A text control takes the text alone.
|
|
4394
|
+
const plainText = data.getData("text/plain");
|
|
4395
|
+
if (plainText && this.run(insertControlText(plainText))) return true;
|
|
2593
4396
|
const text = autolink && !data.getData(FOLI_MIME) ? data.getData("text/plain") : "";
|
|
2594
4397
|
const href = text ? autolinkHref(text) : null;
|
|
2595
4398
|
if (href) {
|
|
@@ -2618,7 +4421,7 @@ export class EditorView {
|
|
|
2618
4421
|
// One empty paragraph: nothing to paste (a lone opaque block is something).
|
|
2619
4422
|
const only = pasted?.doc.childCount === 1 ? pasted.doc.firstChild : null;
|
|
2620
4423
|
if (!pasted || (only?.isTextblock && !only.content.size)) return false;
|
|
2621
|
-
const { doc, open, envelope } = pasted;
|
|
4424
|
+
const { doc, open, envelope, notes } = pasted;
|
|
2622
4425
|
// As a slice (text joins the text around the caret); where that cannot be (an opaque block
|
|
2623
4426
|
// at an end), as whole blocks at the caret.
|
|
2624
4427
|
const asSlice = (tr: Transaction) => {
|
|
@@ -2659,6 +4462,7 @@ export class EditorView {
|
|
|
2659
4462
|
withEnvelope(tr, envelope);
|
|
2660
4463
|
setComments(tr, current.comments, envelope.comments);
|
|
2661
4464
|
}
|
|
4465
|
+
for (const { id, story } of notes ?? []) tr.step(new StoryStep(id, null, story));
|
|
2662
4466
|
} catch (error) {
|
|
2663
4467
|
if (error instanceof TransformError) continue;
|
|
2664
4468
|
throw error;
|
|
@@ -2669,7 +4473,7 @@ export class EditorView {
|
|
|
2669
4473
|
}
|
|
2670
4474
|
|
|
2671
4475
|
private onSelectionChange = (): void => {
|
|
2672
|
-
if (!this.composing && this.hasFocus()) this.syncSelection();
|
|
4476
|
+
if (!this.composing && !this.mount && this.hasFocus()) this.syncSelection();
|
|
2673
4477
|
};
|
|
2674
4478
|
}
|
|
2675
4479
|
|
|
@@ -2715,7 +4519,10 @@ function layoutScale(page: HTMLElement, settings: DocumentSettings): number {
|
|
|
2715
4519
|
return page.getBoundingClientRect().width / (settings.pageSize.width * PX_PER_MM) || 1;
|
|
2716
4520
|
}
|
|
2717
4521
|
|
|
2718
|
-
/**
|
|
4522
|
+
/**
|
|
4523
|
+
* A block's measurement: border-box height across its fragments (layout px), margins, lines.
|
|
4524
|
+
* @internal
|
|
4525
|
+
*/
|
|
2719
4526
|
export interface Measure {
|
|
2720
4527
|
height: number;
|
|
2721
4528
|
marginTop: number;
|
|
@@ -2723,10 +4530,19 @@ export interface Measure {
|
|
|
2723
4530
|
/** Vertical padding and border, which every fragment of a split block repeats. */
|
|
2724
4531
|
box: number;
|
|
2725
4532
|
lines?: Lines;
|
|
4533
|
+
/** At the widths of columns it may land in, when a section's columns differ. */
|
|
4534
|
+
widths?: Map<number, WidthMeasure>;
|
|
2726
4535
|
/** A table's rows and blocks. */
|
|
2727
4536
|
table?: TableMeasure;
|
|
2728
4537
|
}
|
|
2729
4538
|
|
|
4539
|
+
/** A block measured at a width other than where it is. */
|
|
4540
|
+
interface WidthMeasure {
|
|
4541
|
+
height: number;
|
|
4542
|
+
lines(): readonly number[];
|
|
4543
|
+
all(): Lines;
|
|
4544
|
+
}
|
|
4545
|
+
|
|
2730
4546
|
/** The innermost cell around pos (the position before it) and its table's, or null. */
|
|
2731
4547
|
function cellAround(doc: ModelNode, pos: number): { cell: number; table: number } | null {
|
|
2732
4548
|
const $pos = doc.resolve(pos);
|
|
@@ -2787,6 +4603,7 @@ function measureTable(
|
|
|
2787
4603
|
* at its cells' line ends, unless the row may not split (`cantSplit`, unless taller than a
|
|
2788
4604
|
* page), is part of a vertical merge or holds a nested table (shortcut: those split only
|
|
2789
4605
|
* between rows; a nested table stays whole within its row).
|
|
4606
|
+
* @internal
|
|
2790
4607
|
*/
|
|
2791
4608
|
export function breaksOf(
|
|
2792
4609
|
frame: Frame,
|
|
@@ -2848,6 +4665,7 @@ function tableBox(
|
|
|
2848
4665
|
* A flowed table cut into its fragments: the rows each shows (a row split across pages in
|
|
2849
4666
|
* both), the header rows drawn again above a continuation, the fragment of the table each
|
|
2850
4667
|
* block's fragments go in, and where a block of a split row splits (content offsets).
|
|
4668
|
+
* @internal
|
|
2851
4669
|
*/
|
|
2852
4670
|
export function cutTable(
|
|
2853
4671
|
frame: Frame,
|
|
@@ -2937,8 +4755,8 @@ function measureBox(desc: BlockDesc, scale: number): Measure {
|
|
|
2937
4755
|
/**
|
|
2938
4756
|
* What the flow needs of a block: its measurement, its lines (on demand), Word's spacing before
|
|
2939
4757
|
* and after (next to its neighbours), keep with next, keep lines together (not for a block
|
|
2940
|
-
* taller than a page, or one with a
|
|
2941
|
-
* and a page break before the next block ending this one's page.
|
|
4758
|
+
* taller than a page, or one with a break in it), page and column breaks ending their line's
|
|
4759
|
+
* page or column, and a page break before the next block ending this one's page.
|
|
2942
4760
|
*/
|
|
2943
4761
|
function wordBox(
|
|
2944
4762
|
words: readonly WordInfo[],
|
|
@@ -2947,63 +4765,115 @@ function wordBox(
|
|
|
2947
4765
|
measure: Measure,
|
|
2948
4766
|
lines: () => Lines,
|
|
2949
4767
|
layout: BlockLayout,
|
|
4768
|
+
atWidth: (desc: BlockDesc, width: number, kept: boolean) => WidthMeasure,
|
|
4769
|
+
adds: boolean,
|
|
4770
|
+
noteOf: (story: string) => FlowNote | null,
|
|
2950
4771
|
): BlockBox {
|
|
2951
4772
|
const pageHeight = contentHeight(layout.sheet.settings);
|
|
4773
|
+
const { section } = layout;
|
|
4774
|
+
// Without pages nothing is kept off the next one, and a page break ends nothing.
|
|
4775
|
+
const paged = layout.sheet.css !== UNPAGED_CSS;
|
|
2952
4776
|
const next = words[i + 1] ? { word: words[i + 1] as WordInfo } : undefined;
|
|
2953
|
-
const { before, after } = spacing(words[i - 1], desc.word, next?.word);
|
|
2954
|
-
const
|
|
2955
|
-
(
|
|
2956
|
-
leaf.dom.nodeType !== Node.TEXT_NODE && (leaf.dom as Element).hasAttribute(
|
|
2957
|
-
|
|
2958
|
-
const
|
|
2959
|
-
const
|
|
4777
|
+
const { before, after } = spacing(words[i - 1], desc.word, next?.word, adds);
|
|
4778
|
+
const leavesWith = (attr: string) =>
|
|
4779
|
+
desc.leaves.filter(
|
|
4780
|
+
(leaf) => leaf.dom.nodeType !== Node.TEXT_NODE && (leaf.dom as Element).hasAttribute(attr),
|
|
4781
|
+
);
|
|
4782
|
+
const pageBreaks = leavesWith(PAGE_BREAK_ATTR);
|
|
4783
|
+
const columnBreaks = leavesWith(WORD_COLUMN_BREAK_ATTR);
|
|
4784
|
+
const hasBreak = pageBreaks.length + columnBreaks.length > 0;
|
|
4785
|
+
const keep = desc.word.keepLines && !hasBreak;
|
|
4786
|
+
const kept = keep && measure.height <= pageHeight;
|
|
2960
4787
|
const bottoms = () => (kept ? [measure.height] : lines().bottoms);
|
|
4788
|
+
/** The block as it is in `column`, when the columns' widths differ. */
|
|
4789
|
+
const inColumn = (column: number) =>
|
|
4790
|
+
atWidth(desc, section.columns.widths[column] as number, keep);
|
|
4791
|
+
// The line holding a break, among the column's lines: the last starting at or before it.
|
|
4792
|
+
const linesOf = (leaves: readonly LeafDesc[], column = 0) => {
|
|
4793
|
+
if (!leaves.length) return [];
|
|
4794
|
+
const { starts } = section.unequal ? inColumn(column).all() : lines();
|
|
4795
|
+
return leaves.map((leaf) => {
|
|
4796
|
+
let line = starts.length - 1;
|
|
4797
|
+
while (line > 0 && (starts[line] as number) > leaf.offset) line--;
|
|
4798
|
+
return line;
|
|
4799
|
+
});
|
|
4800
|
+
};
|
|
4801
|
+
const references = referencesIn(desc.node);
|
|
4802
|
+
const notes = references.flatMap((ref) => {
|
|
4803
|
+
const note = noteOf(ref.story);
|
|
4804
|
+
return note ? [{ note, offset: ref.offset - 1 }] : [];
|
|
4805
|
+
});
|
|
2961
4806
|
return {
|
|
4807
|
+
notes: notes.length
|
|
4808
|
+
? (column) => {
|
|
4809
|
+
if (kept) return notes.map(({ note }) => ({ line: 0, note }));
|
|
4810
|
+
const { starts } = section.unequal ? inColumn(column).all() : lines();
|
|
4811
|
+
return notes.map(({ note, offset }) => {
|
|
4812
|
+
let line = starts.length - 1;
|
|
4813
|
+
while (line > 0 && (starts[line] as number) > offset) line--;
|
|
4814
|
+
return { line, note };
|
|
4815
|
+
});
|
|
4816
|
+
}
|
|
4817
|
+
: undefined,
|
|
2962
4818
|
height: measure.height,
|
|
2963
4819
|
marginTop: before,
|
|
2964
4820
|
marginBottom: after,
|
|
2965
4821
|
keepWithNext: desc.word.keepNext,
|
|
4822
|
+
// A node view's parts are not lines: no widow or orphan control.
|
|
4823
|
+
anyLine: !!desc.parts,
|
|
2966
4824
|
pageHeight,
|
|
4825
|
+
section: section.flow,
|
|
4826
|
+
sectionMark: !!desc.node.attrs.section && desc.word.empty,
|
|
4827
|
+
inColumn: section.unequal ? inColumn : undefined,
|
|
2967
4828
|
lines: bottoms,
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
return line;
|
|
2975
|
-
});
|
|
2976
|
-
if (next?.word.pageBreakBefore || layout.breakAfter) breaks.push(bottoms().length - 1);
|
|
4829
|
+
columnBreaksAfter: (column) => linesOf(columnBreaks, column),
|
|
4830
|
+
breaksAfter: (column = 0) => {
|
|
4831
|
+
if (!paged) return [];
|
|
4832
|
+
const breaks = linesOf(pageBreaks, column);
|
|
4833
|
+
if (next?.word.pageBreakBefore)
|
|
4834
|
+
breaks.push((section.unequal ? inColumn(column).lines() : bottoms()).length - 1);
|
|
2977
4835
|
return breaks;
|
|
2978
4836
|
},
|
|
2979
4837
|
};
|
|
2980
4838
|
}
|
|
2981
4839
|
|
|
4840
|
+
/** The footnotes a table refers to, each on the break at or after its reference's line. */
|
|
4841
|
+
function tableNotes(
|
|
4842
|
+
frame: Frame,
|
|
4843
|
+
measure: Measure,
|
|
4844
|
+
blocks: readonly WordBlockDesc[],
|
|
4845
|
+
lines: (desc: BlockDesc) => Lines,
|
|
4846
|
+
breaks: () => number[],
|
|
4847
|
+
noteOf: (story: string) => FlowNote | null,
|
|
4848
|
+
): BlockBox["notes"] {
|
|
4849
|
+
const t = measure.table as TableMeasure;
|
|
4850
|
+
const found: { note: FlowNote; unit: number; offset: number }[] = [];
|
|
4851
|
+
for (let unit = frame.first; unit < frame.end; unit++)
|
|
4852
|
+
for (const ref of referencesIn((blocks[unit] as WordBlockDesc).node)) {
|
|
4853
|
+
const note = noteOf(ref.story);
|
|
4854
|
+
if (note && t.tops.get(unit) != null) found.push({ note, unit, offset: ref.offset - 1 });
|
|
4855
|
+
}
|
|
4856
|
+
if (!found.length) return undefined;
|
|
4857
|
+
return () => {
|
|
4858
|
+
const list = breaks();
|
|
4859
|
+
return found.map(({ note, unit, offset }) => {
|
|
4860
|
+
const { starts, bottoms } = lines(blocks[unit] as WordBlockDesc);
|
|
4861
|
+
let k = starts.length - 1;
|
|
4862
|
+
while (k > 0 && (starts[k] as number) > offset) k--;
|
|
4863
|
+
const y = (t.tops.get(unit) as number) + (bottoms[k] as number);
|
|
4864
|
+
const line = list.findIndex((b) => b >= y - 0.5);
|
|
4865
|
+
return { line: line < 0 ? list.length - 1 : line, note };
|
|
4866
|
+
});
|
|
4867
|
+
};
|
|
4868
|
+
}
|
|
4869
|
+
|
|
2982
4870
|
/**
|
|
2983
|
-
* Writes Word's space above each v3 block as
|
|
2984
|
-
*
|
|
2985
|
-
* and only on the first page or after an explicit break (a page the text flowed onto drops it).
|
|
2986
|
-
* Written only when it changes.
|
|
4871
|
+
* Writes Word's space above each v3 block, as the flow worked it out, as its top margin. Written
|
|
4872
|
+
* only when it changes.
|
|
2987
4873
|
*/
|
|
2988
|
-
function applyGaps(
|
|
2989
|
-
firsts: readonly HTMLElement[],
|
|
2990
|
-
pages: readonly (readonly number[])[],
|
|
2991
|
-
boxes: readonly BlockBox[],
|
|
2992
|
-
): void {
|
|
4874
|
+
function applyGaps(firsts: readonly HTMLElement[], spaces: readonly number[]): void {
|
|
2993
4875
|
firsts.forEach((dom, i) => {
|
|
2994
|
-
const
|
|
2995
|
-
const above = pages[i - 1];
|
|
2996
|
-
const box = boxes[i] as BlockBox;
|
|
2997
|
-
let gap: number;
|
|
2998
|
-
if (above && above[above.length - 1] === page)
|
|
2999
|
-
gap = (boxes[i - 1] as BlockBox).marginBottom + box.marginTop;
|
|
3000
|
-
else {
|
|
3001
|
-
const prior = boxes[i - 1];
|
|
3002
|
-
const breaks = prior?.breaksAfter?.() ?? [];
|
|
3003
|
-
const forced =
|
|
3004
|
-
page === 0 || (!!prior && breaks.length > 0 && breaks.includes(prior.lines().length - 1));
|
|
3005
|
-
gap = forced ? box.marginTop : 0;
|
|
3006
|
-
}
|
|
4876
|
+
const gap = spaces[i] ?? 0;
|
|
3007
4877
|
if (gaps.get(dom) === gap) return;
|
|
3008
4878
|
gaps.set(dom, gap);
|
|
3009
4879
|
dom.style.marginTop = `${gap}px`;
|
|
@@ -3046,6 +4916,7 @@ function reuseOf(
|
|
|
3046
4916
|
};
|
|
3047
4917
|
}
|
|
3048
4918
|
|
|
4919
|
+
/** @internal */
|
|
3049
4920
|
export interface Lines {
|
|
3050
4921
|
/** Content offset where each line starts. */
|
|
3051
4922
|
starts: number[];
|
|
@@ -3081,6 +4952,8 @@ function measureLines(desc: BlockDesc, scale: number): Lines {
|
|
|
3081
4952
|
if (!fragment.contains(leaf.dom)) continue;
|
|
3082
4953
|
if (leaf.dom.nodeType !== Node.TEXT_NODE) {
|
|
3083
4954
|
const br = leaf.dom as Element;
|
|
4955
|
+
// A raised number says nothing about where its line is.
|
|
4956
|
+
if (br.hasAttribute(NOTE_NUMBER_ATTR)) continue;
|
|
3084
4957
|
items.push({ offset: leaf.offset, rect: () => br.getBoundingClientRect() });
|
|
3085
4958
|
continue;
|
|
3086
4959
|
}
|
|
@@ -3105,6 +4978,16 @@ function measureLines(desc: BlockDesc, scale: number): Lines {
|
|
|
3105
4978
|
)
|
|
3106
4979
|
items.push({ offset: desc.node.content.size, rect: () => tail.getBoundingClientRect() });
|
|
3107
4980
|
const from = f ? (desc.splits[f - 1] as number) : 0;
|
|
4981
|
+
const parts = (desc as WordBlockDesc).parts;
|
|
4982
|
+
if (!items.length && parts && desc.fragments.length === 1) {
|
|
4983
|
+
// A node view drawn whole: it may break after each of its root's children.
|
|
4984
|
+
for (const bottom of parts()) {
|
|
4985
|
+
starts.push(0);
|
|
4986
|
+
bottoms.push(bottom / scale);
|
|
4987
|
+
}
|
|
4988
|
+
base += box.height;
|
|
4989
|
+
continue;
|
|
4990
|
+
}
|
|
3108
4991
|
if (!items.length) {
|
|
3109
4992
|
starts.push(from);
|
|
3110
4993
|
bottoms.push((base + box.height) / scale);
|
|
@@ -3185,7 +5068,7 @@ function clusterBoundary(doc: ModelNode, pos: number, forward: boolean): number
|
|
|
3185
5068
|
* Scrolls every scrollable ancestor of `from`, then the window, so that `rect` is inside its
|
|
3186
5069
|
* visible area (minus `scroll-padding`, e.g. for a sticky toolbar). Vertical only: text wraps.
|
|
3187
5070
|
*/
|
|
3188
|
-
function scrollRectIntoView(from: HTMLElement, rect: DOMRect): void {
|
|
5071
|
+
function scrollRectIntoView(from: HTMLElement, rect: Pick<DOMRect, "top" | "bottom">): void {
|
|
3189
5072
|
const doc = from.ownerDocument;
|
|
3190
5073
|
const win = doc.defaultView;
|
|
3191
5074
|
if (!win) return;
|
|
@@ -3213,6 +5096,26 @@ function scrollRectIntoView(from: HTMLElement, rect: DOMRect): void {
|
|
|
3213
5096
|
if (move) win.scrollBy(0, move);
|
|
3214
5097
|
}
|
|
3215
5098
|
|
|
5099
|
+
const SCROLL_OPTIONS = { capture: true, passive: true };
|
|
5100
|
+
/** Room kept above what is scrolled to for find, in px. */
|
|
5101
|
+
const REVEAL_ABOVE = 200;
|
|
5102
|
+
|
|
5103
|
+
/** Word's keys for finding and going places. */
|
|
5104
|
+
const NAVIGATION_KEYS: Readonly<Record<string, NavigationRequest>> = {
|
|
5105
|
+
"Mod-f": "find",
|
|
5106
|
+
"Mod-h": "replace",
|
|
5107
|
+
"Mod-g": "goTo",
|
|
5108
|
+
F3: "next",
|
|
5109
|
+
"Shift-F3": "previous",
|
|
5110
|
+
"Mod-Shift-F5": "bookmarks",
|
|
5111
|
+
};
|
|
5112
|
+
|
|
5113
|
+
/** Shift+Alt+N (Shift+Option+N): from a note's reference to the note, and back. */
|
|
5114
|
+
const NOTE_KEY = "Alt-Shift-n";
|
|
5115
|
+
|
|
5116
|
+
/** Whether story `id` of `state`'s document exists (a number can outlive its note on screen). */
|
|
5117
|
+
const isNoteStory = (state: EditorState, id: string) => !!wordContext(state)?.stories.has(id);
|
|
5118
|
+
|
|
3216
5119
|
function before(node: Node): DomPoint {
|
|
3217
5120
|
const parent = node.parentNode as Node;
|
|
3218
5121
|
return { node: parent, offset: Array.prototype.indexOf.call(parent.childNodes, node) };
|
|
@@ -3243,7 +5146,22 @@ export function keyName(event: KeyboardEvent): string {
|
|
|
3243
5146
|
const mod = IS_MAC ? event.metaKey : event.ctrlKey;
|
|
3244
5147
|
// Non-Latin layouts: Ctrl+B still means "b" (use the physical key when the character is not a-z);
|
|
3245
5148
|
// with Shift, Ctrl+Shift+7 still means "7" (the character is "&" or "/" depending on layout).
|
|
3246
|
-
|
|
5149
|
+
// Option on macOS types a character (Option+N is a dead key): Alt+N still means "n". But AltGr
|
|
5150
|
+
// (Ctrl+Alt on Windows) typing a character is that character: "[" is AltGr+F on a Hungarian
|
|
5151
|
+
// layout, and must not be read as Ctrl+Alt+F (a footnote).
|
|
5152
|
+
// (macOS has no AltGr: some browsers report Option as AltGraph, and Option is handled above.)
|
|
5153
|
+
// shortcut: Ctrl+Alt giving any other character counts as AltGr (not all browsers report its
|
|
5154
|
+
// state), so Ctrl+Alt+F on a non-Latin layout is not Mod-Alt-f; drop the guess if they all do.
|
|
5155
|
+
const altGraph =
|
|
5156
|
+
!IS_MAC &&
|
|
5157
|
+
(event.getModifierState?.("AltGraph") ||
|
|
5158
|
+
(event.ctrlKey && event.altKey && key.length === 1 && !/^[a-z0-9]$/i.test(key)));
|
|
5159
|
+
if (
|
|
5160
|
+
(mod || event.altKey) &&
|
|
5161
|
+
!altGraph &&
|
|
5162
|
+
!/^[a-z0-9]$/.test(key) &&
|
|
5163
|
+
/^(Key[A-Z]|Digit[0-9])$/.test(event.code)
|
|
5164
|
+
)
|
|
3247
5165
|
key = event.code.slice(-1).toLowerCase();
|
|
3248
5166
|
let name = key;
|
|
3249
5167
|
if (event.shiftKey && key !== "Shift") name = `Shift-${name}`;
|
|
@@ -3316,12 +5234,27 @@ function holdsFloat(node: ModelNode): boolean {
|
|
|
3316
5234
|
return found;
|
|
3317
5235
|
}
|
|
3318
5236
|
|
|
3319
|
-
/**
|
|
5237
|
+
/**
|
|
5238
|
+
* A change a node view made to its own drawing (content loaded later, a chart drawn): not input,
|
|
5239
|
+
* never read back. Inside a custom node's box, which is not editable.
|
|
5240
|
+
*/
|
|
5241
|
+
function inNodeView(record: MutationRecord): boolean {
|
|
5242
|
+
const { target } = record;
|
|
5243
|
+
const element = target.nodeType === 1 ? (target as Element) : target.parentElement;
|
|
5244
|
+
return !!element?.closest('[data-foli-custom][contenteditable="false"]');
|
|
5245
|
+
}
|
|
5246
|
+
|
|
5247
|
+
/** A change that only adds or removes the view's own marks (a resize handle, a control's frame). */
|
|
3320
5248
|
function handleOnly(record: MutationRecord): boolean {
|
|
3321
5249
|
const nodes = [...record.addedNodes, ...record.removedNodes];
|
|
3322
5250
|
return (
|
|
3323
5251
|
record.type === "childList" &&
|
|
3324
5252
|
nodes.length > 0 &&
|
|
3325
|
-
nodes.every(
|
|
5253
|
+
nodes.every(
|
|
5254
|
+
(n) =>
|
|
5255
|
+
n.nodeType === 1 &&
|
|
5256
|
+
((n as Element).hasAttribute("data-foli-resize") ||
|
|
5257
|
+
(n as Element).hasAttribute(CONTROL_UI_ATTR)),
|
|
5258
|
+
)
|
|
3326
5259
|
);
|
|
3327
5260
|
}
|