Debian Codegraph @

cloud_sptheme/themes/cloud/static/cloud.js_t

raw ◀ ▶
1 Debian patch touch this file
1 /* ~~~~~~~~~~~~~~
2 * cloud.js_t
3 *~~~~~~~~~~~~~~
4 *
5 * Various bits of javascript driving the moving parts behind various
6 * parts of the cloud theme. Handles things such as toggleable sections,
7 * collapsing the sidebar, etc.
8 *
9 * :copyright: Copyright 2011-2012 by Assurance Technologies
10 * :license: BSD
11 */
12
13 {# helper vars based on location of sidebar #}
14 {% if theme_rightsidebar | tobool %}
15 {% set sidebar_side = "right" %}
16 {% set sidebar_opp = "left" %}
17 {% else %}
18 {% set sidebar_side = "left" %}
19 {% set sidebar_opp = "right" %}
20 {% endif %}
21
22 // begin encapsulation
23 (function (window, $, _, CST) {
24
25 /*==========================================================================
26 * common helpers
27 *==========================================================================*/
28 var isUndef = _.isUndefined,
29 TEXT_NODE = 3, // could use Node.TEXT_NODE, but IE doesn't define it :(
30 $window = $(window),
31 utils = CST.utils,
32 shorten_url = utils.shortenUrl,
33 baseUrl = utils.baseUrl;
34
35 // helper that retrieves css property in pixels
36 function csspx(elem, prop) {
37 return parseInt($(elem).css(prop).replace("px", ""), 10);
38 }
39
40 // NOTE: would use $().offset(), but it's document-relative,
41 // and we need viewport-relative... which means getBoundingClientRect().
42 // NOTE: 'window.frameElement' will only work we're embedded in an iframe on same domain.
43 var parentFrame = window.frameElement;
44 if (window.parent && window.parent !== window) {
45 $(window.parent).scroll(function () {
46 $window.scroll();
47 });
48 }
49
50 function leftFrameOffset() {
51 return parentFrame ? parentFrame.getBoundingClientRect().left : 0;
52 }
53
54 function topFrameOffset() {
55 return parentFrame ? parentFrame.getBoundingClientRect().top : 0;
56 }
57
58 function leftViewOffset($node) {
59 return ($node && $node.length > 0) ? $node[0].getBoundingClientRect().left + leftFrameOffset() : 0;
60 }
61
62 function topViewOffset($node) {
63 return ($node && $node.length > 0) ? $node[0].getBoundingClientRect().top + topFrameOffset() : 0;
64 }
65
66 function bottomViewOffset($node) {
67 return ($node && $node.length > 0) ? $node[0].getBoundingClientRect().bottom + topFrameOffset() : 0;
68 }
69
70 {# return top offset relative to parent, or to frame/viewport if parent is omitted #}
71 function topOffset($target, $parent) {
72 if (!($target && $target[0])) {
73 return 0;
74 }
75 var offset = $target[0].getBoundingClientRect().top;
76 if ($parent && $parent[0]) {
77 offset -= $parent[0].getBoundingClientRect().top;
78 }
79 else {
80 offset += topFrameOffset();
81 }
82 return offset;
83 }
84
85 // return normalized nodename, takes in node or jquery selector
86 // (can't trust nodeName, per http://ejohn.org/blog/nodename-case-sensitivity/)
87 function nodeName(elem) {
88 if (elem && elem.length) {
89 elem = elem[0];
90 }
91 return elem && elem.nodeName.toUpperCase();
92 }
93
94 /*==========================================================================
95 * Sythesize 'cloud-breakpoint' event
96 *==========================================================================
97 * Event emitted when crossing small <-> medium media breakpoint
98 *==========================================================================*/
99 var smallScreen;
100
101 $(function (){
102 var $smallDiv = $('<div class="hide-for-small" />').appendTo("body"),
103 $html = $("html");
104 function update(){
105 var test = $smallDiv.css("display") == "none";
106 if(test !== smallScreen){
107 smallScreen = test;
108 $html.toggleClass("small-screen", test)
109 .toggleClass("medium-up-screen", !test);
110 $window.trigger("cloud-breakpoint");
111 }
112 }
113 $window.on("DOMContentLoaded load resize", update);
114 update();
115 });
116
117 /*==========================================================================
118 * Highlighter Assist
119 *==========================================================================
120 * Sphinx's highlighter marks some objects when user follows link,
121 * but doesn't include section names, etc. This catches those.
122 *==========================================================================*/
123 $(function () {
124 // helper to locate highlight target based on #fragment
125 function locate_target() {
126 // find id referenced by #fragment
127 var hash = document.location.hash;
128 if (!hash) return null;
129 var section = document.getElementById(hash.substr(1));
130 if (!section) return null;
131
132 // could be div.section, or hidden span at top of div.section
133 var name = nodeName(section);
134 if (name != "DIV") {
135 if (name == "SPAN" && section.innerHTML == "" &&
136 nodeName(section.parentNode) == "DIV") {
137 section = section.parentNode;
138 }
139 else if (name == "DT" && section.children.length &&
140 $(section).children("tt.descname, code.descname").length > 0) {
141 // not a section, but an object definition, e.g. a class, func, or attr
142 return $(section);
143 }
144 }
145 // now at section div and either way we have to find title element - h2, h3, etc.
146 var header = $(section).children("h2, h3, h4, h5, h6").first();
147 return header.length ? header : null;
148 }
149
150 // init highlight
151 var target = locate_target();
152 if (target) target.addClass("highlighted");
153
154 // update highlight if hash changes
155 $window.on("hashchange", function () {
156 if (target) target.removeClass("highlighted");
157 target = locate_target();
158 if (target) target.addClass("highlighted");
159 });
160 });
161
162 /*==========================================================================
163 * Toggleable Sections
164 *==========================================================================
165 * Added expand/collapse button to any collapsible RST sections.
166 * Looks for sections with CSS class "html-toggle",
167 * along with the optional classes "expanded" or "collapsed".
168 * Button toggles "html-toggle.expanded/collapsed" classes,
169 * and relies on CSS to do the rest of the job displaying them as appropriate.
170 *==========================================================================*/
171
172 // given "#hash-name-with.periods", escape so it's usable as CSS selector
173 // (e.g. "#hash-name-with\\.periods")
174 // XXX: replace this with proper CSS.escape polyfill?
175 function escapeHash(hash) {
176 return hash.replace(/\./g, "\\.");
177 }
178
179 $(function () {
180 function init() {
181 // get header & section, and add static classes
182 var header = $(this);
183 var section = header.parent();
184 header.addClass("html-toggle-button");
185
186 // helper to test if url hash is within this section
187 function contains_hash() {
188 var hash = document.location.hash;
189 return hash && (section[0].id == hash.substr(1) ||
190 section.find(escapeHash(hash)).length > 0);
191 }
192
193 // helper to control toggle state
194 function set_state(expanded) {
195 expanded = !!expanded; // toggleClass et al need actual boolean
196 section.toggleClass("expanded", expanded);
197 section.toggleClass("collapsed", !expanded);
198 section.children().toggle(expanded);
199 if (!expanded) {
200 section.children("span:first-child:empty").show();
201 /* for :ref: span tag */
202 header.show();
203 }
204 }
205
206 // initialize state
207 set_state(section.hasClass("expanded") || contains_hash());
208
209 // bind toggle callback
210 header.click(function (evt) {
211 var state = section.hasClass("expanded")
212 if (state && $(evt.target).is(".headerlink")) {
213 return;
214 }
215 set_state(!state);
216 $window.trigger('cloud-section-toggled', section[0]);
217 });
218
219 // open section if user jumps to it from w/in page
220 $window.on("hashchange", function () {
221 if (contains_hash()) set_state(true);
222 });
223 }
224
225 $(".html-toggle.section > h2, .html-toggle.section > h3, .html-toggle.section > h4, .html-toggle.section > h5, .html-toggle.section > h6").each(init);
226 });
227
228 /*==========================================================================
229 * mobile menu / collapsible sidebar
230 *==========================================================================
231 * Instruments sidebar toggle buttons. Relies on applying classes
232 * to div.document in order to trigger css rules that show/hide sidebar.
233 * Persists sidebar state via session cookie.
234 * Sidebar state for small screens is tracked separately,
235 * and is NOT persisted.
236 *==========================================================================*/
237 $(function () {
238 // get nodes
239 if (!$(".sphinxsidebar").length) { return; }
240
241 var $doc = $('div.document'),
242 $hide = $('button#sidebar-hide'),
•243 $show = $('button#sidebar-show');
244
245 // set sidebar state for current media size
246 var lastSmall = false,
247 smallState = false,
248 largeState = false;
249 function setState(visible){
250 $doc.toggleClass("sidebar-hidden", !smallScreen && !visible)
251 .toggleClass("document-hidden", smallScreen && visible);
252 $hide.toggleVis(visible);
253 $show.toggleVis(!visible);
254 lastSmall = smallScreen;
255 if(smallScreen) {
256 smallState = visible;
257 if(visible) { largeState = true; }
258 } else {
259 largeState = visible;
260 if(!visible) { smallState = false; }
261 }
262 $window.trigger("cloud-sidebar-toggled", visible);
263 }
264
265 // change when buttons clicked
266 $show.click(function () { setState(true); });
267 $hide.click(function () { setState(false); });
268
269 // refresh sidebar state when crossing breakpoints
270 $window.on("cloud-breakpoint", function (){
271 setState(smallScreen ? smallState : largeState);
272 });
273
274 // load initial state
275 if(smallScreen){
276 setState(false);
277 } else {
•278 var value = "";
279 {% if theme_defaultcollapsed | tobool %}
280 if (!value) value = "collapsed";
281 {% endif %}
282 setState(value != "collapsed");
283 }
284
285 // make buttons visible now that they're instrumented
286 $(".sidebar-toggle-group").removeClass("no-js");
287 });
288
289 {%- if theme_stickysidebar | tobool %}
290 /*==========================================================================
291 * sticky sidebar
292 *==========================================================================
293 * Instrument sidebar so that it sticks in place as page is scrolled.
294 *==========================================================================*/
295
296 function resetStickyState($target){
297 $target.css({
298 position: "",
299 marginLeft: "",
300 top: "",
301 {{sidebar_side}}: "",
302 bottom: ""
303 });
304 }
305
306 // helper to update 'sticky' state of target --
307 // tried to make this generic, but some bits are specific to sidebar
308 function setStickyState($target, top, start, end, $container){
309 if (top >= start) {
310 // top of sidebar is above stickyStart -- scroll with document
311 resetStickyState($target);
312 } else if (top > end) {
313 $target.css({
314 position: "fixed",
315 marginLeft: 0,
316 top: start - topFrameOffset(),
317 {{sidebar_side}}: leftViewOffset($container),
318 bottom: ""
319 });
320 } else {
321 // bottom of sidebar is below stickyEnd -- scroll with document,
322 // but place at bottom of container
323 $target.css({
324 position: "absolute",
325 marginLeft: 0,
326 top: "",
327 {{sidebar_side}}: 0,
328 bottom: 0
329 });
330 }
331 }
332
333 $(function () {
334 // initialize references to relevant elements,
335 // and internal state
336 var $bodywrapper = $(".bodywrapper"), // element that contains content
337 $bodytoc = $('.sphinxglobaltoc a[href="#"]').parent(), // element containing toc for page
338 $container = $('.document'), // element to stick within
339 $target = $('.sphinxsidebar'), // element to sticky
340 $toggle = $(".sidebar-toggle-group"), // extra element to sticky
341 targetMargin = 0, // $target top margin
342 windowHeight = 0, // cache of window height
343 disable = false, // whether sticky is disabled for given window size
344 start = 0, // start sticking when top of target goes above this point
345 lastTop = null, // tracks last offset for scroll+hover handling
346 containerOffset = 0, // top margin of target (included)
347 offset = 0, // offset within target
348 offsetMin = Math.max(0, start); // min offset
349
350 // func to update sidebar position based on scrollbar & container positions
351 function update_sticky(evt) {
352 if (disable) { return; }
353
354 // calc stats
355 // HACK: using $container for offset so we don't have to reset_sticky() for calc.
356 // then add cached container-relative offset to get topViewOffset($target).
357 var top = topViewOffset($container),
358 targetHeight = $target.outerHeight(true),
359 end = targetHeight - $container.height();
360
361 // adjust offset if users scrolls while hovering over sidebar
362 if (evt && evt.type == "scroll" && ($target.first().is(":hover") ||
363 // make sure local toc scrolls into view
364 // XXX: will this still work right if window height < bodytoc height?
365 ($bodytoc.length && bottomViewOffset($bodytoc) + 16 >= windowHeight))) {
366 offset -= top - lastTop;
367 }
368 lastTop = top;
369
370 // see note in top init (above), but doing this here
371 // so it doesn't affect offset adjustment
372 top += containerOffset;
373
374 // limit offset to container bounds
375 if (offset < offsetMin) {
376 offset = offsetMin;
377 } else {
378 var offsetMax = targetHeight - windowHeight - start;
379 offset = Math.max(offsetMin, Math.min(offset, -top, offsetMax));
380 }
381
382 // offset = 0;
383 // console.debug("sticky sidebar: top=%o offset=%o start=%o end=%o",
384 // top, offset, start, end);
385
386 // set sticky state
387 setStickyState($target, top, start - offset, end - offset, $container);
388
389 // set button sticky state -- has to stay at top of screen
390 setStickyState($toggle, top, start - Math.min(offset, targetMargin), -1e9, $container);
391 }
392
393 // func to update sidebar measurements, and then call update_sticky()
394 function update_measurements() {
395 // if body shorter than sidebar, setting sidebar to 'fixed' would cause doc
396 // to shrink below sidebar height, so have to disable sticky mode in this case.
397 resetStickyState($target);
398 resetStickyState($toggle);
399 disable = (smallScreen || $bodywrapper.height() < $target.height());
400 if (disable) {
401 return;
402 }
403
404 // calc stats
405 windowHeight = $window.height();
406 targetMargin = csspx($target, "margin-top");
407 if($target.css("display") == "none"){
408 // so toggle positioned correctly on collapsed sidebar
409 containerOffset = 0;
410 } else {
411 // NOTE: this includes margin-top since it's not removed by sticky code above
412 containerOffset = topOffset($target, $container) - targetMargin;
413 }
414
415 // update state
416 update_sticky();
417 }
418
419 // run function now, and every time window scrolls
420 // XXX: would it help to throttle/raf() scroll & resize calls?
421 $window.scroll(update_sticky)
422 .on("resize hashchange cloud-section-toggled cloud-sidebar-toggled", update_measurements);
423 update_measurements();
424
425 // hack to fix errant initial-layout issue
426 $window.on("load", update_sticky);
427 });
428 {% endif %}
429
430 // flag set by smooth scroller to temporarily disable toc sliding.
431 var scrollingActive = false;
432
433 {%- if theme_highlighttoc | tobool %}
434 /*==========================================================================
435 * sidebar toc highlighter
436 *==========================================================================
437 * highlights toc entry for current section being viewed;
438 * as well as expands & collapses entries for sections that aren't onscreen.
439 *==========================================================================*/
440 $(function () {
441 // scan all links, gathering info about their relationships
442 var $sbody = $("div.body"),
443 localDB = [], // entries that are part of local page OR child page
444 toggleDB = []; // subset of localDB which has $ul defined
445
446 // scan all links w/o TOCs
447 $(".sphinxlocaltoc ul a, .sphinxglobaltoc ul a").each(function (idx, link) {
448 // grab basic info about link
449 var $link = $(link),
450 // NOTE: reading link.attr() so highlight parameter
451 // from current location isn't included...
452 href = shorten_url($link.attr("href")) || "#",
453 isLocal = (href[0] == "#"),
454 isTop = (href == "#"),
455 $li = $link.parent("li"),
456 parent = $li.parent("ul").prev("a").data("toc"),
457 $target;
458
459 // determine type of link & target element for visibility calc
460 if (isLocal) {
461 // css code relies on all local links starting with "#"
462 // so make sure links use right representation
463 $link.attr("href", href);
464
465 // needing for styling
466 $li.addClass("local");
467
468 // link points to section in current document.
469 // use that section as visibility target
470 if(isTop){
471 $target = $sbody;
472
473 // don't bother traversing to parent entry if outside page
474 parent = null;
475 } else {
476 $target = $(document.getElementById(href.slice(1)));
477
478 // XXX: what about rare border case where there's
479 // multiple toplevel entries? not sure *how* to handle that.
480 // (parent will be null in this case)
481 }
482
483 } else if (parent) {
484 // needing for styling
485 $li.addClass("child");
486
487 // parent (or some ancestor) is part of page,
488 // so this is link for child page.
489 // prefer to use actual link in document as visibility target
490 $target = parent.$target.find("a").filter(function () {
491 return shorten_url(this.href) == href;
492 });
493 if (!$target.length) {
494 // target link not actually visible in document
495 // XXX: what if target has multiple links, but to subfragments
496 // e.g. (passlib.hash manpage's link to passlib.hash.ldap_std)?
497 return;
498 }
499 if (($target.parent("li").attr("class") || '').search(/(^|\w)toctree-/) == 0) {
500 // it's part of embedded toc tree, use whole LI as target.
501 $target = $target.parent("li");
502 }
503 // XXX: what if target link is w/in subsection,
504 // even though it belongs at this level in TOC?
505 // *think* active_child code below will prevent spurious highlighting.
506 } else {
507 // this link isn't local, nor is any ancestor, so ignore this one.
508 return;
509 }
510
511 // add to update list
512 var entry = {
513 //
514 // static vars
515 //
516 $target: $target, // section/object controlling link's visibility
517 $li: $li, // list item we're instrumenting
518 parent: parent, // reference to parent entry
519 children: [], // list of child nodes
520 href: href, // normalized copy of li > a[href]
521 isLocal: isLocal, // whether href points to local page
522
523 // filled by $ul pass, below
524 $ul: null, // list of child items if we're doing collapse checking, else null
525 openSize: 0, // avg # of child items expecting to be visible at a time.
526
527 //
528 // state vars modified by updateTOC()
529 //
530 rect: null, // cache of client bounding rect
531 visible: false, // whether target is onscreen
532 active: false, // whether this entry (or child) is marked active
533 justOpened: false // whether toc-toggle was opened during this updateTOC() pass
534 };
535 localDB.push(entry);
536 if(parent) { parent.children.push(entry); }
537 $link.data("toc", entry); // used to get parent entry (above), and for debugging
538 });
539
540 // if no local links found, don't bother w/ update hook
541 //console.debug("localDB: %o", localDB);
542 if (!localDB.length) return;
543
544 // figure out which nodes should be collapsible.
545 // go in reverse order, so we have count available for parent elements.
546 // fills in $ul & viewCount in entries
547 for(var i=localDB.length - 1; i>=0; --i){
548 // don't fill in $ul for toplevel, or ones w/ no entries.
549 var entry = localDB[i],
550 $ul = entry.$li.children("ul");
551 if(!i || !$ul.length){ continue; }
552
553 // calculate how many children will be visible at a time
554 // when $ul is open. this is # of children, plus number
555 // of descendants always visible in non-collapsing children,
556 // plus the largest visibility count of all collapsing children.
557 var weight = entry.children.length,
558 dynamic = 0;
559 entry.children.forEach(function (child){
560 if(!child.$ul) {
561 // always open
562 weight += child.openSize;
563 } else if(child.openSize > dynamic){
564 // largest collapsible child seen so far
565 dynamic = child.openSize;
566 }
567 });
568 entry.openSize = (weight += dynamic);
569
570 // determine if this one should actually be collapsible
571 // TODO: this max weight should really depend on how much
572 // room is available; and/or be decided when parent
573 // is comparing all the children.
574 // NOTE: 'toc-always-open' and 'toc-always-toggle' are control
575 // flags that can be applied via rst-class to section header.
576 if((weight > 3 && !entry.$target.hasClass("toc-always-open") ||
577 entry.$target.hasClass("toc-always-toggle")))
578 {
579 entry.$ul = $ul;
580 entry.$li.addClass("toc-toggle");
581 toggleDB.push(entry);
582 }
583 }
584
585 // debugging helper
586 // var cutoffPrefix = 'pointer-events: none; position: fixed; left: 0; right: 0; background: ',
587 // $cutoff = $('<div/>', {style: cutoffPrefix + 'rgba(0,0,255,0.3)'}).appendTo("body"),
588 // $cutoff2 = $('<div/>', {style: cutoffPrefix + 'rgba(0,255,0,0.3)'}).appendTo("body");
589
590 // function to update cutoff settings
591 var winHeight, // window height
592 lineHeight, // sbody's line height (px)
593 minCutoff, // minimum viewport offset where we assume user is reading
594 curHash; // hash of current highlighted section
595
596 function updateConfig(_evt, first_run){
597 // determine viewable range
598 lineHeight = csspx($sbody, "line-height");
599 winHeight = $window.height();
600 minCutoff = Math.floor(Math.min(winHeight * 0.2, 7 * lineHeight));
601 curHash = shorten_url(document.location.hash) || "#";
602
603 // update TOC markers
604 updateTOC(_evt, first_run);
605 }
606
607 // function to update toc markers
608 function updateTOC(_evt, first_run) {
609 // recalc readline -- attempt to estimate where user who's
610 // scanning through docs is "reading". We start w/ minCutoff,
611 // but when at bottom of screen, may have a bunch of sections visible,
612 // and want to have them expand as last bit of document scrolls into view,
613 // so the readline moves down page when document gets to the end.
614 var readline = minCutoff,
615 bodyBottom = $sbody[0].getBoundingClientRect().bottom,
616 useMaxRatio = (2 * winHeight - bodyBottom - minCutoff) / (winHeight - minCutoff);
617 if (useMaxRatio > 0) {
618 var maxCutoff = Math.min(bodyBottom - 3 * lineHeight, winHeight);
619 readline = minCutoff + (maxCutoff - minCutoff) * Math.min(useMaxRatio, 1);
620 }
621 if (winHeight > $sbody.height()) {
622 readline = 0;
623 }
624
625 // debug stats
626 // console.debug("useMaxRatio=%o", useMaxRatio);
627 // $cutoff.css({height: readline, top: 0});
628 // $cutoff2.css({height: minCutoff, top: 0});
629
630 // reset entries -- recalc .rect & .visible; clear .active flag;
631 // clear active/focus styling classes
632 localDB.forEach(function (entry){
633 var rect = entry.rect = entry.$target[0].getBoundingClientRect();
634 entry.visible = (rect.top <= winHeight && rect.bottom >= 0 &&
635 (rect.width || rect.height));
636 entry.active = false;
637 entry.$li.removeClass("active focus");
638 });
639
640 // pick focus at top TOC level, then check if one of it's
641 // children would be better choice, and so on until
642 // there are no children that could hold focus.
643 // NOTE: assumes children are listed in reading order.
644 var focus = localDB[0];
645 while (true) {
646 var best = null,
647 children = focus.children,
648 cutoff = readline;
649 for(var i = 0, e = children.length; i < e; ++i){
650 var child = children[i];
651 // skip hidden children
652 if(!child.visible) { continue; }
653
654 // pick bottom-most child which starts above readline.
655 else if (child.rect.top <= cutoff) {
656 best = child;
657
658 // if child is highlighted, keep it open longer,
659 // by raising the readline up to minCutoff.
660 if(child.href == curHash){
661 cutoff = minCutoff;
662 }
663 }
664 }
665 var $li = focus.$li;
666 focus.active = true;
667 $li.addClass("active");
668 if (best) {
669 if(!best.isLocal && focus.isLocal){
670 // set focus on final local section
671 // as well as child link
672 $li.addClass("focus");
673 }
674 focus = best;
675 } else {
676 $li.addClass("focus");
677 break;
678 }
679 }
680
681 // update open/closed status of nested ULs
682 // TODO: would like to do cleaner job tracking
683 // which sections are being animated open/close,
684 // and sync it w/ smooth-scrolling code (below).
685 // for now, only have '.justOpened' hack to detect
686 // if we're currently animating a parent element.
687 toggleDB.forEach(function (entry){
688 var $li = entry.$li,
689 $ul = entry.$ul,
690 closed = (!entry.visible || !entry.active ||
691 entry.$target.hasClass("collapsed"));
692 if(smallScreen) { closed = false; first_run = true; }
693 entry.justOpened = false;
694 if ($li.hasClass("closed") == closed) { return; }
695 if (closed) {
696 if (first_run) {
697 $ul.hide(); // don't animate things on first run
698 } else {
699 $ul.slideUp();
700 }
701 } else {
702 var parent = entry.parent;
703 if (first_run || (parent && parent.justOpened)) {
704 $ul.show(); // don't animate if parent is animated.
705 } else {
706 $ul.slideDown();
707 }
708 entry.justOpened = true;
709 }
710 $li.toggleClass("closed", closed);
711 });
712 }
713
714 // run function now, and every time window is resized
715 // TODO: disable when sidebar isn't sticky (including when window is too small)
716 // and when sidebar is collapsed / invisible
717 function scrollWrapper(evt){
718 if(scrollingActive) { return; }
719 return updateTOC(evt);
720 }
721 $window.on("scroll", scrollWrapper)
722 .on('resize hashchange cloud-section-toggled cloud-sidebar-toggled',
723 updateConfig);
724 updateConfig(null, true);
725 });
726 {% endif %}
727
728 /* ==========================================================================
729 * header breaker
730 * ==========================================================================
731 * attempts to intelligently insert linebreaks into page titles, where possible.
732 * currently only handles titles such as "module - description",
733 * adding a break after the "-".
734 * ==========================================================================*/
735 $(function () {
736 // get header's content, insert linebreaks
737 var header = $("h1");
738 var orig = header[0].innerHTML;
739 var shorter = orig;
740 if ($("h1 > a:first > tt > span.pre").length > 0) {
741 shorter = orig.replace(/(<\/tt><\/a>\s*[-\u2013\u2014:]\s+)/im, "$1<br> ");
742 }
743 else if ($("h1 > tt.literal:first").length > 0) {
744 shorter = orig.replace(/(<\/tt>\s*[-\u2013\u2014:]\s+)/im, "$1<br> ");
745 }
746 if (shorter == orig) {
747 return;
748 }
749
750 // hack to determine full width of header
751 header.css({whiteSpace: "nowrap", position: "absolute"});
752 var header_width = header.width();
753 header.css({whiteSpace: "", position: ""});
754
755 // func to insert linebreaks when needed
756 function layout_header() {
757 header[0].innerHTML = (header_width > header.parent().width()) ? shorter : orig;
758 }
759
760 // run function now, and every time window is resized
761 layout_header();
762 $window.on('resize cloud-sidebar-toggled', layout_header);
763 });
764
765 {% if theme_cleanup_toc|tobool %}
766 /*==========================================================================
767 * toc cleaner
768 *==========================================================================
769 * attempts to remove clutter from toc lists.
770 * mainly, looks for toc entries with format "{module} -- {desc}"",
771 * and reduces them down to just "{module}" to save space.
772 *==========================================================================*/
773 $(function () {
774 var $toc = $(".sphinxglobaltoc"),
775 candidates = {};
776
777 // scan TOC for module entries
778 $toc.find("a.internal.reference:has(.literal:first-child > .pre)").each(function () {
779 var $this = $(this),
780 text = $this.find(".literal").text();
781
782 // wrap details in .objdesc class
783 $this.contents().filter(function () {
784 return ((this.nodeType == TEXT_NODE))
785 }).wrap('<span class="objdesc"></span>');
786
787 // work out modules that have exactly 1 toc entry
788 if (isUndef(candidates[text])) {
789 candidates[text] = $this;
790 } else {
791 candidates[text] = null;
792 }
793 });
794
795 // for all modules that had unique names, add 'unique' flag
796 $.each(candidates, function (text, $entry) {
797 if ($entry) {
798 $entry.children(".objdesc").addClass("unique");
799 }
800 });
801
802 });
803 {% endif %}
804
805 {% if theme_smooth_scroll_links|int %}
806 /*==========================================================================
807 * smooth scrolling
808 * instrument toc links w/in same page to use smooth scrolling
809 *==========================================================================*/
810 var scrollSpeed = {{ theme_smooth_scroll_links|int }};
811 $(function () {
812 $('.sphinxsidebar a[href^="#"]').click(function (event) {
813 var hash = this.hash;
814 event.preventDefault();
815 scrollingActive = true; // disable toc focus calc
816 $('html,body').animate({
817 // NOTE: hash == "" for top of document
818 scrollTop: hash ? $(escapeHash(hash)).offset().top : 0
819 }, scrollSpeed).promise().always(function (){
820 // enable & redraw toc focus
821 // xxx: would really like to update *before* animation starts,
822 // so it's animation happened in parallel to scrolling animation
823 scrollingActive = false;
824 $window.trigger("cloud-sidebar-toggled");
825 });
826 if (window.history.pushState) {
827 window.history.pushState(null, "", hash || "#");
828 }
829 $window.trigger("hashchange"); // for toggle section code
830 });
831 });
832 {% endif %}
833
834 {% if theme_inline_admonitions == "auto" %}
835 /*==========================================================================
836 * auto determine when admonition should have inline / block title
837 * under this mode, the css will default to styling everything like a block,
838 * so we just mark everything that shouldn't be blocked out.
839 *==========================================================================*/
840 $(function () {
841 $("div.body div.admonition:not(.inline-title):not(.block-title)" +
842 ":not(.danger):not(.error)" +
843 ":has(p:first-child + p:last-child)").addClass("inline-title");
844 });
845 {% endif %}
846
847 /*==========================================================================
848 * patch sphinx search code to try to and prevent rest markup from showing up
849 * in search results
850 *==========================================================================*/
851 var Search = window.Search;
852 if (Search && Search.makeSearchSummary) {
853 var sphinxSummary = Search.makeSearchSummary;
854 Search.makeSearchSummary = function (text, keywords, hlwords) {
855 /* very primitive regex hack to turn headers into dots */
856 text = text.replace(/^(\s|\n)*([-#=.])\2{6,}\s*\n/, '');
857 text = text.replace(/^([-#=.])\1{6,}\s*$/mg, '\u26AB');
858 text = text.replace(/^\s*#\.\s*/mg, '\u2022 ');
859 //console.debug("makeSearchSummary: text=%o keywords=%o hlwords=%o", text, keywords, hlwords);
860 return sphinxSummary.call(this, text, keywords, hlwords);
861 }
862 }
863
864 /*==========================================================================
865 * toc page styling
866 *==========================================================================
867 * adds some classes to TOC page so items can be styled.
868 * sets li.page and div.highlight-pages markers
869 *==========================================================================*/
870 $(function () {
871 $("div.body div.toctree-wrapper").each(function (){
872 var $div = $(this),
873 highlight = false;
874 $div.find("li").each(function (){
875 var $li = $(this),
876 url = baseUrl($li.children("a").attr("href")),
877 $parent = $li.parent("ul").prev("a"),
878 parentUrl = baseUrl($parent.attr("href"));
879 if(!$parent.length || parentUrl != url){
880 $li.addClass("page");
881 } else {
882 highlight = true;
883 }
884 });
885 if(highlight) { $div.addClass("highlight-pages"); }
886 });
887
888 var $toc = $("#table-of-contents div.toctree-wrapper.highlight-pages");
889 if($toc.length){
890 $('<label id="hide-page-sections"><input type="checkbox" /> {{ _("Hide page sections") }}</label>')
891 .insertBefore($toc).find("input")
892 .change(function (evt){
893 $toc.toggleClass("hide-sections", evt.target.checked);
894 }).change();
895 $(".sphinxglobaltoc > h3").css("margin-top", "4px").wrap('<ul><li class="current active"></li></ul>');
896 }
897 });
898
899 /* ==========================================================================
900 * codeblock lineno aligner
901 * if document contains multiple codeblocks, and some have different counts
902 * (e.g. 10 lines vs 300 lines), the alignment will look off, since the
903 * 300 line block will be indented 1 extra space to account for the hundreds.
904 * this unifies the widths of all such blocks (issue 19)
905 *==========================================================================*/
906 $(function () {
907 var $lines = $(".linenodiv pre");
908 if (!$lines.length) {
909 return;
910 }
911 // NOTE: using ems so this holds under font size changes
912 var largest = Math.max.apply(null, $lines.map(function () {
913 return $(this).innerWidth();
914 })),
915 em_to_px = csspx($lines, "font-size");
916 $lines.css("width", (largest / em_to_px) + "em").css("text-align", "right");
917 });
918
919 /*==========================================================================
920 * codeblock copy helper button
921 *==========================================================================
922 *
923 * Add a [>>>] button on the top-right corner of code samples to hide
924 * the '>>>' and '...' prompts and the output and thus make the code
925 * copyable. Also hides linenumbers.
926 *
927 * Adapted from copybutton.js,
928 * Copyright 2014 PSF. Licensed under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
929 * File originates from the cpython source found in Doc/tools/sphinxext/static/copybutton.js
930 *==========================================================================*/
931 $(function () {
932 // TODO: enhance this to hide linenos for ALL highlighted code blocks,
933 // and only perform python-specific hiding as-needed.
934
935 // static text
936 var hide_text = 'Hide the prompts and output',
937 show_text = 'Show the prompts and output';
938
939 // helper which sets button & codeblock state
940 function setButtonState($button, active) {
941 $button.parent().find('.go, .gp, .gt').toggle(!active);
942 $button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', active ? 'hidden' : 'visible');
943 $button.closest(".highlighttable").find(".linenos pre").css('visibility', active ? 'hidden' : 'visible');
944 $button.attr('title', active ? show_text : hide_text);
945 $button.toggleClass("active", active);
946 }
947
948 // create and add the button to all the code blocks containing a python prompt
949 var $blocks = $('.highlight-python, .highlight-python3');
950 $blocks.find(".highlight:has(pre .gp)").each(function () {
951 var $block = $(this);
952
953 // tracebacks (.gt) contain bare text elements that need to be
954 // wrapped in a span to work with .nextUntil() call in setButtonState()
955 $block.find('pre:has(.gt)').contents().filter(function () {
956 return ((this.nodeType == TEXT_NODE) && (this.data.trim().length > 0));
957 }).wrap('<span>');
958
959 // insert button into block
960 var $button = $('<button class="copybutton">&gt;&gt;&gt;</button>');
961 $block.css("position", "relative").prepend($button);
962 setButtonState($button, false);
963 });
964
965 // toggle button state when clicked
966 $('.copybutton').click(
967 function () {
968 var $button = $(this);
969 setButtonState($button, !$button.hasClass("active"));
970 });
971 });
972
973 /*==========================================================================
974 * nested section helper
975 *==========================================================================
976 * fills out 'data-nested-label' for nested sections (e.g. those w/in a class def)
977 * based on name of containing class. this is used to generate a "return to top"
978 * link w/in nested section header.
979 *==========================================================================*/
980 {% if theme_object_header_prefix %}
981 $(function () {
982 var template = _.template(({{ theme_object_header_prefix }}).replace(
983 /\\(\d{4})/g, function (m, char) { return String.fromCharCode(parseInt(char,16)); }
984 ));
985 $(".desc-section > .section-header").each(function (idx, header) {
986 var $header = $(header),
987 $parent = $header.closest("dd").prev("dt"),
988 name = $parent.find(".descname").text();
989 if (!name) {
990 return;
991 }
992 $header.attr("data-nested-label", template({name: name, parent: $parent}));
993 });
994 });
995 {% endif %}
996
997 /*==========================================================================
998 * field definition markup
999 * XXX: could try to do this via an extension
1000 *==========================================================================*/
1001 $(function () {
1002 // sphinx2 doesn't distinguish classmethod/staticmethod, so add helper class for styling.
1003 $("dl.method").each(function (){
1004 var $item = $(this),
1005 type = $item.find("> dt > em.property:first-child").text().trim();
1006 if(type){
1007 $item.attr("subtype", type);
1008 }
1009 });
1010
1011 // detect which ones end w/ headerlink, to adjust markup
1012 // NOTE: .classmethod & .staticmethod can be removed when sphinx 1.x is dropped.
1013 $("dl.object, dl.data, dl.function, dl.method, dl.attribute, dl.class , dl.exception, dl.classmethod, dl.staticmethod")
1014 .filter(":has(> dt > a.headerlink:last-child)").addClass("has-headerlink");
1015 });
1016
1017 /*==========================================================================
1018 * eof
1019 *==========================================================================*/
1020
1021 // end encapsulation
1022 // NOTE: sphinx provides underscore.js as $u
1023 }(window, jQuery, $u, CST));