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.

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