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.

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