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.

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