You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1175 lines
36 KiB

  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. sessionStorage.filterString = val;
  408. }
  409. if (val === '') {
  410. // Clear 'filtered' class
  411. $('#toc li').removeClass(filtered).removeClass(hide);
  412. tocFilterClearButton.fadeOut();
  413. return;
  414. }
  415. tocFilterClearButton.fadeIn();
  416. // Get leaf nodes
  417. $('#toc li>a').filter(function (i, e) {
  418. return $(e).siblings().length === 0
  419. }).each(function (i, anchor) {
  420. var text = $(anchor).attr('title');
  421. var parent = $(anchor).parent();
  422. var parentNodes = parent.parents('ul>li');
  423. for (var i = 0; i < parentNodes.length; i++) {
  424. var parentText = $(parentNodes[i]).children('a').attr('title');
  425. if (parentText) text = parentText + '.' + text;
  426. };
  427. if (filterNavItem(text, val)) {
  428. parent.addClass(show);
  429. parent.removeClass(hide);
  430. } else {
  431. parent.addClass(hide);
  432. parent.removeClass(show);
  433. }
  434. });
  435. $('#toc li>a').filter(function (i, e) {
  436. return $(e).siblings().length > 0
  437. }).each(function (i, anchor) {
  438. var parent = $(anchor).parent();
  439. if (parent.find('li.show').length > 0) {
  440. parent.addClass(show);
  441. parent.addClass(filtered);
  442. parent.removeClass(hide);
  443. } else {
  444. parent.addClass(hide);
  445. parent.removeClass(show);
  446. parent.removeClass(filtered);
  447. }
  448. })
  449. function filterNavItem(name, text) {
  450. if (!text) return true;
  451. if (name && name.toLowerCase().indexOf(text.toLowerCase()) > -1) return true;
  452. return false;
  453. }
  454. });
  455. // toc filter clear button
  456. tocFilterClearButton.hide();
  457. tocFilterClearButton.on("click", function(e){
  458. tocFilterInput.val("");
  459. tocFilterInput.trigger('input');
  460. if (typeof(Storage) !== "undefined") {
  461. sessionStorage.filterString = "";
  462. }
  463. });
  464. //Set toc filter from local session storage on page load
  465. if (typeof(Storage) !== "undefined") {
  466. tocFilterInput.val(sessionStorage.filterString);
  467. tocFilterInput.trigger('input');
  468. }
  469. }
  470. function loadToc() {
  471. var tocPath = $("meta[property='docfx\\:tocrel']").attr("content");
  472. if (!tocPath) {
  473. return;
  474. }
  475. tocPath = tocPath.replace(/\\/g, '/');
  476. $('#sidetoc').load(tocPath + " #sidetoggle > div", function () {
  477. var index = tocPath.lastIndexOf('/');
  478. var tocrel = '';
  479. if (index > -1) {
  480. tocrel = tocPath.substr(0, index + 1);
  481. }
  482. var currentHref = util.getAbsolutePath(window.location.pathname);
  483. $('#sidetoc').find('a[href]').each(function (i, e) {
  484. var href = $(e).attr("href");
  485. if (util.isRelativePath(href)) {
  486. href = tocrel + href;
  487. $(e).attr("href", href);
  488. }
  489. if (util.getAbsolutePath(e.href) === currentHref) {
  490. $(e).addClass(active);
  491. }
  492. $(e).breakWord();
  493. });
  494. renderSidebar();
  495. });
  496. }
  497. }
  498. function renderBreadcrumb() {
  499. var breadcrumb = [];
  500. $('#navbar a.active').each(function (i, e) {
  501. breadcrumb.push({
  502. href: e.href,
  503. name: e.innerHTML
  504. });
  505. })
  506. $('#toc a.active').each(function (i, e) {
  507. breadcrumb.push({
  508. href: e.href,
  509. name: e.innerHTML
  510. });
  511. })
  512. var html = util.formList(breadcrumb, 'breadcrumb');
  513. $('#breadcrumb').html(html);
  514. }
  515. //Setup Affix
  516. function renderAffix() {
  517. var hierarchy = getHierarchy();
  518. if (hierarchy && hierarchy.length > 0) {
  519. var html = '<h5 class="title">In This Article</h5>'
  520. html += util.formList(hierarchy, ['nav', 'bs-docs-sidenav']);
  521. $("#affix").empty().append(html);
  522. if ($('footer').is(':visible')) {
  523. $(".sideaffix").css("bottom", "70px");
  524. }
  525. $('#affix a').click(function(e) {
  526. var scrollspy = $('[data-spy="scroll"]').data()['bs.scrollspy'];
  527. var target = e.target.hash;
  528. if (scrollspy && target) {
  529. scrollspy.activate(target);
  530. }
  531. });
  532. }
  533. function getHierarchy() {
  534. // supported headers are h1, h2, h3, and h4
  535. var $headers = $($.map(['h1', 'h2', 'h3', 'h4'], function (h) { return ".article article " + h; }).join(", "));
  536. // a stack of hierarchy items that are currently being built
  537. var stack = [];
  538. $headers.each(function (i, e) {
  539. if (!e.id) {
  540. return;
  541. }
  542. var item = {
  543. name: htmlEncode($(e).text()),
  544. href: "#" + e.id,
  545. items: []
  546. };
  547. if (!stack.length) {
  548. stack.push({ type: e.tagName, siblings: [item] });
  549. return;
  550. }
  551. var frame = stack[stack.length - 1];
  552. if (e.tagName === frame.type) {
  553. frame.siblings.push(item);
  554. } else if (e.tagName[1] > frame.type[1]) {
  555. // we are looking at a child of the last element of frame.siblings.
  556. // push a frame onto the stack. After we've finished building this item's children,
  557. // we'll attach it as a child of the last element
  558. stack.push({ type: e.tagName, siblings: [item] });
  559. } else { // e.tagName[1] < frame.type[1]
  560. // we are looking at a sibling of an ancestor of the current item.
  561. // pop frames from the stack, building items as we go, until we reach the correct level at which to attach this item.
  562. while (e.tagName[1] < stack[stack.length - 1].type[1]) {
  563. buildParent();
  564. }
  565. if (e.tagName === stack[stack.length - 1].type) {
  566. stack[stack.length - 1].siblings.push(item);
  567. } else {
  568. stack.push({ type: e.tagName, siblings: [item] });
  569. }
  570. }
  571. });
  572. while (stack.length > 1) {
  573. buildParent();
  574. }
  575. function buildParent() {
  576. var childrenToAttach = stack.pop();
  577. var parentFrame = stack[stack.length - 1];
  578. var parent = parentFrame.siblings[parentFrame.siblings.length - 1];
  579. $.each(childrenToAttach.siblings, function (i, child) {
  580. parent.items.push(child);
  581. });
  582. }
  583. if (stack.length > 0) {
  584. var topLevel = stack.pop().siblings;
  585. if (topLevel.length === 1) { // if there's only one topmost header, dump it
  586. return topLevel[0].items;
  587. }
  588. return topLevel;
  589. }
  590. return undefined;
  591. }
  592. function htmlEncode(str) {
  593. if (!str) return str;
  594. return str
  595. .replace(/&/g, '&amp;')
  596. .replace(/"/g, '&quot;')
  597. .replace(/'/g, '&#39;')
  598. .replace(/</g, '&lt;')
  599. .replace(/>/g, '&gt;');
  600. }
  601. function htmlDecode(value) {
  602. if (!str) return str;
  603. return value
  604. .replace(/&quot;/g, '"')
  605. .replace(/&#39;/g, "'")
  606. .replace(/&lt;/g, '<')
  607. .replace(/&gt;/g, '>')
  608. .replace(/&amp;/g, '&');
  609. }
  610. function cssEscape(str) {
  611. // see: http://stackoverflow.com/questions/2786538/need-to-escape-a-special-character-in-a-jquery-selector-string#answer-2837646
  612. if (!str) return str;
  613. return str
  614. .replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g, "\\$&");
  615. }
  616. }
  617. // Show footer
  618. function renderFooter() {
  619. initFooter();
  620. $(window).on("scroll", showFooterCore);
  621. function initFooter() {
  622. if (needFooter()) {
  623. shiftUpBottomCss();
  624. $("footer").show();
  625. } else {
  626. resetBottomCss();
  627. $("footer").hide();
  628. }
  629. }
  630. function showFooterCore() {
  631. if (needFooter()) {
  632. shiftUpBottomCss();
  633. $("footer").fadeIn();
  634. } else {
  635. resetBottomCss();
  636. $("footer").fadeOut();
  637. }
  638. }
  639. function needFooter() {
  640. var scrollHeight = $(document).height();
  641. var scrollPosition = $(window).height() + $(window).scrollTop();
  642. return (scrollHeight - scrollPosition) < 1;
  643. }
  644. function resetBottomCss() {
  645. $(".sidetoc").removeClass("shiftup");
  646. $(".sideaffix").removeClass("shiftup");
  647. }
  648. function shiftUpBottomCss() {
  649. $(".sidetoc").addClass("shiftup");
  650. $(".sideaffix").addClass("shiftup");
  651. }
  652. }
  653. function renderLogo() {
  654. // For LOGO SVG
  655. // Replace SVG with inline SVG
  656. // http://stackoverflow.com/questions/11978995/how-to-change-color-of-svg-image-using-css-jquery-svg-image-replacement
  657. jQuery('img.svg').each(function () {
  658. var $img = jQuery(this);
  659. var imgID = $img.attr('id');
  660. var imgClass = $img.attr('class');
  661. var imgURL = $img.attr('src');
  662. jQuery.get(imgURL, function (data) {
  663. // Get the SVG tag, ignore the rest
  664. var $svg = jQuery(data).find('svg');
  665. // Add replaced image's ID to the new SVG
  666. if (typeof imgID !== 'undefined') {
  667. $svg = $svg.attr('id', imgID);
  668. }
  669. // Add replaced image's classes to the new SVG
  670. if (typeof imgClass !== 'undefined') {
  671. $svg = $svg.attr('class', imgClass + ' replaced-svg');
  672. }
  673. // Remove any invalid XML tags as per http://validator.w3.org
  674. $svg = $svg.removeAttr('xmlns:a');
  675. // Replace image with new SVG
  676. $img.replaceWith($svg);
  677. }, 'xml');
  678. });
  679. }
  680. function renderTabs() {
  681. var contentAttrs = {
  682. id: 'data-bi-id',
  683. name: 'data-bi-name',
  684. type: 'data-bi-type'
  685. };
  686. var Tab = (function () {
  687. function Tab(li, a, section) {
  688. this.li = li;
  689. this.a = a;
  690. this.section = section;
  691. }
  692. Object.defineProperty(Tab.prototype, "tabIds", {
  693. get: function () { return this.a.getAttribute('data-tab').split(' '); },
  694. enumerable: true,
  695. configurable: true
  696. });
  697. Object.defineProperty(Tab.prototype, "condition", {
  698. get: function () { return this.a.getAttribute('data-condition'); },
  699. enumerable: true,
  700. configurable: true
  701. });
  702. Object.defineProperty(Tab.prototype, "visible", {
  703. get: function () { return !this.li.hasAttribute('hidden'); },
  704. set: function (value) {
  705. if (value) {
  706. this.li.removeAttribute('hidden');
  707. this.li.removeAttribute('aria-hidden');
  708. }
  709. else {
  710. this.li.setAttribute('hidden', 'hidden');
  711. this.li.setAttribute('aria-hidden', 'true');
  712. }
  713. },
  714. enumerable: true,
  715. configurable: true
  716. });
  717. Object.defineProperty(Tab.prototype, "selected", {
  718. get: function () { return !this.section.hasAttribute('hidden'); },
  719. set: function (value) {
  720. if (value) {
  721. this.a.setAttribute('aria-selected', 'true');
  722. this.a.tabIndex = 0;
  723. this.section.removeAttribute('hidden');
  724. this.section.removeAttribute('aria-hidden');
  725. }
  726. else {
  727. this.a.setAttribute('aria-selected', 'false');
  728. this.a.tabIndex = -1;
  729. this.section.setAttribute('hidden', 'hidden');
  730. this.section.setAttribute('aria-hidden', 'true');
  731. }
  732. },
  733. enumerable: true,
  734. configurable: true
  735. });
  736. Tab.prototype.focus = function () {
  737. this.a.focus();
  738. };
  739. return Tab;
  740. }());
  741. initTabs(document.body);
  742. function initTabs(container) {
  743. var queryStringTabs = readTabsQueryStringParam();
  744. var elements = container.querySelectorAll('.tabGroup');
  745. var state = { groups: [], selectedTabs: [] };
  746. for (var i = 0; i < elements.length; i++) {
  747. var group = initTabGroup(elements.item(i));
  748. if (!group.independent) {
  749. updateVisibilityAndSelection(group, state);
  750. state.groups.push(group);
  751. }
  752. }
  753. container.addEventListener('click', function (event) { return handleClick(event, state); });
  754. if (state.groups.length === 0) {
  755. return state;
  756. }
  757. selectTabs(queryStringTabs, container);
  758. updateTabsQueryStringParam(state);
  759. notifyContentUpdated();
  760. return state;
  761. }
  762. function initTabGroup(element) {
  763. var group = {
  764. independent: element.hasAttribute('data-tab-group-independent'),
  765. tabs: []
  766. };
  767. var li = element.firstElementChild.firstElementChild;
  768. while (li) {
  769. var a = li.firstElementChild;
  770. a.setAttribute(contentAttrs.name, 'tab');
  771. var dataTab = a.getAttribute('data-tab').replace(/\+/g, ' ');
  772. a.setAttribute('data-tab', dataTab);
  773. var section = element.querySelector("[id=\"" + a.getAttribute('aria-controls') + "\"]");
  774. var tab = new Tab(li, a, section);
  775. group.tabs.push(tab);
  776. li = li.nextElementSibling;
  777. }
  778. element.setAttribute(contentAttrs.name, 'tab-group');
  779. element.tabGroup = group;
  780. return group;
  781. }
  782. function updateVisibilityAndSelection(group, state) {
  783. var anySelected = false;
  784. var firstVisibleTab;
  785. for (var _i = 0, _a = group.tabs; _i < _a.length; _i++) {
  786. var tab = _a[_i];
  787. tab.visible = tab.condition === null || state.selectedTabs.indexOf(tab.condition) !== -1;
  788. if (tab.visible) {
  789. if (!firstVisibleTab) {
  790. firstVisibleTab = tab;
  791. }
  792. }
  793. tab.selected = tab.visible && arraysIntersect(state.selectedTabs, tab.tabIds);
  794. anySelected = anySelected || tab.selected;
  795. }
  796. if (!anySelected) {
  797. for (var _b = 0, _c = group.tabs; _b < _c.length; _b++) {
  798. var tabIds = _c[_b].tabIds;
  799. for (var _d = 0, tabIds_1 = tabIds; _d < tabIds_1.length; _d++) {
  800. var tabId = tabIds_1[_d];
  801. var index = state.selectedTabs.indexOf(tabId);
  802. if (index === -1) {
  803. continue;
  804. }
  805. state.selectedTabs.splice(index, 1);
  806. }
  807. }
  808. var tab = firstVisibleTab;
  809. tab.selected = true;
  810. state.selectedTabs.push(tab.tabIds[0]);
  811. }
  812. }
  813. function getTabInfoFromEvent(event) {
  814. if (!(event.target instanceof HTMLElement)) {
  815. return null;
  816. }
  817. var anchor = event.target.closest('a[data-tab]');
  818. if (anchor === null) {
  819. return null;
  820. }
  821. var tabIds = anchor.getAttribute('data-tab').split(' ');
  822. var group = anchor.parentElement.parentElement.parentElement.tabGroup;
  823. if (group === undefined) {
  824. return null;
  825. }
  826. return { tabIds: tabIds, group: group, anchor: anchor };
  827. }
  828. function handleClick(event, state) {
  829. var info = getTabInfoFromEvent(event);
  830. if (info === null) {
  831. return;
  832. }
  833. event.preventDefault();
  834. info.anchor.href = 'javascript:';
  835. setTimeout(function () { return info.anchor.href = '#' + info.anchor.getAttribute('aria-controls'); });
  836. var tabIds = info.tabIds, group = info.group;
  837. var originalTop = info.anchor.getBoundingClientRect().top;
  838. if (group.independent) {
  839. for (var _i = 0, _a = group.tabs; _i < _a.length; _i++) {
  840. var tab = _a[_i];
  841. tab.selected = arraysIntersect(tab.tabIds, tabIds);
  842. }
  843. }
  844. else {
  845. if (arraysIntersect(state.selectedTabs, tabIds)) {
  846. return;
  847. }
  848. var previousTabId = group.tabs.filter(function (t) { return t.selected; })[0].tabIds[0];
  849. state.selectedTabs.splice(state.selectedTabs.indexOf(previousTabId), 1, tabIds[0]);
  850. for (var _b = 0, _c = state.groups; _b < _c.length; _b++) {
  851. var group_1 = _c[_b];
  852. updateVisibilityAndSelection(group_1, state);
  853. }
  854. updateTabsQueryStringParam(state);
  855. }
  856. notifyContentUpdated();
  857. var top = info.anchor.getBoundingClientRect().top;
  858. if (top !== originalTop && event instanceof MouseEvent) {
  859. window.scrollTo(0, window.pageYOffset + top - originalTop);
  860. }
  861. }
  862. function selectTabs(tabIds) {
  863. for (var _i = 0, tabIds_1 = tabIds; _i < tabIds_1.length; _i++) {
  864. var tabId = tabIds_1[_i];
  865. var a = document.querySelector(".tabGroup > ul > li > a[data-tab=\"" + tabId + "\"]:not([hidden])");
  866. if (a === null) {
  867. return;
  868. }
  869. a.dispatchEvent(new CustomEvent('click', { bubbles: true }));
  870. }
  871. }
  872. function readTabsQueryStringParam() {
  873. var qs = parseQueryString();
  874. var t = qs.tabs;
  875. if (t === undefined || t === '') {
  876. return [];
  877. }
  878. return t.split(',');
  879. }
  880. function updateTabsQueryStringParam(state) {
  881. var qs = parseQueryString();
  882. qs.tabs = state.selectedTabs.join();
  883. var url = location.protocol + "//" + location.host + location.pathname + "?" + toQueryString(qs) + location.hash;
  884. if (location.href === url) {
  885. return;
  886. }
  887. history.replaceState({}, document.title, url);
  888. }
  889. function toQueryString(args) {
  890. var parts = [];
  891. for (var name_1 in args) {
  892. if (args.hasOwnProperty(name_1) && args[name_1] !== '' && args[name_1] !== null && args[name_1] !== undefined) {
  893. parts.push(encodeURIComponent(name_1) + '=' + encodeURIComponent(args[name_1]));
  894. }
  895. }
  896. return parts.join('&');
  897. }
  898. function parseQueryString(queryString) {
  899. var match;
  900. var pl = /\+/g;
  901. var search = /([^&=]+)=?([^&]*)/g;
  902. var decode = function (s) { return decodeURIComponent(s.replace(pl, ' ')); };
  903. if (queryString === undefined) {
  904. queryString = '';
  905. }
  906. queryString = queryString.substring(1);
  907. var urlParams = {};
  908. while (match = search.exec(queryString)) {
  909. urlParams[decode(match[1])] = decode(match[2]);
  910. }
  911. return urlParams;
  912. }
  913. function arraysIntersect(a, b) {
  914. for (var _i = 0, a_1 = a; _i < a_1.length; _i++) {
  915. var itemA = a_1[_i];
  916. for (var _a = 0, b_1 = b; _a < b_1.length; _a++) {
  917. var itemB = b_1[_a];
  918. if (itemA === itemB) {
  919. return true;
  920. }
  921. }
  922. }
  923. return false;
  924. }
  925. function notifyContentUpdated() {
  926. // Dispatch this event when needed
  927. // window.dispatchEvent(new CustomEvent('content-update'));
  928. }
  929. }
  930. function utility() {
  931. this.getAbsolutePath = getAbsolutePath;
  932. this.isRelativePath = isRelativePath;
  933. this.isAbsolutePath = isAbsolutePath;
  934. this.getDirectory = getDirectory;
  935. this.formList = formList;
  936. function getAbsolutePath(href) {
  937. // Use anchor to normalize href
  938. var anchor = $('<a href="' + href + '"></a>')[0];
  939. // Ignore protocal, remove search and query
  940. return anchor.host + anchor.pathname;
  941. }
  942. function isRelativePath(href) {
  943. if (href === undefined || href === '' || href[0] === '/') {
  944. return false;
  945. }
  946. return !isAbsolutePath(href);
  947. }
  948. function isAbsolutePath(href) {
  949. return (/^(?:[a-z]+:)?\/\//i).test(href);
  950. }
  951. function getDirectory(href) {
  952. if (!href) return '';
  953. var index = href.lastIndexOf('/');
  954. if (index == -1) return '';
  955. if (index > -1) {
  956. return href.substr(0, index);
  957. }
  958. }
  959. function formList(item, classes) {
  960. var level = 1;
  961. var model = {
  962. items: item
  963. };
  964. var cls = [].concat(classes).join(" ");
  965. return getList(model, cls);
  966. function getList(model, cls) {
  967. if (!model || !model.items) return null;
  968. var l = model.items.length;
  969. if (l === 0) return null;
  970. var html = '<ul class="level' + level + ' ' + (cls || '') + '">';
  971. level++;
  972. for (var i = 0; i < l; i++) {
  973. var item = model.items[i];
  974. var href = item.href;
  975. var name = item.name;
  976. if (!name) continue;
  977. html += href ? '<li><a href="' + href + '">' + name + '</a>' : '<li>' + name;
  978. html += getList(item, cls) || '';
  979. html += '</li>';
  980. }
  981. html += '</ul>';
  982. return html;
  983. }
  984. }
  985. /**
  986. * Add <wbr> into long word.
  987. * @param {String} text - The word to break. It should be in plain text without HTML tags.
  988. */
  989. function breakPlainText(text) {
  990. if (!text) return text;
  991. return text.replace(/([a-z])([A-Z])|(\.)(\w)/g, '$1$3<wbr>$2$4')
  992. }
  993. /**
  994. * Add <wbr> into long word. The jQuery element should contain no html tags.
  995. * If the jQuery element contains tags, this function will not change the element.
  996. */
  997. $.fn.breakWord = function () {
  998. if (this.html() == this.text()) {
  999. this.html(function (index, text) {
  1000. return breakPlainText(text);
  1001. })
  1002. }
  1003. return this;
  1004. }
  1005. }
  1006. // adjusted from https://stackoverflow.com/a/13067009/1523776
  1007. function workAroundFixedHeaderForAnchors() {
  1008. var HISTORY_SUPPORT = !!(history && history.pushState);
  1009. var ANCHOR_REGEX = /^#[^ ]+$/;
  1010. function getFixedOffset() {
  1011. return $('header').first().height();
  1012. }
  1013. /**
  1014. * If the provided href is an anchor which resolves to an element on the
  1015. * page, scroll to it.
  1016. * @param {String} href
  1017. * @return {Boolean} - Was the href an anchor.
  1018. */
  1019. function scrollIfAnchor(href, pushToHistory) {
  1020. var match, rect, anchorOffset;
  1021. if (!ANCHOR_REGEX.test(href)) {
  1022. return false;
  1023. }
  1024. match = document.getElementById(href.slice(1));
  1025. if (match) {
  1026. rect = match.getBoundingClientRect();
  1027. anchorOffset = window.pageYOffset + rect.top - getFixedOffset();
  1028. window.scrollTo(window.pageXOffset, anchorOffset);
  1029. // Add the state to history as-per normal anchor links
  1030. if (HISTORY_SUPPORT && pushToHistory) {
  1031. history.pushState({}, document.title, location.pathname + href);
  1032. }
  1033. }
  1034. return !!match;
  1035. }
  1036. /**
  1037. * Attempt to scroll to the current location's hash.
  1038. */
  1039. function scrollToCurrent() {
  1040. scrollIfAnchor(window.location.hash);
  1041. }
  1042. /**
  1043. * If the click event's target was an anchor, fix the scroll position.
  1044. */
  1045. function delegateAnchors(e) {
  1046. var elem = e.target;
  1047. if (scrollIfAnchor(elem.getAttribute('href'), true)) {
  1048. e.preventDefault();
  1049. }
  1050. }
  1051. $(window).on('hashchange', scrollToCurrent);
  1052. $(window).load(function () {
  1053. // scroll to the anchor if present, offset by the header
  1054. scrollToCurrent();
  1055. });
  1056. $(document).ready(function () {
  1057. // Exclude tabbed content case
  1058. $('a:not([data-tab])').click(function (e) { delegateAnchors(e); });
  1059. });
  1060. }
  1061. });