Debian Codegraph @

cloud_sptheme/themes/cloud/static/cloud.js_t

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