@a200888213/gbdocx 0.6.1 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/package.json +1 -1
  2. package/src/app/file-io.js +122 -122
  3. package/src/app/main.js +9 -9
  4. package/src/app/word/catalog.js +52 -52
  5. package/src/app/word/comments.js +112 -112
  6. package/src/app/word/doc.js +113 -113
  7. package/src/app/word/edit.js +72 -72
  8. package/src/app/word/hf.js +76 -76
  9. package/src/app/word/layout.js +155 -155
  10. package/src/app/word/notes.js +110 -110
  11. package/src/app/word/shared.js +22 -22
  12. package/src/app/word-sheets.js +101 -101
  13. package/src/kernel/docx/codec/blocks.js +123 -123
  14. package/src/kernel/docx/codec/carry.js +129 -129
  15. package/src/kernel/docx/codec/comments.js +25 -25
  16. package/src/kernel/docx/codec/docx.js +198 -198
  17. package/src/kernel/docx/codec/docxStyles.js +177 -177
  18. package/src/kernel/docx/codec/fonts.js +195 -195
  19. package/src/kernel/docx/codec/helpers.js +161 -161
  20. package/src/kernel/docx/codec/hfHtml.js +152 -152
  21. package/src/kernel/docx/codec/html.js +739 -739
  22. package/src/kernel/docx/codec/losses.js +420 -420
  23. package/src/kernel/docx/codec/markdown.js +170 -170
  24. package/src/kernel/docx/codec/parts.js +249 -249
  25. package/src/kernel/docx/codec/read.js +603 -603
  26. package/src/kernel/docx/codec/render.js +1156 -1156
  27. package/src/kernel/docx/codec/roundtrip.js +236 -236
  28. package/src/kernel/docx/codec/write.js +833 -833
  29. package/src/kernel/docx/comments.js +14 -14
  30. package/src/kernel/docx/pageGeometry.js +123 -123
  31. package/src/kernel/docx/pagination.js +481 -481
  32. package/src/kernel/docx/watermark.js +45 -45
  33. package/src/kernel/editor/constants.js +8 -8
  34. package/src/kernel/editor/engine/blocks.js +594 -594
  35. package/src/kernel/editor/engine/blocksEnter.js +109 -109
  36. package/src/kernel/editor/engine/blocksInsert.js +254 -254
  37. package/src/kernel/editor/engine/blocksStructure.js +226 -226
  38. package/src/kernel/editor/engine/commands.js +181 -181
  39. package/src/kernel/editor/engine/dom.js +646 -646
  40. package/src/kernel/editor/engine/history.js +149 -149
  41. package/src/kernel/editor/engine/inline.js +656 -656
  42. package/src/kernel/editor/engine/input.js +554 -554
  43. package/src/kernel/editor/engine/interaction.js +137 -137
  44. package/src/kernel/editor/engine/pointer.js +39 -39
  45. package/src/kernel/editor/engine/revision.js +138 -138
  46. package/src/kernel/editor/engine/schema.js +417 -417
  47. package/src/kernel/editor/engine/selection.js +119 -119
  48. package/src/kernel/editor/engine/state.js +118 -118
  49. package/src/kernel/editor/engine/tableClip.js +154 -154
  50. package/src/kernel/editor/engine/tableGrid.js +55 -55
  51. package/src/kernel/editor/engine/tableInteraction.js +388 -388
  52. package/src/kernel/editor/engine/tableMenu.js +250 -250
  53. package/src/kernel/editor/engine/tableOps.js +174 -174
  54. package/src/kernel/editor/engine/tables.js +732 -732
  55. package/src/kernel/editor/overlayGeometry.js +20 -20
  56. package/src/kernel/editor/utils.js +48 -48
  57. package/src/kernel/keyboard.js +114 -114
  58. package/src/kernel/textStyles.js +84 -84
  59. package/src/kernel/util/imageFile.js +91 -91
  60. package/src/kernel/util/shortcutKey.js +33 -33
  61. package/src/surface/editor-surface.js +600 -600
  62. package/src/ui/color-panel.js +69 -69
  63. package/src/ui/context-menu.js +133 -133
  64. package/src/ui/find-bar.js +151 -151
  65. package/src/ui/menubar.js +28 -28
  66. package/src/ui/panels.js +115 -115
  67. package/src/ui/prompt.js +89 -89
  68. package/src/ui/ribbon.js +485 -485
  69. package/src/ui/special-chars.js +39 -39
  70. package/src/ui/statusbar.js +81 -81
  71. package/src/ui/toolbar.js +32 -32
  72. package/styles/editor-content.css +440 -440
  73. package/styles/tokens.css +154 -154
  74. package/styles/word-panel.css +1 -1
@@ -1,481 +1,481 @@
1
- // [文件] web·office·docx·分页 —— 行级装箱:跨页段落按行断开、跨页表格按行断开并重复表头、多栏按栏容器排
2
- /*
3
- [设计] 只保留行级档:Word 的正文段落本来就是「按行跨页」的,整块搬运会在页底留下半页空白,
4
- 页数因此比 Word 多一页(公文最后一页把版记挤到新页就是这条)。
5
- [设计] 分页产物全是运行期结构(页间占位 / 栏容器 / 分隔线 / 拆分家族标记),内核装载与序列化统一还原,
6
- 正文落盘永远是单流;分页改写经内核 quietly 静默窗口,不入历史、不标脏。
7
- [坑] 测量一律走 getBoundingClientRect ÷ 页面缩放系数,且页间占位高度计入自然流折算:
8
- 页面缩放同时作用于纸层与正文层,用 offset 系或忘折算都会让装箱结果随缩放漂移。
9
- */
10
- import { moveAttributes, restoreRuntimeStructures } from '../editor/engine/dom.js';
11
- import { DOC_CLASS } from '../editor/engine/schema.js';
12
-
13
- /** 页间占位块类名(纯运行时布局元素,禁落盘:内核装载/序列化都会清掉) */
14
- const GAP_CLASS = 'wd-page-gap';
15
-
16
- /** 多栏栏容器类名(纯运行时布局元素,禁落盘) */
17
- const COL_CLASS = 'wd-col';
18
-
19
- /** 栏间分隔线类名(纯运行时布局元素,禁落盘) */
20
- const SEP_CLASS = 'wd-col-sep';
21
-
22
- /** 行级拆分家族标记:同一家族由同一个原始块拆出,还原时按文档顺序并回首个块 */
23
- const SPLIT_ATTR = 'data-wd-split';
24
-
25
- /** 容差(px):浮点余量不触发换栏 */
26
- const EPS = 0.5;
27
-
28
- let splitSeq = 0;
29
-
30
- /** 剥掉全部分页产物,还原成单流正文(内核同一实现在装载/序列化也跑) */
31
- export const flatten = (root) => restoreRuntimeStructures(root);
32
-
33
- /* ==================== 测量(正文根坐标,已折回缩放) ==================== */
34
-
35
- /** 块的布局盒(top/end 含下外边距;h 为块自身高,判定「一栏装不下整块」只用它) */
36
- const box = (el, rootTop, scale, shift) => {
37
- const rect = el.getBoundingClientRect();
38
- const mb = parseFloat(getComputedStyle(el).marginBottom) || 0;
39
- const top = (rect.top - rootTop) / scale - shift;
40
- return {
41
- top,
42
- end: top + rect.height / scale + mb,
43
- h: rect.height / scale + mb,
44
- };
45
- };
46
-
47
- /** 块内第 len 个字符的 (node, offset)(只数文本节点;IMG/BR 等原子内容不占字符位) */
48
- const pointAt = (el, len) => {
49
- let acc = 0;
50
- let hit = null;
51
- const walk = (node) => {
52
- if (hit) return;
53
- if (node.nodeType === Node.TEXT_NODE) {
54
- const n = node.nodeValue.length;
55
- if (acc + n >= len) {
56
- hit = { node, offset: Math.max(0, len - acc) };
57
- return;
58
- }
59
- acc += n;
60
- return;
61
- }
62
- for (const child of Array.from(node.childNodes)) walk(child);
63
- };
64
- walk(el);
65
- return hit;
66
- };
67
-
68
- /** 块内前 len 个字符占的高度(布局 px;Range 的 rect 同样按页缩放折算) */
69
- const heightUpTo = (el, len, scale) => {
70
- const p = pointAt(el, len);
71
- if (!p) return Infinity;
72
- const r = document.createRange();
73
- r.setStart(el, 0);
74
- try {
75
- r.setEnd(p.node, p.offset);
76
- } catch {
77
- return Infinity;
78
- }
79
- return r.getBoundingClientRect().height / (scale || 1);
80
- };
81
-
82
- /** 表格的正文行(不含 thead 行;拆行与行高记账都以它为序) */
83
- const tableRows = (el) => Array.from(el.tBodies).flatMap((tb) => Array.from(tb.rows));
84
-
85
- /**
86
- * 表格:本段还能再装几行 → {take, used, left};null = 拆不动(整段装得下 / 只剩单行)
87
- * [设计] used / left 都把表头高算进去:续表必带表头(splitTable 同一契约),不折进去每拆一页都会越出纸。
88
- * [坑] 行高必须与装箱口径同单位:avail 已折回未缩放坐标,offsetHeight 含页面 zoom,非 100% 时会算错行数
89
- */
90
- const fitTable = (el, avail, scale = 1) => {
91
- const rows = tableRows(el);
92
- if (rows.length < 2) return null;
93
- const heightOf = (row) => (row.getBoundingClientRect?.().height || row.offsetHeight) / (scale || 1);
94
- const head = el.tHead ? heightOf(el.tHead) : 0;
95
- let used = 0;
96
- let take = 0;
97
- for (const row of rows) {
98
- const rowH = heightOf(row);
99
- if (used + rowH > avail - head) break;
100
- used += rowH;
101
- take += 1;
102
- }
103
- if (take < 1 || take >= rows.length) return null;
104
- const rest = rows.slice(take).reduce((sum, row) => sum + heightOf(row), 0);
105
- return { take, used: used + head, left: rest + (el.tHead ? head : heightOf(rows[0])) };
106
- };
107
-
108
- /**
109
- * 段落:二分出本段能装多少字 → {take, used, left};null = 拆不动(整段装得下 / 只剩单字)
110
- * [坑] Range 的 rect 只包字形、不含行盒的上下半行距:整段量出来比版面矮两三成,
111
- * 直接跟 avail 比会误判「装得下」——三次跨页拆分全被这一步吞掉,页底就留出上百 px 的空洞。
112
- * 行距是上下对称的,用「盒高 − Range 整段高」把这段行距加回去,前缀高度才与版面同口径。
113
- */
114
- const fitText = (el, avail, scale) => {
115
- const total = (el.textContent || '').length;
116
- if (total < 2) return null;
117
- const boxH = el.getBoundingClientRect().height / (scale || 1);
118
- const totalH = heightUpTo(el, total, scale);
119
- if (!Number.isFinite(totalH) || totalH <= 0) return null;
120
- const lead = Math.max(0, boxH - totalH);
121
- if (boxH <= avail) return null;
122
- const fits = (len) => heightUpTo(el, len, scale) + lead <= avail;
123
- let lo = 1;
124
- let hi = total - 1;
125
- let best = 0;
126
- while (lo <= hi) {
127
- const mid = (lo + hi) >> 1;
128
- if (fits(mid)) {
129
- best = mid;
130
- lo = mid + 1;
131
- } else {
132
- hi = mid - 1;
133
- }
134
- }
135
- if (best < 1) return null;
136
- const used = heightUpTo(el, best, scale) + lead;
137
- return { take: best, used, left: Math.max(0, boxH - used) };
138
- };
139
-
140
- /** 块在本栏剩余高度 avail 内的拆分方案;null = 不拆(整块挪栏或放行溢出) */
141
- const fitOf = (el, avail, scale) => {
142
- if (avail <= EPS || !el) return null;
143
- // keepLines / keepNext:整块不拆(Word 的「与下段同页」在行级档以不拆近似,跨页组交给块级档)
144
- if (el.classList?.contains(DOC_CLASS.KEEP_LINES) || el.classList?.contains(DOC_CLASS.KEEP_NEXT)) return null;
145
- if (el.tagName === 'TABLE') return fitTable(el, avail, scale);
146
- // 图片/分隔线拆开没有意义(拆出来是半个图与两块空壳)
147
- if (el.tagName === 'HR' || el.querySelector?.('img')) return null;
148
- return fitText(el, avail, scale);
149
- };
150
-
151
- /** 块的计算行高(px,折回页面缩放系数);取不到或明显异常时按 0 记(调用方跳过约束) */
152
- const lineHeightOf = (el, scale) => {
153
- const v = Number.parseFloat(getComputedStyle(el).lineHeight);
154
- if (!Number.isFinite(v) || v <= 0) return 0;
155
- const px = v / (scale || 1);
156
- return px >= 6 && px <= 120 ? px : 0;
157
- };
158
-
159
- /* ==================== 跨页拆分(段落按字、表格按行) ==================== */
160
-
161
- /** 段落按字符偏移拆成两块,返回后半块(null = 拆不动);尾块顶边距压零(续段从分页线/栏顶起排,间距不再重复给) */
162
- const splitText = (el, offset) => {
163
- const p = pointAt(el, offset);
164
- if (!p) return null;
165
- const r = document.createRange();
166
- r.setStart(p.node, p.offset);
167
- r.setEnd(el, el.childNodes.length);
168
- if (r.collapsed) return null;
169
- const tail = document.createElement(el.tagName);
170
- moveAttributes(el, tail);
171
- tail.style.marginTop = '0';
172
- tail.appendChild(r.extractContents());
173
- el.after(tail);
174
- return tail;
175
- };
176
-
177
- /**
178
- * 表格按行拆成两张,返回续表(null = 拆不动)
179
- * [设计] 表头一律进续表的 thead:原表有 thead 就复制一份,没有就把首行复制进新 thead——
180
- * 「续表的 thead 整块丢弃」因此成为还原合并的单一契约(克隆行与真行不再需要辨认),
181
- * 且跨页表格没有表头等于没法读(对齐 Word 的 tblHeader 口径)。
182
- * [坑] 重复表头挂 contenteditable="false":它是克隆件,可编辑的话键入内容会在下一次还原合并时随克隆一起丢掉。
183
- */
184
- const splitTable = (el, keepRows) => {
185
- const rows = tableRows(el);
186
- if (keepRows < 1 || keepRows >= rows.length) return null;
187
- const tail = document.createElement('table');
188
- moveAttributes(el, tail);
189
- const cg = el.querySelector('colgroup');
190
- if (cg) tail.appendChild(cg.cloneNode(true));
191
- const head = el.tHead ? el.tHead.cloneNode(true) : document.createElement('thead');
192
- if (!el.tHead) head.appendChild(rows[0].cloneNode(true));
193
- head.setAttribute('contenteditable', 'false');
194
- tail.appendChild(head);
195
- const tb = document.createElement('tbody');
196
- rows.slice(keepRows).forEach((row) => tb.appendChild(row));
197
- tail.appendChild(tb);
198
- el.after(tail);
199
- return tail;
200
- };
201
-
202
- /** 执行拆分并打家族标记,返回后半块
203
- * [坑] 跨多页的块会被反复拆分:再拆时必须沿用原家族 id——每段换新 id 会把家族链拆散,
204
- * 还原合并只并得回最后一对,前面拆出去的段全成孤儿(保存时表现为丢内容)。 */
205
- const splitBlock = (el, offset) => {
206
- const tail = el.tagName === 'TABLE' ? splitTable(el, offset) : splitText(el, offset);
207
- if (!tail) return null;
208
- const id = el.getAttribute(SPLIT_ATTR) || `s${(splitSeq += 1)}`;
209
- el.setAttribute(SPLIT_ATTR, id);
210
- tail.setAttribute(SPLIT_ATTR, id);
211
- return tail;
212
- };
213
-
214
- /* ==================== 光标搬运(拆正文前后按字符偏移复现选区) ==================== */
215
-
216
- const caretOffset = (root, node, offset) => {
217
- let acc = 0;
218
- const tw = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
219
- let cur = tw.nextNode();
220
- while (cur) {
221
- if (cur === node) return acc + offset;
222
- acc += cur.nodeValue.length;
223
- cur = tw.nextNode();
224
- }
225
- return -1;
226
- };
227
-
228
- const offsetCaret = (root, target) => {
229
- let acc = 0;
230
- let last = null;
231
- const tw = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
232
- let cur = tw.nextNode();
233
- while (cur) {
234
- const n = cur.nodeValue.length;
235
- if (acc + n >= target) return { node: cur, offset: Math.max(0, target - acc) };
236
- acc += n;
237
- last = cur;
238
- cur = tw.nextNode();
239
- }
240
- // 目标位置超出正文长度(内容被删短了):退到末尾,别把光标丢掉
241
- return last ? { node: last, offset: last.nodeValue.length } : null;
242
- };
243
-
244
- /** 记下正文内的选区字符偏移(DOM 重建后 Range 会失效,只能按字符位置复现) */
245
- const saveCaret = (root) => {
246
- const sel = window.getSelection();
247
- if (!sel?.rangeCount || !sel.anchorNode || !root.contains(sel.anchorNode)) return null;
248
- const r = sel.getRangeAt(0);
249
- const start = caretOffset(root, r.startContainer, r.startOffset);
250
- const end = caretOffset(root, r.endContainer, r.endOffset);
251
- return start >= 0 && end >= 0 ? { start, end } : null;
252
- };
253
-
254
- const restoreCaret = (root, saved) => {
255
- if (!saved) return;
256
- const a = offsetCaret(root, saved.start);
257
- const b = offsetCaret(root, saved.end);
258
- if (!a || !b) return;
259
- const r = document.createRange();
260
- r.setStart(a.node, a.offset);
261
- r.setEnd(b.node, b.offset);
262
- const sel = window.getSelection();
263
- sel.removeAllRanges();
264
- sel.addRange(r);
265
- };
266
-
267
- /* ==================== 落分页产物 ==================== */
268
-
269
- /** 插一条零高占位带(页间缝的份额先由 --wd-gutter 给着,补高在结构定形后做) */
270
- const makeGap = (root, before, gutter) => {
271
- const gap = document.createElement('div');
272
- gap.className = GAP_CLASS;
273
- gap.setAttribute('contenteditable', 'false');
274
- gap.style.height = `calc(0px + var(--gbd-wd-gutter, ${gutter}px))`;
275
- root.insertBefore(gap, before);
276
- return gap;
277
- };
278
-
279
- /**
280
- * 占位带补高:把锚块顶边钉到目标页的版心线上
281
- * [设计] 高度用实测定而不是按公式算:外边距折叠 / 表格边框 / 负边距各按各的规则参与排版,
282
- * 只有 DOM 自己知道锚块最终落在哪——实测定高对这些规则一概免疫,也不受页面缩放折算牵连。
283
- * @param ctx {rootTop, scale, pageH, padTop, gutter}
284
- */
285
- const fillGap = (gap, before, page, ctx) => {
286
- const { rootTop, scale = 1, pageH, padTop, gutter } = ctx;
287
- const crossed = page - 1; // 跨过的页数 = 已经垫过的页间缝条数
288
- const cur = (before.getBoundingClientRect().top - rootTop) / scale;
289
- const g = gap.getBoundingClientRect().height / scale; // 本模式下页间缝的实测高(打印态为 0)
290
- const base = Math.max(0, crossed * pageH + padTop - (cur - crossed * g));
291
- gap.style.height = `calc(${base}px + var(--gbd-wd-gutter, ${gutter}px))`;
292
- };
293
-
294
- /** 单栏断点处落占位带:先整批零高插上,再按文档序逐条补高(补高必须等结构定形,量一条补一条) */
295
- const insertGaps = (root, at, ctx) => {
296
- const gaps = [];
297
- at.forEach((c, el) => {
298
- if (c.newPage) gaps.push([makeGap(root, el, ctx.gutter), el, c.page]);
299
- });
300
- gaps.forEach(([gap, el, page]) => fillGap(gap, el, page, ctx));
301
- };
302
-
303
- /**
304
- * 多栏:断点处开一个新栏容器,页间断点额外插一条占位块(占位块自带 clear 把浮动收行,下一页从新行起)
305
- * [坑] 栏容器走 float 而不是 inline-block:inline-block 之间的换行空白会被渲染成额外栏距,
306
- * 栏宽当场对不上 colgroup 与导出侧的 w:gridCol。
307
- */
308
- const packColumns = (root, at, { colW, colGap, cellH, gutter, colSeparator }, ctx) => {
309
- /** 栏间分隔线画在间隙正中(栏容器是 relative,线挂在栏右外侧半个 gap 处) */
310
- const newCol = () => {
311
- const col = document.createElement('div');
312
- col.className = COL_CLASS;
313
- col.setAttribute('contenteditable', 'false');
314
- col.style.width = `${colW}px`;
315
- col.style.minHeight = `${cellH}px`;
316
- if (colGap) col.style.marginRight = `${colGap}px`;
317
- if (colSeparator && colGap) {
318
- const sep = document.createElement('div');
319
- sep.className = SEP_CLASS;
320
- sep.setAttribute('contenteditable', 'false');
321
- sep.style.right = `${-colGap / 2}px`;
322
- col.appendChild(sep);
323
- }
324
- return col;
325
- };
326
- /** 收尾一页的末栏:间距与分隔线都不该留在页尾 */
327
- const closeCol = (c) => {
328
- c.style.marginRight = '0';
329
- c.querySelector(`.${SEP_CLASS}`)?.remove();
330
- };
331
- let col = newCol();
332
- root.insertBefore(col, root.firstChild);
333
- const gaps = [];
334
- Array.from(root.children).forEach((el) => {
335
- if (el === col || el.classList.contains(COL_CLASS)) return;
336
- const c = at.get(el);
337
- if (c) {
338
- if (c.newPage) {
339
- gaps.push([makeGap(root, el, gutter), el, c.page]);
340
- // [坑] 每页最后一栏必须去掉栏间距:N 栏各带一份 marginRight 会让总宽多出一个间距,
341
- // float 因此提前换行,本该在这一页的第 N 栏被挤到下一页。
342
- if (col) closeCol(col);
343
- }
344
- col = newCol();
345
- root.insertBefore(col, el);
346
- }
347
- col.appendChild(el);
348
- });
349
- if (col) closeCol(col); // 末页末栏同上
350
- // 结构定形后再补高:浮动行高随栏内容变,边铺边量会把后面的带子量歪
351
- gaps.forEach(([gap, el, page]) => fillGap(gap, el, page, ctx));
352
- };
353
-
354
- /**
355
- * 重排分页
356
- * @param {HTMLElement} root 正文根(.re-content)
357
- * @param {Object} opts {cellH, cellsPerPage, gapOf, gutter, padTop, colW, colGap, colSeparator, padLeft, padRight, scale}
358
- * @returns {number} 页数
359
- */
360
- export const repaginate = (root, opts) => (root ? repaginateRows(root, opts, opts.scale ?? 1) : 1);
361
-
362
- /**
363
- * 行级档:还原 → 边装边拆 → 铺栏/落占位(全程保光标)
364
- * [设计] 边装边拆而不是先整体规划:拆出来的尾块接着排队再装,跨多页的超高块因此会被一栏一栏拆下去;
365
- * 每轮都在真实 DOM 上测量,行高等信息不用预估,也不会像纯函数规划那样把已消费的偏移算错一轮。
366
- */
367
- const repaginateRows = (root, opts, scale) => {
368
- const { cellH, cellsPerPage = 1, gapOf, gutter, padTop = 0, colW, colGap, padLeft = 0, padRight = 0 } = opts;
369
- const capOf = (p) => (typeof cellH === 'function' ? cellH(p) : cellH);
370
- // [坑] 光标偏移必须在还原成单流之后记:还原会丢掉复印件(续表克隆的 thead 等),
371
- // 先记会把克隆文字算进字符偏移,重排后光标落到错误位置
372
- flatten(root);
373
- const caret = saveCaret(root);
374
-
375
- // [坑] 多栏必须按栏宽测量:块在窄栏里会折成更多行,拿整幅版心宽量出来的高度去装箱,
376
- // 装进栏里必然溢出(或撑出大片空白)——分栏页数老算不对就是这一条。
377
- // 测量期把正文临时压到「栏宽 + 左右页边距」(正文层是 border-box,宽度含内边距),量完立刻还原。
378
- const prevWidth = root.style.width;
379
- const multi = cellsPerPage > 1;
380
- if (multi) root.style.width = `${colW + padLeft + padRight}px`;
381
-
382
- const rootTop = root.getBoundingClientRect().top;
383
- const breaks = [];
384
- let page = 1;
385
- let col = 1;
386
- let top = null;
387
- let end = 0;
388
-
389
- /** 断点只记「断在谁前、去第几页」;占位带高在铺好后按实测补(见 fillGap) */
390
- const breakBefore = (before, newPage) => {
391
- if (newPage) {
392
- page += 1;
393
- col = 1;
394
- breaks.push({ el: before, page, newPage: true });
395
- } else {
396
- col += 1;
397
- breaks.push({ el: before, page: 0, newPage: false });
398
- }
399
- top = null;
400
- end = 0;
401
- };
402
-
403
- const queue = Array.from(root.children);
404
- while (queue.length) {
405
- const el = queue.shift();
406
- const b = box(el, rootTop, scale, 0);
407
- if (el.classList.contains(DOC_CLASS.PAGEBREAK)) {
408
- if (top === null) top = b.top;
409
- end = Math.max(end, b.end);
410
- breakBefore(el.nextElementSibling, true);
411
- continue;
412
- }
413
- // 段前分页(w:pageBreakBefore):本栏已有内容 → 本块先换栏再排
414
- if (el.classList.contains(DOC_CLASS.PBB) && top !== null && end - top > EPS) {
415
- breakBefore(el, col % cellsPerPage === 0);
416
- queue.unshift(el);
417
- continue;
418
- }
419
- if (top === null) {
420
- top = b.top;
421
- end = b.top; // 新栏还没有内容:下面统一按「本栏已用高度」判定
422
- }
423
- const used = end - top;
424
- if (used + b.h <= capOf(page) + EPS) {
425
- end = top + used + b.h;
426
- continue;
427
- }
428
- // widowControl(Word 默认开):拆分时尾部预留两行,避免页尾孤行;显式关闭的不留
429
- // [坑] 预留量不能超过「块高 − 一行」:一行的空段/短段按两行预留会算出负的可用高度,
430
- // 于是整块被无谓地推到下一页(页底又是一片空白)
431
- const lh = lineHeightOf(el, scale);
432
- const widowPad = el.classList?.contains(DOC_CLASS.WIDOW_OFF) || lh <= 0 ? 0 : Math.min(lh * 2, Math.max(0, b.h - lh));
433
- const plan = fitOf(el, capOf(page) - used - widowPad, scale);
434
- const tail = plan ? splitBlock(el, plan.take) : null;
435
- if (tail) {
436
- breakBefore(tail, col % cellsPerPage === 0);
437
- queue.unshift(tail);
438
- continue;
439
- }
440
- if (used > EPS) {
441
- // 拆不动且本栏已有内容:整块挪下一栏
442
- breakBefore(el, col % cellsPerPage === 0);
443
- queue.unshift(el);
444
- continue;
445
- }
446
- // 拆不动且本栏空(原子块 / 单行超栏):放行溢出,由后续块接管换栏
447
- end = top + used + b.h;
448
- }
449
- if (multi) root.style.width = prevWidth;
450
-
451
- const at = new Map();
452
- breaks.forEach((c) => {
453
- if (c.el) at.set(c.el, c);
454
- });
455
- const ctx = { rootTop: root.getBoundingClientRect().top, scale, pageH: gapOf + capOf(1), padTop, gutter };
456
- if (multi) packColumns(root, at, { colW, colGap, cellH: capOf(1), gutter, colSeparator: opts.colSeparator }, ctx);
457
- else insertGaps(root, at, ctx);
458
- restoreCaret(root, caret);
459
-
460
- root.__wdPageSig = `rows:${cellsPerPage}:${breaks.map((c) => `${c.newPage ? 'P' : 'C'}${c.page}`).join('|')}`;
461
- return page;
462
- };
463
-
464
- /** 换文档 / 改页面设置后清掉分页状态(新文档不该沿用上一份的分页结构) */
465
- export const resetPagination = (root) => {
466
- if (!root) return;
467
- flatten(root);
468
- delete root.__wdPageSig;
469
- };
470
-
471
- /** 元素在第几页:数它前面的页间占位带(分页产物把「页」落在 DOM 序上;多栏的页间断点同样落带) */
472
- export const pageOfElement = (root, el) => {
473
- let page = 1;
474
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
475
- let cur = walker.nextNode();
476
- while (cur && cur !== el) {
477
- if (cur.classList?.contains(GAP_CLASS)) page += 1;
478
- cur = walker.nextNode();
479
- }
480
- return page;
481
- };
1
+ // [文件] web·office·docx·分页 —— 行级装箱:跨页段落按行断开、跨页表格按行断开并重复表头、多栏按栏容器排
2
+ /*
3
+ [设计] 只保留行级档:Word 的正文段落本来就是「按行跨页」的,整块搬运会在页底留下半页空白,
4
+ 页数因此比 Word 多一页(公文最后一页把版记挤到新页就是这条)。
5
+ [设计] 分页产物全是运行期结构(页间占位 / 栏容器 / 分隔线 / 拆分家族标记),内核装载与序列化统一还原,
6
+ 正文落盘永远是单流;分页改写经内核 quietly 静默窗口,不入历史、不标脏。
7
+ [坑] 测量一律走 getBoundingClientRect ÷ 页面缩放系数,且页间占位高度计入自然流折算:
8
+ 页面缩放同时作用于纸层与正文层,用 offset 系或忘折算都会让装箱结果随缩放漂移。
9
+ */
10
+ import { moveAttributes, restoreRuntimeStructures } from '../editor/engine/dom.js';
11
+ import { DOC_CLASS } from '../editor/engine/schema.js';
12
+
13
+ /** 页间占位块类名(纯运行时布局元素,禁落盘:内核装载/序列化都会清掉) */
14
+ const GAP_CLASS = 'wd-page-gap';
15
+
16
+ /** 多栏栏容器类名(纯运行时布局元素,禁落盘) */
17
+ const COL_CLASS = 'wd-col';
18
+
19
+ /** 栏间分隔线类名(纯运行时布局元素,禁落盘) */
20
+ const SEP_CLASS = 'wd-col-sep';
21
+
22
+ /** 行级拆分家族标记:同一家族由同一个原始块拆出,还原时按文档顺序并回首个块 */
23
+ const SPLIT_ATTR = 'data-wd-split';
24
+
25
+ /** 容差(px):浮点余量不触发换栏 */
26
+ const EPS = 0.5;
27
+
28
+ let splitSeq = 0;
29
+
30
+ /** 剥掉全部分页产物,还原成单流正文(内核同一实现在装载/序列化也跑) */
31
+ export const flatten = (root) => restoreRuntimeStructures(root);
32
+
33
+ /* ==================== 测量(正文根坐标,已折回缩放) ==================== */
34
+
35
+ /** 块的布局盒(top/end 含下外边距;h 为块自身高,判定「一栏装不下整块」只用它) */
36
+ const box = (el, rootTop, scale, shift) => {
37
+ const rect = el.getBoundingClientRect();
38
+ const mb = parseFloat(getComputedStyle(el).marginBottom) || 0;
39
+ const top = (rect.top - rootTop) / scale - shift;
40
+ return {
41
+ top,
42
+ end: top + rect.height / scale + mb,
43
+ h: rect.height / scale + mb,
44
+ };
45
+ };
46
+
47
+ /** 块内第 len 个字符的 (node, offset)(只数文本节点;IMG/BR 等原子内容不占字符位) */
48
+ const pointAt = (el, len) => {
49
+ let acc = 0;
50
+ let hit = null;
51
+ const walk = (node) => {
52
+ if (hit) return;
53
+ if (node.nodeType === Node.TEXT_NODE) {
54
+ const n = node.nodeValue.length;
55
+ if (acc + n >= len) {
56
+ hit = { node, offset: Math.max(0, len - acc) };
57
+ return;
58
+ }
59
+ acc += n;
60
+ return;
61
+ }
62
+ for (const child of Array.from(node.childNodes)) walk(child);
63
+ };
64
+ walk(el);
65
+ return hit;
66
+ };
67
+
68
+ /** 块内前 len 个字符占的高度(布局 px;Range 的 rect 同样按页缩放折算) */
69
+ const heightUpTo = (el, len, scale) => {
70
+ const p = pointAt(el, len);
71
+ if (!p) return Infinity;
72
+ const r = document.createRange();
73
+ r.setStart(el, 0);
74
+ try {
75
+ r.setEnd(p.node, p.offset);
76
+ } catch {
77
+ return Infinity;
78
+ }
79
+ return r.getBoundingClientRect().height / (scale || 1);
80
+ };
81
+
82
+ /** 表格的正文行(不含 thead 行;拆行与行高记账都以它为序) */
83
+ const tableRows = (el) => Array.from(el.tBodies).flatMap((tb) => Array.from(tb.rows));
84
+
85
+ /**
86
+ * 表格:本段还能再装几行 → {take, used, left};null = 拆不动(整段装得下 / 只剩单行)
87
+ * [设计] used / left 都把表头高算进去:续表必带表头(splitTable 同一契约),不折进去每拆一页都会越出纸。
88
+ * [坑] 行高必须与装箱口径同单位:avail 已折回未缩放坐标,offsetHeight 含页面 zoom,非 100% 时会算错行数
89
+ */
90
+ const fitTable = (el, avail, scale = 1) => {
91
+ const rows = tableRows(el);
92
+ if (rows.length < 2) return null;
93
+ const heightOf = (row) => (row.getBoundingClientRect?.().height || row.offsetHeight) / (scale || 1);
94
+ const head = el.tHead ? heightOf(el.tHead) : 0;
95
+ let used = 0;
96
+ let take = 0;
97
+ for (const row of rows) {
98
+ const rowH = heightOf(row);
99
+ if (used + rowH > avail - head) break;
100
+ used += rowH;
101
+ take += 1;
102
+ }
103
+ if (take < 1 || take >= rows.length) return null;
104
+ const rest = rows.slice(take).reduce((sum, row) => sum + heightOf(row), 0);
105
+ return { take, used: used + head, left: rest + (el.tHead ? head : heightOf(rows[0])) };
106
+ };
107
+
108
+ /**
109
+ * 段落:二分出本段能装多少字 → {take, used, left};null = 拆不动(整段装得下 / 只剩单字)
110
+ * [坑] Range 的 rect 只包字形、不含行盒的上下半行距:整段量出来比版面矮两三成,
111
+ * 直接跟 avail 比会误判「装得下」——三次跨页拆分全被这一步吞掉,页底就留出上百 px 的空洞。
112
+ * 行距是上下对称的,用「盒高 − Range 整段高」把这段行距加回去,前缀高度才与版面同口径。
113
+ */
114
+ const fitText = (el, avail, scale) => {
115
+ const total = (el.textContent || '').length;
116
+ if (total < 2) return null;
117
+ const boxH = el.getBoundingClientRect().height / (scale || 1);
118
+ const totalH = heightUpTo(el, total, scale);
119
+ if (!Number.isFinite(totalH) || totalH <= 0) return null;
120
+ const lead = Math.max(0, boxH - totalH);
121
+ if (boxH <= avail) return null;
122
+ const fits = (len) => heightUpTo(el, len, scale) + lead <= avail;
123
+ let lo = 1;
124
+ let hi = total - 1;
125
+ let best = 0;
126
+ while (lo <= hi) {
127
+ const mid = (lo + hi) >> 1;
128
+ if (fits(mid)) {
129
+ best = mid;
130
+ lo = mid + 1;
131
+ } else {
132
+ hi = mid - 1;
133
+ }
134
+ }
135
+ if (best < 1) return null;
136
+ const used = heightUpTo(el, best, scale) + lead;
137
+ return { take: best, used, left: Math.max(0, boxH - used) };
138
+ };
139
+
140
+ /** 块在本栏剩余高度 avail 内的拆分方案;null = 不拆(整块挪栏或放行溢出) */
141
+ const fitOf = (el, avail, scale) => {
142
+ if (avail <= EPS || !el) return null;
143
+ // keepLines / keepNext:整块不拆(Word 的「与下段同页」在行级档以不拆近似,跨页组交给块级档)
144
+ if (el.classList?.contains(DOC_CLASS.KEEP_LINES) || el.classList?.contains(DOC_CLASS.KEEP_NEXT)) return null;
145
+ if (el.tagName === 'TABLE') return fitTable(el, avail, scale);
146
+ // 图片/分隔线拆开没有意义(拆出来是半个图与两块空壳)
147
+ if (el.tagName === 'HR' || el.querySelector?.('img')) return null;
148
+ return fitText(el, avail, scale);
149
+ };
150
+
151
+ /** 块的计算行高(px,折回页面缩放系数);取不到或明显异常时按 0 记(调用方跳过约束) */
152
+ const lineHeightOf = (el, scale) => {
153
+ const v = Number.parseFloat(getComputedStyle(el).lineHeight);
154
+ if (!Number.isFinite(v) || v <= 0) return 0;
155
+ const px = v / (scale || 1);
156
+ return px >= 6 && px <= 120 ? px : 0;
157
+ };
158
+
159
+ /* ==================== 跨页拆分(段落按字、表格按行) ==================== */
160
+
161
+ /** 段落按字符偏移拆成两块,返回后半块(null = 拆不动);尾块顶边距压零(续段从分页线/栏顶起排,间距不再重复给) */
162
+ const splitText = (el, offset) => {
163
+ const p = pointAt(el, offset);
164
+ if (!p) return null;
165
+ const r = document.createRange();
166
+ r.setStart(p.node, p.offset);
167
+ r.setEnd(el, el.childNodes.length);
168
+ if (r.collapsed) return null;
169
+ const tail = document.createElement(el.tagName);
170
+ moveAttributes(el, tail);
171
+ tail.style.marginTop = '0';
172
+ tail.appendChild(r.extractContents());
173
+ el.after(tail);
174
+ return tail;
175
+ };
176
+
177
+ /**
178
+ * 表格按行拆成两张,返回续表(null = 拆不动)
179
+ * [设计] 表头一律进续表的 thead:原表有 thead 就复制一份,没有就把首行复制进新 thead——
180
+ * 「续表的 thead 整块丢弃」因此成为还原合并的单一契约(克隆行与真行不再需要辨认),
181
+ * 且跨页表格没有表头等于没法读(对齐 Word 的 tblHeader 口径)。
182
+ * [坑] 重复表头挂 contenteditable="false":它是克隆件,可编辑的话键入内容会在下一次还原合并时随克隆一起丢掉。
183
+ */
184
+ const splitTable = (el, keepRows) => {
185
+ const rows = tableRows(el);
186
+ if (keepRows < 1 || keepRows >= rows.length) return null;
187
+ const tail = document.createElement('table');
188
+ moveAttributes(el, tail);
189
+ const cg = el.querySelector('colgroup');
190
+ if (cg) tail.appendChild(cg.cloneNode(true));
191
+ const head = el.tHead ? el.tHead.cloneNode(true) : document.createElement('thead');
192
+ if (!el.tHead) head.appendChild(rows[0].cloneNode(true));
193
+ head.setAttribute('contenteditable', 'false');
194
+ tail.appendChild(head);
195
+ const tb = document.createElement('tbody');
196
+ rows.slice(keepRows).forEach((row) => tb.appendChild(row));
197
+ tail.appendChild(tb);
198
+ el.after(tail);
199
+ return tail;
200
+ };
201
+
202
+ /** 执行拆分并打家族标记,返回后半块
203
+ * [坑] 跨多页的块会被反复拆分:再拆时必须沿用原家族 id——每段换新 id 会把家族链拆散,
204
+ * 还原合并只并得回最后一对,前面拆出去的段全成孤儿(保存时表现为丢内容)。 */
205
+ const splitBlock = (el, offset) => {
206
+ const tail = el.tagName === 'TABLE' ? splitTable(el, offset) : splitText(el, offset);
207
+ if (!tail) return null;
208
+ const id = el.getAttribute(SPLIT_ATTR) || `s${(splitSeq += 1)}`;
209
+ el.setAttribute(SPLIT_ATTR, id);
210
+ tail.setAttribute(SPLIT_ATTR, id);
211
+ return tail;
212
+ };
213
+
214
+ /* ==================== 光标搬运(拆正文前后按字符偏移复现选区) ==================== */
215
+
216
+ const caretOffset = (root, node, offset) => {
217
+ let acc = 0;
218
+ const tw = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
219
+ let cur = tw.nextNode();
220
+ while (cur) {
221
+ if (cur === node) return acc + offset;
222
+ acc += cur.nodeValue.length;
223
+ cur = tw.nextNode();
224
+ }
225
+ return -1;
226
+ };
227
+
228
+ const offsetCaret = (root, target) => {
229
+ let acc = 0;
230
+ let last = null;
231
+ const tw = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
232
+ let cur = tw.nextNode();
233
+ while (cur) {
234
+ const n = cur.nodeValue.length;
235
+ if (acc + n >= target) return { node: cur, offset: Math.max(0, target - acc) };
236
+ acc += n;
237
+ last = cur;
238
+ cur = tw.nextNode();
239
+ }
240
+ // 目标位置超出正文长度(内容被删短了):退到末尾,别把光标丢掉
241
+ return last ? { node: last, offset: last.nodeValue.length } : null;
242
+ };
243
+
244
+ /** 记下正文内的选区字符偏移(DOM 重建后 Range 会失效,只能按字符位置复现) */
245
+ const saveCaret = (root) => {
246
+ const sel = window.getSelection();
247
+ if (!sel?.rangeCount || !sel.anchorNode || !root.contains(sel.anchorNode)) return null;
248
+ const r = sel.getRangeAt(0);
249
+ const start = caretOffset(root, r.startContainer, r.startOffset);
250
+ const end = caretOffset(root, r.endContainer, r.endOffset);
251
+ return start >= 0 && end >= 0 ? { start, end } : null;
252
+ };
253
+
254
+ const restoreCaret = (root, saved) => {
255
+ if (!saved) return;
256
+ const a = offsetCaret(root, saved.start);
257
+ const b = offsetCaret(root, saved.end);
258
+ if (!a || !b) return;
259
+ const r = document.createRange();
260
+ r.setStart(a.node, a.offset);
261
+ r.setEnd(b.node, b.offset);
262
+ const sel = window.getSelection();
263
+ sel.removeAllRanges();
264
+ sel.addRange(r);
265
+ };
266
+
267
+ /* ==================== 落分页产物 ==================== */
268
+
269
+ /** 插一条零高占位带(页间缝的份额先由 --wd-gutter 给着,补高在结构定形后做) */
270
+ const makeGap = (root, before, gutter) => {
271
+ const gap = document.createElement('div');
272
+ gap.className = GAP_CLASS;
273
+ gap.setAttribute('contenteditable', 'false');
274
+ gap.style.height = `calc(0px + var(--gbd-wd-gutter, ${gutter}px))`;
275
+ root.insertBefore(gap, before);
276
+ return gap;
277
+ };
278
+
279
+ /**
280
+ * 占位带补高:把锚块顶边钉到目标页的版心线上
281
+ * [设计] 高度用实测定而不是按公式算:外边距折叠 / 表格边框 / 负边距各按各的规则参与排版,
282
+ * 只有 DOM 自己知道锚块最终落在哪——实测定高对这些规则一概免疫,也不受页面缩放折算牵连。
283
+ * @param ctx {rootTop, scale, pageH, padTop, gutter}
284
+ */
285
+ const fillGap = (gap, before, page, ctx) => {
286
+ const { rootTop, scale = 1, pageH, padTop, gutter } = ctx;
287
+ const crossed = page - 1; // 跨过的页数 = 已经垫过的页间缝条数
288
+ const cur = (before.getBoundingClientRect().top - rootTop) / scale;
289
+ const g = gap.getBoundingClientRect().height / scale; // 本模式下页间缝的实测高(打印态为 0)
290
+ const base = Math.max(0, crossed * pageH + padTop - (cur - crossed * g));
291
+ gap.style.height = `calc(${base}px + var(--gbd-wd-gutter, ${gutter}px))`;
292
+ };
293
+
294
+ /** 单栏断点处落占位带:先整批零高插上,再按文档序逐条补高(补高必须等结构定形,量一条补一条) */
295
+ const insertGaps = (root, at, ctx) => {
296
+ const gaps = [];
297
+ at.forEach((c, el) => {
298
+ if (c.newPage) gaps.push([makeGap(root, el, ctx.gutter), el, c.page]);
299
+ });
300
+ gaps.forEach(([gap, el, page]) => fillGap(gap, el, page, ctx));
301
+ };
302
+
303
+ /**
304
+ * 多栏:断点处开一个新栏容器,页间断点额外插一条占位块(占位块自带 clear 把浮动收行,下一页从新行起)
305
+ * [坑] 栏容器走 float 而不是 inline-block:inline-block 之间的换行空白会被渲染成额外栏距,
306
+ * 栏宽当场对不上 colgroup 与导出侧的 w:gridCol。
307
+ */
308
+ const packColumns = (root, at, { colW, colGap, cellH, gutter, colSeparator }, ctx) => {
309
+ /** 栏间分隔线画在间隙正中(栏容器是 relative,线挂在栏右外侧半个 gap 处) */
310
+ const newCol = () => {
311
+ const col = document.createElement('div');
312
+ col.className = COL_CLASS;
313
+ col.setAttribute('contenteditable', 'false');
314
+ col.style.width = `${colW}px`;
315
+ col.style.minHeight = `${cellH}px`;
316
+ if (colGap) col.style.marginRight = `${colGap}px`;
317
+ if (colSeparator && colGap) {
318
+ const sep = document.createElement('div');
319
+ sep.className = SEP_CLASS;
320
+ sep.setAttribute('contenteditable', 'false');
321
+ sep.style.right = `${-colGap / 2}px`;
322
+ col.appendChild(sep);
323
+ }
324
+ return col;
325
+ };
326
+ /** 收尾一页的末栏:间距与分隔线都不该留在页尾 */
327
+ const closeCol = (c) => {
328
+ c.style.marginRight = '0';
329
+ c.querySelector(`.${SEP_CLASS}`)?.remove();
330
+ };
331
+ let col = newCol();
332
+ root.insertBefore(col, root.firstChild);
333
+ const gaps = [];
334
+ Array.from(root.children).forEach((el) => {
335
+ if (el === col || el.classList.contains(COL_CLASS)) return;
336
+ const c = at.get(el);
337
+ if (c) {
338
+ if (c.newPage) {
339
+ gaps.push([makeGap(root, el, gutter), el, c.page]);
340
+ // [坑] 每页最后一栏必须去掉栏间距:N 栏各带一份 marginRight 会让总宽多出一个间距,
341
+ // float 因此提前换行,本该在这一页的第 N 栏被挤到下一页。
342
+ if (col) closeCol(col);
343
+ }
344
+ col = newCol();
345
+ root.insertBefore(col, el);
346
+ }
347
+ col.appendChild(el);
348
+ });
349
+ if (col) closeCol(col); // 末页末栏同上
350
+ // 结构定形后再补高:浮动行高随栏内容变,边铺边量会把后面的带子量歪
351
+ gaps.forEach(([gap, el, page]) => fillGap(gap, el, page, ctx));
352
+ };
353
+
354
+ /**
355
+ * 重排分页
356
+ * @param {HTMLElement} root 正文根(.re-content)
357
+ * @param {Object} opts {cellH, cellsPerPage, gapOf, gutter, padTop, colW, colGap, colSeparator, padLeft, padRight, scale}
358
+ * @returns {number} 页数
359
+ */
360
+ export const repaginate = (root, opts) => (root ? repaginateRows(root, opts, opts.scale ?? 1) : 1);
361
+
362
+ /**
363
+ * 行级档:还原 → 边装边拆 → 铺栏/落占位(全程保光标)
364
+ * [设计] 边装边拆而不是先整体规划:拆出来的尾块接着排队再装,跨多页的超高块因此会被一栏一栏拆下去;
365
+ * 每轮都在真实 DOM 上测量,行高等信息不用预估,也不会像纯函数规划那样把已消费的偏移算错一轮。
366
+ */
367
+ const repaginateRows = (root, opts, scale) => {
368
+ const { cellH, cellsPerPage = 1, gapOf, gutter, padTop = 0, colW, colGap, padLeft = 0, padRight = 0 } = opts;
369
+ const capOf = (p) => (typeof cellH === 'function' ? cellH(p) : cellH);
370
+ // [坑] 光标偏移必须在还原成单流之后记:还原会丢掉复印件(续表克隆的 thead 等),
371
+ // 先记会把克隆文字算进字符偏移,重排后光标落到错误位置
372
+ flatten(root);
373
+ const caret = saveCaret(root);
374
+
375
+ // [坑] 多栏必须按栏宽测量:块在窄栏里会折成更多行,拿整幅版心宽量出来的高度去装箱,
376
+ // 装进栏里必然溢出(或撑出大片空白)——分栏页数老算不对就是这一条。
377
+ // 测量期把正文临时压到「栏宽 + 左右页边距」(正文层是 border-box,宽度含内边距),量完立刻还原。
378
+ const prevWidth = root.style.width;
379
+ const multi = cellsPerPage > 1;
380
+ if (multi) root.style.width = `${colW + padLeft + padRight}px`;
381
+
382
+ const rootTop = root.getBoundingClientRect().top;
383
+ const breaks = [];
384
+ let page = 1;
385
+ let col = 1;
386
+ let top = null;
387
+ let end = 0;
388
+
389
+ /** 断点只记「断在谁前、去第几页」;占位带高在铺好后按实测补(见 fillGap) */
390
+ const breakBefore = (before, newPage) => {
391
+ if (newPage) {
392
+ page += 1;
393
+ col = 1;
394
+ breaks.push({ el: before, page, newPage: true });
395
+ } else {
396
+ col += 1;
397
+ breaks.push({ el: before, page: 0, newPage: false });
398
+ }
399
+ top = null;
400
+ end = 0;
401
+ };
402
+
403
+ const queue = Array.from(root.children);
404
+ while (queue.length) {
405
+ const el = queue.shift();
406
+ const b = box(el, rootTop, scale, 0);
407
+ if (el.classList.contains(DOC_CLASS.PAGEBREAK)) {
408
+ if (top === null) top = b.top;
409
+ end = Math.max(end, b.end);
410
+ breakBefore(el.nextElementSibling, true);
411
+ continue;
412
+ }
413
+ // 段前分页(w:pageBreakBefore):本栏已有内容 → 本块先换栏再排
414
+ if (el.classList.contains(DOC_CLASS.PBB) && top !== null && end - top > EPS) {
415
+ breakBefore(el, col % cellsPerPage === 0);
416
+ queue.unshift(el);
417
+ continue;
418
+ }
419
+ if (top === null) {
420
+ top = b.top;
421
+ end = b.top; // 新栏还没有内容:下面统一按「本栏已用高度」判定
422
+ }
423
+ const used = end - top;
424
+ if (used + b.h <= capOf(page) + EPS) {
425
+ end = top + used + b.h;
426
+ continue;
427
+ }
428
+ // widowControl(Word 默认开):拆分时尾部预留两行,避免页尾孤行;显式关闭的不留
429
+ // [坑] 预留量不能超过「块高 − 一行」:一行的空段/短段按两行预留会算出负的可用高度,
430
+ // 于是整块被无谓地推到下一页(页底又是一片空白)
431
+ const lh = lineHeightOf(el, scale);
432
+ const widowPad = el.classList?.contains(DOC_CLASS.WIDOW_OFF) || lh <= 0 ? 0 : Math.min(lh * 2, Math.max(0, b.h - lh));
433
+ const plan = fitOf(el, capOf(page) - used - widowPad, scale);
434
+ const tail = plan ? splitBlock(el, plan.take) : null;
435
+ if (tail) {
436
+ breakBefore(tail, col % cellsPerPage === 0);
437
+ queue.unshift(tail);
438
+ continue;
439
+ }
440
+ if (used > EPS) {
441
+ // 拆不动且本栏已有内容:整块挪下一栏
442
+ breakBefore(el, col % cellsPerPage === 0);
443
+ queue.unshift(el);
444
+ continue;
445
+ }
446
+ // 拆不动且本栏空(原子块 / 单行超栏):放行溢出,由后续块接管换栏
447
+ end = top + used + b.h;
448
+ }
449
+ if (multi) root.style.width = prevWidth;
450
+
451
+ const at = new Map();
452
+ breaks.forEach((c) => {
453
+ if (c.el) at.set(c.el, c);
454
+ });
455
+ const ctx = { rootTop: root.getBoundingClientRect().top, scale, pageH: gapOf + capOf(1), padTop, gutter };
456
+ if (multi) packColumns(root, at, { colW, colGap, cellH: capOf(1), gutter, colSeparator: opts.colSeparator }, ctx);
457
+ else insertGaps(root, at, ctx);
458
+ restoreCaret(root, caret);
459
+
460
+ root.__wdPageSig = `rows:${cellsPerPage}:${breaks.map((c) => `${c.newPage ? 'P' : 'C'}${c.page}`).join('|')}`;
461
+ return page;
462
+ };
463
+
464
+ /** 换文档 / 改页面设置后清掉分页状态(新文档不该沿用上一份的分页结构) */
465
+ export const resetPagination = (root) => {
466
+ if (!root) return;
467
+ flatten(root);
468
+ delete root.__wdPageSig;
469
+ };
470
+
471
+ /** 元素在第几页:数它前面的页间占位带(分页产物把「页」落在 DOM 序上;多栏的页间断点同样落带) */
472
+ export const pageOfElement = (root, el) => {
473
+ let page = 1;
474
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
475
+ let cur = walker.nextNode();
476
+ while (cur && cur !== el) {
477
+ if (cur.classList?.contains(GAP_CLASS)) page += 1;
478
+ cur = walker.nextNode();
479
+ }
480
+ return page;
481
+ };