UNPKG

docsify

Version:

A magical documentation generator.

1,854 lines (1,520 loc) 158 kB
(function () { /** * Create a cached version of a pure function. * @param {*} fn The function call to be cached * @void */ function cached(fn) { var cache = Object.create(null); return function(str) { var key = isPrimitive(str) ? str : JSON.stringify(str); var hit = cache[key]; return hit || (cache[key] = fn(str)); }; } /** * Hyphenate a camelCase string. */ var hyphenate = cached(function (str) { return str.replace(/([A-Z])/g, function (m) { return '-' + m.toLowerCase(); }); }); var hasOwn = Object.prototype.hasOwnProperty; /** * Simple Object.assign polyfill * @param {Object} to The object to be merged with * @returns {Object} The merged object */ var merge = Object.assign || function(to) { var arguments$1 = arguments; for (var i = 1; i < arguments.length; i++) { var from = Object(arguments$1[i]); for (var key in from) { if (hasOwn.call(from, key)) { to[key] = from[key]; } } } return to; }; /** * Check if value is primitive * @param {*} value Checks if a value is primitive * @returns {Boolean} Result of the check */ function isPrimitive(value) { return typeof value === 'string' || typeof value === 'number'; } /** * Performs no operation. * @void */ function noop() {} /** * Check if value is function * @param {*} obj Any javascript object * @returns {Boolean} True if the passed-in value is a function */ function isFn(obj) { return typeof obj === 'function'; } var currentScript = document.currentScript; function config() { var config = merge( { el: '#app', repo: '', maxLevel: 6, subMaxLevel: 0, loadSidebar: null, loadNavbar: null, homepage: 'README.md', coverpage: '', basePath: '', auto2top: false, name: '', themeColor: '', nameLink: window.location.pathname, autoHeader: false, executeScript: null, noEmoji: false, ga: '', ext: '.md', mergeNavbar: false, formatUpdated: '', // This config for the links inside markdown externalLinkTarget: '_blank', // This config for the corner cornerExternalLinkTarget: '_blank', externalLinkRel: 'noopener', routerMode: 'hash', noCompileLinks: [], relativePath: false, topMargin: 0, }, window.$docsify ); var script = currentScript || [].slice .call(document.getElementsByTagName('script')) .filter(function (n) { return /docsify\./.test(n.src); })[0]; if (script) { for (var prop in config) { if (hasOwn.call(config, prop)) { var val = script.getAttribute('data-' + hyphenate(prop)); if (isPrimitive(val)) { config[prop] = val === '' ? true : val; } } } } if (config.loadSidebar === true) { config.loadSidebar = '_sidebar' + config.ext; } if (config.loadNavbar === true) { config.loadNavbar = '_navbar' + config.ext; } if (config.coverpage === true) { config.coverpage = '_coverpage' + config.ext; } if (config.repo === true) { config.repo = ''; } if (config.name === true) { config.name = ''; } window.$docsify = config; return config; } var inBrowser = !false; var isMobile = document.body.clientWidth <= 600; /** * @see https://github.com/MoOx/pjax/blob/master/lib/is-supported.js */ var supportsPushState = (function() { // Borrowed wholesale from https://github.com/defunkt/jquery-pjax return ( window.history && window.history.pushState && window.history.replaceState && // PushState isn’t reliable on iOS until 5. !navigator.userAgent.match( /((iPod|iPhone|iPad).+\bOS\s+[1-4]\D|WebApps\/.+CFNetwork)/ ) ); })(); var cacheNode = {}; /** * Get Node * @param {String|Element} el A DOM element * @param {Boolean} noCache Flag to use or not use the cache * @return {Element} The found node element */ function getNode(el, noCache) { if ( noCache === void 0 ) noCache = false; if (typeof el === 'string') { if (typeof window.Vue !== 'undefined') { return find(el); } el = noCache ? find(el) : cacheNode[el] || (cacheNode[el] = find(el)); } return el; } var $ = document; var body = $.body; var head = $.head; /** * Find elements * @param {String|Element} el The root element where to perform the search from * @param {Element} node The query * @returns {Element} The found DOM element * @example * find('nav') => document.querySelector('nav') * find(nav, 'a') => nav.querySelector('a') */ function find(el, node) { return node ? el.querySelector(node) : $.querySelector(el); } /** * Find all elements * @param {String|Element} el The root element where to perform the search from * @param {Element} node The query * @returns {Array<Element>} An array of DOM elements * @example * findAll('a') => [].slice.call(document.querySelectorAll('a')) * findAll(nav, 'a') => [].slice.call(nav.querySelectorAll('a')) */ function findAll(el, node) { return [].slice.call( node ? el.querySelectorAll(node) : $.querySelectorAll(el) ); } function create(node, tpl) { node = $.createElement(node); if (tpl) { node.innerHTML = tpl; } return node; } function appendTo(target, el) { return target.appendChild(el); } function before(target, el) { return target.insertBefore(el, target.children[0]); } function on(el, type, handler) { isFn(type) ? window.addEventListener(el, type) : el.addEventListener(type, handler); } function off(el, type, handler) { isFn(type) ? window.removeEventListener(el, type) : el.removeEventListener(type, handler); } /** * Toggle class * @param {String|Element} el The element that needs the class to be toggled * @param {Element} type The type of action to be performed on the classList (toggle by default) * @param {String} val Name of the class to be toggled * @void * @example * toggleClass(el, 'active') => el.classList.toggle('active') * toggleClass(el, 'add', 'active') => el.classList.add('active') */ function toggleClass(el, type, val) { el && el.classList[val ? type : 'toggle'](val || type); } function style(content) { appendTo(head, create('style', content)); } var dom = /*#__PURE__*/Object.freeze({ __proto__: null, getNode: getNode, $: $, body: body, head: head, find: find, findAll: findAll, create: create, appendTo: appendTo, before: before, on: on, off: off, toggleClass: toggleClass, style: style }); var barEl; var timeId; /** * Init progress component */ function init() { var div = create('div'); div.classList.add('progress'); appendTo(body, div); barEl = div; } /** * Render progress bar */ function progressbar(ref) { var loaded = ref.loaded; var total = ref.total; var step = ref.step; var num; !barEl && init(); if (step) { num = parseInt(barEl.style.width || 0, 10) + step; num = num > 80 ? 80 : num; } else { num = Math.floor((loaded / total) * 100); } barEl.style.opacity = 1; barEl.style.width = num >= 95 ? '100%' : num + '%'; if (num >= 95) { clearTimeout(timeId); // eslint-disable-next-line no-unused-vars timeId = setTimeout(function (_) { barEl.style.opacity = 0; barEl.style.width = '0%'; }, 200); } } /* eslint-disable no-unused-vars */ var cache = {}; /** * Ajax GET implmentation * @param {string} url Resource URL * @param {boolean} [hasBar=false] Has progress bar * @param {String[]} headers Array of headers * @return {Promise} Promise response */ function get(url, hasBar, headers) { if ( hasBar === void 0 ) hasBar = false; if ( headers === void 0 ) headers = {}; var xhr = new XMLHttpRequest(); var on = function() { xhr.addEventListener.apply(xhr, arguments); }; var cached = cache[url]; if (cached) { return { then: function (cb) { return cb(cached.content, cached.opt); }, abort: noop }; } xhr.open('GET', url); for (var i in headers) { if (hasOwn.call(headers, i)) { xhr.setRequestHeader(i, headers[i]); } } xhr.send(); return { then: function(success, error) { if ( error === void 0 ) error = noop; if (hasBar) { var id = setInterval( function (_) { return progressbar({ step: Math.floor(Math.random() * 5 + 1), }); }, 500 ); on('progress', progressbar); on('loadend', function (evt) { progressbar(evt); clearInterval(id); }); } on('error', error); on('load', function (ref) { var target = ref.target; if (target.status >= 400) { error(target); } else { var result = (cache[url] = { content: target.response, opt: { updatedAt: xhr.getResponseHeader('last-modified'), }, }); success(result.content, result.opt); } }); }, abort: function (_) { return xhr.readyState !== 4 && xhr.abort(); }, }; } function replaceVar(block, color) { block.innerHTML = block.innerHTML.replace( /var\(\s*--theme-color.*?\)/g, color ); } function cssVars(color) { // Variable support if (window.CSS && window.CSS.supports && window.CSS.supports('(--v:red)')) { return; } var styleBlocks = findAll('style:not(.inserted),link'); [].forEach.call(styleBlocks, function (block) { if (block.nodeName === 'STYLE') { replaceVar(block, color); } else if (block.nodeName === 'LINK') { var href = block.getAttribute('href'); if (!/\.css$/.test(href)) { return; } get(href).then(function (res) { var style = create('style', res); head.appendChild(style); replaceVar(style, color); }); } }); } function initLifecycle(vm) { var hooks = [ 'init', 'mounted', 'beforeEach', 'afterEach', 'doneEach', 'ready' ]; vm._hooks = {}; vm._lifecycle = {}; hooks.forEach(function (hook) { var arr = (vm._hooks[hook] = []); vm._lifecycle[hook] = function (fn) { return arr.push(fn); }; }); } function callHook(vm, hook, data, next) { if ( next === void 0 ) next = noop; var queue = vm._hooks[hook]; var step = function(index) { var hook = queue[index]; if (index >= queue.length) { next(data); } else if (typeof hook === 'function') { if (hook.length === 2) { hook(data, function (result) { data = result; step(index + 1); }); } else { var result = hook(data); data = result === undefined ? data : result; step(index + 1); } } else { step(index + 1); } }; step(0); } /* eslint-disable no-unused-vars */ var title = $.title; /** * Toggle button * @param {Element} el Button to be toggled * @void */ function btn(el) { var toggle = function (_) { return body.classList.toggle('close'); }; el = getNode(el); if (el === null || el === undefined) { return; } on(el, 'click', function (e) { e.stopPropagation(); toggle(); }); isMobile && on( body, 'click', function (_) { return body.classList.contains('close') && toggle(); } ); } function collapse(el) { el = getNode(el); if (el === null || el === undefined) { return; } on(el, 'click', function (ref) { var target = ref.target; if ( target.nodeName === 'A' && target.nextSibling && target.nextSibling.classList.contains('app-sub-sidebar') ) { toggleClass(target.parentNode, 'collapse'); } }); } function sticky() { var cover = getNode('section.cover'); if (!cover) { return; } var coverHeight = cover.getBoundingClientRect().height; if (window.pageYOffset >= coverHeight || cover.classList.contains('hidden')) { toggleClass(body, 'add', 'sticky'); } else { toggleClass(body, 'remove', 'sticky'); } } /** * Get and active link * @param {Object} router Router * @param {String|Element} el Target element * @param {Boolean} isParent Active parent * @param {Boolean} autoTitle Automatically set title * @return {Element} Active element */ function getAndActive(router, el, isParent, autoTitle) { el = getNode(el); var links = []; if (el !== null && el !== undefined) { links = findAll(el, 'a'); } var hash = decodeURI(router.toURL(router.getCurrentPath())); var target; links .sort(function (a, b) { return b.href.length - a.href.length; }) .forEach(function (a) { var href = a.getAttribute('href'); var node = isParent ? a.parentNode : a; if (hash.indexOf(href) === 0 && !target) { target = a; toggleClass(node, 'add', 'active'); } else { toggleClass(node, 'remove', 'active'); } }); if (autoTitle) { $.title = target ? target.title || ((target.innerText) + " - " + title) : title; } return target; } var decode = decodeURIComponent; var encode = encodeURIComponent; function parseQuery(query) { var res = {}; query = query.trim().replace(/^(\?|#|&)/, ''); if (!query) { return res; } // Simple parse query.split('&').forEach(function(param) { var parts = param.replace(/\+/g, ' ').split('='); res[parts[0]] = parts[1] && decode(parts[1]); }); return res; } function stringifyQuery(obj, ignores) { if ( ignores === void 0 ) ignores = []; var qs = []; for (var key in obj) { if (ignores.indexOf(key) > -1) { continue; } qs.push( obj[key] ? ((encode(key)) + "=" + (encode(obj[key]))).toLowerCase() : encode(key) ); } return qs.length ? ("?" + (qs.join('&'))) : ''; } var isAbsolutePath = cached(function (path) { return /(:|(\/{2}))/g.test(path); }); var getParentPath = cached(function (path) { if (/\/$/g.test(path)) { return path; } var matchingParts = path.match(/(\S*\/)[^/]+$/); return matchingParts ? matchingParts[1] : ''; }); var cleanPath = cached(function (path) { return path.replace(/^\/+/, '/').replace(/([^:])\/{2,}/g, '$1/'); }); var resolvePath = cached(function (path) { var segments = path.replace(/^\//, '').split('/'); var resolved = []; for (var i = 0, len = segments.length; i < len; i++) { var segment = segments[i]; if (segment === '..') { resolved.pop(); } else if (segment !== '.') { resolved.push(segment); } } return '/' + resolved.join('/'); }); function getPath() { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return cleanPath(args.join('/')); } var replaceSlug = cached(function (path) { return path.replace('#', '?id='); }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var SingleTweener = function () { function SingleTweener() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, SingleTweener); this.start = opts.start; this.end = opts.end; this.decimal = opts.decimal; } _createClass(SingleTweener, [{ key: "getIntermediateValue", value: function getIntermediateValue(tick) { if (this.decimal) { return tick; } else { return Math.round(tick); } } }, { key: "getFinalValue", value: function getFinalValue() { return this.end; } }]); return SingleTweener; }(); var _createClass$1 = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }(); function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Tweezer = function () { function Tweezer() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck$1(this, Tweezer); this.duration = opts.duration || 1000; this.ease = opts.easing || this._defaultEase; this.tweener = opts.tweener || new SingleTweener(opts); this.start = this.tweener.start; this.end = this.tweener.end; this.frame = null; this.next = null; this.isRunning = false; this.events = {}; this.direction = this.start < this.end ? 'up' : 'down'; } _createClass$1(Tweezer, [{ key: 'begin', value: function begin() { if (!this.isRunning && this.next !== this.end) { this.frame = window.requestAnimationFrame(this._tick.bind(this)); } return this; } }, { key: 'stop', value: function stop() { window.cancelAnimationFrame(this.frame); this.isRunning = false; this.frame = null; this.timeStart = null; this.next = null; return this; } }, { key: 'on', value: function on(name, handler) { this.events[name] = this.events[name] || []; this.events[name].push(handler); return this; } }, { key: '_emit', value: function _emit(name, val) { var _this = this; var e = this.events[name]; e && e.forEach(function (handler) { return handler.call(_this, val); }); } }, { key: '_tick', value: function _tick(currentTime) { this.isRunning = true; var lastTick = this.next || this.start; if (!this.timeStart) { this.timeStart = currentTime; } this.timeElapsed = currentTime - this.timeStart; this.next = this.ease(this.timeElapsed, this.start, this.end - this.start, this.duration); if (this._shouldTick(lastTick)) { this._emit('tick', this.tweener.getIntermediateValue(this.next)); this.frame = window.requestAnimationFrame(this._tick.bind(this)); } else { this._emit('tick', this.tweener.getFinalValue()); this._emit('done', null); } } }, { key: '_shouldTick', value: function _shouldTick(lastTick) { return { up: this.next < this.end && lastTick <= this.next, down: this.next > this.end && lastTick >= this.next }[this.direction]; } }, { key: '_defaultEase', value: function _defaultEase(t, b, c, d) { if ((t /= d / 2) < 1) { return c / 2 * t * t + b; } return -c / 2 * (--t * (t - 2) - 1) + b; } }]); return Tweezer; }(); var nav = {}; var hoverOver = false; var scroller = null; var enableScrollEvent = true; var coverHeight = 0; function scrollTo(el, offset) { if ( offset === void 0 ) offset = 0; if (scroller) { scroller.stop(); } enableScrollEvent = false; scroller = new Tweezer({ start: window.pageYOffset, end: el.getBoundingClientRect().top + window.pageYOffset - offset, duration: 500, }) .on('tick', function (v) { return window.scrollTo(0, v); }) .on('done', function () { enableScrollEvent = true; scroller = null; }) .begin(); } function highlight(path) { if (!enableScrollEvent) { return; } var sidebar = getNode('.sidebar'); var anchors = findAll('.anchor'); var wrap = find(sidebar, '.sidebar-nav'); var active = find(sidebar, 'li.active'); var doc = document.documentElement; var top = ((doc && doc.scrollTop) || document.body.scrollTop) - coverHeight; var last; for (var i = 0, len = anchors.length; i < len; i += 1) { var node = anchors[i]; if (node.offsetTop > top) { if (!last) { last = node; } break; } else { last = node; } } if (!last) { return; } var li = nav[getNavKey(decodeURIComponent(path), last.getAttribute('data-id'))]; if (!li || li === active) { return; } active && active.classList.remove('active'); li.classList.add('active'); active = li; // Scroll into view // https://github.com/vuejs/vuejs.org/blob/master/themes/vue/source/js/common.js#L282-L297 if (!hoverOver && body.classList.contains('sticky')) { var height = sidebar.clientHeight; var curOffset = 0; var cur = active.offsetTop + active.clientHeight + 40; var isInView = active.offsetTop >= wrap.scrollTop && cur <= wrap.scrollTop + height; var notThan = cur - curOffset < height; var top$1 = isInView ? wrap.scrollTop : notThan ? curOffset : cur - height; sidebar.scrollTop = top$1; } } function getNavKey(path, id) { return (path + "?id=" + id); } function scrollActiveSidebar(router) { var cover = find('.cover.show'); coverHeight = cover ? cover.offsetHeight : 0; var sidebar = getNode('.sidebar'); var lis = []; if (sidebar !== null && sidebar !== undefined) { lis = findAll(sidebar, 'li'); } for (var i = 0, len = lis.length; i < len; i += 1) { var li = lis[i]; var a = li.querySelector('a'); if (!a) { continue; } var href = a.getAttribute('href'); if (href !== '/') { var ref = router.parse(href); var id = ref.query.id; var path$1 = ref.path; if (id) { href = getNavKey(path$1, id); } } if (href) { nav[decodeURIComponent(href)] = li; } } if (isMobile) { return; } var path = router.getCurrentPath(); off('scroll', function () { return highlight(path); }); on('scroll', function () { return highlight(path); }); on(sidebar, 'mouseover', function () { hoverOver = true; }); on(sidebar, 'mouseleave', function () { hoverOver = false; }); } function scrollIntoView(path, id) { if (!id) { return; } var topMargin = config().topMargin; var section = find('#' + id); section && scrollTo(section, topMargin); var li = nav[getNavKey(path, id)]; var sidebar = getNode('.sidebar'); var active = find(sidebar, 'li.active'); active && active.classList.remove('active'); li && li.classList.add('active'); } var scrollEl = $.scrollingElement || $.documentElement; function scroll2Top(offset) { if ( offset === void 0 ) offset = 0; scrollEl.scrollTop = offset === true ? 0 : Number(offset); } /** * Render github corner * @param {Object} data URL for the View Source on Github link * @param {String} cornerExternalLinkTarge value of the target attribute of the link * @return {String} SVG element as string */ function corner(data, cornerExternalLinkTarge) { if (!data) { return ''; } if (!/\/\//.test(data)) { data = 'https://github.com/' + data; } data = data.replace(/^git\+/, ''); // Double check cornerExternalLinkTarge = cornerExternalLinkTarge || '_blank'; return ( "<a href=\"" + data + "\" target=\"" + cornerExternalLinkTarge + "\" class=\"github-corner\" aria-label=\"View source on Github\">" + '<svg viewBox="0 0 250 250" aria-hidden="true">' + '<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>' + '<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>' + '<path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path>' + '</svg>' + '</a>' ); } /** * Renders main content * @param {Object} config Configuration object * @returns {String} HTML of the main content */ function main(config) { var name = config.name ? config.name : ''; var aside = '<button class="sidebar-toggle" aria-label="Menu">' + '<div class="sidebar-toggle-button">' + '<span></span><span></span><span></span>' + '</div>' + '</button>' + '<aside class="sidebar">' + (config.name ? ("<h1 class=\"app-name\"><a class=\"app-name-link\" data-nosearch>" + (config.logo ? ("<img alt=\"" + name + "\" src=" + (config.logo) + ">") : name) + "</a></h1>") : '') + '<div class="sidebar-nav"><!--sidebar--></div>' + '</aside>'; return ( (isMobile ? (aside + "<main>") : ("<main>" + aside)) + '<section class="content">' + '<article class="markdown-section" id="main"><!--main--></article>' + '</section>' + '</main>' ); } /** * Cover Page * @returns {String} Cover page */ function cover() { var SL = ', 100%, 85%'; var bgc = 'linear-gradient(to left bottom, ' + "hsl(" + (Math.floor(Math.random() * 255) + SL) + ") 0%," + "hsl(" + (Math.floor(Math.random() * 255) + SL) + ") 100%)"; return ( "<section class=\"cover show\" style=\"background: " + bgc + "\">" + '<div class="cover-main"><!--cover--></div>' + '<div class="mask"></div>' + '</section>' ); } /** * Render tree * @param {Array} toc Array of TOC section links * @param {String} tpl TPL list * @return {String} Rendered tree */ function tree(toc, tpl) { if ( tpl === void 0 ) tpl = '<ul class="app-sub-sidebar">{inner}</ul>'; if (!toc || !toc.length) { return ''; } var innerHTML = ''; toc.forEach(function (node) { innerHTML += "<li><a class=\"section-link\" href=\"" + (node.slug) + "\">" + (node.title) + "</a></li>"; if (node.children) { innerHTML += tree(node.children, tpl); } }); return tpl.replace('{inner}', innerHTML); } function helper(className, content) { return ("<p class=\"" + className + "\">" + (content.slice(5).trim()) + "</p>"); } function theme(color) { return ("<style>:root{--theme-color: " + color + ";}</style>"); } /** * Gen toc tree * @link https://github.com/killercup/grock/blob/5280ae63e16c5739e9233d9009bc235ed7d79a50/styles/solarized/assets/js/behavior.coffee#L54-L81 * @param {Array} toc List of TOC elements * @param {Number} maxLevel Deep level * @return {Array} Headlines */ function genTree(toc, maxLevel) { var headlines = []; var last = {}; toc.forEach(function (headline) { var level = headline.level || 1; var len = level - 1; if (level > maxLevel) { return; } if (last[len]) { last[len].children = (last[len].children || []).concat(headline); } else { headlines.push(headline); } last[level] = headline; }); return headlines; } var cache$1 = {}; var re = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g; function lower(string) { return string.toLowerCase(); } function slugify(str) { if (typeof str !== 'string') { return ''; } var slug = str .trim() .replace(/[A-Z]+/g, lower) .replace(/<[^>\d]+>/g, '') .replace(re, '') .replace(/\s/g, '-') .replace(/-+/g, '-') .replace(/^(\d)/, '_$1'); var count = cache$1[slug]; count = hasOwn.call(cache$1, slug) ? count + 1 : 0; cache$1[slug] = count; if (count) { slug = slug + '-' + count; } return slug; } slugify.clear = function() { cache$1 = {}; }; function replace(m, $1) { return ( '<img class="emoji" src="https://github.githubassets.com/images/icons/emoji/' + $1 + '.png" alt="' + $1 + '" />' ); } function emojify(text) { return text .replace(/<(pre|template|code)[^>]*?>[\s\S]+?<\/(pre|template|code)>/g, function (m) { return m.replace(/:/g, '__colon__'); } ) .replace(/:(\w+?):/gi, ( window.emojify) || replace) .replace(/__colon__/g, ':'); } function getAndRemoveConfig(str) { if ( str === void 0 ) str = ''; var config = {}; if (str) { str = str .replace(/^'/, '') .replace(/'$/, '') .replace(/(?:^|\s):([\w-]+:?)=?([\w-]+)?/g, function (m, key, value) { if (key.indexOf(':') === -1) { config[key] = (value && value.replace(/&quot;/g, '')) || true; return ''; } return m; }) .trim(); } return { str: str, config: config }; } var imageCompiler = function (ref) { var renderer = ref.renderer; var contentBase = ref.contentBase; var router = ref.router; return (renderer.image = function (href, title, text) { var url = href; var attrs = []; var ref = getAndRemoveConfig(title); var str = ref.str; var config = ref.config; title = str; if (config['no-zoom']) { attrs.push('data-no-zoom'); } if (title) { attrs.push(("title=\"" + title + "\"")); } if (config.size) { var ref$1 = config.size.split('x'); var width = ref$1[0]; var height = ref$1[1]; if (height) { attrs.push(("width=\"" + width + "\" height=\"" + height + "\"")); } else { attrs.push(("width=\"" + width + "\" height=\"" + width + "\"")); } } if (config.class) { attrs.push(("class=\"" + (config.class) + "\"")); } if (config.id) { attrs.push(("id=\"" + (config.id) + "\"")); } if (!isAbsolutePath(href)) { url = getPath(contentBase, getParentPath(router.getCurrentPath()), href); } if (attrs.length > 0) { return ("<img src=\"" + url + "\" data-origin=\"" + href + "\" alt=\"" + text + "\" " + (attrs.join( ' ' )) + " />"); } return ("<img src=\"" + url + "\" data-origin=\"" + href + "\" alt=\"" + text + "\"" + attrs + ">"); }); }; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var prism = createCommonjsModule(function (module) { /* ********************************************** Begin prism-core.js ********************************************** */ var _self = (typeof window !== 'undefined') ? window // if in browser : ( (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) ? self // if in worker : {} // if in node js ); /** * Prism: Lightweight, robust, elegant syntax highlighting * MIT license http://www.opensource.org/licenses/mit-license.php/ * @author Lea Verou http://lea.verou.me */ var Prism = (function (_self){ // Private helper vars var lang = /\blang(?:uage)?-([\w-]+)\b/i; var uniqueId = 0; var _ = { manual: _self.Prism && _self.Prism.manual, disableWorkerMessageHandler: _self.Prism && _self.Prism.disableWorkerMessageHandler, util: { encode: function (tokens) { if (tokens instanceof Token) { return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias); } else if (Array.isArray(tokens)) { return tokens.map(_.util.encode); } else { return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' '); } }, type: function (o) { return Object.prototype.toString.call(o).slice(8, -1); }, objId: function (obj) { if (!obj['__id']) { Object.defineProperty(obj, '__id', { value: ++uniqueId }); } return obj['__id']; }, // Deep clone a language definition (e.g. to extend it) clone: function deepClone(o, visited) { var clone, id, type = _.util.type(o); visited = visited || {}; switch (type) { case 'Object': id = _.util.objId(o); if (visited[id]) { return visited[id]; } clone = {}; visited[id] = clone; for (var key in o) { if (o.hasOwnProperty(key)) { clone[key] = deepClone(o[key], visited); } } return clone; case 'Array': id = _.util.objId(o); if (visited[id]) { return visited[id]; } clone = []; visited[id] = clone; o.forEach(function (v, i) { clone[i] = deepClone(v, visited); }); return clone; default: return o; } }, /** * Returns the Prism language of the given element set by a `language-xxxx` or `lang-xxxx` class. * * If no language is set for the element or the element is `null` or `undefined`, `none` will be returned. * * @param {Element} element * @returns {string} */ getLanguage: function (element) { while (element && !lang.test(element.className)) { element = element.parentElement; } if (element) { return (element.className.match(lang) || [, 'none'])[1].toLowerCase(); } return 'none'; }, /** * Returns the script element that is currently executing. * * This does __not__ work for line script element. * * @returns {HTMLScriptElement | null} */ currentScript: function () { if (typeof document === 'undefined') { return null; } if ('currentScript' in document) { return document.currentScript; } // IE11 workaround // we'll get the src of the current script by parsing IE11's error stack trace // this will not work for inline scripts try { throw new Error(); } catch (err) { // Get file src url from stack. Specifically works with the format of stack traces in IE. // A stack will look like this: // // Error // at _.util.currentScript (http://localhost/components/prism-core.js:119:5) // at Global code (http://localhost/components/prism-core.js:606:1) var src = (/at [^(\r\n]*\((.*):.+:.+\)$/i.exec(err.stack) || [])[1]; if (src) { var scripts = document.getElementsByTagName('script'); for (var i in scripts) { if (scripts[i].src == src) { return scripts[i]; } } } return null; } } }, languages: { extend: function (id, redef) { var lang = _.util.clone(_.languages[id]); for (var key in redef) { lang[key] = redef[key]; } return lang; }, /** * Insert a token before another token in a language literal * As this needs to recreate the object (we cannot actually insert before keys in object literals), * we cannot just provide an object, we need an object and a key. * @param inside The key (or language id) of the parent * @param before The key to insert before. * @param insert Object with the key/value pairs to insert * @param root The object that contains `inside`. If equal to Prism.languages, it can be omitted. */ insertBefore: function (inside, before, insert, root) { root = root || _.languages; var grammar = root[inside]; var ret = {}; for (var token in grammar) { if (grammar.hasOwnProperty(token)) { if (token == before) { for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { ret[newToken] = insert[newToken]; } } } // Do not insert token which also occur in insert. See #1525 if (!insert.hasOwnProperty(token)) { ret[token] = grammar[token]; } } } var old = root[inside]; root[inside] = ret; // Update references in other language definitions _.languages.DFS(_.languages, function(key, value) { if (value === old && key != inside) { this[key] = ret; } }); return ret; }, // Traverse a language definition with Depth First Search DFS: function DFS(o, callback, type, visited) { visited = visited || {}; var objId = _.util.objId; for (var i in o) { if (o.hasOwnProperty(i)) { callback.call(o, i, o[i], type || i); var property = o[i], propertyType = _.util.type(property); if (propertyType === 'Object' && !visited[objId(property)]) { visited[objId(property)] = true; DFS(property, callback, null, visited); } else if (propertyType === 'Array' && !visited[objId(property)]) { visited[objId(property)] = true; DFS(property, callback, i, visited); } } } } }, plugins: {}, highlightAll: function(async, callback) { _.highlightAllUnder(document, async, callback); }, highlightAllUnder: function(container, async, callback) { var env = { callback: callback, container: container, selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code' }; _.hooks.run('before-highlightall', env); env.elements = Array.prototype.slice.apply(env.container.querySelectorAll(env.selector)); _.hooks.run('before-all-elements-highlight', env); for (var i = 0, element; element = env.elements[i++];) { _.highlightElement(element, async === true, env.callback); } }, highlightElement: function(element, async, callback) { // Find language var language = _.util.getLanguage(element); var grammar = _.languages[language]; // Set language on the element, if not present element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language; // Set language on the parent, for styling var parent = element.parentNode; if (parent && parent.nodeName.toLowerCase() === 'pre') { parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language; } var code = element.textContent; var env = { element: element, language: language, grammar: grammar, code: code }; function insertHighlightedCode(highlightedCode) { env.highlightedCode = highlightedCode; _.hooks.run('before-insert', env); env.element.innerHTML = env.highlightedCode; _.hooks.run('after-highlight', env); _.hooks.run('complete', env); callback && callback.call(env.element); } _.hooks.run('before-sanity-check', env); if (!env.code) { _.hooks.run('complete', env); callback && callback.call(env.element); return; } _.hooks.run('before-highlight', env); if (!env.grammar) { insertHighlightedCode(_.util.encode(env.code)); return; } if (async && _self.Worker) { var worker = new Worker(_.filename); worker.onmessage = function(evt) { insertHighlightedCode(evt.data); }; worker.postMessage(JSON.stringify({ language: env.language, code: env.code, immediateClose: true })); } else { insertHighlightedCode(_.highlight(env.code, env.grammar, env.language)); } }, highlight: function (text, grammar, language) { var env = { code: text, grammar: grammar, language: language }; _.hooks.run('before-tokenize', env); env.tokens = _.tokenize(env.code, env.grammar); _.hooks.run('after-tokenize', env); return Token.stringify(_.util.encode(env.tokens), env.language); }, matchGrammar: function (text, strarr, grammar, index, startPos, oneshot, target) { for (var token in grammar) { if (!grammar.hasOwnProperty(token) || !grammar[token]) { continue; } var patterns = grammar[token]; patterns = Array.isArray(patterns) ? patterns : [patterns]; for (var j = 0; j < patterns.length; ++j) { if (target && target == token + ',' + j) { return; } var pattern = patterns[j], inside = pattern.inside, lookbehind = !!pattern.lookbehind, greedy = !!pattern.greedy, lookbehindLength = 0, alias = pattern.alias; if (greedy && !pattern.pattern.global) { // Without the global flag, lastIndex won't work var flags = pattern.pattern.toString().match(/[imsuy]*$/)[0]; pattern.pattern = RegExp(pattern.pattern.source, flags + 'g'); } pattern = pattern.pattern || pattern; // Don’t cache length as it changes during the loop for (var i = index, pos = startPos; i < strarr.length; pos += strarr[i].length, ++i) { var str = strarr[i]; if (strarr.length > text.length) { // Something went terribly wrong, ABORT, ABORT! return; } if (str instanceof Token) { continue; } if (greedy && i != strarr.length - 1) { pattern.lastIndex = pos; var match = pattern.exec(text); if (!match) { break; } var from = match.index + (lookbehind && match[1] ? match[1].length : 0), to = match.index + match[0].length, k = i, p = pos; for (var len = strarr.length; k < len && (p < to || (!strarr[k].type && !strarr[k - 1].greedy)); ++k) { p += strarr[k].length; // Move the index i to the element in strarr that is closest to from if (from >= p) { ++i; pos = p; } } // If strarr[i] is a Token, then the match starts inside another Token, which is invalid if (strarr[i] instanceof Token) { continue; } // Number of tokens to delete and replace with the new match delNum = k - i; str = text.slice(pos, p); match.index -= pos; } else { pattern.lastIndex = 0; var match = pattern.exec(str), delNum = 1; } if (!match) { if (oneshot) { break; } continue; } if(lookbehind) { lookbehindLength = match[1] ? match[1].length : 0; } var from = match.index + lookbehindLength, match = match[0].slice(lookbehindLength), to = from + match.length, before = str.slice(0, from), after = str.slice(to); var args = [i, delNum]; if (before) { ++i; pos += before.length; args.push(before); } var wrapped = new Token(token, inside? _.tokenize(match, inside) : match, alias, match, greedy); args.push(wrapped); if (after) { args.push(after); } Array.prototype.splice.apply(strarr, args); if (delNum != 1) { _.matchGrammar(text, strarr, grammar, i, pos, true, token + ',' + j); } if (oneshot) { break; } } } } }, tokenize: function(text, grammar) { var strarr = [text]; var rest = grammar.rest; if (rest) { for (var token in rest) { grammar[token] = rest[token]; } delete grammar.rest; } _.matchGrammar(text, strarr, grammar, 0, 0, false); return strarr; }, hooks: { all: {}, add: function (name, callback) { var hooks = _.hooks.all; hooks[name] = hooks[name] || []; hooks[name].push(callback); }, run: function (name, env) { var callbacks = _.hooks.all[name]; if (!callbacks || !callbacks.length) { return; } for (var i=0, callback; callback = callbacks[i++];) { callback(env); } } }, Token: Token }; _self.Prism = _; function Token(type, content, alias, matchedStr, greedy) { this.type = type; this.content = content; this.alias = alias; // Copy of the full string this token was created from this.length = (matchedStr || '').length|0; this.greedy = !!greedy; } Token.stringify = function(o, language) { if (typeof o == 'string') { return o; } if (Array.isArray(o)) { return o.map(function(element) { return Token.stringify(element, language); }).join(''); } var env = { type: o.type, content: Token.stringify(o.content, language), tag: 'span', classes: ['token', o.type], attributes: {}, language: language }; if (o.alias) { var aliases = Array.isArray(o.alias) ? o.alias : [o.alias]; Array.prototype.push.apply(env.classes, aliases); } _.hooks.run('wrap', env); var attributes = Object.keys(env.attributes).map(function(name) { return name + '="' + (env.attributes[name] || '').replace(/"/g, '&quot;') + '"'; }).join(' '); return '<' + env.tag + ' class="' + env.classes.join(' ') + '"' + (attributes ? ' ' + attributes : '') + '>' + env.content + '</' + env.tag + '>'; }; if (!_self.document) { if (!_self.addEventListener) { // in Node.js return _; } if (!_.disableWorkerMessageHandler) { // In worker _self.addEventListener('message', function (evt) { var message = JSON.parse(evt.data), lang = message.language, code = message.code, immediateClose = message.immediateClose; _self.postMessage(_.highlight(code, _.languages[lang], lang)); if (immediateClose) { _self.close(); } }, false); } return _; } //Get current script and highlight var script = _.util.currentScript(); if (script) { _.filename = script.src; if (script.hasAttribute('data-manual')) { _.manual = true; } } if (!_.manual) { function highlightAutomaticallyCallback() { if (!_.manual) { _.highlightAll(); } } // If the document state is "loading", then we'll use DOMContentLoaded. // If the document state is "interactive" and the prism.js script is deferred, then we'll also use the // DOMContentLoaded event because there might be some plugins or languages which have also been deferred and they // might take longer one animation frame to execute which can create a race condition where only some plugins have // been loaded when Prism.highlightAll() is executed, depending on h