docfx.js 36 KB

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