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.

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