-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMathbook.js
More file actions
1283 lines (1096 loc) · 45.5 KB
/
Mathbook.js
File metadata and controls
1283 lines (1096 loc) · 45.5 KB
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
/*******************************************************************************
* Mathbook.js
*******************************************************************************
* The main front-end controller for Mathbook documents.
*
* Homepage: http://mathbook.pugetsound.edu
* Issue Tracker: https://github.com/BooksHTML/mathbook-assets/issues
* Repository: https://github.com/BooksHTML/mathbook-assets
*
* Authors: Michael DuBois, David Farmer, Rob Beezer
*
*******************************************************************************
*/
/* document.write is deprecated for scripts
if(typeof MathJax == 'undefined' ) {
document.write('<script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML-full"></script>')
}
*/
/* load MathJax if not already loaded */
if(typeof MathJax == 'undefined' ) {
(function(d, script) {
script = d.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.onload = function() {
// remote script has loaded
};
script.onerror = function(){
// something went wrong
}
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML-full';
d.getElementsByTagName('head')[0].appendChild(script);
}(document));
}
/* global MathJax, jQuery */
// Leading semicolon safeguards against errors in script concatenation
// Pass dependencies into this closure from the bottom of the file
;(function($, w, Espy, undefined) {
'use strict'; // Use EMCAScript 5 strict mode within this closure
// Define our class on the window object under the Mathbook namespace
var Mathbook = function(options) {
var defaults = {
loadingClass: "mathbook-loading",
loadedClass: "mathbook-loaded",
sectionTrackingLoadedClass: "mathbook-section-tracking-loaded",
stickyWrapperStuckClass: "stuck",
// SELECTORS
//----------
selectors: {
body: "body",
primaryNavbar: "#primary-navbar",
main: ".main",
content: "#content",
toc: "#toc",
previousButton: ".previous-button",
nextButton: ".next-button",
sidebarLeftToggleButton: ".sidebar-left-toggle-button",
sidebarRightToggleButton: ".sidebar-right-toggle-button",
sidebarLeft: "#sidebar-left",
sidebarRight: "#sidebar-right",
sidebarLeftExtras: "#sidebar-left .extras",
sections: "section",
sectionLinks: "#toc a"
},
// BREAKPOINTS
//--------------
screenXsMin: 481,
screenSmMin: 641,
screenMdMin: 801,
screenLgMin: 1200,
// SECTION TRACKING
//-----------------
sectionHashAttribute: "id",
sectionLinkHashAttribute: "data-scroll",
sectionActiveClass: "active",
sectionLinkActiveClass: "active",
/**
* When scrolling down...
* Sections will be exited once their bottom edge rises above this
* It is defined relative to the top of the screen OR the bottom
* edge of any fixed UI elements.
*/
enterSectionTriggerTop: 20,
/**
* When scrolling down...
* Sections will be entered once their top edge rises above this
* It is defined relative to the top of the screen OR the bottom
* edge of any fixed UI elements.
* This will be automatically rounded to the bottom of the screen
* if the viewport is smaller than the defined trigger size
*/
enterSectionTriggerBottom: 150,
// The desired top offset of the active link in the ToC
tocScrollToActiveOffsetTop: 100,
// Called when the viewport enters any tracked section
onEnterSection: null,
// Called when the viewport exits any tracked section
onExitSection: null,
// Called when a section link is activated
// This is probably the best place to log analytics
onActivateSectionLink: null,
// Whether or not to call onEnterSection and onExitSection for
// sections without links.
shouldTrackOnlyLinkedSections: false,
/**
* Interval upon which scrollSpy recomputes section positions
* Should be often enough to catch DOM changes
* but infrequent enough to be reasonably performant
*/
scrollspyRecomputeInterval: 600, // ms
autoScrollDuration: 400, // ms
// linear feels mechanical, but we don't want to load jquery.ui.easing
autoScrollEasing: "linear",
// SIDEBAR SETTINGS
//-----------------
sidebarToggleDuration: 400,
toggleButtonActiveClass: "active",
toggleButtonInactiveClass: "",
hasSidebarLeftClass: "has-sidebar-left",
hasSidebarRightClass: "has-sidebar-right",
sidebarLeftOpenClass: "sidebar-left-open",
sidebarRightOpenClass: "sidebar-right-open",
sidebarLeftClosedClass: "sidebar-left-closed",
sidebarRightClosedClass: "sidebar-right-closed",
shouldDisableSidebarTogglesAtMedium: false,
shouldDisableSidebarTogglesAtLarge: false
};
// Overwrite defaults with any options passed in.
var settings = $.extend({}, defaults, options);
// But don't allow namespaced options to be overwritten
// Extend them instead
var property;
for(property in options) {
if( typeof options !== "undefined" &&
options.hasOwnProperty(property) &&
defaults.hasOwnProperty(property) &&
$.isPlainObject(options[property]) &&
$.isPlainObject(defaults[property]) )
{
settings[property] =
$.extend({}, defaults[property], options[property]);
}
}
var self = this;
var hashOnLoad,
debouncedResizeDuration = 50, // ms
debouncedResizeTimeoutId;
// Layout stuff
var isLayoutInitialized = false,
_shouldSidebarsPush = false,
isPrimaryNavbarBottom = false;
// Sidebar stuff
var maxOpenSidebars = 2,
isSidebarTogglesDisabled = true,
hasSidebarLeft,
hasSidebarRight,
sidebarLeftTransitionTimeoutId,
sidebarRightTransitionTimeoutId;
// Section stuff
var sectionMap = {},
isAutoScrolling = false,
espy;
self.$w = $(window);
/**
* Constructor for ToggleView objects
* These can be used for both toggle buttons and sidebars
*/
var ToggleView = function(options) {
var defaults = {
isActive: false
};
var settings;
this.initialize = function(options) {
settings = defaults;
this.reset(options);
this.toggle(settings.isActive);
};
// Private vars
this.toggle = function(shouldActivate) {
// If not explicitly set, toggle to opposite state
if(typeof shouldActivate === "undefined"){
shouldActivate = !this.isActive();
}
if(shouldActivate) {
if(typeof this.onActivate === "function") {
this.onActivate.call(this.$el.get());
}
this.$el.addClass(settings.activeClass);
this.$el.removeClass(settings.inactiveClass);
} else {
if(typeof this.onDeactivate === "function") {
this.onDeactivate.call(this.$el.get());
}
this.$el.addClass(settings.inactiveClass);
this.$el.removeClass(settings.activeClass);
}
settings.isActive = shouldActivate;
};
this.reset = function(options) {
settings = $.extend(settings,options);
this.$el = $(settings.el);
this.onActivate = settings.onActivate;
this.onDeactivate = settings.onDeactivate;
//this.toggle(this.isActive());
};
this.isActive = function () {
return settings.isActive;
};
// Call init
this.initialize(options);
};
/**
* Constructor for Layout objects that hold configurations for different
* widths.
* @param {String} debugName
* @param {Number} minWidth
* @param {Function} onEnter
* @param {Function} onExit
*/
var Layout = function(options) {
this.minWidth = options.minWidth;
this.debugName = options.debugName;
this.onEnter = options.onEnter;
this.onExit = options.onExit;
/**
* Called when a Layout is applied.
*/
this.enter = function() {
if(typeof this.onEnter === "function") {
this.onEnter.apply(this, arguments);
}
};
/**
* Called when a Layout is removed
*/
this.exit = function() {
if(typeof this.onExit === "function") {
this.onExit.apply(this, arguments);
}
};
};
// LAYOUT DEFINITIONS
// IMPORTANT: MUST MATCH MEDIA QUERIES IN CSS!!!
// Try to keep layout onEnter functions declarative in nature
var layouts = {
// Since layouts rely on the minWidth, add one pixel
SMALL : new Layout({
debugName: "small",
minWidth: 0,
onEnter: function(){
// This must come before adjusting sidebars
self.shouldSidebarsPush(true);
maxOpenSidebars = 1;
self.toggleSidebarLeft(false);
self.toggleSidebarRight(false);
// with primary nav on bottom
isPrimaryNavbarBottom = true;
self.initializeStickies();
self.sidebarTogglesDisabled(false);
}
}),
MEDIUM : new Layout({
debugName: "medium",
minWidth: settings.screenMdMin,
onEnter: function() {
// This must come before adjusting sidebars
self.shouldSidebarsPush(false);
maxOpenSidebars = 1;
self.toggleSidebarLeft(true);
self.toggleSidebarRight(false);
isPrimaryNavbarBottom = false;
self.initializeStickies();
if(settings.shouldDisableSidebarTogglesAtMedium) {
self.sidebarTogglesDisabled(true);
}
}
}),
LARGE : new Layout({
debugName: "large",
minWidth: settings.screenLgMin,
onEnter: function() {
// This must come before adjusting sidebars
self.shouldSidebarsPush(false);
maxOpenSidebars = 2;
self.toggleSidebarLeft(true);
self.toggleSidebarRight(true);
isPrimaryNavbarBottom = false;
self.initializeStickies();
if(settings.shouldDisableSidebarTogglesAtLarge) {
self.sidebarTogglesDisabled(true);
}
}
})
};
var currentLayout = layouts.LARGE;
// Methods
// -----------------------------------------------------------------
/**
* Initialize this object.
*/
self.initialize = function() {
hashOnLoad = w.location.hash;
self.cacheDOMObjects();
self.$body.addClass(settings.loadingClass);
self.initializeSidebars();
self.$w.resize(function() { self.resize(); });
// Set up sticky navigation and section tracking.
self.initializeStickies();
self.setMathJaxOverrides();
self.resize();
self.scrollTocToActiveItem();
self.$body.addClass(settings.loadedClass);
self.$body.removeClass(settings.loadingClass);
};
/**
* Caches all the DOM Objects we need, with JQuery
*/
self.cacheDOMObjects = function() {
self.$w = $(w);
var property;
for(property in settings.selectors) {
if(settings.selectors.hasOwnProperty(property)) {
var prefixed = "$" + property;
self[prefixed] = $(settings.selectors[property]);
}
}
// Cache values
hasSidebarLeft = self.hasSidebarLeft();
hasSidebarRight = self.hasSidebarRight();
};
/**
* By default, MathJax scrolls the window to the hash location
* after "End Typeset" event. We need to override this functionality
* so things work nicely with our sticky header
*/
self.setMathJaxOverrides = function() {
if(typeof MathJax !== "undefined" ) {
// Before MathJax applies the page's configuration
MathJax.Hub.Register.StartupHook("Begin Config", function() {
// Modify that configuration to apply overrides
MathJax.Hub.Config({
positionToHash: false
});
});
// when MathJax is finished rendering,
MathJax.Hub.Register.StartupHook("End Typeset", function () {
self.postMathJax();
});
} else {
self.postMathJax();
}
};
self.postMathJax = function() {
// we handle the hash positioning so that it lines up
// nicely with our fixed header
self.initializeSectionTracking();
self.scrollToSection(hashOnLoad.substr(1));
self.$body.addClass(settings.sectionTrackingLoadedClass);
// TODO expand knowl from hash if there's a match?
};
/**
* Initializes the sticky navigation
*/
self.initializeStickies = function() {
var primaryNavbarHeight = self.$primaryNavbar.outerHeight();
self.$primaryNavbar.unstick();
// Stick navbar stuff
if(!isPrimaryNavbarBottom){
self.$primaryNavbar.sticky({
className: settings.stickyWrapperStuckClass,
wrapperClassName:"navbar",
topSpacing: 0,
});
// Update the position in case scroll is already below
// the stickyifying point
self.$primaryNavbar.sticky("update");
}
// Stick left sidebar
if(hasSidebarLeft) {
self.$sidebarLeft.unstick();
// If primaryNavbar is top, offset sidebar by it's height,
// else offset zero
var sidebarLeftTopSpacing =
isPrimaryNavbarBottom ? 0 : primaryNavbarHeight;
self.$sidebarLeft.sticky({
className: settings.stickyWrapperStuckClass,
wrapperClassName:"sidebar",
topSpacing : sidebarLeftTopSpacing
});
self.$sidebarLeftStickyWrapper = self.$sidebarLeft.parent();
self.resizeSidebarLeftStickyWrapper();
// Update the position in case scroll is already below
// the stickyifying point
self.$sidebarLeft.sticky("update");
}
};
////////////////////////////////////////////////////////////////////////////
// SECTIONS / NAV
////////////////////////////////////////////////////////////////////////////
self.initializeSectionTracking = function() {
espy = new Espy(w, self.onSectionStateChange);
self.reconfigureEspy();
// Generate a map for all linked sections
self.$sections.each(function() {
var $section = $(this);
var hash = $section.attr(settings.sectionHashAttribute);
// Find the corresponding link
var linkSelector =
"["+settings.sectionLinkHashAttribute+"='"+hash+"']";
var $link = self.$sectionLinks.filter(linkSelector);
// If this section has a link
if($link.size() > 0) {
// Create an entry in our section map
sectionMap[hash] = {
$section: $section,
$link: $link,
isActive: false
};
$link.on("click", self.onSectionLinkClick);
if(settings.shouldTrackOnlyLinkedSections) {
// Add them one at a time
espy.add($section);
}
}
});
if(!settings.shouldTrackOnlyLinkedSections) {
// Add all sections to tracking all at once
espy.add(self.$sections);
}
// When the dom changes, espy needs to recompute the positions
// of all the sections. It seems unreasonable, in this case,
// to expect people to call the refresh method everytime the DOM
// changes, so we will resort to an interval.
setInterval(function(){
// Only worth updating if ToC is visible
if(!self.isSidebarLeftClosed()) {
self.refreshEspy();
}
}, settings.spyscrollRecomputeInterval);
};
self.reconfigureEspy = function() {
// Espy's offset is the offset to the top edge of the trigger
// We want to configure the offset from the top edge of the screen
// to the bottom edge of the trigger
var espyOptions = {};
var navbarHeight = self.$primaryNavbar.outerHeight();
var activeArea = self.$w.innerHeight() - navbarHeight;
// Compute offset from top of screen
espyOptions.offset = navbarHeight + settings.enterSectionTriggerTop;
// Compute size of trigger
espyOptions.size = settings.enterSectionTriggerBottom -
settings.enterSectionTriggerTop;
// Limit size to the size of the activeArea
espyOptions.size = Math.min(activeArea, espyOptions.size);
// To be safe, don't allow negative
espyOptions.size = Math.max(espyOptions.size, 0);
espy.configure(espyOptions);
};
self.refreshEspy = function() {
espy.reload();
};
self.onSectionLinkClick = function(e) {
// Called in the context of the link node
var hash = $(this).attr(settings.sectionLinkHashAttribute);
var success =
self.scrollToSection(hash, self.updateLinks, self, [hash]);
// If sidebars are set to push
if(self.shouldSidebarsPush()) {
// then we should automatically close the sidebar
self.toggleSidebarLeft(false);
}
if(success) {
e.preventDefault();
}
};
self.scrollTocToActiveItem = function(duration) {
var $activeItems =
self.$toc.find("." + settings.sectionLinkActiveClass);
if($activeItems.size() > 0) {
// Scroll to the last of the active links
self.scrollTocToItem($activeItems.last(), duration);
}
};
/**
* This function assumes the toc has relative or absolute positioning.
*/
self.scrollTocToItem = function(element, duration) {
if(typeof duration === "undefined") {
duration = settings.autoScrollDuration;
}
var $item = $(element);
// IF the given item is in the toc
if($item.parents().filter(self.$toc).size() > 0) {
// The offset from the top of the toc is the difference
// between the offsets from the top of the document
var tocDocumentTopOffset = self.$toc.position().top;
var itemDocumentTopOffset = $item.position().top;
var itemTocTopOffset =
itemDocumentTopOffset - tocDocumentTopOffset;
// targeted offset between top of frame and active item
var scrollOffset = settings.tocScrollToActiveOffsetTop;
var targetScrollTop =
self.$toc.scrollTop() + itemTocTopOffset - scrollOffset;
var maxScrollTop =
self.$toc.prop('scrollHeight') - self.$toc.innerHeight();
// Apply limits
targetScrollTop = Math.max(targetScrollTop,0);
targetScrollTop = Math.min(targetScrollTop, maxScrollTop);
self.$toc.animate({
scrollTop: targetScrollTop
},
duration,
settings.autoScrollEasing);
}
};
// Animated scroll to a section
// Returns false if no section to scroll to on this page
self.scrollToSection = function(hash, callback, scope, params) {
var sectionExists = false;
var selector = "#" + hash;
var $matchedSection = $(selector).first();
if($matchedSection.length > 0) {
isAutoScrolling = true;
var targetOffsetTop = $matchedSection.offset().top;
var uiHeight =
isPrimaryNavbarBottom ? 0 : self.$primaryNavbar.outerHeight();
// Subtract screen offset for entering sections
targetOffsetTop += -(settings.enterSectionTriggerTop) + 1;
// Subtract UI element heights
targetOffsetTop += -(uiHeight);
// Add fudge so we do, in fact, enter the section
targetOffsetTop += 1;
// Limit to positive numbers
var targetScrollTop = Math.max(targetOffsetTop, 0);
// Define some things we need to do after scrolling
var wrappedCallback = function() {
isAutoScrolling = false;
if(callback && typeof callback === "function") {
callback.call(scope, params);
}
};
// Perform the scroll
$('body,html').animate({
scrollTop: targetScrollTop
},
settings.autoScrollDuration,
settings.autoScrollEasing,
wrappedCallback);
sectionExists = true;
}
// Return false if no section to scroll to on this page
return sectionExists;
};
self.onSectionStateChange = function(isEntered, state) {
/*jshint unused:false */
// Called with the element Node's context
var element = this;
var $section = $(element);
var hash = $section.attr(settings.sectionHashAttribute);
if(sectionMap.hasOwnProperty(hash)) {
sectionMap[hash].isActive = isEntered;
}
// Don't update links during auto scrolls
// It just slows things down
if(!isAutoScrolling) {
self.updateLinks();
}
if(isEntered) {
$section.addClass(settings.sectionActiveClass);
if(typeof settings.onEnterSection === "function"){
settings.onEnterSection.apply(element, arguments);
}
window.thefocus = element.id;
} else {
$section.removeClass(settings.sectionRemoveClass);
if(typeof settings.onExitSection === "function"){
settings.onEnterSection.apply(element, arguments);
}
}
};
self.updateLinks = function() {
var deepestHash = null;
// for all sections in document order
self.$sections.each(function() {
var $section = $(this);
var hash = $section.attr(settings.sectionHashAttribute);
if(sectionMap.hasOwnProperty(hash)) {
if(sectionMap[hash].isActive) {
deepestHash = hash;
}
}
});
if(deepestHash !== null) {
var $link = sectionMap[deepestHash].$link;
if(!$link.hasClass(settings.sectionLinkActiveClass)) {
self.$sectionLinks.removeClass(settings.sectionLinkActiveClass);
$link.addClass(settings.sectionLinkActiveClass);
if(settings.onActivateSectionLink === "function") {
settings.onActivateSectionLink.call($link.get());
}
// We have temporarily disabled setHash because the scrolling
// to the target section does not work properly.
// The scrolling of the TOC still works okay.
// self.setHash(deepestHash);
self.scrollTocToActiveItem();
}
}
};
// Set the hash to reflect the current position in the page
// This function temporarily removes the anchor matching this
// hash so that the page doesn't jump as we change the hash
// It's sort of expensive, so don't call it needlessly
self.setHash = function(hash) {
if(hash === w.location.hash.substr(1)) {
return;
}
if(settings.pushHistory && history.pushState) {
history.pushState({}, hash, "#" + hash);
} else if(history.replaceState) {
history.replaceState({}, hash, "#" + hash);
} else if(settings.provideHistoryFallback) {
// we do it the hacky way
var $fx;
var $nodes = $( '#' + hash + ',[name=\"' + hash + '\"]' );
var ids = [];
var names = [];
var i = 0;
// Remove id and name from all matched nodes
$nodes.each(function() {
var node = $(this);
ids[i] = node.attr('id');
names[i] = node.attr('name');
node.attr( 'id', '' );
node.attr( 'name', '' );
i++;
});
if($nodes.length) {
// Some browsers will try to scroll to where the element
// was last seen, so we create a dummy
$fx = $( '<div></div>' )
.css({
position:'absolute',
visibility:'hidden',
top: self.$w.scrollTop() + 'px'
})
.attr( 'id', hash )
.appendTo( document.body );
}
// finally, set the hash
document.location.hash = hash;
i = 0;
// Return ids and names to matched nodes
$nodes.each(function() {
var node = $(this);
node.attr( 'id', ids[i] );
node.attr( 'name', names[i] );
i++;
});
// Remove our dummy
if($nodes.length) {
$fx.remove();
}
}
};
////////////////////////////////////////////////////////////////////////////
// SIDEBARS
////////////////////////////////////////////////////////////////////////////
/**
* Initializes SidebarViews and registers listeners
*/
self.initializeSidebars = function() {
if(hasSidebarLeft) {
self.sidebarLeftToggleButtonView = new ToggleView({
el: self.$sidebarLeftToggleButton,
activeClass: settings.toggleButtonActiveClass,
inactiveClass: settings.toggleButtonInactiveClass,
});
self.sidebarLeftView = new ToggleView({
el: self.$body, // We want classes to be applied here
activeClass : settings.sidebarLeftOpenClass,
inactiveClass :settings.sidebarLeftClosedClass,
onActivate: function() {
self.onSidebarOpen();
},
onDeactivate: function() {
self.onSidebarClose();
}
});
}
if(hasSidebarRight) {
self.sidebarRightToggleButtonView = new ToggleView({
el: self.$sidebarRightToggleButton,
activeClass: settings.toggleButtonActiveClass,
inactiveClass: settings.toggleButtonInactiveClass,
});
self.sidebarRightView = new ToggleView({
el: self.$body, // We want classes to be applied here
activeClass : settings.sidebarRightOpenClass,
inactiveClass :settings.sidebarRightClosedClass,
onActivate: function() {
self.onSidebarOpen();
},
onDeactivate: function() {
self.onSidebarClose();
}
});
}
self.sidebarTogglesDisabled(false);
};
self.sidebarTogglesDisabled = function(isDisabled) {
if(typeof isDisabled === "undefined") {
return isSidebarTogglesDisabled;
}
if(isDisabled !== isSidebarTogglesDisabled) {
if(!isDisabled) {
if(hasSidebarLeft) {
self.$sidebarLeftToggleButton
.on("click", function(e) {
self.toggleSidebarLeft();
});
}
if(hasSidebarRight) {
self.$sidebarRightToggleButton
.on("click", function(e) {
self.toggleSidebarRight();
});
}
} else {
if(hasSidebarLeft) {
self.$sidebarLeftToggleButton.off("click");
}
if(hasSidebarRight) {
self.$sidebarRightToggleButton.off("click");
}
}
isSidebarTogglesDisabled = true && isDisabled;
}
};
// TODO combine left and right toggle functions?
/**
* Toggles the left sidebar to the shouldOpen state
* or the reverse of the current state if shouldOpen is undefined.
* @param shouldOpen {Boolean}
*/
self.toggleSidebarLeft = function(shouldOpen) {
if(hasSidebarLeft) {
if(typeof shouldOpen === "undefined") {
shouldOpen = self.isSidebarLeftClosed();
}
// Impose max sidebars limit
if(shouldOpen &&
maxOpenSidebars === 1 &&
!self.isSidebarRightClosed()
){
self.toggleSidebarRight(false);
}
// If we are opening
if(shouldOpen) {
// Scroll toc to active link without animation
self.scrollTocToActiveItem(0);
}
self.sidebarLeftToggleButtonView.toggle(shouldOpen);
self.sidebarLeftView.toggle(shouldOpen);
// We might need to do some things at transition end
// Cancel the current timeout, if there is one
clearTimeout(sidebarLeftTransitionTimeoutId);
// Set a new one
sidebarLeftTransitionTimeoutId = setTimeout(function() {
self.refreshEspy();
}, settings.sidebarTransitionDuration);
}
};
/**
* Toggles the right sidebar to the shouldOpen state
* or the reverse of the current state if shouldOpen is undefined.
* @param shouldOpen {Boolean}
*/
self.toggleSidebarRight = function(shouldOpen) {
if(hasSidebarRight) {
if(typeof shouldOpen === "undefined") {
shouldOpen = self.isSidebarRightClosed();
}
if(shouldOpen &&
maxOpenSidebars === 1 &&
!self.isSidebarLeftClosed()
){
self.toggleSidebarLeft(false);
}
self.sidebarRightToggleButtonView.toggle(shouldOpen);
self.sidebarRightView.toggle(shouldOpen);
// We might need to do some things at transition end
// Cancel the current timeout, if there is one
clearTimeout(sidebarRightTransitionTimeoutId);
// Set a new one
sidebarRightTransitionTimeoutId = setTimeout(function() {
self.refreshEspy();
}, settings.sidebarTransitionDuration);
}
};
/**
* Returns true if the left sidebar is present in HTML
* Use the cached variable instead of this function.
*/
self.hasSidebarLeft = function() {
// To be safe, we'll require everything
return self.$sidebarLeft.size() > 0 &&
self.$sidebarLeftToggleButton.size() > 0 &&
self.$main.size() > 0;
};
/**
* Returns true if the right sidebar is present in HTML
* Use the cached variable instead of this function.
*/
self.hasSidebarRight = function() {
// To be safe, we'll require everything
return self.$sidebarRight.size() > 0 &&
self.$sidebarRightToggleButton.size() > 0 &&
self.$main.size() > 0;
};
/**
* Sets whether sidebars should push or slide when opening.
* Push fixes the width of the main content and moves it aside.
* Slide subtracts the sidebar's width from the main width.
*
* @param shouldPush {Boolean} true to push, false to slide
*/
self.shouldSidebarsPush = function(shouldSidebarsPush) {
if(typeof shouldSidebarsPush === "undefined") {
return _shouldSidebarsPush;
}
_shouldSidebarsPush = shouldSidebarsPush;
if(!_shouldSidebarsPush) {
self.unlockMainWidth();
}
};
/**
* Called when a sidebar begins pushing
*/
self.onSidebarOpen = function () {
if(self.shouldSidebarsPush()) {
self.lockMainWidth();
}
};
/**
* Called when a sidebar closes
*/
self.onSidebarClose = function() {