1 /* global window, document, $, hljs, elasticlunr, base_url, is_top_frame */
2 /* exported getParam, onIframeLoad */
5 // The full page consists of a main window with navigation and table of contents, and an inner
6 // iframe containing the current article. Which article is shown is determined by the main
7 // window's #hash portion of the URL. In fact, we use the simple rule: main window's URL of
8 // "rootUrl#relPath" corresponds to iframe's URL of "rootUrl/relPath".
10 // The main frame and the contents of the index page actually live in a single generated html
11 // file: the outer frame hides one half, and the inner hides the other. TODO: this should be
12 // possible to greatly simplify after mkdocs-1.0 release.
14 var mainWindow = is_top_frame ? window : (window.parent !== window ? window.parent : null);
15 var iframeWindow = null;
16 var rootUrl = qualifyUrl(base_url);
17 var searchIndex = null;
18 var showPageToc = true;
19 var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
28 function startsWith(str, prefix) { return str.lastIndexOf(prefix, 0) === 0; }
29 function endsWith(str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; }
32 * Returns whether to use small-screen mode. Note that the same size is used in css @media block.
34 function isSmallScreen() {
35 return window.matchMedia("(max-width: 600px)").matches;
39 * Given a relative URL, returns the absolute one, relying on the browser to convert it.
41 function qualifyUrl(url) {
42 var a = document.createElement('a');
48 * Turns an absolute path to relative, stripping out rootUrl + separator.
50 function getRelPath(separator, absUrl) {
51 var prefix = rootUrl + (endsWith(rootUrl, separator) ? '' : separator);
52 return startsWith(absUrl, prefix) ? absUrl.slice(prefix.length) : null;
56 * Turns a relative path to absolute, adding a prefix of rootUrl + separator.
58 function getAbsUrl(separator, relPath) {
59 var sep = endsWith(rootUrl, separator) ? '' : separator;
60 return relPath === null ? null : rootUrl + sep + relPath;
64 * Redirects the iframe to reflect the path represented by the main window's current URL.
65 * (In our design, nothing should change iframe's src except via updateIframe(), or back/forward
66 * history is likely to get messed up.)
68 function updateIframe(enableForwardNav) {
69 // Grey out the "forward" button if we don't expect 'forward' to work.
70 $('#hist-fwd').toggleClass('greybtn', !enableForwardNav);
72 var targetRelPath = getRelPath('#', mainWindow.location.href) || '';
73 var targetIframeUrl = getAbsUrl('/', targetRelPath);
74 var loc = iframeWindow.location;
75 var currentIframeUrl = _safeGetLocationHref(loc);
77 console.log("updateIframe: %s -> %s (%s)", currentIframeUrl, targetIframeUrl,
78 currentIframeUrl === targetIframeUrl ? "same" : "replacing");
80 if (currentIframeUrl !== targetIframeUrl) {
81 loc.replace(targetIframeUrl);
82 onIframeBeforeLoad(targetIframeUrl);
84 document.body.scrollTop = 0;
88 * Returns location.href, catching exception that's triggered if the iframe is on a different domain.
90 function _safeGetLocationHref(location) {
99 * Returns the value of the given parameter in the URL's query portion.
101 function getParam(key) {
102 var params = window.location.search.substring(1).split('&');
103 for (var i = 0; i < params.length; i++) {
104 var param = params[i].split('=');
105 if (param[0] === key) {
106 return decodeURIComponent(param[1].replace(/\+/g, '%20'));
112 * Update the state of the button toggling table-of-contents. TOC has different behavior
113 * depending on screen size, so the button's behavior depends on that too.
115 function updateTocButtonState() {
117 if (isSmallScreen()) {
118 shown = $('.wm-toc-pane').hasClass('wm-toc-dropdown');
120 shown = !$('#main-content').hasClass('wm-toc-hidden');
122 $('#wm-toc-button').toggleClass('active', shown);
126 * Update the height of the iframe container. On small screens, we adjust it to fit the iframe
127 * contents, so that the page scrolls as a whole rather than inside the iframe.
129 function updateContentHeight() {
130 if (isSmallScreen()) {
131 $('.wm-content-pane').height(iframeWindow.document.body.offsetHeight + 20);
132 $('.wm-article').attr('scrolling', 'no');
134 $('.wm-content-pane').height('');
135 $('.wm-article').attr('scrolling', 'auto');
140 * When TOC is a dropdown (on small screens), close it.
142 function closeTempItems() {
143 $('.wm-toc-dropdown').removeClass('wm-toc-dropdown');
144 $('#mkdocs-search-query').closest('.wm-top-tool').removeClass('wm-top-tool-expanded');
145 updateTocButtonState();
149 * Visit the given URL. This changes the hash of the top page to reflect the new URL's relative
150 * path, and points the iframe to the new URL.
152 function visitUrl(url, event) {
153 var relPath = getRelPath('/', url);
154 if (relPath !== null) {
155 event.preventDefault();
156 var newUrl = getAbsUrl('#', relPath);
157 if (newUrl !== mainWindow.location.href) {
158 mainWindow.history.pushState(null, '', newUrl);
162 iframeWindow.focus();
167 * Adjusts link to point to a top page, converting URL from "base/path" to "base#path". It also
168 * sets a data-adjusted attribute on the link, to skip adjustments on future clicks.
170 function adjustLink(linkEl) {
171 if (!linkEl.hasAttribute('data-wm-adjusted')) {
172 linkEl.setAttribute('data-wm-adjusted', 'done');
173 var relPath = getRelPath('/', linkEl.href);
174 if (relPath !== null) {
175 var newUrl = getAbsUrl('#', relPath);
176 linkEl.href = newUrl;
182 * Given a URL, strips query and fragment, returning just the path.
184 function cleanUrlPath(relUrl) {
185 return relUrl.replace(/[#?].*/, '');
189 * Initialize the main window.
191 function initMainWindow() {
192 // wm-toc-button either opens the table of contents in the side-pane, or (on smaller screens)
193 // shows the side-pane as a drop-down.
194 $('#wm-toc-button').on('click', function(e) {
195 if (isSmallScreen()) {
196 $('.wm-toc-pane').toggleClass('wm-toc-dropdown');
197 $('#wm-main-content').removeClass('wm-toc-hidden');
199 $('#main-content').toggleClass('wm-toc-hidden');
202 updateTocButtonState();
205 // Update the state of the wm-toc-button
206 updateTocButtonState();
207 $(window).on('resize', function() {
208 updateTocButtonState();
209 updateContentHeight();
212 // Connect up the Back and Forward buttons (if present).
213 $('#hist-back').on('click', function(e) { window.history.back(); });
214 $('#hist-fwd').on('click', function(e) { window.history.forward(); });
216 // When the side-pane is a dropdown, hide it on click-away.
217 $(window).on('blur', closeTempItems);
219 // When we click on an opener in the table of contents, open it.
220 $('.wm-toc-pane').on('click', '.wm-toc-opener', function(e) {
221 $(this).toggleClass('wm-toc-open');
222 $(this).next('.wm-toc-li-nested').collapse('toggle');
224 $('.wm-toc-pane').on('click', '.wm-page-toc-opener', function(e) {
225 // Ignore clicks while transitioning.
226 if ($(this).next('.wm-page-toc').hasClass('collapsing')) { return; }
227 showPageToc = !showPageToc;
228 $(this).toggleClass('wm-page-toc-open', showPageToc);
229 $(this).next('.wm-page-toc').collapse(showPageToc ? 'show' : 'hide');
232 // Once the article loads in the side-pane, close the dropdown.
233 $('.wm-article').on('load', function() {
234 document.title = iframeWindow.document.title;
235 updateContentHeight();
237 // We want to update content height whenever the height of the iframe's content changes.
238 // Using MutationObserver seems to be the best way to do that.
239 var observer = new MutationObserver(updateContentHeight);
240 observer.observe(iframeWindow.document.body, {
247 iframeWindow.focus();
250 // Initialize search functionality.
253 // Load the iframe now, and whenever we navigate the top frame.
254 setTimeout(function() { updateIframe(false); }, 0);
255 // For our usage, 'popstate' or 'hashchange' would work, but only 'hashchange' work on IE.
256 $(window).on('hashchange', function() { updateIframe(true); });
259 function onIframeBeforeLoad(url) {
260 $('.wm-current').removeClass('wm-current');
263 var tocLi = getTocLi(url);
264 tocLi.addClass('wm-current');
265 tocLi.parents('.wm-toc-li-nested')
266 // It's better to open parent items immediately without a transition.
267 .removeClass('collapsing').addClass('collapse in').height('')
268 .prev('.wm-toc-opener').addClass('wm-toc-open');
271 function getTocLi(url) {
272 var relPath = getAbsUrl('#', getRelPath('/', cleanUrlPath(url)));
273 var selector = '.wm-article-link[href="' + relPath + '"]';
274 return $(selector).closest('.wm-toc-li');
277 var _deferIframeLoad = false;
279 // Sometimes iframe is loaded before main window's ready callback. In this case, we defer
280 // onIframeLoad call until the main window has initialized.
281 function ensureIframeLoaded() {
282 if (_deferIframeLoad) {
287 function onIframeLoad() {
288 if (!iframeWindow) { _deferIframeLoad = true; return; }
289 var url = iframeWindow.location.href;
290 onIframeBeforeLoad(url);
292 if (iframeWindow.pageToc) {
293 var relPath = getAbsUrl('#', getRelPath('/', cleanUrlPath(url)));
294 renderPageToc(getTocLi(url), relPath, iframeWindow.pageToc);
296 iframeWindow.focus();
300 * Hides a bootstrap collapsible element, and removes it from DOM once hidden.
302 function collapseAndRemove(collapsibleElem) {
303 if (!collapsibleElem.hasClass('in')) {
304 // If the element is already hidden, just remove it immediately.
305 collapsibleElem.remove();
307 collapsibleElem.on('hidden.bs.collapse', function() {
308 collapsibleElem.remove();
314 function renderPageToc(parentElem, pageUrl, pageToc) {
315 var ul = $('<ul class="wm-toctree">');
316 function addItem(tocItem) {
317 ul.append($('<li class="wm-toc-li">')
318 .append($('<a class="wm-article-link wm-page-toc-text">')
319 .attr('href', pageUrl + tocItem.url)
320 .attr('data-wm-adjusted', 'done')
321 .text(tocItem.title)));
322 if (tocItem.children) {
323 tocItem.children.forEach(addItem);
326 pageToc.forEach(addItem);
328 $('.wm-page-toc-opener').removeClass('wm-page-toc-opener wm-page-toc-open');
329 collapseAndRemove($('.wm-page-toc'));
331 parentElem.addClass('wm-page-toc-opener').toggleClass('wm-page-toc-open', showPageToc);
332 $('<li class="wm-page-toc wm-toc-li-nested collapse">').append(ul).insertAfter(parentElem)
333 .collapse(showPageToc ? 'show' : 'hide');
338 // This is a page that ought to be in an iframe. Redirect to load the top page instead.
339 var topUrl = getAbsUrl('#', getRelPath('/', window.location.href));
341 window.location.href = topUrl;
345 // Adjust all links to point to the top page with the right hash fragment.
346 $(document).ready(function() {
347 $('a').each(function() { adjustLink(this); });
350 // For any dynamically-created links, adjust them on click.
351 $(document).on('click', 'a:not([data-wm-adjusted])', function(e) { adjustLink(this); });
356 $(document).ready(function() {
357 iframeWindow = $('.wm-article')[0].contentWindow;
359 ensureIframeLoaded();
364 iframeWindow = window;
366 mainWindow.onIframeLoad();
369 // Other initialization of iframe contents.
370 hljs.initHighlightingOnLoad();
371 $(document).ready(function() {
372 $('table').addClass('table table-striped table-hover table-bordered table-condensed');
377 var searchIndexReady = false;
380 * Initialize search functionality.
382 function initSearch() {
383 // Create elasticlunr index.
384 searchIndex = elasticlunr(function() {
385 this.setRef('location');
386 this.addField('title');
387 this.addField('text');
390 var searchBox = $('#mkdocs-search-query');
391 var searchResults = $('#mkdocs-search-results');
393 // Fetch the prebuilt index data, and add to the index.
394 $.getJSON(base_url + '/search/search_index.json')
395 .done(function(data) {
396 data.docs.forEach(function(doc) {
397 searchIndex.addDoc(doc);
399 searchIndexReady = true;
400 $(document).trigger('searchIndexReady');
403 function showSearchResults(optShow) {
404 var show = (optShow === false ? false : Boolean(searchBox.val()));
407 resultsElem: searchResults,
408 query: searchBox.val(),
413 searchResults.parent().toggleClass('open', show);
417 searchBox.on('click', function(e) {
418 if (!searchResults.parent().hasClass('open')) {
419 if (showSearchResults()) {
425 // Search automatically and show results on keyup event.
426 searchBox.on('keyup', function(e) {
427 var show = (e.which !== Keys.ESCAPE && e.which !== Keys.ENTER);
428 showSearchResults(show);
431 // Open the search box (and run the search) on up/down arrow keys.
432 searchBox.on('keydown', function(e) {
433 if (e.which === Keys.UP || e.which === Keys.DOWN) {
434 if (showSearchResults()) {
437 setTimeout(function() {
438 searchResults.find('a').eq(e.which === Keys.UP ? -1 : 0).focus();
444 searchResults.on('keydown', function(e) {
445 if (e.which === Keys.UP || e.which === Keys.DOWN) {
446 if (searchResults.find('a').eq(e.which === Keys.UP ? 0 : -1)[0] === e.target) {
454 $(searchResults).on('click', '.search-all', function(e) {
457 $('#wm-search-form').trigger('submit');
460 // Redirect to the search page on Enter or button-click (form submit).
461 $('#wm-search-form').on('submit', function(e) {
462 var url = this.action + '?' + $(this).serialize();
464 searchResults.parent().removeClass('open');
467 $('#wm-search-show,#wm-search-go').on('click', function(e) {
468 if (isSmallScreen()) {
470 var el = $('#mkdocs-search-query').closest('.wm-top-tool');
471 el.toggleClass('wm-top-tool-expanded');
472 if (el.hasClass('wm-top-tool-expanded')) {
473 setTimeout(function() {
474 $('#mkdocs-search-query').focus();
477 $('#mkdocs-search-query').focus();
483 function escapeRegex(s) {
484 return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
488 * This helps construct useful snippets to show in search results, and highlight matches.
490 function SnippetBuilder(query) {
491 var termsPattern = elasticlunr.tokenizer(query).map(escapeRegex).join("|");
492 this._termsRegex = termsPattern ? new RegExp(termsPattern, "gi") : null;
495 SnippetBuilder.prototype.getSnippet = function(text, len) {
496 if (!this._termsRegex) {
497 return text.slice(0, len);
500 // Find a position that includes something we searched for.
501 var pos = text.search(this._termsRegex);
502 if (pos < 0) { pos = 0; }
504 // Find a period before that position (a good starting point).
505 var start = text.lastIndexOf('.', pos) + 1;
506 if (pos - start > 30) {
507 // If too long to previous period, give it 30 characters, and find a space before that.
508 start = text.lastIndexOf(' ', pos - 30) + 1;
510 var rawSnippet = text.slice(start, start + len);
511 return rawSnippet.replace(this._termsRegex, '<b>$&</b>');
515 * Search the elasticlunr index for the given query, and populate the dropdown with results.
517 function doSearch(options) {
518 var resultsElem = options.resultsElem;
521 // If the index isn't ready, wait for it, and search again when ready.
522 if (!searchIndexReady) {
523 resultsElem.append($('<li class="disabled"><a class="search-link">SEARCHING...</a></li>'));
524 $(document).one('searchIndexReady', function() { doSearch(options); });
528 var query = options.query;
529 var snippetLen = options.snippetLen;
530 var limit = options.limit;
532 if (query === '') { return; }
534 var results = searchIndex.search(query, {
535 fields: { title: {boost: 10}, text: { boost: 1 } },
540 var snippetBuilder = new SnippetBuilder(query);
541 if (results.length > 0){
542 var len = Math.min(results.length, limit || Infinity);
543 for (var i = 0; i < len; i++) {
544 var doc = searchIndex.documentStore.getDoc(results[i].ref);
545 var snippet = snippetBuilder.getSnippet(doc.text, snippetLen);
547 $('<li>').append($('<a class="search-link">').attr('href', pathJoin(base_url, doc.location))
548 .append($('<div class="search-title">').text(doc.title))
549 .append($('<div class="search-text">').html(snippet)))
552 resultsElem.find('a').each(function() { adjustLink(this); });
554 resultsElem.append($('<li role="separator" class="divider"></li>'));
555 resultsElem.append($(
556 '<li><a class="search-link search-all" href="' + base_url + '/search.html">' +
557 '<div class="search-title">SEE ALL RESULTS</div></a></li>'));
560 resultsElem.append($('<li class="disabled"><a class="search-link">NO RESULTS FOUND</a></li>'));
564 function pathJoin(prefix, suffix) {
565 var nPrefix = endsWith(prefix, "/") ? prefix.slice(0, -1) : prefix;
566 var nSuffix = startsWith(suffix, "/") ? suffix.slice(1) : suffix;
567 return nPrefix + "/" + nSuffix;