docs_layout.js 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944
  1. /*
  2. ArozOS Office - Docs layout engine
  3. ==================================
  4. Everything about how a document is laid out that CSS cannot decide on
  5. its own, so that the page the editor shows is the page a word processor
  6. would print - and, because the PDF exporter draws this very DOM, the
  7. page the PDF gets.
  8. Four passes over a rendered subtree (the editor, a header/footer copy,
  9. a footnote area):
  10. lineHeights Word and Google Docs size a line from the font's own
  11. ascent and descent, rounded to whole pixels one side at
  12. a time: ceil(ascent x size x spacing) + ceil(descent x
  13. size x spacing). CSS line-height is size x number and
  14. drifts by a pixel or two a line, which over a page is a
  15. different page break. Every block that holds text gets
  16. that exact line height in px, and inline elements get
  17. line-height 0 (docs.css) so a run in another font cannot
  18. make its line taller than the rule says; a run in a
  19. bigger size gets its own px height and grows its line.
  20. numbering list markers ("1.", "b)", bullets) are computed here into
  21. li[data-marker] and drawn by li::before - a real value
  22. the PDF exporter can read, formats CSS counters do not
  23. have ("%1.%2."), and numbering that carries on across a
  24. list interrupted by a paragraph (same data-num).
  25. tabs span.doc-tab is sized to reach the next tab stop: the
  26. paragraph's own stops (data-tabs, right/center/left, with
  27. leaders) or the default 36pt grid.
  28. footnotes references are numbered in document order.
  29. And pagination (paginate): the document is one contenteditable flow,
  30. and page boundaries are made real in it. What crosses a boundary is
  31. split into two elements - a paragraph at a line, the list or quote
  32. around it, a table row cell by cell - and a spacer element between the
  33. halves pushes the second one to the top of the next sheet, so long
  34. paragraphs, lists and tables break where a word processor breaks them
  35. and every half is a box of its own (borders and shading end at the
  36. page). Spacers carry .doc-autobreak; splits are undone, and spacers
  37. removed, on everything that is saved (docs.js cleanedHtml). Headings keep with the paragraph after
  38. them, data-keep-lines paragraphs do not split, data-widow paragraphs
  39. keep two lines on each side, footnotes take their space at the bottom of
  40. the page that references them.
  41. Coordinates are layout px relative to #page's padding box (offsetTop
  42. space, unaffected by the framework's CSS zoom).
  43. */
  44. var DocsLayout = (function () {
  45. "use strict";
  46. var PT = 96 / 72; // css px per point
  47. var MM = 96 / 25.4; // css px per millimetre
  48. var DEFAULT_TAB_PT = 36;
  49. /* ---------------- font metrics ---------------- */
  50. /* ascent/descent per em of the font a family list actually resolves to.
  51. A canvas at 2048px reports the font's own units exactly (ArialMT:
  52. 1854/434), and it resolves a font stack the same way the text did. */
  53. var ratioCache = {};
  54. var ratioCtx = null;
  55. /* Fonts a browser reports taller metrics for than the word processor
  56. lays their lines out with. Consolas is the one that matters: in
  57. Google Docs a Consolas code line is exactly as tall as an Arial line,
  58. while its OS/2 win metrics would overshoot that by a pixel a line. */
  59. var LINE_METRICS = {
  60. "consolas": { asc: 1854 / 2048, desc: 434 / 2048 }
  61. };
  62. function fontRatios(family) {
  63. var key = family || "";
  64. if (ratioCache[key]) return ratioCache[key];
  65. var out = { asc: 0.905, desc: 0.212 };
  66. try {
  67. if (!ratioCtx) ratioCtx = document.createElement("canvas").getContext("2d");
  68. ratioCtx.font = "2048px " + (family || "sans-serif");
  69. var m = ratioCtx.measureText("Hxg");
  70. if (m && m.fontBoundingBoxAscent > 0) {
  71. out = { asc: m.fontBoundingBoxAscent / 2048, desc: m.fontBoundingBoxDescent / 2048 };
  72. }
  73. var first = String(family || "").split(",")[0].trim().replace(/^["']|["']$/g, "").toLowerCase();
  74. if (LINE_METRICS[first] && Math.abs(m.fontBoundingBoxAscent - 1884) < 2) out = LINE_METRICS[first];
  75. } catch (e) { /* estimate */ }
  76. ratioCache[key] = out;
  77. return out;
  78. }
  79. // the word-processor line height rule, in px
  80. function lineHeightPx(sizePx, family, mult) {
  81. var r = fontRatios(family);
  82. var s = sizePx * (mult > 0 ? mult : 1);
  83. return Math.ceil(r.asc * s - 1e-6) + Math.ceil(r.desc * s - 1e-6);
  84. }
  85. /* ---------------- helpers ---------------- */
  86. var INLINE_TAGS = {
  87. A: 1, ABBR: 1, B: 1, BDI: 1, BDO: 1, BR: 1, CITE: 1, CODE: 1, DATA: 1, DEL: 1,
  88. DFN: 1, EM: 1, FONT: 1, I: 1, IMG: 1, INS: 1, KBD: 1, MARK: 1, Q: 1, S: 1,
  89. SAMP: 1, SMALL: 1, SPAN: 1, STRIKE: 1, STRONG: 1, SUB: 1, SUP: 1, TIME: 1,
  90. TT: 1, U: 1, VAR: 1, WBR: 1
  91. };
  92. function isInlineEl(el) {
  93. if (!INLINE_TAGS[el.tagName]) return false;
  94. // an anchored picture or a line spacer is display:block
  95. if (el.classList.contains("doc-anchor") || el.classList.contains("doc-autobreak")) return false;
  96. return true;
  97. }
  98. function isSpacer(el) {
  99. return el.nodeType === 1 && el.classList.contains("doc-autobreak");
  100. }
  101. // does this element hold inline content of its own (a "line block")?
  102. function holdsInline(el) {
  103. for (var c = el.firstChild; c; c = c.nextSibling) {
  104. if (c.nodeType === 3) {
  105. if (c.nodeValue && c.nodeValue.length) return true;
  106. } else if (c.nodeType === 1 && isInlineEl(c)) {
  107. return true;
  108. }
  109. }
  110. return false;
  111. }
  112. function hasBlockChild(el) {
  113. for (var c = el.firstElementChild; c; c = c.nextElementSibling) {
  114. if (!isInlineEl(c) && !isSpacer(c)) return true;
  115. }
  116. return false;
  117. }
  118. // multiple of single spacing stated on a block, or the legacy
  119. // unitless line-height an older document carries
  120. function blockSpacing(el, defLS) {
  121. var ls = parseFloat(el.getAttribute("data-ls"));
  122. if (ls > 0) return ls;
  123. // documents from before data-ls said it as a unitless line-height
  124. var inline = el.style.lineHeight;
  125. if (inline && /^[\d.]+$/.test(inline) && parseFloat(inline) > 0) {
  126. el.setAttribute("data-ls", inline);
  127. return parseFloat(inline);
  128. }
  129. return defLS;
  130. }
  131. function cssLenPx(v) {
  132. v = String(v || "").trim();
  133. var n = parseFloat(v);
  134. if (isNaN(n)) return 0;
  135. if (/pt$/.test(v)) return n * PT;
  136. if (/mm$/.test(v)) return n * MM;
  137. if (/in$/.test(v)) return n * 96;
  138. return n;
  139. }
  140. /* ---------------- line heights ---------------- */
  141. /* lineHeights sets the px line height of every block in root that
  142. holds text, and the own height of any run that is bigger than its
  143. block's smallest run. */
  144. function applyLineHeights(root, defLS) {
  145. if (!root) return;
  146. defLS = defLS > 0 ? defLS : 1.15;
  147. var blocks = [];
  148. if (holdsInline(root) || !root.firstElementChild) blocks.push(root);
  149. var all = root.getElementsByTagName("*");
  150. for (var i = 0; i < all.length; i++) {
  151. var el = all[i];
  152. if (isInlineEl(el) || isSpacer(el)) continue;
  153. if (el.tagName === "TABLE" || el.tagName === "TBODY" || el.tagName === "TR" ||
  154. el.tagName === "COLGROUP" || el.tagName === "COL") continue;
  155. if (holdsInline(el) || !el.firstElementChild) blocks.push(el);
  156. }
  157. blocks.forEach(function (b) { lineHeightFor(b, defLS); });
  158. }
  159. function lineHeightFor(block, defLS) {
  160. var bcs = window.getComputedStyle(block);
  161. if (bcs.display === "none") return;
  162. var exact = block.getAttribute("data-lsexact");
  163. if (exact) {
  164. block.style.lineHeight = cssLenPx(exact) + "px";
  165. return;
  166. }
  167. var mult = blockSpacing(block, defLS);
  168. var minPx = cssLenPx(block.getAttribute("data-lsmin"));
  169. // the runs directly in this block: their sizes decide the lines
  170. var runs = [];
  171. var walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT, {
  172. acceptNode: function (n) {
  173. // text of a nested block belongs to that block
  174. for (var p = n.parentNode; p && p !== block; p = p.parentNode) {
  175. if (p.nodeType === 1 && !isInlineEl(p)) return NodeFilter.FILTER_REJECT;
  176. }
  177. return NodeFilter.FILTER_ACCEPT;
  178. }
  179. });
  180. var preWs = bcs.whiteSpace.indexOf("pre") === 0 || bcs.whiteSpace === "break-spaces";
  181. var node;
  182. while ((node = walker.nextNode())) {
  183. var txt = node.nodeValue;
  184. if (!txt || (!preWs && !/\S/.test(txt))) continue;
  185. var host = node.parentNode;
  186. // superscript / subscript never make a line taller
  187. var inScript = false;
  188. for (var q = host; q && q !== block; q = q.parentNode) {
  189. if (q.tagName === "SUP" || q.tagName === "SUB") { inScript = true; break; }
  190. }
  191. if (inScript) continue;
  192. var cs = window.getComputedStyle(host);
  193. runs.push({ el: host, size: parseFloat(cs.fontSize) || 14.67, family: cs.fontFamily });
  194. }
  195. var baseSize = parseFloat(bcs.fontSize) || 14.67;
  196. var baseFamily = bcs.fontFamily;
  197. var strut;
  198. if (!runs.length) {
  199. strut = lineHeightPx(baseSize, baseFamily, mult);
  200. } else {
  201. var min = runs[0], direct = false;
  202. runs.forEach(function (r) {
  203. if (r.size < min.size) min = r;
  204. if (r.el === block) direct = true;
  205. });
  206. // the paragraph's own font (its mark) takes part in every line;
  207. // so does text standing in the block itself, which has no
  208. // element to carry a height of its own - a heading with a small
  209. // link in it would otherwise get the link's lines
  210. strut = Math.max(lineHeightPx(min.size, min.family, mult),
  211. direct || baseSize <= min.size + 0.01 ? lineHeightPx(baseSize, baseFamily, mult) : 0);
  212. // bigger runs carry their own height so only their lines grow
  213. runs.forEach(function (r) {
  214. if (r.el === block) return;
  215. if (r.size > min.size + 0.01) {
  216. var own = Math.max(lineHeightPx(r.size, r.family, mult), minPx);
  217. if (r.el.style.lineHeight !== own + "px") r.el.style.lineHeight = own + "px";
  218. } else if (r.el.style.lineHeight) {
  219. r.el.style.lineHeight = "";
  220. }
  221. });
  222. }
  223. if (minPx > strut) strut = minPx;
  224. var v = strut + "px";
  225. if (block.style.lineHeight !== v) block.style.lineHeight = v;
  226. if (!runs.length) pictureLines(block, strut, baseSize, baseFamily, mult);
  227. }
  228. /* A line holding pictures is as tall as the tallest picture, plus 1.75pt
  229. above it and the part of a text line that hangs below the baseline
  230. under it - the pictures sit on the baseline. In a paragraph that holds
  231. only pictures that is set exactly: each picture is aligned to the
  232. bottom of its line and carries those two amounts as margins, so the
  233. line comes out the word processor's height to the fraction of a pixel
  234. (baseline alignment would round the picture's top to a whole pixel,
  235. which over a page of screenshots is a paragraph's worth of drift).
  236. Where the text baseline sits is the one thing CSS and a word
  237. processor disagree on: CSS splits the leading evenly around the
  238. glyphs, Word and Google Docs put nearly all the leading that 1.15
  239. spacing adds below them. The marks are undone before saving
  240. (data-picline). */
  241. var PICTURE_TOP_PX = 1.75 * PT;
  242. function pictureLines(block, strut, sizePx, family, mult) {
  243. var imgs = block.getElementsByTagName("img");
  244. if (!imgs.length) return;
  245. var r = fontRatios(family);
  246. var single = lineHeightPx(sizePx, family, 1);
  247. var baseline = Math.ceil(r.asc * sizePx - 1e-6) + 0.2 * (strut - single);
  248. var below = Math.max(0, strut - baseline);
  249. for (var i = 0; i < imgs.length; i++) {
  250. var im = imgs[i];
  251. if (im.classList.contains("doc-anchor")) continue;
  252. if (im.parentNode !== block && !isInlineEl(im.parentNode)) continue;
  253. im.setAttribute("data-picline", "1");
  254. im.style.verticalAlign = "bottom";
  255. im.style.marginTop = PICTURE_TOP_PX + "px";
  256. im.style.marginBottom = below + "px";
  257. }
  258. }
  259. function restorePictureLines(root) {
  260. var imgs = root.querySelectorAll("img[data-picline]");
  261. for (var i = 0; i < imgs.length; i++) {
  262. imgs[i].style.verticalAlign = "";
  263. imgs[i].style.marginTop = "";
  264. imgs[i].style.marginBottom = "";
  265. imgs[i].removeAttribute("data-picline");
  266. if (!imgs[i].getAttribute("style")) imgs[i].removeAttribute("style");
  267. }
  268. }
  269. /* ---------------- table borders ----------------
  270. A browser draws a border in whole device pixels, so a 1pt (1.33px)
  271. table rule takes 1px of layout - and a table of 40 rows comes out 13px
  272. shorter than on paper. The difference goes back in as cell padding,
  273. which is invisible and keeps the rows exactly as tall as the document
  274. says. The padding the document states is kept in data-pad0 and put
  275. back before anything is saved. */
  276. function applyTableBorders(root) {
  277. if (!root) return;
  278. var tables = root.getElementsByTagName("table");
  279. for (var t = 0; t < tables.length; t++) {
  280. var tbl = tables[t];
  281. // a table whose size has not moved since it was last fixed up
  282. // needs nothing (the signature is a property, never saved)
  283. if (tbl.__docsSig && tbl.__docsSig === tableSignature(tbl)) continue;
  284. fixTable(tbl);
  285. if (tbl.hasAttribute("data-docx")) roundRows(tbl);
  286. tbl.__docsSig = tableSignature(tbl);
  287. }
  288. }
  289. function tableSignature(tbl) {
  290. return tbl.rows.length + ":" + tbl.offsetHeight + ":" + tbl.offsetWidth + ":" + (scaleOf(tbl) || 1).toFixed(3);
  291. }
  292. function fixTable(tbl) {
  293. var rows = tbl.rows;
  294. var cells = [];
  295. // put back the stated padding first (writes only) ...
  296. for (var r = 0; r < rows.length; r++) {
  297. if (rows[r].classList.contains("doc-autobreak") || rows[r].closest("table") !== tbl) continue;
  298. for (var c = 0; c < rows[r].cells.length; c++) {
  299. var td = rows[r].cells[c];
  300. var orig = td.getAttribute("data-pad0");
  301. if (orig === null) {
  302. orig = td.style.padding || "";
  303. td.setAttribute("data-pad0", orig);
  304. } else if (td.style.padding !== orig) {
  305. td.style.padding = orig;
  306. }
  307. cells.push({ td: td, last: r + td.rowSpan >= rows.length });
  308. }
  309. }
  310. // ... then measure everything once ...
  311. cells.forEach(function (it) {
  312. var wantTop = declaredBorder(it.td, "Top");
  313. var wantBottom = declaredBorder(it.td, "Bottom");
  314. if (!(wantTop > 0) && !(wantBottom > 0)) return;
  315. var cs = window.getComputedStyle(it.td);
  316. it.padTop = parseFloat(cs.paddingTop) || 0;
  317. it.padBottom = parseFloat(cs.paddingBottom) || 0;
  318. it.dTop = wantTop > 0 ? wantTop - (parseFloat(cs.borderTopWidth) || 0) : 0;
  319. it.dBottom = it.last && wantBottom > 0 ? wantBottom - (parseFloat(cs.borderBottomWidth) || 0) : 0;
  320. });
  321. // ... and write the differences
  322. cells.forEach(function (it) {
  323. if (it.dTop > 0.01) it.td.style.paddingTop = (it.padTop + it.dTop) + "px";
  324. if (it.dBottom > 0.01) it.td.style.paddingBottom = (it.padBottom + it.dBottom) + "px";
  325. });
  326. }
  327. /* Google Docs makes every table row a whole number of pixels tall
  328. (rounding up), so a row of one 10pt line is 31px, not 30.67. Read all
  329. the rows first and write after, so this costs one layout, not one
  330. per row. */
  331. function roundRows(tbl) {
  332. var scale = scaleOf(tbl) || 1;
  333. var rows = [];
  334. for (var r = 0; r < tbl.rows.length; r++) {
  335. var row = tbl.rows[r];
  336. if (row.classList.contains("doc-autobreak") || row.closest("table") !== tbl) continue;
  337. rows.push({ row: row, h: row.getBoundingClientRect().height / scale });
  338. }
  339. var writes = [];
  340. rows.forEach(function (it) {
  341. var extra = Math.ceil(it.h - 0.05) - it.h;
  342. if (extra <= 0.01) return;
  343. for (var c = 0; c < it.row.cells.length; c++) {
  344. var td = it.row.cells[c];
  345. if (td.rowSpan > 1) continue;
  346. writes.push({ td: td, pb: (parseFloat(window.getComputedStyle(td).paddingBottom) || 0) + extra });
  347. }
  348. });
  349. writes.forEach(function (w) { w.td.style.paddingBottom = w.pb + "px"; });
  350. }
  351. // the border width the document states (the specified value, before the
  352. // browser rounds it to device pixels)
  353. function declaredBorder(td, side) {
  354. var st = td.style["border" + side + "Style"];
  355. if (!st || st === "none" || st === "hidden") return 0;
  356. return cssLenPx(td.style["border" + side + "Width"]);
  357. }
  358. function restoreTablePadding(root) {
  359. var cells = root.querySelectorAll("[data-pad0]");
  360. for (var i = 0; i < cells.length; i++) {
  361. cells[i].style.padding = cells[i].getAttribute("data-pad0");
  362. cells[i].removeAttribute("data-pad0");
  363. }
  364. }
  365. /* ---------------- list numbering ---------------- */
  366. var BULLETS = [String.fromCharCode(0x25CF), String.fromCharCode(0x25CB), String.fromCharCode(0x25A0)];
  367. var ORDERED = ["decimal", "lowerLetter", "lowerRoman"];
  368. function roman(n) {
  369. if (n < 1 || n > 3999) return String(n);
  370. var v = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
  371. var s = ["m", "cm", "d", "cd", "c", "xc", "l", "xl", "x", "ix", "v", "iv", "i"];
  372. var out = "";
  373. for (var i = 0; i < v.length; i++) while (n >= v[i]) { out += s[i]; n -= v[i]; }
  374. return out;
  375. }
  376. function formatNumber(n, fmt) {
  377. switch (fmt) {
  378. case "lowerLetter":
  379. case "upperLetter":
  380. if (n < 1) return String(n);
  381. var ch = String.fromCharCode(97 + (n - 1) % 26);
  382. var s = new Array(Math.floor((n - 1) / 26) + 2).join(ch);
  383. return fmt === "upperLetter" ? s.toUpperCase() : s;
  384. case "lowerRoman": return roman(n);
  385. case "upperRoman": return roman(n).toUpperCase();
  386. case "decimalZero": return n < 10 ? "0" + n : String(n);
  387. case "none":
  388. case "bullet": return "";
  389. }
  390. return String(n);
  391. }
  392. function isList(el) { return el && (el.tagName === "OL" || el.tagName === "UL"); }
  393. /* depth of a list among its list ancestors (0 = outermost) */
  394. function listDepth(list, root) {
  395. var d = 0;
  396. for (var p = list.parentNode; p && p !== root; p = p.parentNode) {
  397. if (isList(p)) d++;
  398. }
  399. return d;
  400. }
  401. function applyNumbering(root) {
  402. if (!root) return;
  403. var lists = root.querySelectorAll("ol, ul");
  404. // continuation state per list instance and level
  405. var carried = {};
  406. // a list split across a page carries on in its tail, and the tail
  407. // of a split item is the same item (no marker, no count)
  408. var splitEnd = {}, splitItem = {};
  409. for (var i = 0; i < lists.length; i++) {
  410. var list = lists[i];
  411. if (list.classList.contains("of-checklist")) continue;
  412. var depth = listDepth(list, root);
  413. var ordered = list.tagName === "OL";
  414. var fmt = list.getAttribute("data-fmt") ||
  415. (ordered ? ORDERED[depth % ORDERED.length] : "bullet");
  416. var text = list.getAttribute("data-lvltext");
  417. if (text === null) {
  418. text = fmt === "bullet" ? BULLETS[depth % BULLETS.length] : "%" + (depth + 1) + ".";
  419. }
  420. var num = list.getAttribute("data-num");
  421. var key = num ? num + ":" + depth : null;
  422. var start = parseInt(list.getAttribute("start"), 10);
  423. var counter;
  424. var listOf = list.getAttribute("data-split-of");
  425. if (key && carried[key] !== undefined) counter = carried[key];
  426. else if (listOf && splitEnd[listOf] !== undefined) counter = splitEnd[listOf];
  427. else counter = (isNaN(start) ? 1 : start) - 1;
  428. for (var c = list.firstElementChild; c; c = c.nextElementSibling) {
  429. if (c.tagName !== "LI") continue;
  430. var itemOf = c.getAttribute("data-split-of");
  431. if (itemOf) {
  432. var headItem = splitItem[itemOf];
  433. c.setAttribute("data-n", headItem ? headItem.getAttribute("data-n") : counter);
  434. if (c.getAttribute("data-marker") !== "") c.setAttribute("data-marker", "");
  435. if (c.hasAttribute("data-split")) splitItem[c.getAttribute("data-split")] = headItem || c;
  436. continue;
  437. }
  438. if (c.hasAttribute("data-split")) splitItem[c.getAttribute("data-split")] = c;
  439. var v = parseInt(c.getAttribute("value"), 10);
  440. counter = isNaN(v) ? counter + 1 : v;
  441. c.setAttribute("data-n", counter);
  442. var marker = text.replace(/%(\d)/g, function (m, lvl) {
  443. var want = parseInt(lvl, 10) - 1;
  444. if (want === depth) return formatNumber(counter, fmt);
  445. var anc = ancestorItem(c, want, root);
  446. if (!anc) return "";
  447. var ancList = anc.parentNode;
  448. var ancFmt = ancList.getAttribute("data-fmt") ||
  449. (ancList.tagName === "OL" ? ORDERED[want % ORDERED.length] : "bullet");
  450. return formatNumber(parseInt(anc.getAttribute("data-n"), 10) || 1, ancFmt);
  451. });
  452. if (fmt === "none") marker = text.replace(/%\d/g, "");
  453. if (c.getAttribute("data-marker") !== marker) c.setAttribute("data-marker", marker);
  454. }
  455. if (key) carried[key] = counter;
  456. if (list.hasAttribute("data-split")) splitEnd[list.getAttribute("data-split")] = counter;
  457. // a deeper level restarts once a shallower item of the same list
  458. // comes along
  459. if (key) {
  460. for (var k in carried) {
  461. var parts = k.split(":");
  462. if (parts[0] === num && parseInt(parts[1], 10) > depth) delete carried[k];
  463. }
  464. }
  465. }
  466. }
  467. // the list item at a given depth that a nested list item hangs off
  468. function ancestorItem(li, depth, root) {
  469. var list = li.parentNode;
  470. while (list && list !== root) {
  471. var parent = list.parentNode;
  472. var d = listDepth(list, root);
  473. if (d === depth + 1 || (d > depth && isList(parent) && listDepth(parent, root) === depth)) {
  474. // nested directly in a list: the item before it
  475. if (isList(parent)) {
  476. for (var p = list.previousElementSibling; p; p = p.previousElementSibling) {
  477. if (p.tagName === "LI") return p;
  478. }
  479. return null;
  480. }
  481. if (parent && parent.tagName === "LI") return parent;
  482. }
  483. list = parent;
  484. }
  485. return null;
  486. }
  487. /* ---------------- tabs ---------------- */
  488. // the edge tab stops are measured from: a table cell's content box, or
  489. // the text column
  490. function tabOrigin(span, rootEl) {
  491. for (var p = span.parentNode; p && p !== rootEl; p = p.parentNode) {
  492. if (p.tagName === "TD" || p.tagName === "TH") {
  493. var r = p.getBoundingClientRect();
  494. var cs = window.getComputedStyle(p);
  495. return r.left + (parseFloat(cs.borderLeftWidth) || 0) + (parseFloat(cs.paddingLeft) || 0) * scaleOf(p);
  496. }
  497. }
  498. var rr = rootEl.getBoundingClientRect();
  499. var rcs = window.getComputedStyle(rootEl);
  500. return rr.left + (parseFloat(rcs.paddingLeft) || 0) * scaleOf(rootEl);
  501. }
  502. function scaleOf(el) {
  503. var h = el.offsetWidth;
  504. var r = el.getBoundingClientRect().width;
  505. return h > 0 && r > 0 ? r / h : 1;
  506. }
  507. function parseTabs(block) {
  508. var out = [];
  509. for (var b = block; b; b = b.parentElement) {
  510. var raw = b.getAttribute && b.getAttribute("data-tabs");
  511. if (raw) {
  512. raw.split(";").forEach(function (t) {
  513. var p = t.split(":");
  514. var pos = parseFloat(p[1]);
  515. if (!isNaN(pos)) out.push({ align: p[0] || "left", pos: pos * PT, leader: p[2] || "none" });
  516. });
  517. break;
  518. }
  519. if (!isInlineEl(b) && !holdsInline(b)) break;
  520. }
  521. out.sort(function (a, b) { return a.pos - b.pos; });
  522. return out;
  523. }
  524. function lineBlockOf(el, rootEl) {
  525. for (var p = el.parentNode; p && p !== rootEl; p = p.parentNode) {
  526. if (p.nodeType === 1 && !isInlineEl(p)) return p;
  527. }
  528. return rootEl;
  529. }
  530. function applyTabs(root) {
  531. if (!root) return;
  532. // a tab's position only depends on what comes before it, and the
  533. // ones before it are sized first - so each tab can be measured as
  534. // it stands and written only when its width really changes, which
  535. // on an unchanged document means no layout work at all
  536. var spans = root.querySelectorAll("span.doc-tab");
  537. for (var i = 0; i < spans.length; i++) sizeTab(spans[i], root);
  538. }
  539. function underlinedTab(span, block) {
  540. for (var n = span; n && n !== block && n.nodeType === 1; n = n.parentNode) {
  541. var d = window.getComputedStyle(n).textDecorationLine || "";
  542. if (d.indexOf("underline") >= 0 || n.tagName === "U") return true;
  543. }
  544. return false;
  545. }
  546. function sizeTab(span, root) {
  547. var block = lineBlockOf(span, root);
  548. var scale = scaleOf(root) || 1;
  549. if (span.style.display !== "inline-block") span.style.display = "inline-block";
  550. var origin = tabOrigin(span, root);
  551. var x = (span.getBoundingClientRect().left - origin) / scale;
  552. var stops = parseTabs(block);
  553. var stop = null;
  554. for (var i = 0; i < stops.length; i++) {
  555. if (stops[i].pos > x + 0.5) { stop = stops[i]; break; }
  556. }
  557. var w;
  558. if (!stop) {
  559. var grid = DEFAULT_TAB_PT * PT;
  560. w = (Math.floor(x / grid + 1e-6) + 1) * grid - x;
  561. if (w < 1) w += grid;
  562. } else if (stop.align === "right" || stop.align === "center" || stop.align === "decimal") {
  563. // the text after the tab, up to the next tab or the end of the line
  564. var follow = followingWidth(span, block) / scale;
  565. // a right stop sits on the margin more often than not; a hair of
  566. // slack keeps the number from wrapping to a line of its own
  567. w = stop.pos - x - (stop.align === "center" ? follow / 2 : follow) - 1;
  568. if (w < 0) w = 0;
  569. } else {
  570. w = stop.pos - x;
  571. }
  572. w = Math.max(0, w);
  573. if (Math.abs((parseFloat(span.style.width) || -1) - w) > 0.25) span.style.width = w + "px";
  574. var leader = stop && stop.leader && stop.leader !== "none" ? stop.leader : null;
  575. // an underline does not reach into the tab's box (it is an inline
  576. // block), so a tab inside underlined text draws its own - the blank
  577. // to write on that a form's "Name: ____" is made of
  578. if (!leader && underlinedTab(span, block)) leader = "underscore";
  579. // a leader's marks are placed from a box of no height (docs.css)
  580. var lh = leader ? "0" : "";
  581. if (span.style.lineHeight !== lh) span.style.lineHeight = lh;
  582. if (span.getAttribute("data-leader") !== leader) {
  583. if (leader) span.setAttribute("data-leader", leader);
  584. else span.removeAttribute("data-leader");
  585. }
  586. }
  587. function followingWidth(span, block) {
  588. var range = document.createRange();
  589. range.setStartAfter(span);
  590. var end = null;
  591. var walker = document.createTreeWalker(block, NodeFilter.SHOW_ELEMENT, null);
  592. walker.currentNode = span;
  593. var n;
  594. while ((n = walker.nextNode())) {
  595. if (n.classList && n.classList.contains("doc-tab")) { end = n; break; }
  596. if (n.tagName === "BR") { end = n; break; }
  597. }
  598. if (end) range.setEndBefore(end);
  599. else range.setEnd(block, block.childNodes.length);
  600. var rects = range.getClientRects();
  601. if (!rects.length) return 0;
  602. // only what stays on the tab's own line counts
  603. var top = span.getBoundingClientRect().top;
  604. var left = Infinity, right = -Infinity;
  605. for (var i = 0; i < rects.length; i++) {
  606. if (Math.abs(rects[i].top - top) > rects[i].height) continue;
  607. left = Math.min(left, rects[i].left);
  608. right = Math.max(right, rects[i].right);
  609. }
  610. return right > left ? right - left : 0;
  611. }
  612. /* ---------------- footnote references ---------------- */
  613. function numberFootnotes(root) {
  614. var order = [];
  615. if (!root) return order;
  616. var refs = root.querySelectorAll("sup.doc-fnref");
  617. for (var i = 0; i < refs.length; i++) {
  618. var id = refs[i].getAttribute("data-fn");
  619. var n = order.indexOf(id);
  620. if (n < 0) { order.push(id); n = order.length - 1; }
  621. var label = String(n + 1);
  622. if (refs[i].textContent !== label) refs[i].textContent = label;
  623. refs[i].setAttribute("contenteditable", "false");
  624. }
  625. return order;
  626. }
  627. /* ---------------- pagination ---------------- */
  628. function Paginator(o) {
  629. this.o = o;
  630. this.editor = o.editor;
  631. this.pageEl = o.pageEl;
  632. this.sheetH = o.sheetH;
  633. this.gap = o.gap;
  634. this.mTop = o.mTop;
  635. this.mBot = o.mBot;
  636. }
  637. // y of an element's border-box top in #page padding-box coordinates
  638. Paginator.prototype.top = function (el) {
  639. var y = 0;
  640. var n = el;
  641. while (n && n !== this.pageEl) {
  642. y += n.offsetTop;
  643. n = n.offsetParent;
  644. if (n === document.body || !n) {
  645. // #page is not the offset parent chain root: measure
  646. return this.rectTop(el.getBoundingClientRect());
  647. }
  648. }
  649. return y;
  650. };
  651. Paginator.prototype.bottom = function (el) {
  652. return this.top(el) + el.offsetHeight;
  653. };
  654. Paginator.prototype.scale = function () {
  655. var h = this.pageEl.offsetHeight;
  656. var r = this.pageEl.getBoundingClientRect().height;
  657. return h > 0 && r > 0 ? r / h : 1;
  658. };
  659. Paginator.prototype.rectTop = function (rect) {
  660. var pr = this.pageEl.getBoundingClientRect();
  661. return (rect.top - pr.top) / this._scale - this.pageEl.clientTop;
  662. };
  663. Paginator.prototype.rectBottom = function (rect) {
  664. var pr = this.pageEl.getBoundingClientRect();
  665. return (rect.bottom - pr.top) / this._scale - this.pageEl.clientTop;
  666. };
  667. Paginator.prototype.sheetTop = function (i) { return i * (this.sheetH + this.gap); };
  668. Paginator.prototype.contentTop = function (i) { return this.sheetTop(i) + this.mTop; };
  669. Paginator.prototype.contentBottom = function (i) { return this.sheetTop(i) + this.sheetH - this.mBot; };
  670. /* ---- splitting what crosses a page ----
  671. A page boundary is real in the DOM. Whatever runs across it - a
  672. paragraph, the list or quote around it, a table row and the cells of
  673. that row - is cut into two elements: the head keeps what fits on the
  674. page, a shallow copy (the tail) receives the rest, and a spacer
  675. between them pushes the tail to the top of the next sheet. A border,
  676. a shading or a cell rule therefore ends at the bottom of its page and
  677. starts again on the next one, and nothing is left painted across the
  678. gap between the sheets.
  679. The two halves are paired with a token: data-split on the head,
  680. data-split-of on the tail, data-pair on the spacer. Undoing a split
  681. (before a relayout, and on everything that is saved) moves the tail's
  682. content back into its head - an inner pair (a span or a cell cut in
  683. the same place) is joined along the way - and the text node that was
  684. divided is joined again. The caret is followed through all of it. */
  685. var splitSeq = 0;
  686. var splitBase = Math.floor(Math.random() * 46656).toString(36) + "-";
  687. function newToken() {
  688. splitSeq++;
  689. return splitBase + splitSeq.toString(36);
  690. }
  691. // the selection, followed through the node moves a split makes
  692. var track = null;
  693. function beginTrack(root) {
  694. var outer = track;
  695. var sel = window.getSelection ? window.getSelection() : null;
  696. if (!outer && sel && sel.rangeCount && sel.anchorNode && root.contains(sel.anchorNode)) {
  697. track = {
  698. sel: sel, a: sel.anchorNode, ao: sel.anchorOffset,
  699. f: sel.focusNode, fo: sel.focusOffset, moved: false
  700. };
  701. }
  702. return { outer: outer, mine: !outer && !!track };
  703. }
  704. function endTrack(t) {
  705. if (!t.mine) return;
  706. var tr = track;
  707. track = null;
  708. if (!tr || !tr.moved) return;
  709. if (!tr.a.isConnected || !tr.f.isConnected) return;
  710. var len = function (n) { return n.nodeType === 3 ? n.nodeValue.length : n.childNodes.length; };
  711. try {
  712. tr.sel.setBaseAndExtent(tr.a, Math.min(tr.ao, len(tr.a)), tr.f, Math.min(tr.fo, len(tr.f)));
  713. } catch (e) { /* a selection the browser will not take back: leave it */ }
  714. }
  715. function noteMoved() {
  716. if (track) track.moved = true;
  717. }
  718. function splitText(node, offset) {
  719. var tail = node.splitText(offset);
  720. if (track) {
  721. if (track.a === node && track.ao > offset) { track.a = tail; track.ao -= offset; }
  722. if (track.f === node && track.fo > offset) { track.f = tail; track.fo -= offset; }
  723. track.moved = true;
  724. }
  725. return tail;
  726. }
  727. function joinText(prev, next) {
  728. var n = prev.nodeValue.length;
  729. if (track) {
  730. if (track.a === next) { track.a = prev; track.ao += n; }
  731. if (track.f === next) { track.f = prev; track.fo += n; }
  732. track.moved = true;
  733. }
  734. prev.nodeValue += next.nodeValue;
  735. next.parentNode.removeChild(next);
  736. }
  737. var SPLIT_BOX = { TR: 1, TD: 1, TH: 1, TBODY: 1, THEAD: 1, TFOOT: 1 };
  738. function cloneShell(el) {
  739. var c = el.cloneNode(false);
  740. c.removeAttribute("id");
  741. c.removeAttribute("data-split");
  742. c.removeAttribute("data-split-of");
  743. c.removeAttribute("data-marker");
  744. c.classList.remove("doc-split-head", "doc-split-tail");
  745. if (!c.getAttribute("class")) c.removeAttribute("class");
  746. if (el.tagName === "OL") c.removeAttribute("start");
  747. if (el.classList.contains("doc-colsec")) {
  748. // the rest of a column section is laid out afresh on its page
  749. c.style.height = "";
  750. c.classList.remove("doc-colsec-fill");
  751. if (!c.getAttribute("style")) c.removeAttribute("style");
  752. }
  753. if (el.tagName === "TR") {
  754. c.style.height = "";
  755. c.removeAttribute("height");
  756. if (!c.getAttribute("style")) c.removeAttribute("style");
  757. }
  758. if (el.tagName === "TABLE") {
  759. // the tail of a table needs the column widths too
  760. for (var k = el.firstElementChild; k; k = k.nextElementSibling) {
  761. if (k.tagName !== "COLGROUP") continue;
  762. var cg = k.cloneNode(true);
  763. cg.setAttribute("data-split-copy", "1");
  764. c.appendChild(cg);
  765. }
  766. }
  767. return c;
  768. }
  769. function pairUp(head, tail) {
  770. var k = newToken();
  771. head.setAttribute("data-split", k);
  772. tail.setAttribute("data-split-of", k);
  773. if (!SPLIT_BOX[head.tagName] && !isInlineEl(head)) {
  774. head.classList.add("doc-split-head");
  775. tail.classList.add("doc-split-tail");
  776. }
  777. return k;
  778. }
  779. /* unmark drops one role from an element - "head" or "tail" - or both.
  780. An element can be both at once (the middle of a row that spans three
  781. pages), so undoing one split must leave the other alone. deep strips
  782. everything below it too (a split that is being given up). */
  783. function unmark(el, role, deep) {
  784. var list = deep ? [el].concat(Array.prototype.slice.call(el.querySelectorAll("[data-split],[data-split-of]"))) : [el];
  785. list.forEach(function (n, i) {
  786. var r = i === 0 ? role : "both";
  787. if (r !== "tail") {
  788. n.removeAttribute("data-split");
  789. n.classList.remove("doc-split-head");
  790. }
  791. if (r !== "head") {
  792. n.removeAttribute("data-split-of");
  793. n.classList.remove("doc-split-tail");
  794. }
  795. if (!n.getAttribute("class")) n.removeAttribute("class");
  796. });
  797. }
  798. function meaningful(n) {
  799. if (n.nodeType === 3) return /\S/.test(n.nodeValue);
  800. return n.nodeType === 1 && !isSpacer(n) && !n.hasAttribute("data-split-copy");
  801. }
  802. function prevMeaningful(n) {
  803. for (var p = n.previousSibling; p; p = p.previousSibling) if (meaningful(p)) return p;
  804. return null;
  805. }
  806. function nextMeaningful(n) {
  807. for (var p = n.nextSibling; p; p = p.nextSibling) if (meaningful(p)) return p;
  808. return null;
  809. }
  810. function nextInOrder(node, stop) {
  811. for (var n = node; n && n !== stop; n = n.parentNode) {
  812. if (n.nextSibling) return n.nextSibling;
  813. }
  814. return null;
  815. }
  816. /* splitTree moves `start` and everything after it, up to the end of
  817. `boundary`, into shallow copies of the ancestors in between. Returns
  818. the node directly inside boundary that the moved content begins with.
  819. An ancestor whose content all moves is taken along whole instead of
  820. being copied, so no half is ever left empty. */
  821. function splitTree(start, boundary) {
  822. var cur = start;
  823. if (!cur || cur === boundary || !boundary.contains(cur)) return null;
  824. while (cur && cur.parentNode && cur.parentNode !== boundary) {
  825. var parent = cur.parentNode;
  826. if (!prevMeaningful(cur)) {
  827. cur = parent;
  828. continue;
  829. }
  830. var clone = cloneShell(parent);
  831. pairUp(parent, clone);
  832. parent.parentNode.insertBefore(clone, parent.nextSibling);
  833. var n = cur;
  834. while (n) {
  835. var nx = n.nextSibling;
  836. clone.appendChild(n);
  837. n = nx;
  838. }
  839. noteMoved();
  840. cur = clone;
  841. }
  842. return cur;
  843. }
  844. // the node a line cut starts the moved content with (text divided there)
  845. function lineStartNode(cut) {
  846. if (cut.beforeEl) return cut.beforeEl;
  847. var node = cut.node;
  848. var len = node.nodeValue.length;
  849. var at = cut.offset;
  850. // the space a line wrapped at stays at the end of the line above,
  851. // where it collapses; at the start of the next page it would not
  852. var ws = node.parentNode ? window.getComputedStyle(node.parentNode).whiteSpace : "normal";
  853. if (ws.indexOf("pre") !== 0 && ws !== "break-spaces") {
  854. while (at > 0 && at < len && /\s/.test(node.nodeValue.charAt(at))) at++;
  855. }
  856. cut = { el: cut.el, node: node, offset: at };
  857. if (cut.offset > 0 && cut.offset < len) return splitText(node, cut.offset);
  858. if (cut.offset >= len) return nextInOrder(node, cut.el);
  859. return node;
  860. }
  861. /* mergePair undoes one split: the tail's content goes back to the end
  862. of its head (for a table row, cell by cell) and the tail goes away */
  863. function mergePair(head, tail) {
  864. if (!head || !tail || !tail.parentNode) return;
  865. noteMoved();
  866. if (head.tagName === "TR" && tail.tagName === "TR") {
  867. var tcells = Array.prototype.slice.call(tail.cells);
  868. for (var i = 0; i < tcells.length; i++) {
  869. var hc = head.cells[i];
  870. if (hc) {
  871. mergeChildren(hc, tcells[i]);
  872. unmark(hc, "head");
  873. } else {
  874. unmark(tcells[i], "tail");
  875. head.appendChild(tcells[i]);
  876. }
  877. }
  878. } else {
  879. mergeChildren(head, tail);
  880. }
  881. if (tail.parentNode) tail.parentNode.removeChild(tail);
  882. unmark(head, "head");
  883. if (head.classList.contains("doc-colsec")) resetColumns(head);
  884. }
  885. function mergeChildren(head, tail) {
  886. var c, nx;
  887. for (c = tail.firstChild; c; c = nx) {
  888. nx = c.nextSibling;
  889. if (c.nodeType === 1 && c.hasAttribute("data-split-copy")) tail.removeChild(c);
  890. }
  891. // an inner pair cut at the same place (a span, a list, a nested
  892. // table) joins first, so the content meets inside it
  893. var last = head.lastChild;
  894. while (last && !meaningful(last)) last = last.previousSibling;
  895. var first = tail.firstChild;
  896. while (first && !meaningful(first)) first = first.nextSibling;
  897. if (last && first && last.nodeType === 1 && first.nodeType === 1) {
  898. var k = first.getAttribute("data-split-of");
  899. if (k && last.getAttribute("data-split") === k) mergePair(last, first);
  900. }
  901. var seam = head.lastChild;
  902. while (tail.firstChild) head.appendChild(tail.firstChild);
  903. if (seam && seam.nodeType === 3 && seam.nextSibling && seam.nextSibling.nodeType === 3) {
  904. joinText(seam, seam.nextSibling);
  905. }
  906. }
  907. // undo the split a spacer stands for (the spacer is already gone)
  908. function mergeAround(root, k, prev, next) {
  909. if (!k) return;
  910. var head = prev && prev.nodeType === 1 && prev.getAttribute("data-split") === k ? prev : null;
  911. var tail = next && next.nodeType === 1 && next.getAttribute("data-split-of") === k ? next : null;
  912. if (!head) {
  913. var hs = root.querySelectorAll('[data-split="' + k + '"]');
  914. head = hs.length ? hs[hs.length - 1] : null;
  915. }
  916. if (!tail) tail = root.querySelector('[data-split-of="' + k + '"]');
  917. if (head && tail) mergePair(head, tail);
  918. else {
  919. if (head) unmark(head, "head");
  920. if (tail) unmark(tail, "tail");
  921. }
  922. }
  923. function removeSpacerList(list, root) {
  924. for (var i = list.length - 1; i >= 0; i--) {
  925. var el = list[i];
  926. var parent = el.parentNode;
  927. if (!parent) continue;
  928. var k = el.getAttribute("data-pair");
  929. var rs = el.getAttribute("data-rowspans");
  930. if (rs) joinRowspans(root, rs.split(","));
  931. var prev = el.previousSibling, next = el.nextSibling;
  932. while (prev && !meaningful(prev) && !isSpacer(prev)) prev = prev.previousSibling;
  933. while (next && !meaningful(next) && !isSpacer(next)) next = next.nextSibling;
  934. parent.removeChild(el);
  935. noteMoved();
  936. if (k) {
  937. mergeAround(root, k, prev, next);
  938. } else if (prev && next && prev.nodeType === 3 && next.nodeType === 3 &&
  939. prev.nextSibling === next) {
  940. // a line spacer from an older layout divided this text
  941. joinText(prev, next);
  942. }
  943. }
  944. }
  945. function isInner(el) {
  946. var p = el.parentNode;
  947. return !!(p && p.nodeType === 1 && (p.hasAttribute("data-split") || p.hasAttribute("data-split-of")));
  948. }
  949. /* repairSplits puts right what editing did to a split: a tail whose
  950. spacer was deleted joins its head again, and a marker left without
  951. its partner (the tail typed away, a copy made by Enter) is dropped.
  952. With all, every remaining pair is undone - what is saved has none. */
  953. function repairSplits(root, all) {
  954. var tails = root.querySelectorAll("[data-split-of]");
  955. var i;
  956. for (i = tails.length - 1; i >= 0; i--) {
  957. var tl = tails[i];
  958. if (!tl.parentNode || !root.contains(tl) || isInner(tl)) continue;
  959. var k = tl.getAttribute("data-split-of");
  960. var prev = tl.previousSibling;
  961. while (prev && !meaningful(prev) && !isSpacer(prev)) prev = prev.previousSibling;
  962. if (!all && prev && isSpacer(prev) && prev.getAttribute("data-pair") === k) continue;
  963. var head = prev && prev.nodeType === 1 && prev.getAttribute("data-split") === k ? prev : null;
  964. if (head) mergePair(head, tl);
  965. else unmark(tl, "tail", true);
  966. }
  967. var heads = root.querySelectorAll("[data-split]");
  968. for (i = 0; i < heads.length; i++) {
  969. var h = heads[i];
  970. if (!h.isConnected || !h.hasAttribute("data-split") || isInner(h)) continue;
  971. var nx = h.nextSibling;
  972. while (nx && !meaningful(nx) && !isSpacer(nx)) nx = nx.nextSibling;
  973. if (!all && nx && isSpacer(nx) && nx.getAttribute("data-pair") === h.getAttribute("data-split")) continue;
  974. unmark(h, "head", true);
  975. }
  976. }
  977. function removeSpacers(root) {
  978. var t = beginTrack(root);
  979. try {
  980. removeSpacerList(root.querySelectorAll(".doc-autobreak"), root);
  981. repairSplits(root, true);
  982. joinRowspans(root);
  983. unwrapColumns(root);
  984. var breaks = root.querySelectorAll(".doc-pagebreak");
  985. for (var i = 0; i < breaks.length; i++) breaks[i].style.height = "0px";
  986. } finally {
  987. endTrack(t);
  988. }
  989. }
  990. /* unsplitWithin undoes the splits inside an element (a table about to
  991. gain or lose a row or column) */
  992. function unsplitWithin(root, el) {
  993. if (!root || !el) return false;
  994. var list = el.querySelectorAll(".doc-autobreak");
  995. if (!list.length) return false;
  996. var t = beginTrack(root);
  997. try {
  998. removeSpacerList(list, root);
  999. repairSplits(root, false);
  1000. } finally {
  1001. endTrack(t);
  1002. }
  1003. return true;
  1004. }
  1005. /* unsplitAtCaret is called before a key edits the document. A
  1006. Backspace at the start of what a page break moved, a Delete at the
  1007. end of what it left behind, or any key over a selection that spans a
  1008. page boundary would otherwise act on the spacer rather than on the
  1009. text; the split in the way is undone first, and the edit then does
  1010. what it would do in one continuous paragraph. */
  1011. function edgeEmpty(el, caretNode, caretOffset, atStart) {
  1012. var r = document.createRange();
  1013. try {
  1014. if (atStart) {
  1015. r.setStart(el, 0);
  1016. r.setEnd(caretNode, caretOffset);
  1017. } else {
  1018. r.setStart(caretNode, caretOffset);
  1019. r.setEnd(el, el.childNodes.length);
  1020. }
  1021. } catch (e) { return false; }
  1022. if (r.toString().replace(/\s/g, "").split(String.fromCharCode(0x200B)).join("") !== "") return false;
  1023. var frag = r.cloneContents();
  1024. return !frag.querySelector || !frag.querySelector("img,table,hr");
  1025. }
  1026. function unsplitAtCaret(root, backward) {
  1027. var sel = window.getSelection ? window.getSelection() : null;
  1028. if (!sel || !sel.rangeCount) return false;
  1029. var r = sel.getRangeAt(0);
  1030. if (!root.contains(r.commonAncestorContainer)) return false;
  1031. var spacers = [];
  1032. var all, i;
  1033. if (!r.collapsed) {
  1034. all = root.querySelectorAll(".doc-autobreak");
  1035. for (i = 0; i < all.length; i++) {
  1036. if (r.intersectsNode(all[i])) spacers.push(all[i]);
  1037. }
  1038. } else {
  1039. var node = backward ? r.startContainer : r.endContainer;
  1040. var off = backward ? r.startOffset : r.endOffset;
  1041. var el = node.nodeType === 1 ? node : node.parentNode;
  1042. while (el && el !== root) {
  1043. if (el.tagName !== "TR" && !edgeEmpty(el, node, off, backward) &&
  1044. !((el.tagName === "TD" || el.tagName === "TH") && el.hasAttribute(backward ? "data-split-of" : "data-split"))) {
  1045. break;
  1046. }
  1047. var sib = backward ? el.previousSibling : el.nextSibling;
  1048. while (sib && !meaningful(sib) && !isSpacer(sib)) sib = backward ? sib.previousSibling : sib.nextSibling;
  1049. if (sib && isSpacer(sib)) {
  1050. spacers.push(sib);
  1051. break;
  1052. }
  1053. if (el.tagName === "TD" || el.tagName === "TH") {
  1054. el = el.parentNode;
  1055. continue;
  1056. }
  1057. if (sib) break;
  1058. el = el.parentNode;
  1059. }
  1060. }
  1061. if (!spacers.length) return false;
  1062. var t = beginTrack(root);
  1063. try {
  1064. removeSpacerList(spacers, root);
  1065. repairSplits(root, false);
  1066. } finally {
  1067. endTrack(t);
  1068. }
  1069. return true;
  1070. }
  1071. /* ---- columns ----
  1072. A multi-column page is laid out in column sections: every run of
  1073. text that flows in columns (everything between two full-width blocks,
  1074. .col-span-all) is wrapped in a div.doc-colsec with CSS columns, and a
  1075. full-width block stays outside, across the page. A section that fits
  1076. on its page balances its columns; one that runs past the page bottom
  1077. is given the height that is left and filled column by column, and it
  1078. splits - like any other block - at the first content that spilled
  1079. into a column past the last one. The copy of the section carries the
  1080. rest to the next page, where it is laid out the same way.
  1081. Sections are layout only, like spacers: made before every layout of a
  1082. columned document and taken out again on everything that is saved. */
  1083. function isSpanning(el) {
  1084. return el.classList.contains("col-span-all") || el.classList.contains("doc-pagebreak") ||
  1085. el.getAttribute("data-page-break-before") === "1";
  1086. }
  1087. function resetColumns(sec) {
  1088. sec.classList.remove("doc-colsec-fill");
  1089. sec.style.height = "";
  1090. if (!sec.getAttribute("style")) sec.removeAttribute("style");
  1091. }
  1092. function unwrapColumns(root) {
  1093. var secs = root.querySelectorAll(".doc-colsec");
  1094. for (var i = secs.length - 1; i >= 0; i--) {
  1095. var sec = secs[i];
  1096. var parent = sec.parentNode;
  1097. if (!parent) continue;
  1098. while (sec.firstChild) parent.insertBefore(sec.firstChild, sec);
  1099. parent.removeChild(sec);
  1100. noteMoved();
  1101. }
  1102. }
  1103. function wrapColumns(root) {
  1104. var sec = null;
  1105. for (var n = root.firstChild; n; ) {
  1106. var next = n.nextSibling;
  1107. var breaks = n.nodeType === 1 && (isSpacer(n) || isSpanning(n) || n.classList.contains("doc-colsec"));
  1108. if (breaks) {
  1109. sec = null;
  1110. } else if (n.nodeType === 1 || (n.nodeType === 3 && /\S/.test(n.nodeValue))) {
  1111. if (!sec) {
  1112. sec = document.createElement("div");
  1113. sec.className = "doc-colsec";
  1114. root.insertBefore(sec, n);
  1115. }
  1116. sec.appendChild(n);
  1117. noteMoved();
  1118. } else if (sec) {
  1119. sec.appendChild(n);
  1120. }
  1121. n = next;
  1122. }
  1123. }
  1124. /* the first content of a column section that sits in a column past the
  1125. last one the page has: { before: el } or { block, node, offset } /
  1126. { block, beforeEl } for a line inside a paragraph */
  1127. Paginator.prototype.columnOverflow = function (sec) {
  1128. var n = Math.max(1, this.o.columns || 1);
  1129. var cs = window.getComputedStyle(sec);
  1130. var gap = parseFloat(cs.columnGap) || 0;
  1131. var colW = (sec.clientWidth - gap * (n - 1)) / n;
  1132. var scale = this._scale || 1;
  1133. var limit = sec.getBoundingClientRect().left + (n * colW + (n - 0.5) * gap) * scale;
  1134. function past(rect) { return rect.left >= limit - 0.5; }
  1135. function anyPast(rects) {
  1136. for (var i = 0; i < rects.length; i++) if (past(rects[i])) return true;
  1137. return false;
  1138. }
  1139. var range = document.createRange();
  1140. function charRect(node, i, len) {
  1141. for (; i < len; i++) {
  1142. range.setStart(node, i);
  1143. range.setEnd(node, i + 1);
  1144. var rr = range.getClientRects();
  1145. if (rr.length && rr[0].height > 0) return { rect: rr[rr.length - 1], at: i };
  1146. }
  1147. return null;
  1148. }
  1149. function inLine(block) {
  1150. var walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, null);
  1151. var node;
  1152. while ((node = walker.nextNode())) {
  1153. if (node.nodeType === 1) {
  1154. if (node.tagName === "IMG" && anyPast(node.getClientRects())) return { block: block, beforeEl: node };
  1155. continue;
  1156. }
  1157. if (!node.nodeValue) continue;
  1158. range.selectNodeContents(node);
  1159. if (!anyPast(range.getClientRects())) continue;
  1160. var len = node.nodeValue.length;
  1161. var lo = 0, hi = len - 1, ans = len;
  1162. while (lo <= hi) {
  1163. var mid = (lo + hi) >> 1;
  1164. var cr = charRect(node, mid, len);
  1165. if (!cr) { hi = mid - 1; continue; }
  1166. if (past(cr.rect)) { ans = Math.min(ans, cr.at); hi = mid - 1; }
  1167. else lo = cr.at + 1;
  1168. }
  1169. return { block: block, node: node, offset: Math.min(ans, len) };
  1170. }
  1171. return null;
  1172. }
  1173. function find(container) {
  1174. for (var c = container.firstElementChild; c; c = c.nextElementSibling) {
  1175. if (isSpacer(c)) continue;
  1176. var rects = c.getClientRects();
  1177. if (!rects.length) continue;
  1178. if (past(rects[0])) return { before: c };
  1179. if (!anyPast(rects)) continue;
  1180. if (c.tagName === "TABLE") {
  1181. var rows = rowsOf(c);
  1182. for (var r = 0; r < rows.length; r++) {
  1183. if (anyPast(rows[r].getClientRects())) return { before: r === 0 ? c : rows[r] };
  1184. }
  1185. return { before: c };
  1186. }
  1187. if (c.tagName === "IMG" || c.tagName === "HR" || c.tagName === "VIDEO" || c.tagName === "IFRAME") {
  1188. return { before: c };
  1189. }
  1190. if (hasBlockChild(c)) {
  1191. var inner = find(c);
  1192. if (inner) return inner;
  1193. return { before: c };
  1194. }
  1195. return inLine(c) || { before: c };
  1196. }
  1197. return null;
  1198. };
  1199. return find(sec);
  1200. };
  1201. Paginator.prototype.splitColumns = function (sec, B, C, boundary) {
  1202. var top = this.top(sec);
  1203. var avail = B - top;
  1204. if (avail < 2) return top > C + 1 ? this.beforeCut(sec, C, boundary) : { kind: "overflow", y: top };
  1205. sec.classList.add("doc-colsec-fill");
  1206. sec.style.height = avail + "px";
  1207. var hit = this.columnOverflow(sec);
  1208. if (!hit) return { kind: "fit" };
  1209. // nothing of the section fits: it moves whole, or spills when it
  1210. // already starts the page
  1211. var startNode = hit.before ? hit.before.parentNode : (hit.beforeEl ? hit.beforeEl.parentNode : hit.node);
  1212. var startOffset = hit.before ? Array.prototype.indexOf.call(hit.before.parentNode.childNodes, hit.before) :
  1213. (hit.beforeEl ? Array.prototype.indexOf.call(hit.beforeEl.parentNode.childNodes, hit.beforeEl) : hit.offset);
  1214. if (edgeEmpty(sec, startNode, startOffset, true)) {
  1215. resetColumns(sec);
  1216. return top > C + 1 ? this.beforeCut(sec, C, boundary) : { kind: "overflow", y: top };
  1217. }
  1218. // the page is full: its footnotes are the references above B in the
  1219. // columns that stay
  1220. if (hit.before) return { kind: "before", el: hit.before, col: true, y: B + 0.5, boundary: boundary };
  1221. return {
  1222. kind: "line", el: hit.block, node: hit.node, offset: hit.offset, beforeEl: hit.beforeEl,
  1223. y: B + 0.5, boundary: boundary
  1224. };
  1225. };
  1226. function blockKids(container) {
  1227. var out = [];
  1228. for (var c = container.firstElementChild; c; c = c.nextElementSibling) {
  1229. if (isSpacer(c)) continue;
  1230. if (c.tagName === "COLGROUP" || c.tagName === "COL") continue;
  1231. out.push(c);
  1232. }
  1233. return out;
  1234. }
  1235. function keepsWithNext(el) {
  1236. if (el.getAttribute("data-keep-next") === "1") return true;
  1237. // headings written in the editor keep with what follows, like the
  1238. // Heading styles of every word processor
  1239. return /^H[1-6]$/.test(el.tagName) && !el.hasAttribute("data-keep-next");
  1240. }
  1241. /* A cut says where page content stops:
  1242. { kind: "before", el } content from el moves (a block, li, row)
  1243. { kind: "line", el, node, offset | beforeEl } a block splits at a line
  1244. { kind: "row", tr, cells: [cut|null per cell] }
  1245. { kind: "explicit", el } a manual page break
  1246. { kind: "overflow" } nothing movable: content spills over
  1247. with y = where the moved content currently starts, and boundary = the
  1248. element the split reaches up to (the editor, or a table cell). */
  1249. Paginator.prototype.findCut = function (container, B, C, boundary) {
  1250. var kids = blockKids(container);
  1251. if (!kids.length) return null;
  1252. // explicit breaks and page-break-before on this level
  1253. for (var e = 0; e < kids.length; e++) {
  1254. var k = kids[e];
  1255. if (k.classList.contains("doc-pagebreak")) {
  1256. var ty = this.top(k);
  1257. if (ty >= C - 1 && ty <= B + 0.5) return { kind: "explicit", el: k, y: ty, boundary: boundary };
  1258. } else if (k.getAttribute("data-page-break-before") === "1") {
  1259. var py = this.top(k);
  1260. if (py > C + 1 && py <= B + 0.5) return this.beforeCut(k, C, boundary);
  1261. }
  1262. }
  1263. // first child whose bottom crosses B (children are in flow order)
  1264. var lo = 0, hi = kids.length - 1, idx = -1;
  1265. while (lo <= hi) {
  1266. var mid = (lo + hi) >> 1;
  1267. if (this.bottom(kids[mid]) > B + 0.5) { idx = mid; hi = mid - 1; }
  1268. else lo = mid + 1;
  1269. }
  1270. if (idx < 0) return null;
  1271. // a float or a negative margin can leave an earlier child lower;
  1272. // walk back over anything that also crosses
  1273. while (idx > 0 && this.bottom(kids[idx - 1]) > B + 0.5) idx--;
  1274. // a child that only hangs its spacing-after over the edge still
  1275. // fits - the cut belongs to whatever comes after it
  1276. for (; idx < kids.length; idx++) {
  1277. if (idx > 0 && this.bottom(kids[idx]) <= B + 0.5) continue;
  1278. var cut = this.splitChild(kids[idx], B, C, boundary);
  1279. if (cut && cut.kind !== "fit") return cut;
  1280. }
  1281. return null;
  1282. };
  1283. Paginator.prototype.splitChild = function (el, B, C, boundary) {
  1284. var top = this.top(el);
  1285. if (top >= B - 0.5) return this.beforeCut(el, C, boundary);
  1286. var tag = el.tagName;
  1287. if (tag === "TABLE") return this.splitTable(el, B, C, boundary);
  1288. if (tag === "IMG" || tag === "HR" || tag === "VIDEO" || tag === "IFRAME") {
  1289. return this.beforeCut(el, C, boundary);
  1290. }
  1291. if (el.classList.contains("doc-pagebreak")) return null;
  1292. if (el.classList.contains("doc-colsec")) return this.splitColumns(el, B, C, boundary);
  1293. if (isList(el) || tag === "TBODY") {
  1294. var inner = this.findCut(el, B, C, boundary);
  1295. return this.hoist(inner, el, C, boundary);
  1296. }
  1297. if (hasBlockChild(el)) {
  1298. if (el.getAttribute("data-keep-lines") === "1" && top > C + 1) return this.beforeCut(el, C, boundary);
  1299. var sub = this.findCut(el, B, C, boundary);
  1300. return this.hoist(sub, el, C, boundary);
  1301. }
  1302. return this.splitLines(el, B, C, boundary);
  1303. };
  1304. // a cut before the first child of a container is a cut before the
  1305. // container (so keep-with-next and page-top checks see the real block)
  1306. Paginator.prototype.hoist = function (cut, container, C, boundary) {
  1307. if (!cut) return { kind: "fit" };
  1308. if (cut.kind === "before" && container !== boundary) {
  1309. var kids = blockKids(container);
  1310. if (kids.length && kids[0] === cut.el && this.top(container) > C + 1) {
  1311. return this.beforeCut(container, C, boundary);
  1312. }
  1313. }
  1314. return cut;
  1315. };
  1316. Paginator.prototype.beforeCut = function (el, C, boundary) {
  1317. var target = el;
  1318. // keep-with-next: pull the blocks that must stay with el along
  1319. for (var guard = 0; guard < 20; guard++) {
  1320. var prev = target.previousElementSibling;
  1321. while (prev && isSpacer(prev)) prev = prev.previousElementSibling;
  1322. if (!prev || prev.classList.contains("doc-pagebreak")) break;
  1323. if (!keepsWithNext(prev)) break;
  1324. if (this.top(prev) <= C + 1) break;
  1325. target = prev;
  1326. }
  1327. var y = this.top(target);
  1328. if (y <= C + 1) {
  1329. if (target !== el) {
  1330. target = el;
  1331. y = this.top(el);
  1332. }
  1333. if (y <= C + 1) return { kind: "overflow", y: y };
  1334. }
  1335. // a cut before the first row of a table is a cut before the table
  1336. if (target.tagName === "TR") {
  1337. var tbl = target.closest("table");
  1338. var rows = rowsOf(tbl);
  1339. if (rows[0] === target && tbl !== boundary) return this.beforeCut(tbl, C, boundary);
  1340. }
  1341. return { kind: "before", el: target, y: y, boundary: boundary };
  1342. };
  1343. function rowsOf(tbl) {
  1344. var out = [];
  1345. for (var i = 0; i < tbl.rows.length; i++) {
  1346. if (!tbl.rows[i].classList.contains("doc-autobreak") &&
  1347. tbl.rows[i].closest("table") === tbl) out.push(tbl.rows[i]);
  1348. }
  1349. return out;
  1350. }
  1351. Paginator.prototype.splitTable = function (tbl, B, C, boundary) {
  1352. var rows = rowsOf(tbl);
  1353. var idx = -1;
  1354. for (var i = 0; i < rows.length; i++) {
  1355. if (this.bottom(rows[i]) > B + 0.5) { idx = i; break; }
  1356. }
  1357. if (idx < 0) return { kind: "fit" };
  1358. var row = rows[idx];
  1359. var rowTop = this.top(row);
  1360. if (rowTop >= B - 1) return this.beforeCut(idx === 0 ? tbl : row, C, boundary);
  1361. // a row that cannot split, or one a merged cell reaches into from
  1362. // above, moves whole - unless it already starts the page
  1363. var spanned = rowspanCrosses(tbl, rows, idx);
  1364. var cant = row.getAttribute("data-cant-split") === "1" || spanned || hasRowspan(row);
  1365. if (cant && rowTop > C + 1) {
  1366. var bc = this.beforeCut(idx === 0 ? tbl : row, C, boundary);
  1367. if (bc.kind !== "overflow") return bc;
  1368. }
  1369. if (spanned || hasRowspan(row)) return { kind: "overflow", y: rowTop };
  1370. var cells = [];
  1371. var any = false, allNothing = true;
  1372. for (var c = 0; c < row.cells.length; c++) {
  1373. var td = row.cells[c];
  1374. var cs = window.getComputedStyle(td);
  1375. var padB = (parseFloat(cs.paddingBottom) || 0) + (parseFloat(cs.borderBottomWidth) || 0);
  1376. var cut = hasBlockChild(td) ? this.findCut(td, B - padB, C, td)
  1377. : this.splitLines(td, B - padB, C, td);
  1378. if (cut && cut.kind === "fit") cut = null;
  1379. if (cut && (cut.kind === "overflow" || (cut.kind === "before" && cut.el === td))) {
  1380. // this cell cannot give anything up (or all of it moves):
  1381. // move the row if we can
  1382. cut = { kind: "cellstart", td: td, y: rowTop };
  1383. }
  1384. if (cut) {
  1385. any = true;
  1386. if (cut.kind !== "cellstart" && !(cut.kind === "before" && cut.el === blockKids(td)[0])) {
  1387. allNothing = false;
  1388. }
  1389. } else {
  1390. allNothing = false;
  1391. }
  1392. cells.push(cut);
  1393. }
  1394. if (!any) return { kind: "fit" };
  1395. if (allNothing && rowTop > C + 1) return this.beforeCut(idx === 0 ? tbl : row, C, boundary);
  1396. var y = Infinity;
  1397. cells.forEach(function (ct) { if (ct && ct.y < y) y = ct.y; });
  1398. return { kind: "row", tr: row, cells: cells, y: y, boundary: boundary };
  1399. };
  1400. function hasRowspan(row) {
  1401. for (var i = 0; i < row.cells.length; i++) {
  1402. if (row.cells[i].rowSpan > 1) return true;
  1403. }
  1404. return false;
  1405. }
  1406. function rowspanCrosses(tbl, rows, idx) {
  1407. for (var r = 0; r < idx; r++) {
  1408. for (var c = 0; c < rows[r].cells.length; c++) {
  1409. if (r + rows[r].cells[c].rowSpan > idx) return true;
  1410. }
  1411. }
  1412. return false;
  1413. }
  1414. /* the visual lines of a block that holds only inline content */
  1415. Paginator.prototype.lines = function (block) {
  1416. var frags = [];
  1417. var self = this;
  1418. var range = document.createRange();
  1419. function visit(parent) {
  1420. for (var n = parent.firstChild; n; n = n.nextSibling) {
  1421. if (n.nodeType === 3) {
  1422. if (!n.nodeValue) continue;
  1423. range.selectNodeContents(n);
  1424. var rects = range.getClientRects();
  1425. for (var i = 0; i < rects.length; i++) {
  1426. if (rects[i].height <= 0) continue;
  1427. frags.push({ node: n, index: i, top: self.rectTop(rects[i]), bottom: self.rectBottom(rects[i]) });
  1428. }
  1429. } else if (n.nodeType === 1) {
  1430. if (isSpacer(n)) continue;
  1431. var disp = n.tagName === "IMG" ? "inline" : window.getComputedStyle(n).display;
  1432. if (n.tagName === "IMG" || (disp === "inline-block" && !n.classList.contains("doc-tab"))) {
  1433. // a picture or an inline-block is one unbreakable box
  1434. var r = n.getBoundingClientRect();
  1435. if (r.height > 0) frags.push({ el: n, top: self.rectTop(r), bottom: self.rectBottom(r) });
  1436. } else if (disp !== "none") {
  1437. visit(n);
  1438. }
  1439. }
  1440. }
  1441. }
  1442. visit(block);
  1443. var lines = [];
  1444. frags.forEach(function (f) {
  1445. var cur = lines[lines.length - 1];
  1446. if (!cur || f.top >= cur.bottom - 1.5) {
  1447. lines.push({ top: f.top, bottom: f.bottom, first: f, text: !f.el });
  1448. } else {
  1449. cur.top = Math.min(cur.top, f.top);
  1450. cur.bottom = Math.max(cur.bottom, f.bottom);
  1451. if (!f.el) cur.text = true;
  1452. }
  1453. });
  1454. // a text rect is the glyphs, not the line: the line box reaches half
  1455. // the leading further down, and that is what has to fit the page
  1456. var lh = parseFloat(window.getComputedStyle(block).lineHeight) || 0;
  1457. lines.forEach(function (ln) {
  1458. var glyphs = ln.bottom - ln.top;
  1459. ln.boxBottom = ln.bottom + (ln.text && lh > glyphs ? (lh - glyphs) / 2 : 0);
  1460. });
  1461. return lines;
  1462. };
  1463. Paginator.prototype.splitLines = function (block, B, C, boundary) {
  1464. var lines = this.lines(block);
  1465. if (!lines.length) {
  1466. return this.bottom(block) > B + 0.5 && this.top(block) > C + 1 ?
  1467. this.beforeCut(block, C, boundary) : { kind: "fit" };
  1468. }
  1469. var k = -1;
  1470. for (var i = 0; i < lines.length; i++) {
  1471. if (lines[i].boxBottom > B + 0.5) { k = i; break; }
  1472. }
  1473. // only the spacing after the last line hangs over: that is allowed
  1474. if (k < 0) return { kind: "fit" };
  1475. var atTop = this.top(block) <= C + 1;
  1476. if (block.getAttribute("data-keep-lines") === "1" && !atTop) k = 0;
  1477. // widow/orphan control is on unless the paragraph turns it off
  1478. if (block.getAttribute("data-widow") !== "0" && lines.length > 1) {
  1479. // a widow (last line alone on the next page) pulls one more line
  1480. // over; an orphan (first line alone on this page) moves the
  1481. // whole paragraph
  1482. if (k > 0 && lines.length - k === 1) k = k - 1;
  1483. if (k === 1 && !atTop) k = 0;
  1484. }
  1485. if (k === 0) {
  1486. if (!atTop) return this.beforeCut(block, C, boundary);
  1487. if (lines.length === 1) return { kind: "overflow", y: lines[0].top };
  1488. k = 1;
  1489. }
  1490. var f = lines[k].first;
  1491. var cut = { kind: "line", el: block, y: lines[k].top, boundary: boundary };
  1492. if (f.el) {
  1493. cut.beforeEl = f.el;
  1494. } else {
  1495. cut.node = f.node;
  1496. cut.offset = f.index === 0 ? 0 : this.lineStartOffset(f.node, lines[k].top);
  1497. }
  1498. return cut;
  1499. };
  1500. // first character of a text node that sits on the line starting at y
  1501. Paginator.prototype.lineStartOffset = function (node, lineTop) {
  1502. var len = node.nodeValue.length;
  1503. var range = document.createRange();
  1504. var self = this;
  1505. function topAt(o) {
  1506. for (var i = o; i < len; i++) {
  1507. range.setStart(node, i);
  1508. range.setEnd(node, i + 1);
  1509. var rr = range.getClientRects();
  1510. if (rr.length && rr[0].height > 0) return { top: self.rectTop(rr[rr.length - 1]), at: i };
  1511. }
  1512. return null;
  1513. }
  1514. var lo = 0, hi = len - 1, ans = len;
  1515. while (lo <= hi) {
  1516. var mid = (lo + hi) >> 1;
  1517. var t = topAt(mid);
  1518. if (!t) { hi = mid - 1; continue; }
  1519. if (t.top >= lineTop - 1.5) { ans = Math.min(ans, t.at); hi = mid - 1; }
  1520. else lo = t.at + 1;
  1521. }
  1522. return Math.min(ans, len);
  1523. };
  1524. /* ---- applying a cut ---- */
  1525. function makeSpacer(kind, cols) {
  1526. var el;
  1527. if (kind === "row") {
  1528. el = document.createElement("tr");
  1529. var td = document.createElement("td");
  1530. td.colSpan = Math.max(1, cols);
  1531. td.className = "doc-autobreak-cell";
  1532. el.appendChild(td);
  1533. } else {
  1534. el = document.createElement("div");
  1535. }
  1536. el.className = "doc-autobreak";
  1537. el.setAttribute("contenteditable", "false");
  1538. el.setAttribute("aria-hidden", "true");
  1539. return el;
  1540. }
  1541. /* A merged cell from a row above that reaches past a page cut would
  1542. stretch over the spacer row - its rules running down through the
  1543. footnotes - and leave the rows on the next page without it. It is cut
  1544. in two like the table: the cell keeps the rows above the break, and
  1545. an empty continuation cell of the layout's own (undone with the
  1546. spacer, never saved) carries it on the next page. Returns the tokens
  1547. of the cells it split. */
  1548. var rowspanSeq = 0;
  1549. function splitRowspans(tr) {
  1550. var tbl = tr.closest("table");
  1551. if (!tbl) return [];
  1552. var rows = rowsOf(tbl);
  1553. var idx = rows.indexOf(tr);
  1554. if (idx <= 0) return [];
  1555. // the grid column each cell starts in, rows 0..idx
  1556. var taken = [], start = [];
  1557. for (var r = 0; r <= idx; r++) {
  1558. start[r] = [];
  1559. var col = 0;
  1560. for (var c = 0; c < rows[r].cells.length; c++) {
  1561. while (taken[r] && taken[r][col]) col++;
  1562. var td = rows[r].cells[c];
  1563. start[r][c] = col;
  1564. for (var y = r; y < r + td.rowSpan; y++) {
  1565. taken[y] = taken[y] || [];
  1566. for (var x = col; x < col + td.colSpan; x++) taken[y][x] = true;
  1567. }
  1568. col += td.colSpan;
  1569. }
  1570. }
  1571. var out = [];
  1572. for (r = 0; r < idx; r++) {
  1573. for (c = 0; c < rows[r].cells.length; c++) {
  1574. var head = rows[r].cells[c];
  1575. if (r + head.rowSpan <= idx) continue;
  1576. var k = "rs" + (++rowspanSeq);
  1577. var tail = document.createElement("td");
  1578. if (head.getAttribute("style")) tail.setAttribute("style", head.getAttribute("style"));
  1579. tail.colSpan = head.colSpan;
  1580. tail.rowSpan = r + head.rowSpan - idx;
  1581. tail.className = "doc-rowspan-tail";
  1582. tail.setAttribute("contenteditable", "false");
  1583. tail.setAttribute("data-rowspan-of", k);
  1584. head.setAttribute("data-rowspan-split", k);
  1585. head.setAttribute("data-rowspan-orig", String(head.rowSpan));
  1586. head.rowSpan = idx - r;
  1587. // into the row after the cut, at the cell's own column
  1588. var before = null;
  1589. for (var j = 0; j < tr.cells.length; j++) {
  1590. if (start[idx][j] > start[r][c]) { before = tr.cells[j]; break; }
  1591. }
  1592. tr.insertBefore(tail, before);
  1593. out.push(k);
  1594. }
  1595. }
  1596. return out;
  1597. }
  1598. // undo splitRowspans for the given tokens (or every split, with none)
  1599. function joinRowspans(root, tokens) {
  1600. var heads = tokens ? tokens.map(function (k) {
  1601. return root.querySelector('[data-rowspan-split="' + k + '"]');
  1602. }) : Array.prototype.slice.call(root.querySelectorAll("[data-rowspan-split]"));
  1603. heads.forEach(function (h) {
  1604. if (!h) return;
  1605. var k = h.getAttribute("data-rowspan-split");
  1606. var t = root.querySelector('[data-rowspan-of="' + k + '"]');
  1607. if (t && t.parentNode) t.parentNode.removeChild(t);
  1608. h.rowSpan = parseInt(h.getAttribute("data-rowspan-orig"), 10) || h.rowSpan;
  1609. h.removeAttribute("data-rowspan-split");
  1610. h.removeAttribute("data-rowspan-orig");
  1611. });
  1612. if (!tokens) {
  1613. var orphans = root.querySelectorAll("td.doc-rowspan-tail");
  1614. for (var i = 0; i < orphans.length; i++) orphans[i].parentNode.removeChild(orphans[i]);
  1615. }
  1616. }
  1617. function marginTopOf(el) {
  1618. return parseFloat(window.getComputedStyle(el).marginTop) || 0;
  1619. }
  1620. // stretch a spacer so that the content after it starts at targetY
  1621. Paginator.prototype.land = function (spacer, targetY, probe) {
  1622. var box = spacer.tagName === "TR" ? spacer.firstChild : spacer;
  1623. box.style.height = "0px";
  1624. for (var i = 0; i < 3; i++) {
  1625. var at = probe ? probe() : this.bottom(spacer);
  1626. var cur = parseFloat(box.style.height) || 0;
  1627. var want = Math.max(0, cur + (targetY - at));
  1628. if (Math.abs(want - cur) < 0.05) break;
  1629. box.style.height = want + "px";
  1630. }
  1631. };
  1632. Paginator.prototype.apply = function (cut, nextC) {
  1633. var self = this;
  1634. var boundary = cut.boundary || this.editor;
  1635. var top, dv;
  1636. switch (cut.kind) {
  1637. case "explicit":
  1638. cut.el.style.height = "0px";
  1639. this.land(cut.el, nextC);
  1640. return;
  1641. case "before":
  1642. var el = cut.el;
  1643. if (el.tagName === "TR" && !cut.col) {
  1644. var cols = 0;
  1645. for (var c = 0; c < el.cells.length; c++) cols += el.cells[c].colSpan;
  1646. var sp = makeSpacer("row", cols);
  1647. var spans = splitRowspans(el);
  1648. if (spans.length) sp.setAttribute("data-rowspans", spans.join(","));
  1649. el.parentNode.insertBefore(sp, el);
  1650. var bw = parseFloat(window.getComputedStyle(el.cells[0] || el).borderTopWidth) || 0;
  1651. this.land(sp, nextC + bw / 2, function () { return self.top(el); });
  1652. return;
  1653. }
  1654. // what holds el (a list, a quote) splits with it, so the
  1655. // spacer sits between two whole boxes
  1656. top = el.parentNode === boundary ? el : splitTree(el, boundary);
  1657. dv = makeSpacer("block");
  1658. if (top !== el && top.getAttribute("data-split-of")) dv.setAttribute("data-pair", top.getAttribute("data-split-of"));
  1659. top.parentNode.insertBefore(dv, top);
  1660. // spacing-before still applies at the top of a page
  1661. this.land(dv, nextC + marginTopOf(el), function () { return self.top(el); });
  1662. return;
  1663. case "line":
  1664. top = splitTree(lineStartNode(cut), boundary);
  1665. if (!top) return;
  1666. dv = makeSpacer("block");
  1667. if (top.getAttribute && top.getAttribute("data-split-of")) dv.setAttribute("data-pair", top.getAttribute("data-split-of"));
  1668. top.parentNode.insertBefore(dv, top);
  1669. this.land(dv, nextC, function () { return self.top(top); });
  1670. return;
  1671. case "row":
  1672. this.splitRow(cut, nextC, true);
  1673. return;
  1674. }
  1675. };
  1676. /* A row that breaks across the page becomes two rows: the head keeps
  1677. what fits in every cell, a copy of the row takes the rest of each
  1678. cell, and a spacer row between them carries the copy to the next
  1679. sheet. Each half has its own cell borders and shading. */
  1680. Paginator.prototype.splitRow = function (cut, nextC, withSpacer) {
  1681. var self = this;
  1682. var tr = cut.tr;
  1683. var tailTr = cloneShell(tr);
  1684. var k = pairUp(tr, tailTr);
  1685. tr.parentNode.insertBefore(tailTr, tr.nextSibling);
  1686. noteMoved();
  1687. var cells = Array.prototype.slice.call(tr.cells);
  1688. cells.forEach(function (td, i) {
  1689. var tailTd = cloneShell(td);
  1690. pairUp(td, tailTd);
  1691. tailTr.appendChild(tailTd);
  1692. var ct = cut.cells[i];
  1693. if (!ct) return;
  1694. var start = null;
  1695. if (ct.kind === "cellstart") {
  1696. start = td.firstChild;
  1697. } else if (ct.kind === "line") {
  1698. start = lineStartNode(ct);
  1699. } else if (ct.kind === "before" || ct.kind === "explicit") {
  1700. start = ct.el;
  1701. } else if (ct.kind === "row") {
  1702. // a nested table splits in the same place; its tail rows go
  1703. // with the rest of this cell
  1704. start = self.splitRow(ct, nextC, false);
  1705. }
  1706. if (!start) return;
  1707. var from = start.parentNode === td ? start : splitTree(start, td);
  1708. while (from) {
  1709. var nx = from.nextSibling;
  1710. tailTd.appendChild(from);
  1711. from = nx;
  1712. }
  1713. });
  1714. if (withSpacer) {
  1715. var cols = 0;
  1716. for (var c = 0; c < cells.length; c++) cols += cells[c].colSpan;
  1717. var sp = makeSpacer("row", cols);
  1718. sp.setAttribute("data-pair", k);
  1719. tr.parentNode.insertBefore(sp, tailTr);
  1720. var bw = parseFloat(window.getComputedStyle(tailTr.cells[0] || tailTr).borderTopWidth) || 0;
  1721. this.land(sp, nextC + bw / 2, function () { return self.top(tailTr); });
  1722. }
  1723. return tailTr;
  1724. };
  1725. /* ---- footnotes ---- */
  1726. Paginator.prototype.refsBetween = function (y0, y1) {
  1727. var out = [];
  1728. var refs = this.o.fnRefs || [];
  1729. for (var i = 0; i < refs.length; i++) {
  1730. var r = refs[i];
  1731. var rect = r.getBoundingClientRect();
  1732. if (!rect.height) continue;
  1733. // a reference in a column past the page's last one is not here
  1734. if (this.o.columns > 1 && rect.left > this.editor.getBoundingClientRect().right + 1) continue;
  1735. var y = this.rectTop(rect);
  1736. if (y >= y0 - 1 && y < y1) {
  1737. var id = r.getAttribute("data-fn");
  1738. if (out.indexOf(id) < 0) out.push(id);
  1739. }
  1740. }
  1741. return out;
  1742. };
  1743. /* ---- the page loop ---- */
  1744. /* Where to start. An edit cannot move a page break that comes before
  1745. it, so when the caller says where the change is (fromY) and hands in
  1746. the previous page records, the pages up to the one before the change
  1747. are kept as they are - with their spacers and splits - and only the
  1748. rest is laid out again. Starting one page early leaves room for a
  1749. widow or a keep-with-next that pulls a line back across the page
  1750. above. */
  1751. Paginator.prototype.resume = function () {
  1752. var o = this.o;
  1753. var prev = o.prevPages;
  1754. if (!(o.fromY >= 0) || !prev || prev.length < 3) return 0;
  1755. var p = 0;
  1756. for (var k = 0; k < prev.length; k++) {
  1757. if (prev[k].sheetTop <= o.fromY) p = k;
  1758. }
  1759. var start = p - 1;
  1760. if (start < 1) return 0;
  1761. var threshold = this.contentTop(start);
  1762. var self = this;
  1763. var stale = [];
  1764. var spacers = this.editor.querySelectorAll(".doc-autobreak");
  1765. for (var i = 0; i < spacers.length; i++) {
  1766. if (self.top(spacers[i]) >= threshold - 0.5) stale.push(spacers[i]);
  1767. }
  1768. var breaks = this.editor.querySelectorAll(".doc-pagebreak");
  1769. var staleBreaks = [];
  1770. for (i = 0; i < breaks.length; i++) {
  1771. if (self.top(breaks[i]) >= threshold - 0.5) staleBreaks.push(breaks[i]);
  1772. }
  1773. removeSpacerList(stale, this.editor);
  1774. repairSplits(this.editor, false);
  1775. staleBreaks.forEach(function (b) { b.style.height = "0px"; });
  1776. return start;
  1777. };
  1778. Paginator.prototype.run = function () {
  1779. var o = this.o;
  1780. this._scale = this.scale();
  1781. var i = this.resume();
  1782. var pages;
  1783. if (i > 0) {
  1784. pages = o.prevPages.slice(0, i).map(function (pg) {
  1785. var copy = {};
  1786. for (var k in pg) copy[k] = pg[k];
  1787. return copy;
  1788. });
  1789. } else {
  1790. removeSpacers(this.editor);
  1791. if (o.columns > 1) wrapColumns(this.editor);
  1792. pages = [];
  1793. }
  1794. var contentEnd = function (self) { return self.bottom(self.editor); };
  1795. for (var guard = 0; guard < 3000; guard++) {
  1796. this._scale = this.scale();
  1797. var C = this.contentTop(i);
  1798. var Bfull = this.contentBottom(i);
  1799. var B = Bfull;
  1800. var ids = [];
  1801. var fnH = 0;
  1802. var cut = null;
  1803. for (var iter = 0; iter < 4; iter++) {
  1804. cut = this.findCut(this.editor, B, C, this.editor);
  1805. if (cut && cut.kind === "fit") cut = null;
  1806. var endY = cut ? cut.y : contentEnd(this);
  1807. var got = o.measureFootnotes ? this.refsBetween(C, Math.min(endY, B + 0.5)) : [];
  1808. var h = got.length ? o.measureFootnotes(got) : 0;
  1809. if (got.join(",") === ids.join(",") && Math.abs(h - fnH) < 0.5) break;
  1810. ids = got;
  1811. fnH = h;
  1812. B = Bfull - fnH;
  1813. }
  1814. var page = {
  1815. index: i, sheetTop: this.sheetTop(i), contentTop: C, contentBottom: B,
  1816. footnotes: ids, footnoteTop: Bfull - fnH
  1817. };
  1818. pages.push(page);
  1819. if (!cut) break;
  1820. var nextC = this.contentTop(i + 1);
  1821. if (cut.kind !== "overflow") this.apply(cut, nextC);
  1822. i++;
  1823. }
  1824. return pages;
  1825. };
  1826. function paginate(opts) {
  1827. var t = beginTrack(opts.editor);
  1828. try {
  1829. return new Paginator(opts).run();
  1830. } finally {
  1831. endTrack(t);
  1832. }
  1833. }
  1834. // forget what fonts measured: a stand-in for a missing font arrived
  1835. // (OfficeFonts.substitute), so the same family list draws differently
  1836. function clearMetrics() { ratioCache = {}; }
  1837. return {
  1838. PT: PT,
  1839. MM: MM,
  1840. fontRatios: fontRatios,
  1841. clearMetrics: clearMetrics,
  1842. lineHeightPx: lineHeightPx,
  1843. applyLineHeights: applyLineHeights,
  1844. applyTableBorders: applyTableBorders,
  1845. restoreTablePadding: restoreTablePadding,
  1846. restorePictureLines: restorePictureLines,
  1847. applyNumbering: applyNumbering,
  1848. applyTabs: applyTabs,
  1849. numberFootnotes: numberFootnotes,
  1850. removeSpacers: removeSpacers,
  1851. unsplitWithin: unsplitWithin,
  1852. unsplitAtCaret: unsplitAtCaret,
  1853. paginate: paginate,
  1854. formatNumber: formatNumber
  1855. };
  1856. })();