docs_layout.js 97 KB

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