/
codexlayout.js
2893 lines (2718 loc) · 144 KB
/
codexlayout.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: Javascript; Character-encoding: utf-8; -*- */
/* ######################### fdjt/codexlayout.js ###################### */
/* Copyright (C) 2009-2015 beingmeta, inc.
This file is a part of the FDJT web toolkit (www.fdjt.org)
It implements a method for breaking narrative HTML content
across multiple pages, attempting to honor page break constraints,
etc.
Check out the 'mini manual' at the bottom of the file or read the
code itself.
This program comes with absolutely NO WARRANTY, including implied
warranties of merchantability or fitness for any particular
purpose.
Use, modification, and redistribution of this program is permitted
under either the GNU General Public License (GPL) Version 2 (or any
later version) or under the GNU Lesser General Public License
(version 3 or later).
These licenses may be found at www.gnu.org, particularly:
http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
http://www.gnu.org/licenses/lgpl-3.0-standalone.html
Use and redistribution (especially embedding in other CC licensed
content) is also permitted under the terms of the Creative Commons
"Attribution-NonCommercial" license:
http://creativecommons.org/licenses/by-nc/3.0/
Other uses may be allowed based on prior agreement with
beingmeta, inc. Inquiries can be addressed to:
licensing@beingmeta.com
Enjoy!
*/
/* jshint browser: true */
// var fdjt=((window)?((window.fdjt)||(window.fdjt={})):({}));
fdjt.CodexLayout=
(function(){
"use strict";
/* globals Promise: false */
var fdjtDOM=fdjt.DOM;
var fdjtLog=fdjt.Log;
var fdjtAsync=fdjt.Async;
var fdjtTime=fdjt.Time;
var fdjtState=fdjt.State;
var RefDB=fdjt.RefDB;
var fdjtID=fdjt.ID;
var hasContent=fdjtDOM.hasContent;
var hasParent=fdjtDOM.hasParent;
var getParent=fdjtDOM.getParent;
var getStyle=fdjtDOM.getStyle;
var parsePX=fdjtDOM.parsePX;
var getLineHeight=fdjtDOM.getLineHeight;
var hasClass=fdjtDOM.hasClass;
var addClass=fdjtDOM.addClass;
var dropClass=fdjtDOM.dropClass;
var toArray=fdjtDOM.toArray;
var getElementValue=fdjtDOM.getElementValue;
var setLocal=fdjtState.setLocal, pushLocal=fdjtState.pushLocal;
var dropLocal=fdjtState.dropLocal, removeLocal=fdjtState.removeLocal;
var floor=Math.floor;
var iDB=fdjt.iDB;
var indexedDB=iDB.indexedDB;
var root_namespace;
if (document.body)
root_namespace=document.body.namespaceURI;
else fdjtDOM.addListener(window,"load",function(){
root_namespace=document.body.namespaceURI;});
var layoutDB;
function appendChildren(node,children,start,end){
var lim=end||children.length; var i=(start)||0;
var frag=document.createDocumentFragment();
while (i<lim) {
var child=children[i++];
if (!(child)) i++;
else if ((child.nodeType===3)&&
(child.nodeValue.length===0)) {}
else frag.appendChild(child);}
node.appendChild(frag);}
var getChildren=fdjtDOM.getChildren;
var getChild=fdjtDOM.getChild;
var Geometry=fdjtDOM.Geometry;
var XGeometry=fdjtDOM.XGeometry;
/* Node testing */
var notspace=/[^ \n\r\t\f\x0b\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u202f\u205f\u3000\uf3ff]/g;
function isEmpty(string){
if (typeof string === "string") {
var pt;
if (string.length===0) return true;
else pt=string.search(notspace);
if (pt<0) return true;
else if (string[pt]!=='&') return false;
else {
string=string.replace(/ /g,"\u00a0");
pt=string.search(notspace);
return (pt<0);}}
else return false;}
function inFlow(node){
var style=getStyle(node);
if ((style.display!=='none')&&
((style.position==='static')||
(style.position==='')))
return node;
else return false;}
function optimizeLayoutRule(rule){
if (!(rule)) return rule;
else if (typeof rule === "string") {
if ((rule[0]===".")&&
(rule.slice(1).search(/\.|#|\[/)<0))
return new RegExp("\\b"+rule.slice(1)+"\\b");
else return new fdjtDOM.Selector(rule);}
else if (rule instanceof RegExp) return rule;
else if (rule.match) return rule;
else if (rule.length) {
var newrules=[]; var firstrules=[];
var classes=[]; var selectors=[];
var i=0, lim=rule.length;
while (i<lim) {
var r=rule[i++];
if (typeof r !== "string") newrules.push(r);
else if (r[0]===".") {
if (r.slice(1).search(/\.|#|\[/)>=0)
// complex selector (not just a classname)
selectors.push(r);
else classes.push(r.slice(1));}
else if ((r[0]==="#")||(r[0]==="["))
selectors.push(r);
else classes.push(r);}
if (classes.length)
firstrules.push(new RegExp("\\b("+classes.join("|")+")\\b"));
if (selectors.length)
firstrules.push(new fdjtDOM.Selector(selectors.join(", ")));
return firstrules.concat(newrules);}
else return rule;}
function testNode(node,test) {
var tests;
if (!(test)) return true;
if (typeof test === 'string') tests=[test];
else if (test instanceof Array) tests=test;
else tests=[test];
var i=0; var lim=tests.length;
while (i<lim) {
var atest=tests[i++];
if (node===test) return true;
else if (atest instanceof RegExp) {
if (!(node.className)) continue;
if (!(node.className.search)) continue;
// Handle inadvertant use of selector syntax
if (node.className.search(atest)>=0) return true;}
else if (typeof atest === 'string') {
if (!(node.className)) continue;
if (!(node.className.search)) continue;
// Handle inadvertant use of selector syntax
if (atest[0]==='.') atest=atest.slice(1);
var classrx=new RegExp("\\b"+atest+"\\b");
if (node.className.search(classrx)>=0) return true;}
else if ((atest.match)&&(atest.match(node)))
// This should get most versions of CSS selectors
return true;
else {}}
return false;}
/* Scaling elements and nodes */
var adjustFontSize=fdjt.DOM.adjustFontSize;
var adjustFonts=fdjt.DOM.adjustFonts;
var tweakImage=fdjt.DOM.tweakImage;
function scaleToPage(elt,width,height,leavefont){
if (typeof elt === "string") elt=fdjtID(elt);
if ((!(elt))||(elt.length===0)) return;
else if (elt.nodeType) {
if (elt.nodeType!==1) return;
if ((hasClass(elt,"_pagescaled"))||(elt.getAttribute("style")))
return;
var ps=elt.getAttribute("data-pagescale")||
elt.getAttribute("pagescale")||
getElementValue(elt,"xdatapagescale");
var psw=1, psh=1;
var style=elt.style;
var cstyle=getStyle(elt);
// If it has an individual transform, don't mess it up
if ((style[fdjtDOM.transform])&&
(style[fdjtDOM.transform]!=="none")&&
(style[fdjtDOM.transform]!==""))
return;
if (ps) {
var psv=ps.split(/ |,|x/g);
if (psv.length===2) {
psw=parseScale(psv[0]);
psh=parseScale(psv[1]);}
else if (psv.length!==1) {
fdjtLog.warn("Bad page scale value %s for %o",ps,elt);
return;}
else psh=psw=parseScale(psv[0]);}
// Target width and height
var tw=width*psw, th=height*psh;
var w=elt.offsetWidth, h=elt.offsetHeight;
// Scale factors for width and height
var sw=tw/w, sh=th/h;
if (elt.tagName==="IMG") {
style.maxHeight=style.minHeight="inherit";
style.maxWidth=style.minWidth="inherit";
// Get width and height again, with the constraints off
// This means that pagescaling trumps CSS constraints,
// but we'll accept that for now
w=elt.offsetWidth; h=elt.offsetHeight; sw=tw/w; sh=th/h;
if (sw<sh) {
style.width=Math.round(w*sw)+"px";
style.height="auto";}
else {
style.height=Math.round(h*sh)+"px";
style.width="auto";}}
else if (leavefont) {
var wrapper=((cstyle.display==="inline")?
(fdjtDOM("span.codexscalewrapper")):
(fdjtDOM("div.codexscalewrapper")));
if (cstyle.display==="inline") {
style.display="inline-block";
wrapper.display="inline-block";}
wrapper.style.width=tw+"px"; wrapper.style.height=th+"px";
elt.style[fdjtDOM.transform]="scale("+sw+","+sh+")";
elt.style[fdjtDOM.transformOrigin]=
((cstyle.textAlign==="left")?("top left"):
(cstyle.textAlign==="right")?("top right"):
("top center"));
elt.parentNode.replaceChild(wrapper,elt);}
else {
adjustFontSize(elt);
if (cstyle.display==="inline")
style.display="inline-block";
style.width=tw+"px"; style.height=th+"px";}
addClass(elt,"_pagescaled");}
else if (elt.length) {
var i=0, lim=elt.length;
while (i<lim) scaleToPage(
elt[i++],width,height,leavefont||false);}
else {}}
function parseScale(s){
if (s.search(/%$/g)>0) {
var pct=parseFloat(s.slice(0,s.length-1));
return pct/100;}
else return parseFloat(s);}
function atPageTop(node,page,body){
if (!(body)) body=document.body;
var scan=node; while (scan) {
if (scan===page) return true;
else if (scan===body) return false;
else if (!(scan.previousSibling)) scan=scan.parentNode;
else if ((scan.previousSibling.nodeType===3)&&
(isEmpty(scan.previousSibling.nodeValue)))
scan=scan.previousSibling;
else if ((scan.previousSibling.nodeType===1)&&
(!(inFlow(scan.previousSibling))))
scan=scan.previousSibling;
else break;}
return ((scan.nodeType===1)&&
(scan.className)&&(scan.className.search)&&
(scan.className.search(/\bcodexpage\b/g)>=0));}
/* Duplicating nodes */
var tmpid_count=1;
var dupstate=/\bcodexdup(start|end)?\b/g;
var codexstate=/\bcodex(dupstart|dup|dupend|relocated)\b/g;
function dupClass(classname,dupclass,pat){
if (!(pat)) pat=dupstate;
if (classname) {
if (classname.search(dupstate)<0)
return classname+" "+dupclass;
else return classname.replace(dupstate,"")+" "+dupclass;}
else return dupclass;}
// This recreates a node and it's DOM context (containers) on
// a new page, calling itself recursively as needed
function dupContext(node,page,dups,crumbs){
if ((node===document.body)||(node.id==="CODEXCONTENT")||
(hasClass(node,"codexroot"))||(hasClass(node,"codexpage")))
return false;
else if (hasParent(node,page)) return node;
else if ((node.className)&&(node.className.search)&&
(node.className.search(/\bcodexwraptext\b/)>=0))
// We don't bother duplicating text wrapping convenience
// classes
return dupContext(node.parentNode,page,dups,crumbs);
// Now we actually duplicate it.
var id=node.id, baseid=node.getAttribute("data-baseid");
if (!(id)) id=baseid;
var duplist=dups[id];
var last_dup=((duplist)&&(duplist.length)&&
(duplist[duplist.length-1]));
// If it doesn't have an ID, we give it one, because we'll want
// to refer to it later while wanting to avoid DOM cycles
if (!(id)) id=node.id="CODEXTMPID"+(tmpid_count++);
else if (duplist) {
// See if it's already been duplicated
var d=duplist.length-1;
while (d>=0) {
if (hasParent(duplist[d],page)) return duplist[d];
else d--;}}
// Duplicate it's parent
var copy=node.cloneNode(false);
var parent=dupContext(node.parentNode,page,dups,crumbs);
var nodeclass=((node.className)&&(node.className.search)&&
(node.className))||"";
var lastclass=((last_dup)&&(last_dup.className)&&
(last_dup.className.search)&&
(last_dup.className));
dropClass(copy,"codexrelocated");
if (baseid) copy.codexbaseid=baseid;
// Jigger the class name
if (!(duplist)) {
node.className=dupClass(nodeclass,"codexdupstart",codexstate);
stripBottomStyles(node,true);
stripTopStyles(copy,true);
copy.className=dupClass(nodeclass,"codexdupend");}
else copy.className=dupClass(nodeclass,"codexdupend");
if (nodeclass.search(/\bcodexdupend\b/g)>=0) {
node.className=dupClass(nodeclass,"codexdup");
stripBottomStyles(node,true);}
if ((lastclass)&&(lastclass.search(/\bcodexdupend\b/g)>=0)) {
last_dup.className=lastclass.replace(
/\bcodexdupend\b/g,"codexdup");
stripBottomStyles(last_dup,true);}
// if (copy.getAttribute("style"))
// If the original had an ID, save it in various ways
if (node.id) {
if (!(baseid))
copy.setAttribute("data-baseid",id);
copy.removeAttribute("id");}
// Record the copy you've made (to avoid recreation)
if (duplist) duplist.push(copy);
else dups[id]=[copy];
// If it's got a copied context, append it to the context;
// otherwise, just append it to the page
if (parent) parent.appendChild(copy);
else page.appendChild(copy);
return copy;}
function stripBottomStyles(node,keep){
var style=node.style;
if ((keep)&&(!(node.hasAttribute("data-savedstyle"))))
node.setAttribute("data-savedstyle",style.cssText);
style.paddingBottom="0px";
style.borderBottomWidth="0px";
style.marginBottom="0px";}
function stripTopStyles(node,keep){
var style=node.style;
if ((keep)&&(!(node.hasAttribute("data-savedstyle"))))
node.setAttribute("data-savedstyle",style.cssText);
style.textIndent="0px";
style.paddingTop="0px";
style.borderTopWidth="0px";
style.marginTop="0px";}
/* Moving nodes */
function getFirstContent(node){
var child=node.firstChild;
while (child) {
if (((child.nodeType===3)&&(!(isEmpty(child.nodeValue))))||
((child.nodeType===1)&&(inFlow(child))))
return child;
else child=child.nextSibling;}
return false;}
// This moves a node into another container, leaving
// a back pointer for restoration
function moveNodeInto(arg,into,blockp,crumbs){
var baseclass; var node=arg, weird=false;
if (hasParent(node,into)) return node;
if (node.nodeType===1) {
baseclass=node.className;
if ((baseclass)&&(typeof baseclass !== "string"))
weird=true;}
else if (node.nodeType===3) {
if (node.nodeValue.search(/\S/g)>=0) {
// Wrap non-empty text nodes in elements before
// moving
var wrapnode=fdjtDOM(
((blockp)?"div.codexwraptext":"span.codexwraptext"));
if (node.parentNode)
node.parentNode.replaceChild(wrapnode,node);
wrapnode.appendChild(node);
baseclass="codexwraptext";
node=wrapnode;}
else node=node.cloneNode(true);}
else {}
if (weird) {}
else if ((node.nodeType===1)&&(hasClass(node,"codextextsplit"))) {}
else if ((node.parentNode)&&((!(node.id))||(!(crumbs[node.id])))) {
// If the node has a parent and hasn't been moved before,
// we leave a "crumb" (a placeholder) in the original
// location.
if (!(node.id)) node.id="CODEXTMPID"+(tmpid_count++);
// Record origin information; we'll use this to revert
// the layout if we need to (for example, before
// laying out again under different constraints)
var crumb=document.createTextNode("");
crumbs[node.id]=crumb;
if (baseclass) node.className=baseclass+" codexrelocated";
else node.className="codexrelocated";
node.parentNode.replaceChild(crumb,node);}
into.appendChild(node);
return node;}
function moveNode(arg,into,blockp,crumbs){
var node=moveNodeInto(arg,into,blockp,crumbs);
if (into) {
var dragged=[], scan=node.nextSibling;
while (scan) {
if ((scan.nodeType===1)&&
(typeof scan.className === "string")&&
(scan.className.search(/\bcodexblock\b/g)>=0))
break;
dragged.push(scan);
scan=scan.nextSibling;}
into.appendChild(node);
if (dragged.length) {
var d=0, ndrags=dragged.length;
while (d<ndrags)
moveNodeInto(dragged[d++],node,false,crumbs);}}
return node;}
function markPageTop(node,force){
if ((!force)&&(hasClass(node,"codexpagetop"))) return;
if ((node.namespaceURI)&&
(node.namespaceURI!==root_namespace))
return;
var nodestyle=node.getAttribute("style")||"";
var newstyle=nodestyle+((nodestyle)?("; "):(""))+
"margin-top: 0px !important;";
if (!(node.hasAttribute("data-savedstyle")))
node.setAttribute("data-savedstyle",nodestyle);
node.setAttribute("style",newstyle);
addClass(node,"codexpagetop");
if (node.childNodes) {
var children=node.childNodes, i=0, lim=children.length;
while (i<lim) {
var child=children[i++];
if (child.nodeType===1) {
var style=getStyle(child);
if ((style.position!=='static')&&(style.position!=='')) {}
else if ((child.classname)&&(child.classname.search)&&
(child.className.search(/\bfdjtskiptext\b/g)>=0)) {}
else return markPageTop(child);}
else if (child.nodeType===3) {
if (!(isEmpty(child.nodeValue))) return;}
else {}}}}
// This moves a node onto a page, recreating (as far as
// possible) its original DOM context on the new page.
function moveNodeToPage(node,page,dups,crumbs){
if (hasParent(node,page)) {
if ((node.nodeType===1)&&(!(hasContent(page,true,false,node))))
markPageTop(node);
return node;}
else {
var move=node, parent=move.parentNode;
// If we're moving a first child, we might as well
// move the parent
while ((parent)&&
(parent!==document.body)&&
(parent.id!=="CODEXCONTENT")&&
(!(hasClass(parent,"codexroot")))&&
(!(hasClass(parent,"codexpage")))&&
(move===getFirstContent(parent))) {
move=parent; parent=move.parentNode;}
if ((!(parent))||(parent===document.body)||
(parent.id==="CODEXCONTENT")||
(hasClass(parent,"codexroot"))||
(hasClass(parent,"codexpage"))) {
// If the node isn't on a page or is at top level of a
// page, the parent doesn't need to be duplicated to
// move the child. However, the motion might modify
// the moved node (for example, cloning it).
if (move===node)
node=move=moveNode(node,page,false,crumbs);
else move=moveNode(move,page,false,crumbs);}
else {
// Otherwise duplicate the parent and move the child
var dup_parent=dupContext(parent,page,dups,crumbs);
if (move===node)
node=move=moveNode(node,dup_parent||page,false,crumbs);
else move=moveNode(move,dup_parent||page,false,crumbs);}
if ((node)&&(node.nodeType===1)&&
(!hasContent(page,true,false,move)))
markPageTop(move);
return node;}}
// Reverting layout
function restoreNode(node,info,crumbs){
var id=node.id;
if (!(id)) return;
var origin=crumbs[id];
if (origin) {
var parent=origin.parentNode;
if (hasClass(node,/\bcodexwraptext\b/g))
parent.replaceChild(node.childNodes[0],origin);
else origin.parentNode.replaceChild(node,origin);}
dropClass(node,"codexrelocated");}
function revertLayout(layout) {
var crumbs=layout.crumbs; var now=fdjtTime(), i=0, lim;
if ((layout.reverting)&&((now-layout.reverting)<10000)) return;
else layout.reverting=now;
var textsplits=layout.textsplits;
var node;
var pagescaled=toArray(
layout.container.getElementsByClassName("_pagescaled"));
i=0; lim=pagescaled.length; while (i<lim) {
var elt=pagescaled[i++];
var wrapper=getParent(elt,".codexscalewrapper");
var saved=elt.getAttribute("data-savedstyle");
dropClass(elt,"_pagescaled");
if (saved) elt.setAttribute("style",saved);
else elt.setAttribute("style","");
if (wrapper) wrapper.parentNode.replaceChild(elt,wrapper);}
var cantsplit=toArray(
layout.container.getElementsByClassName("codexcantsplit"));
dropClass(cantsplit,"codexcantsplit");
var split=toArray(
layout.container.getElementsByClassName("codexsplitstart"));
i=0; lim=split.length; while (i<lim) {
node=split[i++];
var nodeid=node.id;
var text=textsplits[nodeid];
node.parentNode.replaceChild(text,node);}
var shards=toArray(
layout.container.getElementsByClassName("codextextsplit"));
i=0; lim=shards.length; while (i<lim) {
node=shards[i++];
node.parentNode.removeChild(node);}
var ragged=toArray(
layout.container.getElementsByClassName("codexraggedsplit"));
dropClass(ragged,"codexraggedsplit");
var leading=toArray(
layout.container.getElementsByClassName("codexdupleading"));
if ((leading)&&(leading.length)) fdjtDOM.remove(leading);
var moved=toArray(
layout.container.getElementsByClassName("codexrelocated"));
var dupstarts=toArray(layout.container.getElementsByClassName(
"codexdupstart"));
var dupends=toArray(layout.container.getElementsByClassName(
"codexdupend"));
var dupmiddle=toArray(layout.container.getElementsByClassName(
"codexdup"));
var pagetops=toArray(layout.container.getElementsByClassName(
"codexpagetop"));
dropClass(dupstarts,"codexdupstart");
dropClass(dupends,"codexdupend");
dropClass(dupmiddle,"codexdup");
dropClass(pagetops,"codexpagetop");
if ((moved)&&(moved.length)) {
layout.logfn(
"Reverting layout of %d nodes and %d split texts",
moved.length,RefDB.countKeys(textsplits));
var j=moved.length;
while (j>0) {
restoreNode(moved[--j],layout,crumbs);}}
var restyled=fdjtDOM.$("[data-savedstyle]");
i=0; lim=restyled.length;
while (i<lim) {
var rs=restyled[i++];
if (rs.hasAttribute("data-savedstyle")) {
var os=rs.getAttribute("data-savedstyle");
if (os) rs.setAttribute("style",os);
else rs.removeAttribute("style");
rs.removeAttribute("data-savedstyle");}}
fdjtDOM.unwrapChildren("div.fdjtfontwrapper",layout.container);
layout.textsplits={}; layout.crumbs={};}
/* Codex trace levels */
/* 0=notrace
1=trace tracked nodes
2=trace addition of top level chunks
3=trace insertion of page breaks
4=trace every node consideration
*/
function CodexLayout(init){
if (!(init)) init={};
var layout=this;
this.init=init;
this.thenfns=[];
// Layout rules
var fullpages=this.fullpages=
optimizeLayoutRule(init.fullpages||false);
var singlepages=this.singlepages=
optimizeLayoutRule(init.singlepages||false);
var floatpages=this.floatpages=
optimizeLayoutRule(init.floatpages||false);
var floatblocks=this.floatblocks=
optimizeLayoutRule(init.floatblocks||false);
var pageprefix=this.pageprefix=init.pageprefix||"CODEXPAGE";
// Layout Dimensions
var page_height=this.height=init.page_height||fdjtDOM.viewHeight();
var page_width=this.width=init.page_width||fdjtDOM.viewWidth();
// Set the orientation when provided
var orientation=(init.orientation)||
((page_width>page_height)?('landscape'):('portrait'));
this.orientation=orientation;
var pagefn=(init.pagefn)||false;
var serialize=false; // Stop timeslicing
this.serialize=function(val){
if (typeof val === "undefined") serialize=true;
else serialize=val;};
// What constitutes a short page
var short_page_height=
((init.hasOwnProperty("short_page_height"))&&
((init.short_page_height)&&
((init.short_page_height<=1)?(page_height*init.short_page_height):
(init.short_page_height))));
// Break 'paragraphs' (anything with just text and inline nodes)
var break_blocks=this.break_blocks=
((typeof init.break_blocks === 'undefined')?(true):
(init.break_blocks));
// Atomic nodes can't be broken. Specifying this can
// speed up page layout in some cases.
var atomic=init.atomic||false;
if (typeof atomic === "string") atomic=fdjtDOM.selector(atomic);
else if ((atomic.length)&&(atomic.join))
// Arrays of selector strings
atomic=fdjtDOM.selector(atomic.join(","));
else {}
this.atomic=atomic;
this.dontsave=init.dontsave||false;
var use_raf=(!(CodexLayout.dont_rAF))&&
((window.requestAnimationFrame)?(true):(false));
// use_raf=false;
var use_scaling=
((typeof init.use_scaling === 'undefined')?(true):
(init.use_scaling));
// Scale pages (use CSS to shrink pages to fit)
var scale_pages=this.scale_pages=
((use_scaling)&&
((typeof init.scale_pages === 'undefined')?(true):
(init.scale_pages)));
// This is the node DOM container where we place new pages
var container=this.container=
init.container||fdjtDOM("div.codexpages");
var origin=this.origin=init.origin||false;
function noop(){}
var logfn=this.logfn=
init.logfn||CodexLayout.logfn||
((typeof fdjtLog !== 'undefined')?(fdjtLog):(noop));
// STATE variables
var pagenum=this.pagenum=0; // Tracks current page number
var pages=this.pages=[]; // Array of all pages generated, in order
var dups=this.dups={}; // Tracks nodes/contexts already duplicated
// Maps IDs to text nodes left behind as placeholders when
// the original nodes were moved.
var crumbs=this.crumbs={};
var cur_root=this.root=false; // The root currently being added
// Tracks text nodes which have been split, keyed by the
// temporary IDs assigned to them
var textsplits=this.textsplits={};
// Tracks split blocks
var splits=this.splits={};
var page=this.page=init.page; // Contains the currently open page
var prev=this.prev=false; // The last terminal block we processed
var prevstyle=this.prevstyle=false;
var previnfo=this.previnfo=false;
// this.drag[] contains nodes which will go on the next
// page when we get there. The nodes in this.drag[] have
// already been placed on pages, but we keep track of them
// in case we need to move them to a new page to honor
// nobreak constraints.
var drag=this.drag=[];
// this.floating contains fully-assembled page nodes to
// placed in pages after this one; it is intended for
// out-of-flow or 'too bit to fit' content
var floating=this.floating=[];
if (init.layout_id) this.layout_id=init.layout_id;
// Startup
this.started=false; // When we started
var trace=this.tracelevel= // How much to trace
init.tracelevel||CodexLayout.tracelevel||
(fdjtState.getLocal("codexlayout.trace",true))||0;
var track=init.track||CodexLayout.track||
(fdjtState.getLocal("codexlayout.track"))||false;
var debug_match=init.debug||CodexLayout.debug||
fdjtState.getLocal("codexlayout.debug")||false;
if (track) {
this.track=track=fdjtDOM.Selector(track);
if (!(trace)) trace=this.tracelevel=1;}
if (debug_match) {
this.debug=debug_match=fdjtDOM.Selector(debug_match);
if (!(trace)) trace=this.tracelevel=1;}
else this.debug=false;
if (trace) addClass(document.body,"debugcodexlayout");
this.roots=init.roots||[]; // Where all roots can be tracked
this.root_count=0; // Number of root nodes added
this.block_count=0;
this.lastid=false;
this.timeslice=
((init.hasOwnProperty('timeslice'))?(init.timeslice):
(CodexLayout.timeslice));
this.timeskip=
((init.hasOwnProperty('timeskip'))?(init.timeskip):
(CodexLayout.timeskip));
var pagerule=this.pagerule=init.pagerule||false;
function moveUp(node){
if (trace) {
if ((trace>3)||((track)&&(track.match(node))))
logfn("Moving node %o to page %o",node,page);}
// if (lastmove!==node) {allmoves.push(node); lastmove=node;}
return moveNodeToPage(node,page,dups,crumbs);}
function moveChildren(into,children,start,end){
var tomove=[];
if (!(start)) start=0;
if (!(end)) end=children.length;
while (start<end) tomove.push(children[start++]);
start=0; end=tomove.length; while (start<end)
moveNode(tomove[start++],into,false,crumbs);}
// addContent calls loop() exactly once to set up the
// actual loop to be timesliced with repeated calls
// setTimeout and a final call to doneFn. The real
// inner function is step(), which relies on state
// stored in its closure.
function addContent(root,timeslice,timeskip,
trace,progressfn,donefn) {
var newpage=false, newpages=((page)?([page]):([]));
var start=fdjtTime();
if (!(page)) {newPage(); newpage=true;}
if ((timeslice)&&(typeof timeslice !== "number"))
timeslice=layout.timeslice;
if ((timeskip)&&(typeof timeskip !== "number"))
timeskip=layout.timeskip;
if (typeof trace === 'undefined') trace=layout.tracelevel;
if (typeof progressfn === 'undefined')
progressfn=layout.progressfn||false;
if (!(layout.started)) layout.started=start;
// If it's already been added to a page, don't do it again.
if (getParent(root,".codexpage")) {
pagesDone(newpages); newpages=[];
if (donefn) donefn(layout);
return false;}
layout.roots.push(root);
layout.root_count++;
var fullpage=hasClass(root,"codexfullpage")||
((fullpages)&&(testNode(root,fullpages)));
var singlepage=
(fullpage)||
(hasClass(root,"codexsinglepage"))||
(checkSinglePage(root));
if ((fullpage)||(singlepage)) {
if (!(avoidBreakInside(root)))
fullpage=singlepage=false;}
if (newpage) root=moveUp(root);
else if (singlepage) newPage(root);
else if ((mustBreakBefore(root))||
((prev)&&(mustBreakAfter(prev)))) {
root=newPage(root);}
else root=moveUp(root);
var scale_elts=getChildren(root,"[data-pagescale],[pagescale]");
scaleToPage(scale_elts,page_width,page_height);
if ((root.tagName==="IMG")&&
((fullpage)||(singlepage)))
tweakImage(root,page_width,page_height);
else {}
if (singlepage) {
var pw=page.scrollWidth, ph=page.scrollHeight;
if ((pw>page_width)||(ph>page_height))
addClass(page,"codexoversize");
else if ((fullpage)&&
((pw<(0.9*page_width))&&(ph<(0.9*page_height))))
addClass(page,"codexundersize");
else {}
// Start a new page and update the loop state
newPage(); prev=layout.prev=root;
prevstyle=layout.prevstyle=getStyle(root);
previnfo=layout.previnfo=new BlockInfo(root,prevstyle);
pagesDone(newpages); newpages=[];
drag=[];
if (donefn) donefn(layout);
return;}
else {
var geom=new Geometry(root,page); var done=false;
if (mustBreakInside(root)) {}
else if (geom.bottom<=page_height) {
if (cantBreakBefore(root)) drag.push(root);
else if (cantBreakAfter(root)) drag=[root];
else drag=[];
done=true;}
else if (((atomic)&&(atomic.match(root)))||
(avoidBreakInside(root))) {
if (!(newpage)) {
newPage(root); geom=new Geometry(root,page);}
if (geom.bottom<=page_height) {
if (cantBreakAfter(root)) drag=[root];
else drag=[];
done=true;}}
else {}
if (done) {
prev=layout.prev=root;
prevstyle=layout.prevstyle=getStyle(root);
previnfo=layout.previnfo=new BlockInfo(root,prevstyle);
pagesDone(newpages); newpages=[];
if (donefn) donefn(layout);
return;}}
var blocks=[], blockinfo=[], styles=[];
// gather all of the block-level elements
// (recursively) in the node, noting which ones are
// terminals. This should be pretty fast, so we do it
// synchronously
gatherBlocks(root,root,blocks,blockinfo,styles);
layout.block_count=layout.block_count+blocks.length;
if (trace>1)
logfn("Laying out %d blocks from %o; page=%o",
blocks.length,root,page);
// If there aren't any blocks, we try adding the
// content to the current page and, if it goes over,
// create a new page for it and call the donefn. At
// the top level, we only split blocks.
if (blocks.length===0) {
if (!(newpage)) newPage(root);
layout.root=cur_root=false;
pagesDone(newpages); newpages=[];
if (donefn) donefn(layout);
return;}
layout.root=cur_root=root;
var block_i=0, n_blocks=blocks.length;
var block_hidden=0;
// Hide all of the blocks to start; this avoids
// needless computation as blocks are moved onto pages
// from wherever they started.
var hide_i=0; while (hide_i<n_blocks) {
var hide_block=blocks[hide_i++];
hide_block.style.display='none';}
function step(){
var block=blocks[block_i], style=styles[block_i];
var info=blockinfo[block_i], terminal=info.terminal||false;
var next=blocks[block_i+1], nextinfo=blockinfo[block_i+1];
var tracing=false;
if (block.id) layout.lastid=block.id;
// Reveal the block and it's children
if (block_i<=block_hidden) {
var show_i=block_i;
block.style.display='';
while (show_i<n_blocks) {
var show_block=blocks[show_i];
if (hasParent(show_block,block)) {
show_block.style.display=''; show_i++;}
else break;}
block_hidden=show_i;}
if ((trace)&&(block)&&
((trace>3)||((track)&&(track.match(block))))) {
logfn("Considering block %o (#%d from %o); page=%o",
block,block_i,root,page);
tracing=true;}
/*
if ((trace)&&(block)&&
(debug_match)&&(debug_match.match(block))) {
// jshint debug:true
debugger;}
*/
// FIRST, HANDLE DRAGGING
handle_dragging(block,terminal,info,style);
if (block) block=handle_standalone(block,info,style);
// If a block is false, continue
if (!(block)) {block_i++; return;}
// Finally, we check if everything fits. We're
// walking through the blocks[] but only advance
// when an element fits or can't be split or
// tweaked Note that we may process an element [i]
// more than once if we split the node and part of
// the split landed back in [i].
var geom=new Geometry(block,page), lh=getLineHeight(block,style);
var padding_bottom=parsePX(style.paddingBottom);
if ((trace)&&((trace>3)||((track)&&(track.match(block)))))
logfn("Layout/geom %o %j",block,geom);
if (((geom.bottom-padding_bottom)>page_height)||
// Even if we're above the bottom of the page,
// check if the next block goes over the edge
// and whether that would be a bad thing. If
// it's big enough and far down enough, we
// split the current block, making a slightly
// short page.
((next)&&(lh)&&(!(info.avoidbreakinside))&&
(geom.height>3*lh)&&
(((page_height-geom.bottom)/page_height)>0.9)&&
((geom.bottom+(new Geometry(next).height))>page_height)&&
(nextinfo.avoidbreakinside))) {
var use_height=page_height;
if ((geom.bottom-padding_bottom)<=page_height)
// This is the case where the block fits
// but the next block is really the
// problem. We force a split on the
// current block by tweaking the height
// used for splitting to be 2 lines above
// the block's bottom.
use_height=geom.bottom-padding_bottom-2*lh;
if (!(terminal)) {
if (tracing)
logfn("Oversize non-terminal %o, continuing",
block);
block_i++;
return;}
// If we get here, we're a terminal node
// which extends below the bottom of the page
else if (((short_page_height)?
(geom.top>short_page_height):
(geom.top>(use_height-lh*1.2)))&&
(drag.length===0)&&
(!(info.avoidbreakbefore))) {
// Our top is also over the bottom of the page,
// and we can break here, so we just push off
block=newPage(block,info);}
else if (info.floating) {
// If the block can float, let it
floating.push(block); block_i++;}
else if (((!(break_blocks))||
(info.atomic)||(info.avoidbreakinside)||
(hasClass(block,"codexcantsplit")))) {
var broken=handle_unbreakable(
block,info,style,geom,tracing);
if (!(broken)) block_i++;
else block=broken;}
else {
// Now we try to split the block, we store
// the 'split block' back in the blocks
// variable because we might need to split
// it again.
if (tracing)
logfn("Splitting block %o @ %o",block,page);