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.

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