mirror of
https://github.com/JonnyBro/JaBa.git
synced 2024-11-25 22:55:00 +05:00
1 line
No EOL
16 KiB
Text
1 line
No EOL
16 KiB
Text
{"version":3,"file":"zero-md.min.js","sources":["../src/index.js"],"sourcesContent":["export class ZeroMd extends HTMLElement {\n get src () { return this.getAttribute('src') }\n set src (val) { this.reflect('src', val) }\n get manualRender () { return this.hasAttribute('manual-render') }\n set manualRender (val) { this.reflect('manual-render', val) }\n\n reflect (name, val) {\n if (val === false) {\n this.removeAttribute(name)\n } else {\n this.setAttribute(name, val === true ? '' : val)\n }\n }\n\n static get observedAttributes () {\n return ['src']\n }\n\n attributeChangedCallback (name, old, val) {\n if (name === 'src' && this.connected && !this.manualRender && val !== old) {\n this.render()\n }\n }\n\n constructor (defaults) {\n super()\n this.version = '$VERSION'\n this.config = {\n markedUrl: 'https://cdn.jsdelivr.net/gh/markedjs/marked@2/marked.min.js',\n prismUrl: [\n ['https://cdn.jsdelivr.net/gh/PrismJS/prism@1/prism.min.js', 'data-manual'],\n 'https://cdn.jsdelivr.net/gh/PrismJS/prism@1/plugins/autoloader/prism-autoloader.min.js'\n ],\n cssUrls: [\n 'https://cdn.jsdelivr.net/gh/sindresorhus/github-markdown-css@4/github-markdown.min.css',\n 'https://cdn.jsdelivr.net/gh/PrismJS/prism@1/themes/prism.min.css'\n ],\n hostCss: ':host{display:block;position:relative;contain:content;}:host([hidden]){display:none;}',\n ...defaults,\n ...window.ZeroMdConfig\n }\n this.cache = {}\n this.root = this.hasAttribute('no-shadow') ? this : this.attachShadow({ mode: 'open' })\n if (!this.constructor.ready) {\n this.constructor.ready = Promise.all([\n !!window.marked || this.loadScript(this.config.markedUrl),\n !!window.Prism || this.loadScript(this.config.prismUrl)\n ])\n }\n this.clicked = this.clicked.bind(this)\n if (!this.manualRender) {\n // Scroll to hash id after first render. However, `history.scrollRestoration` inteferes with this on refresh.\n // It's much better to use a `setTimeout` rather than to alter the browser's behaviour.\n this.render().then(() => setTimeout(() => this.goto(location.hash), 250))\n }\n this.observer = new MutationObserver(async () => {\n this.observeChanges()\n if (!this.manualRender) {\n await this.render()\n }\n })\n this.observeChanges()\n }\n\n connectedCallback () {\n this.connected = true\n this.fire('zero-md-connected', {}, { bubbles: false, composed: false })\n this.waitForReady().then(() => {\n this.fire('zero-md-ready')\n })\n if (this.shadowRoot) {\n this.shadowRoot.addEventListener('click', this.clicked)\n }\n }\n\n disconnectedCallback () {\n this.connected = false\n if (this.shadowRoot) {\n this.shadowRoot.removeEventListener('click', this.clicked)\n }\n }\n\n waitForReady () {\n const ready = this.connected || new Promise(resolve => {\n this.addEventListener('zero-md-connected', function handler () {\n this.removeEventListener('zero-md-connected', handler)\n resolve()\n })\n })\n return Promise.all([this.constructor.ready, ready])\n }\n\n fire (name, detail = {}, opts = { bubbles: true, composed: true }) {\n if (detail.msg) {\n console.warn(detail.msg)\n }\n this.dispatchEvent(new CustomEvent(name, {\n detail: { node: this, ...detail },\n ...opts\n }))\n }\n\n tick () {\n return new Promise(resolve => requestAnimationFrame(resolve))\n }\n\n // Coerce anything into an array\n arrify (any) {\n return any ? (Array.isArray(any) ? any : [any]) : []\n }\n\n // Promisify an element's onload callback\n onload (node) {\n return new Promise((resolve, reject) => {\n node.onload = resolve\n node.onerror = err => reject(err.path ? err.path[0] : err.composedPath()[0])\n })\n }\n\n // Load a url or load (in order) an array of urls via <script> tags\n loadScript (urls) {\n return Promise.all(this.arrify(urls).map(item => {\n const [url, ...attrs] = this.arrify(item)\n const el = document.createElement('script')\n el.src = url\n el.async = false\n attrs.forEach(attr => el.setAttribute(attr, ''))\n return this.onload(document.head.appendChild(el))\n }))\n }\n\n // Scroll to selected element\n goto (id) {\n if (id) {\n const el = this.root.getElementById(id.substring(1))\n if (el) {\n el.scrollIntoView()\n }\n }\n }\n\n // Hijack same-doc anchor hash links\n clicked (ev) {\n if (ev.metaKey || ev.ctrlKey || ev.altKey || ev.shiftKey || ev.defaultPrevented) {\n return\n }\n const a = ev.target.closest('a')\n if (a && a.hash && a.host === location.host && a.pathname === location.pathname) {\n this.goto(a.hash)\n }\n }\n\n dedent (str) {\n str = str.replace(/^\\n/, '')\n const match = str.match(/^\\s+/)\n return match ? str.replace(new RegExp(`^${match[0]}`, 'gm'), '') : str\n }\n\n getBaseUrl (src) {\n const a = document.createElement('a')\n a.href = src\n return a.href.substring(0, a.href.lastIndexOf('/') + 1)\n }\n\n // Runs Prism highlight async; falls back to sync if Web Workers throw\n highlight (container) {\n return new Promise(resolve => {\n const unhinted = container.querySelectorAll('pre>code:not([class*=\"language-\"])')\n unhinted.forEach(n => {\n // Dead simple language detection :)\n const lang = n.innerText.match(/^\\s*</) ? 'markup' : n.innerText.match(/^\\s*(\\$|#)/) ? 'bash' : 'js'\n n.classList.add(`language-${lang}`)\n })\n try {\n window.Prism.highlightAllUnder(container, true, resolve())\n } catch {\n window.Prism.highlightAllUnder(container)\n resolve()\n }\n })\n }\n\n // Converts HTML string into node\n makeNode (html) {\n const tpl = document.createElement('template')\n tpl.innerHTML = html\n return tpl.content.firstElementChild\n }\n\n // Construct styles dom and return HTML string\n buildStyles () {\n const get = query => {\n const node = this.querySelector(query)\n return node ? node.innerHTML || ' ' : ''\n }\n const urls = this.arrify(this.config.cssUrls)\n const html = `<div class=\"markdown-styles\"><style>${\n this.config.hostCss}</style>${\n get('template[data-merge=\"prepend\"]')}${\n get('template:not([data-merge])') || urls.reduce((a, c) => `${a}<link rel=\"stylesheet\" href=\"${c}\">`, '')}${\n get('template[data-merge=\"append\"]')}</div>`\n return html\n }\n\n // Construct md nodes and return HTML string\n async buildMd (opts = {}) {\n const src = async () => {\n if (!this.src) {\n return ''\n }\n const resp = await fetch(this.src)\n if (resp.ok) {\n const md = await resp.text()\n return window.marked(md, { baseUrl: this.getBaseUrl(this.src), ...opts })\n } else {\n this.fire('zero-md-error', { msg: `[zero-md] HTTP error ${resp.status} while fetching src`, status: resp.status, src: this.src })\n return ''\n }\n }\n const script = () => {\n const el = this.querySelector('script[type=\"text/markdown\"]')\n if (!el) { return '' }\n const md = el.hasAttribute('data-dedent') ? this.dedent(el.text) : el.text\n return window.marked(md, opts)\n }\n const html = `<div class=\"markdown-body${\n opts.classes ? this.arrify(opts.classes).reduce((a, c) => `${a} ${c}`, ' ') : ''}\">${\n await src() || script()}</div>`\n return html\n }\n\n // Insert or replace HTML styles string into DOM and wait for links to load\n async stampStyles (html) {\n const node = this.makeNode(html)\n const links = [...node.querySelectorAll('link[rel=\"stylesheet\"]')]\n const target = [...this.root.children].find(n => n.classList.contains('markdown-styles'))\n if (target) {\n target.replaceWith(node)\n } else {\n this.root.prepend(node)\n }\n await Promise.all(links.map(l => this.onload(l))).catch(err => {\n this.fire('zero-md-error', { msg: '[zero-md] An external stylesheet failed to load', status: undefined, src: err.href })\n })\n }\n\n // Insert or replace HTML body string into DOM and returns the node\n stampBody (html) {\n const node = this.makeNode(html)\n const target = [...this.root.children].find(n => n.classList.contains('markdown-body'))\n if (target) {\n target.replaceWith(node)\n } else {\n this.root.append(node)\n }\n return node\n }\n\n // Start observing for changes in root, templates and scripts\n observeChanges () {\n this.observer.observe(this, { childList: true })\n this.querySelectorAll('template,script[type=\"text/markdown\"]').forEach(n => {\n this.observer.observe(n.content || n, { childList: true, subtree: true, attributes: true, characterData: true })\n })\n }\n\n async render (opts = {}) {\n await this.waitForReady()\n const stamped = {}\n const pending = this.buildMd(opts)\n const css = this.buildStyles()\n if (css !== this.cache.styles) {\n this.cache.styles = css\n await this.stampStyles(css)\n stamped.styles = true\n await this.tick()\n }\n const md = await pending\n if (md !== this.cache.body) {\n this.cache.body = md\n const node = this.stampBody(md)\n stamped.body = true\n await this.highlight(node)\n }\n this.fire('zero-md-rendered', { stamped })\n }\n}\n\ncustomElements.define('zero-md', ZeroMd)\n"],"names":["ZeroMd","HTMLElement","src","this","getAttribute","val","reflect","manualRender","hasAttribute","name","removeAttribute","setAttribute","observedAttributes","attributeChangedCallback","old","connected","render","constructor","defaults","super","version","config","markedUrl","prismUrl","cssUrls","hostCss","window","ZeroMdConfig","cache","root","attachShadow","mode","ready","Promise","all","marked","loadScript","Prism","clicked","bind","then","setTimeout","goto","location","hash","observer","MutationObserver","async","observeChanges","connectedCallback","fire","bubbles","composed","waitForReady","shadowRoot","addEventListener","disconnectedCallback","removeEventListener","resolve","handler","detail","opts","msg","console","warn","dispatchEvent","CustomEvent","node","tick","requestAnimationFrame","arrify","any","Array","isArray","onload","reject","onerror","err","path","composedPath","urls","map","item","url","attrs","el","document","createElement","forEach","attr","head","appendChild","id","getElementById","substring","scrollIntoView","ev","metaKey","ctrlKey","altKey","shiftKey","defaultPrevented","a","target","closest","host","pathname","dedent","str","match","replace","RegExp","getBaseUrl","href","lastIndexOf","highlight","container","querySelectorAll","n","lang","innerText","classList","add","highlightAllUnder","makeNode","html","tpl","innerHTML","content","firstElementChild","buildStyles","get","query","querySelector","reduce","c","classes","resp","fetch","ok","md","text","baseUrl","status","script","links","children","find","contains","replaceWith","prepend","l","catch","undefined","stampBody","append","observe","childList","subtree","attributes","characterData","stamped","pending","buildMd","css","styles","stampStyles","body","customElements","define"],"mappings":"AAAO,MAAMA,UAAeC,YACtBC,UAAS,OAAOC,KAAKC,aAAa,OAClCF,QAAKG,GAAOF,KAAKG,QAAQ,MAAOD,GAChCE,mBAAkB,OAAOJ,KAAKK,aAAa,iBAC3CD,iBAAcF,GAAOF,KAAKG,QAAQ,gBAAiBD,GAEvDC,QAASG,EAAMJ,IACD,IAARA,EACFF,KAAKO,gBAAgBD,GAErBN,KAAKQ,aAAaF,GAAc,IAARJ,EAAe,GAAKA,GAIrCO,gCACT,MAAO,CAAC,OAGVC,yBAA0BJ,EAAMK,EAAKT,GACtB,QAATI,GAAkBN,KAAKY,YAAcZ,KAAKI,cAAgBF,IAAQS,GACpEX,KAAKa,SAITC,YAAaC,GACXC,QACAhB,KAAKiB,QAAU,QACfjB,KAAKkB,OAAS,CACZC,UAAW,8DACXC,SAAU,CACR,CAAC,2DAA4D,eAC7D,0FAEFC,QAAS,CACP,yFACA,oEA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