docfx.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  1. // Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See LICENSE file in the project root for full license information.
  2. $(function () {
  3. var active = 'active';
  4. var expanded = 'in';
  5. var collapsed = 'collapsed';
  6. var filtered = 'filtered';
  7. var show = 'show';
  8. var hide = 'hide';
  9. var util = new utility();
  10. workAroundFixedHeaderForAnchors();
  11. highlight();
  12. enableSearch();
  13. renderTables();
  14. renderAlerts();
  15. renderLinks();
  16. renderNavbar();
  17. renderSidebar();
  18. renderAffix();
  19. renderFooter();
  20. renderLogo();
  21. breakText();
  22. renderTabs();
  23. window.refresh = function (article) {
  24. // Update markup result
  25. if (typeof article == 'undefined' || typeof article.content == 'undefined')
  26. console.error("Null Argument");
  27. $("article.content").html(article.content);
  28. highlight();
  29. renderTables();
  30. renderAlerts();
  31. renderAffix();
  32. renderTabs();
  33. }
  34. // Add this event listener when needed
  35. // window.addEventListener('content-update', contentUpdate);
  36. function breakText() {
  37. $(".xref").addClass("text-break");
  38. var texts = $(".text-break");
  39. texts.each(function () {
  40. $(this).breakWord();
  41. });
  42. }
  43. // Styling for tables in conceptual documents using Bootstrap.
  44. // See http://getbootstrap.com/css/#tables
  45. function renderTables() {
  46. $('table').addClass('table table-bordered table-striped table-condensed').wrap('<div class=\"table-responsive\"></div>');
  47. }
  48. // Styling for alerts.
  49. function renderAlerts() {
  50. $('.NOTE, .TIP').addClass('alert alert-info');
  51. $('.WARNING').addClass('alert alert-warning');
  52. $('.IMPORTANT, .CAUTION').addClass('alert alert-danger');
  53. }
  54. // Enable anchors for headings.
  55. (function () {
  56. anchors.options = {
  57. placement: 'left',
  58. visible: 'touch'
  59. };
  60. anchors.add('article h2:not(.no-anchor), article h3:not(.no-anchor), article h4:not(.no-anchor)');
  61. })();
  62. // Open links to different host in a new window.
  63. function renderLinks() {
  64. if ($("meta[property='docfx:newtab']").attr("content") === "true") {
  65. $(document.links).filter(function () {
  66. return this.hostname !== window.location.hostname;
  67. }).attr('target', '_blank');
  68. }
  69. }
  70. // Enable highlight.js
  71. function highlight() {
  72. $('pre code').each(function (i, block) {
  73. hljs.highlightBlock(block);
  74. });
  75. $('pre code[highlight-lines]').each(function (i, block) {
  76. if (block.innerHTML === "") return;
  77. var lines = block.innerHTML.split('\n');
  78. queryString = block.getAttribute('highlight-lines');
  79. if (!queryString) return;
  80. var ranges = queryString.split(',');
  81. for (var j = 0, range; range = ranges[j++];) {
  82. var found = range.match(/^(\d+)\-(\d+)?$/);
  83. if (found) {
  84. // consider region as `{startlinenumber}-{endlinenumber}`, in which {endlinenumber} is optional
  85. var start = +found[1];
  86. var end = +found[2];
  87. if (isNaN(end) || end > lines.length) {
  88. end = lines.length;
  89. }
  90. } else {
  91. // consider region as a sigine line number
  92. if (isNaN(range)) continue;
  93. var start = +range;
  94. var end = start;
  95. }
  96. if (start <= 0 || end <= 0 || start > end || start > lines.length) {
  97. // skip current region if invalid
  98. continue;
  99. }
  100. lines[start - 1] = '<span class="line-highlight">' + lines[start - 1];
  101. lines[end - 1] = lines[end - 1] + '</span>';
  102. }
  103. block.innerHTML = lines.join('\n');
  104. });
  105. }
  106. // Support full-text-search
  107. function enableSearch() {
  108. var query;
  109. var relHref = $("meta[property='docfx\\:rel']").attr("content");
  110. if (typeof relHref === 'undefined') {
  111. return;
  112. }
  113. try {
  114. var worker = new Worker(relHref + 'styles/search-worker.js');
  115. if (!worker && !window.worker) {
  116. localSearch();
  117. } else {
  118. webWorkerSearch();
  119. }
  120. renderSearchBox();
  121. highlightKeywords();
  122. addSearchEvent();
  123. } catch (e) {
  124. console.error(e);
  125. }
  126. //Adjust the position of search box in navbar
  127. function renderSearchBox() {
  128. autoCollapse();
  129. $(window).on('resize', autoCollapse);
  130. $(document).on('click', '.navbar-collapse.in', function (e) {
  131. if ($(e.target).is('a')) {
  132. $(this).collapse('hide');
  133. }
  134. });
  135. function autoCollapse() {
  136. var navbar = $('#autocollapse');
  137. if (navbar.height() === null) {
  138. setTimeout(autoCollapse, 300);
  139. }
  140. navbar.removeClass(collapsed);
  141. if (navbar.height() > 60) {
  142. navbar.addClass(collapsed);
  143. }
  144. }
  145. }
  146. // Search factory
  147. function localSearch() {
  148. console.log("using local search");
  149. var lunrIndex = lunr(function () {
  150. this.ref('href');
  151. this.field('title', { boost: 50 });
  152. this.field('keywords', { boost: 20 });
  153. });
  154. lunr.tokenizer.seperator = /[\s\-\.]+/;
  155. var searchData = {};
  156. var searchDataRequest = new XMLHttpRequest();
  157. var indexPath = relHref + "index.json";
  158. if (indexPath) {
  159. searchDataRequest.open('GET', indexPath);
  160. searchDataRequest.onload = function () {
  161. if (this.status != 200) {
  162. return;
  163. }
  164. searchData = JSON.parse(this.responseText);
  165. for (var prop in searchData) {
  166. if (searchData.hasOwnProperty(prop)) {
  167. lunrIndex.add(searchData[prop]);
  168. }
  169. }
  170. }
  171. searchDataRequest.send();
  172. }
  173. $("body").bind("queryReady", function () {
  174. var hits = lunrIndex.search(query);
  175. var results = [];
  176. hits.forEach(function (hit) {
  177. var item = searchData[hit.ref];
  178. results.push({ 'href': item.href, 'title': item.title, 'keywords': item.keywords });
  179. });
  180. handleSearchResults(results);
  181. });
  182. }
  183. function webWorkerSearch() {
  184. console.log("using Web Worker");
  185. var indexReady = $.Deferred();
  186. worker.onmessage = function (oEvent) {
  187. switch (oEvent.data.e) {
  188. case 'index-ready':
  189. indexReady.resolve();
  190. break;
  191. case 'query-ready':
  192. var hits = oEvent.data.d;
  193. handleSearchResults(hits);
  194. break;
  195. }
  196. }
  197. indexReady.promise().done(function () {
  198. $("body").bind("queryReady", function () {
  199. worker.postMessage({ q: query });
  200. });
  201. if (query && (query.length >= 3)) {
  202. worker.postMessage({ q: query });
  203. }
  204. });
  205. }
  206. // Highlight the searching keywords
  207. function highlightKeywords() {
  208. var q = url('?q');
  209. if (q !== null) {
  210. var keywords = q.split("%20");
  211. keywords.forEach(function (keyword) {
  212. if (keyword !== "") {
  213. $('.data-searchable *').mark(keyword);
  214. $('article *').mark(keyword);
  215. }
  216. });
  217. }
  218. }
  219. function addSearchEvent() {
  220. $('body').bind("searchEvent", function () {
  221. $('#search-query').keypress(function (e) {
  222. return e.which !== 13;
  223. });
  224. $('#search-query').keyup(function () {
  225. query = $(this).val();
  226. if (query.length < 3) {
  227. flipContents("show");
  228. } else {
  229. flipContents("hide");
  230. $("body").trigger("queryReady");
  231. $('#search-results>.search-list').text('Search Results for "' + query + '"');
  232. }
  233. }).off("keydown");
  234. });
  235. }
  236. function flipContents(action) {
  237. if (action === "show") {
  238. $('.hide-when-search').show();
  239. $('#search-results').hide();
  240. } else {
  241. $('.hide-when-search').hide();
  242. $('#search-results').show();
  243. }
  244. }
  245. function relativeUrlToAbsoluteUrl(currentUrl, relativeUrl) {
  246. var currentItems = currentUrl.split(/\/+/);
  247. var relativeItems = relativeUrl.split(/\/+/);
  248. var depth = currentItems.length - 1;
  249. var items = [];
  250. for (var i = 0; i < relativeItems.length; i++) {
  251. if (relativeItems[i] === '..') {
  252. depth--;
  253. } else if (relativeItems[i] !== '.') {
  254. items.push(relativeItems[i]);
  255. }
  256. }
  257. return currentItems.slice(0, depth).concat(items).join('/');
  258. }
  259. function extractContentBrief(content) {
  260. var briefOffset = 512;
  261. var words = query.split(/\s+/g);
  262. var queryIndex = content.indexOf(words[0]);
  263. var briefContent;
  264. if (queryIndex > briefOffset) {
  265. return "..." + content.slice(queryIndex - briefOffset, queryIndex + briefOffset) + "...";
  266. } else if (queryIndex <= briefOffset) {
  267. return content.slice(0, queryIndex + briefOffset) + "...";
  268. }
  269. }
  270. function handleSearchResults(hits) {
  271. var numPerPage = 10;
  272. $('#pagination').empty();
  273. $('#pagination').removeData("twbs-pagination");
  274. if (hits.length === 0) {
  275. $('#search-results>.sr-items').html('<p>No results found</p>');
  276. } else {
  277. $('#pagination').twbsPagination({
  278. totalPages: Math.ceil(hits.length / numPerPage),
  279. visiblePages: 5,
  280. onPageClick: function (event, page) {
  281. var start = (page - 1) * numPerPage;
  282. var curHits = hits.slice(start, start + numPerPage);
  283. $('#search-results>.sr-items').empty().append(
  284. curHits.map(function (hit) {
  285. var currentUrl = window.location.href;
  286. var itemRawHref = relativeUrlToAbsoluteUrl(currentUrl, relHref + hit.href);
  287. var itemHref = relHref + hit.href + "?q=" + query;
  288. var itemTitle = hit.title;
  289. var itemBrief = extractContentBrief(hit.keywords);
  290. var itemNode = $('<div>').attr('class', 'sr-item');
  291. var itemTitleNode = $('<div>').attr('class', 'item-title').append($('<a>').attr('href', itemHref).attr("target", "_blank").text(itemTitle));
  292. var itemHrefNode = $('<div>').attr('class', 'item-href').text(itemRawHref);
  293. var itemBriefNode = $('<div>').attr('class', 'item-brief').text(itemBrief);
  294. itemNode.append(itemTitleNode).append(itemHrefNode).append(itemBriefNode);
  295. return itemNode;
  296. })
  297. );
  298. query.split(/\s+/).forEach(function (word) {
  299. if (word !== '') {
  300. $('#search-results>.sr-items *').mark(word);
  301. }
  302. });
  303. }
  304. });
  305. }
  306. }
  307. };
  308. // Update href in navbar
  309. function renderNavbar() {
  310. var navbar = $('#navbar ul')[0];
  311. if (typeof (navbar) === 'undefined') {
  312. loadNavbar();
  313. } else {
  314. $('#navbar ul a.active').parents('li').addClass(active);
  315. renderBreadcrumb();
  316. showSearch();
  317. }
  318. function showSearch() {
  319. if ($('#search-results').length !== 0) {
  320. $('#search').show();
  321. $('body').trigger("searchEvent");
  322. }
  323. }
  324. function loadNavbar() {
  325. var navbarPath = $("meta[property='docfx\\:navrel']").attr("content");
  326. if (!navbarPath) {
  327. return;
  328. }
  329. navbarPath = navbarPath.replace(/\\/g, '/');
  330. var tocPath = $("meta[property='docfx\\:tocrel']").attr("content") || '';
  331. if (tocPath) tocPath = tocPath.replace(/\\/g, '/');
  332. $.get(navbarPath, function (data) {
  333. $(data).find("#toc>ul").appendTo("#navbar");
  334. showSearch();
  335. var index = navbarPath.lastIndexOf('/');
  336. var navrel = '';
  337. if (index > -1) {
  338. navrel = navbarPath.substr(0, index + 1);
  339. }
  340. $('#navbar>ul').addClass('navbar-nav');
  341. var currentAbsPath = util.getAbsolutePath(window.location.pathname);
  342. // set active item
  343. $('#navbar').find('a[href]').each(function (i, e) {
  344. var href = $(e).attr("href");
  345. if (util.isRelativePath(href)) {
  346. href = navrel + href;
  347. $(e).attr("href", href);
  348. var isActive = false;
  349. var originalHref = e.name;
  350. if (originalHref) {
  351. originalHref = navrel + originalHref;
  352. if (util.getDirectory(util.getAbsolutePath(originalHref)) === util.getDirectory(util.getAbsolutePath(tocPath))) {
  353. isActive = true;
  354. }
  355. } else {
  356. if (util.getAbsolutePath(href) === currentAbsPath) {
  357. var dropdown = $(e).attr('data-toggle') == "dropdown"
  358. if (!dropdown) {
  359. isActive = true;
  360. }
  361. }
  362. }
  363. if (isActive) {
  364. $(e).addClass(active);
  365. }
  366. }
  367. });
  368. renderNavbar();
  369. });
  370. }
  371. }
  372. function renderSidebar() {
  373. var sidetoc = $('#sidetoggle .sidetoc')[0];
  374. if (typeof (sidetoc) === 'undefined') {
  375. loadToc();
  376. } else {
  377. registerTocEvents();
  378. if ($('footer').is(':visible')) {
  379. $('.sidetoc').addClass('shiftup');
  380. }
  381. // Scroll to active item
  382. var top = 0;
  383. $('#toc a.active').parents('li').each(function (i, e) {
  384. $(e).addClass(active).addClass(expanded);
  385. $(e).children('a').addClass(active);
  386. top += $(e).position().top;
  387. })
  388. $('.sidetoc').scrollTop(top - 50);
  389. if ($('footer').is(':visible')) {
  390. $('.sidetoc').addClass('shiftup');
  391. }
  392. renderBreadcrumb();
  393. }
  394. function registerTocEvents() {
  395. var tocFilterInput = $('#toc_filter_input');
  396. var tocFilterClearButton = $('#toc_filter_clear');
  397. $('.toc .nav > li > .expand-stub').click(function (e) {
  398. $(e.target).parent().toggleClass(expanded);
  399. });
  400. $('.toc .nav > li > .expand-stub + a:not([href])').click(function (e) {
  401. $(e.target).parent().toggleClass(expanded);
  402. });
  403. tocFilterInput.on('input', function (e) {
  404. var val = this.value;
  405. //Save filter string to local session storage
  406. if (typeof(Storage) !== "undefined") {
  407. try {
  408. sessionStorage.filterString = val;
  409. }
  410. catch(e)
  411. {}
  412. }
  413. if (val === '') {
  414. // Clear 'filtered' class
  415. $('#toc li').removeClass(filtered).removeClass(hide);
  416. tocFilterClearButton.fadeOut();
  417. return;
  418. }
  419. tocFilterClearButton.fadeIn();
  420. // set all parent nodes status
  421. $('#toc li>a').filter(function (i, e) {
  422. return $(e).siblings().length > 0
  423. }).each(function (i, anchor) {
  424. var parent = $(anchor).parent();
  425. parent.addClass(hide);
  426. parent.removeClass(show);
  427. parent.removeClass(filtered);
  428. })
  429. // Get leaf nodes
  430. $('#toc li>a').filter(function (i, e) {
  431. return $(e).siblings().length === 0
  432. }).each(function (i, anchor) {
  433. var text = $(anchor).attr('title');
  434. var parent = $(anchor).parent();
  435. var parentNodes = parent.parents('ul>li');
  436. for (var i = 0; i < parentNodes.length; i++) {
  437. var parentText = $(parentNodes[i]).children('a').attr('title');
  438. if (parentText) text = parentText + '.' + text;
  439. };
  440. if (filterNavItem(text, val)) {
  441. parent.addClass(show);
  442. parent.removeClass(hide);
  443. } else {
  444. parent.addClass(hide);
  445. parent.removeClass(show);
  446. }
  447. });
  448. $('#toc li>a').filter(function (i, e) {
  449. return $(e).siblings().length > 0
  450. }).each(function (i, anchor) {
  451. var parent = $(anchor).parent();
  452. if (parent.find('li.show').length > 0) {
  453. parent.addClass(show);
  454. parent.addClass(filtered);
  455. parent.removeClass(hide);
  456. } else {
  457. parent.addClass(hide);
  458. parent.removeClass(show);
  459. parent.removeClass(filtered);
  460. }
  461. })
  462. function filterNavItem(name, text) {
  463. if (!text) return true;
  464. if (name && name.toLowerCase().indexOf(text.toLowerCase()) > -1) return true;
  465. return false;
  466. }
  467. });
  468. // toc filter clear button
  469. tocFilterClearButton.hide();
  470. tocFilterClearButton.on("click", function(e){
  471. tocFilterInput.val("");
  472. tocFilterInput.trigger('input');
  473. if (typeof(Storage) !== "undefined") {
  474. try {
  475. sessionStorage.filterString = "";
  476. }
  477. catch(e)
  478. {}
  479. }
  480. });
  481. //Set toc filter from local session storage on page load
  482. if (typeof(Storage) !== "undefined") {
  483. try {
  484. tocFilterInput.val(sessionStorage.filterString);
  485. tocFilterInput.trigger('input');
  486. }
  487. catch(e)
  488. {}
  489. }
  490. }
  491. function loadToc() {
  492. var tocPath = $("meta[property='docfx\\:tocrel']").attr("content");
  493. if (!tocPath) {
  494. return;
  495. }
  496. tocPath = tocPath.replace(/\\/g, '/');
  497. $('#sidetoc').load(tocPath + " #sidetoggle > div", function () {
  498. var index = tocPath.lastIndexOf('/');
  499. var tocrel = '';
  500. if (index > -1) {
  501. tocrel = tocPath.substr(0, index + 1);
  502. }
  503. var currentHref = util.getAbsolutePath(window.location.pathname);
  504. $('#sidetoc').find('a[href]').each(function (i, e) {
  505. var href = $(e).attr("href");
  506. if (util.isRelativePath(href)) {
  507. href = tocrel + href;
  508. $(e).attr("href", href);
  509. }
  510. if (util.getAbsolutePath(e.href) === currentHref) {
  511. $(e).addClass(active);
  512. }
  513. $(e).breakWord();
  514. });
  515. renderSidebar();
  516. });
  517. }
  518. }
  519. function renderBreadcrumb() {
  520. var breadcrumb = [];
  521. $('#navbar a.active').each(function (i, e) {
  522. breadcrumb.push({
  523. href: e.href,
  524. name: e.innerHTML
  525. });
  526. })
  527. $('#toc a.active').each(function (i, e) {
  528. breadcrumb.push({
  529. href: e.href,
  530. name: e.innerHTML
  531. });
  532. })
  533. var html = util.formList(breadcrumb, 'breadcrumb');
  534. $('#breadcrumb').html(html);
  535. }
  536. //Setup Affix
  537. function renderAffix() {
  538. var hierarchy = getHierarchy();
  539. if (hierarchy && hierarchy.length > 0) {
  540. var html = '<h5 class="title">In This Article</h5>'
  541. html += util.formList(hierarchy, ['nav', 'bs-docs-sidenav']);
  542. $("#affix").empty().append(html);
  543. if ($('footer').is(':visible')) {
  544. $(".sideaffix").css("bottom", "70px");
  545. }
  546. $('#affix a').click(function(e) {
  547. var scrollspy = $('[data-spy="scroll"]').data()['bs.scrollspy'];
  548. var target = e.target.hash;
  549. if (scrollspy && target) {
  550. scrollspy.activate(target);
  551. }
  552. });
  553. }
  554. function getHierarchy() {
  555. // supported headers are h1, h2, h3, and h4
  556. var $headers = $($.map(['h1', 'h2', 'h3', 'h4'], function (h) { return ".article article " + h; }).join(", "));
  557. // a stack of hierarchy items that are currently being built
  558. var stack = [];
  559. $headers.each(function (i, e) {
  560. if (!e.id) {
  561. return;
  562. }
  563. var item = {
  564. name: htmlEncode($(e).text()),
  565. href: "#" + e.id,
  566. items: []
  567. };
  568. if (!stack.length) {
  569. stack.push({ type: e.tagName, siblings: [item] });
  570. return;
  571. }
  572. var frame = stack[stack.length - 1];
  573. if (e.tagName === frame.type) {
  574. frame.siblings.push(item);
  575. } else if (e.tagName[1] > frame.type[1]) {
  576. // we are looking at a child of the last element of frame.siblings.
  577. // push a frame onto the stack. After we've finished building this item's children,
  578. // we'll attach it as a child of the last element
  579. stack.push({ type: e.tagName, siblings: [item] });
  580. } else { // e.tagName[1] < frame.type[1]
  581. // we are looking at a sibling of an ancestor of the current item.
  582. // pop frames from the stack, building items as we go, until we reach the correct level at which to attach this item.
  583. while (e.tagName[1] < stack[stack.length - 1].type[1]) {
  584. buildParent();
  585. }
  586. if (e.tagName === stack[stack.length - 1].type) {
  587. stack[stack.length - 1].siblings.push(item);
  588. } else {
  589. stack.push({ type: e.tagName, siblings: [item] });
  590. }
  591. }
  592. });
  593. while (stack.length > 1) {
  594. buildParent();
  595. }
  596. function buildParent() {
  597. var childrenToAttach = stack.pop();
  598. var parentFrame = stack[stack.length - 1];
  599. var parent = parentFrame.siblings[parentFrame.siblings.length - 1];
  600. $.each(childrenToAttach.siblings, function (i, child) {
  601. parent.items.push(child);
  602. });
  603. }
  604. if (stack.length > 0) {
  605. var topLevel = stack.pop().siblings;
  606. if (topLevel.length === 1) { // if there's only one topmost header, dump it
  607. return topLevel[0].items;
  608. }
  609. return topLevel;
  610. }
  611. return undefined;
  612. }
  613. function htmlEncode(str) {
  614. if (!str) return str;
  615. return str
  616. .replace(/&/g, '&amp;')
  617. .replace(/"/g, '&quot;')
  618. .replace(/'/g, '&#39;')
  619. .replace(/</g, '&lt;')
  620. .replace(/>/g, '&gt;');
  621. }
  622. function htmlDecode(value) {
  623. if (!str) return str;
  624. return value
  625. .replace(/&quot;/g, '"')
  626. .replace(/&#39;/g, "'")
  627. .replace(/&lt;/g, '<')
  628. .replace(/&gt;/g, '>')
  629. .replace(/&amp;/g, '&');
  630. }
  631. function cssEscape(str) {
  632. // see: http://stackoverflow.com/questions/2786538/need-to-escape-a-special-character-in-a-jquery-selector-string#answer-2837646
  633. if (!str) return str;
  634. return str
  635. .replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g, "\\$&");
  636. }
  637. }
  638. // Show footer
  639. function renderFooter() {
  640. initFooter();
  641. $(window).on("scroll", showFooterCore);
  642. function initFooter() {
  643. if (needFooter()) {
  644. shiftUpBottomCss();
  645. $("footer").show();
  646. } else {
  647. resetBottomCss();
  648. $("footer").hide();
  649. }
  650. }
  651. function showFooterCore() {
  652. if (needFooter()) {
  653. shiftUpBottomCss();
  654. $("footer").fadeIn();
  655. } else {
  656. resetBottomCss();
  657. $("footer").fadeOut();
  658. }
  659. }
  660. function needFooter() {
  661. var scrollHeight = $(document).height();
  662. var scrollPosition = $(window).height() + $(window).scrollTop();
  663. return (scrollHeight - scrollPosition) < 1;
  664. }
  665. function resetBottomCss() {
  666. $(".sidetoc").removeClass("shiftup");
  667. $(".sideaffix").removeClass("shiftup");
  668. }
  669. function shiftUpBottomCss() {
  670. $(".sidetoc").addClass("shiftup");
  671. $(".sideaffix").addClass("shiftup");
  672. }
  673. }
  674. function renderLogo() {
  675. // For LOGO SVG
  676. // Replace SVG with inline SVG
  677. // http://stackoverflow.com/questions/11978995/how-to-change-color-of-svg-image-using-css-jquery-svg-image-replacement
  678. jQuery('img.svg').each(function () {
  679. var $img = jQuery(this);
  680. var imgID = $img.attr('id');
  681. var imgClass = $img.attr('class');
  682. var imgURL = $img.attr('src');
  683. jQuery.get(imgURL, function (data) {
  684. // Get the SVG tag, ignore the rest
  685. var $svg = jQuery(data).find('svg');
  686. // Add replaced image's ID to the new SVG
  687. if (typeof imgID !== 'undefined') {
  688. $svg = $svg.attr('id', imgID);
  689. }
  690. // Add replaced image's classes to the new SVG
  691. if (typeof imgClass !== 'undefined') {
  692. $svg = $svg.attr('class', imgClass + ' replaced-svg');
  693. }
  694. // Remove any invalid XML tags as per http://validator.w3.org
  695. $svg = $svg.removeAttr('xmlns:a');
  696. // Replace image with new SVG
  697. $img.replaceWith($svg);
  698. }, 'xml');
  699. });
  700. }
  701. function renderTabs() {
  702. var contentAttrs = {
  703. id: 'data-bi-id',
  704. name: 'data-bi-name',
  705. type: 'data-bi-type'
  706. };
  707. var Tab = (function () {
  708. function Tab(li, a, section) {
  709. this.li = li;
  710. this.a = a;
  711. this.section = section;
  712. }
  713. Object.defineProperty(Tab.prototype, "tabIds", {
  714. get: function () { return this.a.getAttribute('data-tab').split(' '); },
  715. enumerable: true,
  716. configurable: true
  717. });
  718. Object.defineProperty(Tab.prototype, "condition", {
  719. get: function () { return this.a.getAttribute('data-condition'); },
  720. enumerable: true,
  721. configurable: true
  722. });
  723. Object.defineProperty(Tab.prototype, "visible", {
  724. get: function () { return !this.li.hasAttribute('hidden'); },
  725. set: function (value) {
  726. if (value) {
  727. this.li.removeAttribute('hidden');
  728. this.li.removeAttribute('aria-hidden');
  729. }
  730. else {
  731. this.li.setAttribute('hidden', 'hidden');
  732. this.li.setAttribute('aria-hidden', 'true');
  733. }
  734. },
  735. enumerable: true,
  736. configurable: true
  737. });
  738. Object.defineProperty(Tab.prototype, "selected", {
  739. get: function () { return !this.section.hasAttribute('hidden'); },
  740. set: function (value) {
  741. if (value) {
  742. this.a.setAttribute('aria-selected', 'true');
  743. this.a.tabIndex = 0;
  744. this.section.removeAttribute('hidden');
  745. this.section.removeAttribute('aria-hidden');
  746. }
  747. else {
  748. this.a.setAttribute('aria-selected', 'false');
  749. this.a.tabIndex = -1;
  750. this.section.setAttribute('hidden', 'hidden');
  751. this.section.setAttribute('aria-hidden', 'true');
  752. }
  753. },
  754. enumerable: true,
  755. configurable: true
  756. });
  757. Tab.prototype.focus = function () {
  758. this.a.focus();
  759. };
  760. return Tab;
  761. }());
  762. initTabs(document.body);
  763. function initTabs(container) {
  764. var queryStringTabs = readTabsQueryStringParam();
  765. var elements = container.querySelectorAll('.tabGroup');
  766. var state = { groups: [], selectedTabs: [] };
  767. for (var i = 0; i < elements.length; i++) {
  768. var group = initTabGroup(elements.item(i));
  769. if (!group.independent) {
  770. updateVisibilityAndSelection(group, state);
  771. state.groups.push(group);
  772. }
  773. }
  774. container.addEventListener('click', function (event) { return handleClick(event, state); });
  775. if (state.groups.length === 0) {
  776. return state;
  777. }
  778. selectTabs(queryStringTabs, container);
  779. updateTabsQueryStringParam(state);
  780. notifyContentUpdated();
  781. return state;
  782. }
  783. function initTabGroup(element) {
  784. var group = {
  785. independent: element.hasAttribute('data-tab-group-independent'),
  786. tabs: []
  787. };
  788. var li = element.firstElementChild.firstElementChild;
  789. while (li) {
  790. var a = li.firstElementChild;
  791. a.setAttribute(contentAttrs.name, 'tab');
  792. var dataTab = a.getAttribute('data-tab').replace(/\+/g, ' ');
  793. a.setAttribute('data-tab', dataTab);
  794. var section = element.querySelector("[id=\"" + a.getAttribute('aria-controls') + "\"]");
  795. var tab = new Tab(li, a, section);
  796. group.tabs.push(tab);
  797. li = li.nextElementSibling;
  798. }
  799. element.setAttribute(contentAttrs.name, 'tab-group');
  800. element.tabGroup = group;
  801. return group;
  802. }
  803. function updateVisibilityAndSelection(group, state) {
  804. var anySelected = false;
  805. var firstVisibleTab;
  806. for (var _i = 0, _a = group.tabs; _i < _a.length; _i++) {
  807. var tab = _a[_i];
  808. tab.visible = tab.condition === null || state.selectedTabs.indexOf(tab.condition) !== -1;
  809. if (tab.visible) {
  810. if (!firstVisibleTab) {
  811. firstVisibleTab = tab;
  812. }
  813. }
  814. tab.selected = tab.visible && arraysIntersect(state.selectedTabs, tab.tabIds);
  815. anySelected = anySelected || tab.selected;
  816. }
  817. if (!anySelected) {
  818. for (var _b = 0, _c = group.tabs; _b < _c.length; _b++) {
  819. var tabIds = _c[_b].tabIds;
  820. for (var _d = 0, tabIds_1 = tabIds; _d < tabIds_1.length; _d++) {
  821. var tabId = tabIds_1[_d];
  822. var index = state.selectedTabs.indexOf(tabId);
  823. if (index === -1) {
  824. continue;
  825. }
  826. state.selectedTabs.splice(index, 1);
  827. }
  828. }
  829. var tab = firstVisibleTab;
  830. tab.selected = true;
  831. state.selectedTabs.push(tab.tabIds[0]);
  832. }
  833. }
  834. function getTabInfoFromEvent(event) {
  835. if (!(event.target instanceof HTMLElement)) {
  836. return null;
  837. }
  838. var anchor = event.target.closest('a[data-tab]');
  839. if (anchor === null) {
  840. return null;
  841. }
  842. var tabIds = anchor.getAttribute('data-tab').split(' ');
  843. var group = anchor.parentElement.parentElement.parentElement.tabGroup;
  844. if (group === undefined) {
  845. return null;
  846. }
  847. return { tabIds: tabIds, group: group, anchor: anchor };
  848. }
  849. function handleClick(event, state) {
  850. var info = getTabInfoFromEvent(event);
  851. if (info === null) {
  852. return;
  853. }
  854. event.preventDefault();
  855. info.anchor.href = 'javascript:';
  856. setTimeout(function () { return info.anchor.href = '#' + info.anchor.getAttribute('aria-controls'); });
  857. var tabIds = info.tabIds, group = info.group;
  858. var originalTop = info.anchor.getBoundingClientRect().top;
  859. if (group.independent) {
  860. for (var _i = 0, _a = group.tabs; _i < _a.length; _i++) {
  861. var tab = _a[_i];
  862. tab.selected = arraysIntersect(tab.tabIds, tabIds);
  863. }
  864. }
  865. else {
  866. if (arraysIntersect(state.selectedTabs, tabIds)) {
  867. return;
  868. }
  869. var previousTabId = group.tabs.filter(function (t) { return t.selected; })[0].tabIds[0];
  870. state.selectedTabs.splice(state.selectedTabs.indexOf(previousTabId), 1, tabIds[0]);
  871. for (var _b = 0, _c = state.groups; _b < _c.length; _b++) {
  872. var group_1 = _c[_b];
  873. updateVisibilityAndSelection(group_1, state);
  874. }
  875. updateTabsQueryStringParam(state);
  876. }
  877. notifyContentUpdated();
  878. var top = info.anchor.getBoundingClientRect().top;
  879. if (top !== originalTop && event instanceof MouseEvent) {
  880. window.scrollTo(0, window.pageYOffset + top - originalTop);
  881. }
  882. }
  883. function selectTabs(tabIds) {
  884. for (var _i = 0, tabIds_1 = tabIds; _i < tabIds_1.length; _i++) {
  885. var tabId = tabIds_1[_i];
  886. var a = document.querySelector(".tabGroup > ul > li > a[data-tab=\"" + tabId + "\"]:not([hidden])");
  887. if (a === null) {
  888. return;
  889. }
  890. a.dispatchEvent(new CustomEvent('click', { bubbles: true }));
  891. }
  892. }
  893. function readTabsQueryStringParam() {
  894. var qs = parseQueryString();
  895. var t = qs.tabs;
  896. if (t === undefined || t === '') {
  897. return [];
  898. }
  899. return t.split(',');
  900. }
  901. function updateTabsQueryStringParam(state) {
  902. var qs = parseQueryString();
  903. qs.tabs = state.selectedTabs.join();
  904. var url = location.protocol + "//" + location.host + location.pathname + "?" + toQueryString(qs) + location.hash;
  905. if (location.href === url) {
  906. return;
  907. }
  908. history.replaceState({}, document.title, url);
  909. }
  910. function toQueryString(args) {
  911. var parts = [];
  912. for (var name_1 in args) {
  913. if (args.hasOwnProperty(name_1) && args[name_1] !== '' && args[name_1] !== null && args[name_1] !== undefined) {
  914. parts.push(encodeURIComponent(name_1) + '=' + encodeURIComponent(args[name_1]));
  915. }
  916. }
  917. return parts.join('&');
  918. }
  919. function parseQueryString(queryString) {
  920. var match;
  921. var pl = /\+/g;
  922. var search = /([^&=]+)=?([^&]*)/g;
  923. var decode = function (s) { return decodeURIComponent(s.replace(pl, ' ')); };
  924. if (queryString === undefined) {
  925. queryString = '';
  926. }
  927. queryString = queryString.substring(1);
  928. var urlParams = {};
  929. while (match = search.exec(queryString)) {
  930. urlParams[decode(match[1])] = decode(match[2]);
  931. }
  932. return urlParams;
  933. }
  934. function arraysIntersect(a, b) {
  935. for (var _i = 0, a_1 = a; _i < a_1.length; _i++) {
  936. var itemA = a_1[_i];
  937. for (var _a = 0, b_1 = b; _a < b_1.length; _a++) {
  938. var itemB = b_1[_a];
  939. if (itemA === itemB) {
  940. return true;
  941. }
  942. }
  943. }
  944. return false;
  945. }
  946. function notifyContentUpdated() {
  947. // Dispatch this event when needed
  948. // window.dispatchEvent(new CustomEvent('content-update'));
  949. }
  950. }
  951. function utility() {
  952. this.getAbsolutePath = getAbsolutePath;
  953. this.isRelativePath = isRelativePath;
  954. this.isAbsolutePath = isAbsolutePath;
  955. this.getDirectory = getDirectory;
  956. this.formList = formList;
  957. function getAbsolutePath(href) {
  958. // Use anchor to normalize href
  959. var anchor = $('<a href="' + href + '"></a>')[0];
  960. // Ignore protocal, remove search and query
  961. return anchor.host + anchor.pathname;
  962. }
  963. function isRelativePath(href) {
  964. if (href === undefined || href === '' || href[0] === '/') {
  965. return false;
  966. }
  967. return !isAbsolutePath(href);
  968. }
  969. function isAbsolutePath(href) {
  970. return (/^(?:[a-z]+:)?\/\//i).test(href);
  971. }
  972. function getDirectory(href) {
  973. if (!href) return '';
  974. var index = href.lastIndexOf('/');
  975. if (index == -1) return '';
  976. if (index > -1) {
  977. return href.substr(0, index);
  978. }
  979. }
  980. function formList(item, classes) {
  981. var level = 1;
  982. var model = {
  983. items: item
  984. };
  985. var cls = [].concat(classes).join(" ");
  986. return getList(model, cls);
  987. function getList(model, cls) {
  988. if (!model || !model.items) return null;
  989. var l = model.items.length;
  990. if (l === 0) return null;
  991. var html = '<ul class="level' + level + ' ' + (cls || '') + '">';
  992. level++;
  993. for (var i = 0; i < l; i++) {
  994. var item = model.items[i];
  995. var href = item.href;
  996. var name = item.name;
  997. if (!name) continue;
  998. html += href ? '<li><a href="' + href + '">' + name + '</a>' : '<li>' + name;
  999. html += getList(item, cls) || '';
  1000. html += '</li>';
  1001. }
  1002. html += '</ul>';
  1003. return html;
  1004. }
  1005. }
  1006. /**
  1007. * Add <wbr> into long word.
  1008. * @param {String} text - The word to break. It should be in plain text without HTML tags.
  1009. */
  1010. function breakPlainText(text) {
  1011. if (!text) return text;
  1012. return text.replace(/([a-z])([A-Z])|(\.)(\w)/g, '$1$3<wbr>$2$4')
  1013. }
  1014. /**
  1015. * Add <wbr> into long word. The jQuery element should contain no html tags.
  1016. * If the jQuery element contains tags, this function will not change the element.
  1017. */
  1018. $.fn.breakWord = function () {
  1019. if (this.html() == this.text()) {
  1020. this.html(function (index, text) {
  1021. return breakPlainText(text);
  1022. })
  1023. }
  1024. return this;
  1025. }
  1026. }
  1027. // adjusted from https://stackoverflow.com/a/13067009/1523776
  1028. function workAroundFixedHeaderForAnchors() {
  1029. var HISTORY_SUPPORT = !!(history && history.pushState);
  1030. var ANCHOR_REGEX = /^#[^ ]+$/;
  1031. function getFixedOffset() {
  1032. return $('header').first().height();
  1033. }
  1034. /**
  1035. * If the provided href is an anchor which resolves to an element on the
  1036. * page, scroll to it.
  1037. * @param {String} href
  1038. * @return {Boolean} - Was the href an anchor.
  1039. */
  1040. function scrollIfAnchor(href, pushToHistory) {
  1041. var match, rect, anchorOffset;
  1042. if (!ANCHOR_REGEX.test(href)) {
  1043. return false;
  1044. }
  1045. match = document.getElementById(href.slice(1));
  1046. if (match) {
  1047. rect = match.getBoundingClientRect();
  1048. anchorOffset = window.pageYOffset + rect.top - getFixedOffset();
  1049. window.scrollTo(window.pageXOffset, anchorOffset);
  1050. // Add the state to history as-per normal anchor links
  1051. if (HISTORY_SUPPORT && pushToHistory) {
  1052. history.pushState({}, document.title, location.pathname + href);
  1053. }
  1054. }
  1055. return !!match;
  1056. }
  1057. /**
  1058. * Attempt to scroll to the current location's hash.
  1059. */
  1060. function scrollToCurrent() {
  1061. scrollIfAnchor(window.location.hash);
  1062. }
  1063. /**
  1064. * If the click event's target was an anchor, fix the scroll position.
  1065. */
  1066. function delegateAnchors(e) {
  1067. var elem = e.target;
  1068. if (scrollIfAnchor(elem.getAttribute('href'), true)) {
  1069. e.preventDefault();
  1070. }
  1071. }
  1072. $(window).on('hashchange', scrollToCurrent);
  1073. $(window).on('load', function () {
  1074. // scroll to the anchor if present, offset by the header
  1075. scrollToCurrent();
  1076. });
  1077. $(document).ready(function () {
  1078. // Exclude tabbed content case
  1079. $('a:not([data-tab])').click(function (e) { delegateAnchors(e); });
  1080. });
  1081. }
  1082. });