Add: npm zero-md package
Some checks failed
Publish Docker rootless image / Push Docker image to Docker Hub (push) Failing after 38s
Publish Docker image / Push Docker image to Docker Hub (push) Failing after 41s

This commit is contained in:
Aroy-Art 2024-03-27 14:37:57 +01:00
parent 985324970e
commit 092042a42d
Signed by: Aroy
GPG key ID: 583642324A1D2070
9 changed files with 888 additions and 0 deletions

16
node_modules/.package-lock.json generated vendored Normal file
View file

@ -0,0 +1,16 @@
{
"name": "nginx-file-browser",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/zero-md": {
"version": "2.5.4",
"resolved": "https://registry.npmjs.org/zero-md/-/zero-md-2.5.4.tgz",
"integrity": "sha512-FbfH1k2kX3W0l/Wck4PuVJXmdS68JpbW3Iq5JthJctyga4PdVRmgPYt2AuBzmtekihFre+PhX+Hav2H1N41aWA==",
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
}
}
}
}

15
node_modules/zero-md/LICENSE generated vendored Normal file
View file

@ -0,0 +1,15 @@
ISC License
Copyright (c) 2024, Jason Lee <jason@zerodevx.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

445
node_modules/zero-md/README.md generated vendored Normal file
View file

@ -0,0 +1,445 @@
![GitHub package.json version](https://img.shields.io/github/package-json/v/zerodevx/zero-md)
![jsDelivr hits (GitHub)](https://img.shields.io/jsdelivr/gh/hm/zerodevx/zero-md)
# &lt;zero-md&gt;
> Ridiculously simple zero-config markdown displayer
A native markdown-to-html web component based on
[Custom Elements V1 specs](https://www.w3.org/TR/custom-elements/) to load and display an external
MD file. Under the hood, it uses [Marked](https://github.com/markedjs/marked) for super-fast
markdown transformation, and [Prism](https://github.com/PrismJS/prism) for feature-packed syntax
highlighting - automagically rendering into its own self-contained shadow DOM container, while
encapsulating implementation details into one embarassingly easy-to-use package.
**NOTE: This is the V2 branch. If you're looking for the older version, see the
[V1 branch](https://github.com/zerodevx/zero-md/tree/v1).**
Featuring:
- [x] Automated hash-link scrolls
- [x] Built-in FOUC prevention
- [x] Automatically rewrite URLs relative to `src`
- [x] Automatically re-render when `src` changes
- [x] Automatically re-render when inline markdown or style template changes
- [x] Support for >200 code languages with detection for unhinted code blocks
- [x] Easy styling mechanism
- [x] Highly extensible
Documentation: https://zerodevx.github.io/zero-md/
**NOTE: Your markdown file(s) needs to be hosted! Browsers don't generally allow javascript to
access files on the local hard drive because of security concerns. Standard
[CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) rules apply.**
## Installation
### Load via CDN (recommended)
`zero-md` is designed to be zero-config with good defaults. For most use-cases, just importing the
script from CDN and consuming the component directly should suffice.
```html
<head>
...
<!-- Import element definition -->
<script
type="module"
src="https://cdn.jsdelivr.net/gh/zerodevx/zero-md@2/dist/zero-md.min.js"
></script>
...
</head>
<body>
...
<!-- Profit! -->
<zero-md src="/example.md"></zero-md>
...
</body>
```
Latest stable: `https://cdn.jsdelivr.net/gh/zerodevx/zero-md@2/dist/zero-md.min.js`
Latest beta: `https://cdn.jsdelivr.net/npm/zero-md@next/dist/zero-md.min.js`
### Install in web projects
Install package with `npm` or `yarn`. Note that you'll need [Node.js](https://nodejs.org/)
installed.
```
$ npm install --save zero-md
```
Import the class, register the element, and use anywhere.
```js
// Import the element definition
import ZeroMd from 'zero-md'
// Register the custom element
customElements.define('zero-md', ZeroMd)
// Render anywhere
app.render(`<zero-md src=${src}></zero-md>`, target)
```
Or load the distribution directly in HTML.
```html
<script type="module" src="/node_modules/zero-md/dist/zero-md.min.js"></script>
...
<zero-md src="example.md"></zero-md>
```
## Basic Usage
### Display an external markdown file
```html
<!-- Simply set the `src` attribute and win -->
<zero-md src="https://example.com/markdown.md"></zero-md>
```
At its most basic, `<zero-md>` loads and displays an external MD file with **default stylesheets** -
a Github-themed stylesheet paired with a light-themed one for code blocks, just like what you see in
these docs. So internally, the above code block is semantically equivalent to the one below:
```html
<zero-md src="https://example.com/markdown.md">
<!-- By default, this style template gets loaded -->
<template>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/sindresorhus/github-markdown-css@4/github-markdown.min.css"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/PrismJS/prism@1/themes/prism.min.css"
/>
</template>
</zero-md>
```
### Using your own styles
To override the default theme, supply your own style template.
```html
<zero-md src="https://example.com/markdown.md">
<!-- Wrap with a <template> tag -->
<template>
<!-- Define your own styles inside a `<style>` tag -->
<style>
h1 {
color: red;
}
...;
</style>
</template>
</zero-md>
```
### Or your own stylesheets
```html
<zero-md src="https://example.com/markdown.md">
<!-- Wrap with a <template> tag -->
<template>
<!-- Load external stylesheets with a `<link rel="stylesheet">` tag -->
<link rel="stylesheet" href="markdown-styles.css" />
<link rel="stylesheet" href="highlight-styles.css" />
</template>
</zero-md>
```
### Or both
```html
<zero-md src="https://example.com/markdown.md">
<template>
<!-- The CSS load order is respected -->
<link rel="stylesheet" href="markdown-styles.css" />
<style>
h1 {
color: red;
}
</style>
<link rel="stylesheet" href="highlight-styles.css" />
<style>
code {
background: yellow;
}
</style>
</template>
</zero-md>
```
### Write markdown inline
You can pass in your markdown inline too.
```html
<!-- Do not set the `src` attribute -->
<zero-md>
<!-- Write your markdown inside a `<script type="text/markdown">` tag -->
<script type="text/markdown">
# **This** is my [markdown](https://example.com)
</script>
</zero-md>
```
By default, `<zero-md>` first tries to render `src`. If `src` is falsy (undefined, file not found,
empty file etc), it **falls-back** to the contents inside the `<script type="text/markdown">` tag.
### Put it all together
```html
<zero-md src="https://example.com/markdown.md">
<template>
<link rel="stylesheet" href="markdown-styles.css" />
<style>
h1 {
color: red;
}
</style>
<link rel="stylesheet" href="highlight-styles.css" />
<style>
code {
background: yellow;
}
</style>
</template>
<script type="text/markdown">
This is the fall-back markdown that will **only show** when `src` is falsy.
</script>
</zero-md>
```
## API
Advanced usage: https://zerodevx.github.io/zero-md/advanced-usage/
Attributes and helpers: https://zerodevx.github.io/zero-md/attributes-and-helpers/
Configuration: https://zerodevx.github.io/zero-md/configuration/
## Migrating from V1 to V2
1. Support for `<xmp>` tag is removed; use `<script type="text/markdown">` instead.
<!-- prettier-ignore -->
```html
<!-- Previous -->
<zero-md>
<template>
<xmp>
# `This` is my [markdown](example.md)
</xmp>
</template>
</zero-md>
<!-- Now -->
<zero-md>
<!-- No need to wrap with <template> tag -->
<script type="text/markdown">
# `This` is my [markdown](example.md)
</script>
</zero-md>
<!-- If you need your code to be pretty, -->
<zero-md>
<!-- Set `data-dedent` to opt-in to dedent the text during render -->
<script type="text/markdown" data-dedent>
# It is important to be pretty
So having spacing makes me happy.
</script>
</zero-md>
```
2. Markdown source behaviour has changed. Think of `<script type="text/markdown">` as a "fallback".
<!-- prettier-ignore -->
```html
<!-- Previous -->
<zero-md src="will-not-render.md">
<template>
<xmp>
# This has first priority and will be rendered instead of `will-not-render.md`
</xmp>
</template>
<zero-md>
<!-- Now -->
<zero-md src="will-render-unless-falsy.md">
<script type="text/markdown">
# This will NOT be rendered _unless_ `src` resolves to falsy
</script>
</zero-md>
```
3. The `css-urls` attribute is deprecated. Use `<link rel="stylesheet">` instead.
<!-- prettier-ignore -->
```html
<!-- Previous -->
<zero-md src="example.md" css-urls='["/style1.css", "/style2.css"]'><zero-md>
<!-- Now, this... -->
<zero-md src="example.md"></zero-md>
<!-- ...is actually equivalent to this -->
<zero-md src="example.md">
<template>
<!-- These are the default stylesheets -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/sindresorhus/github-markdown-css@4/github-markdown.min.css"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/PrismJS/prism@1/themes/prism.min.css"
/>
</template>
</zero-md>
<!-- So, to apply your own external stylesheets... -->
<zero-md src="example.md">
<!-- ...you overwrite the default template -->
<template>
<!-- Use <link> tags to reference your own stylesheets -->
<link rel="stylesheet" href="/style1.css" />
<link rel="stylesheet" href="/style2.css" />
<!-- You can even apply additional styles -->
<style>
p {
color: red;
}
</style>
</template>
</zero-md>
<!-- If you like the default stylesheets but wish to apply some overrides -->
<zero-md src="example.md">
<!-- Set `data-merge` to "append" to apply this template AFTER the default template -->
<!-- Or "prepend" to apply this template BEFORE -->
<template data-merge="append">
<style>
p {
color: red;
}
</style>
</template>
</zero-md>
```
4. The attributes `marked-url` and `prism-url` are deprecated. To load `marked` or `prism` from
another location, simply load their scripts _before_ importing `zero-md`.
```html
<head>
...
<script defer src="/lib/marked.js"></script>
<script defer src="/lib/prism.js"></script>
<script type="module" src="/lib/zero-md.min.js"></script>
</head>
```
5. The global config object has been renamed from `ZeroMd.config` to `ZeroMdConfig`.
```html
<!-- Previous -->
<script src="/node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
<script>
window.ZeroMd = {
config: {
cssUrls: ['/styles/my-markdown-theme.css', '/styles/my-highlight-theme.css']
}
}
</script>
<script
type="module"
src="https://cdn.jsdelivr.net/gh/zerodevx/zero-md@1/src/zero-md.min.js"
></script>
<!-- Now -->
<script>
window.ZeroMdConfig = {
cssUrls: ['/styles/my-markdown-theme.css', '/styles/my-highlight-theme.css']
}
</script>
<script
type="module"
src="https://cdn.jsdelivr.net/gh/zerodevx/zero-md@2/dist/zero-md.min.js"
></script>
```
6. The convenience events `zero-md-marked-ready` and `zero-md-prism-ready` are removed and **will no
longer fire**. Instead, the `zero-md-ready` event guarantees that everything is ready, and that
render can begin.
## Contributing
### Noticed a bug? Have a feature request?
Open a new [issue](https://github.com/zerodevx/zero-md/issues) in the Github repo, or raise a
[PR](https://github.com/zerodevx/zero-md/pulls)! I'd be stoked to accept any contributions!
### Development
Standard Github [contribution workflow](https://github.com/firstcontributions/first-contributions)
applies.
#### Run the dev server
```
$ npm run dev
```
Point your browser to `http://localhost:8000` and you should see the test suite running.
#### Testing
Tests are browser-based and run on [Mocha](https://mochajs.org/) with
[Chai](https://www.chaijs.com/) asserts. If you're adding a new feature or bugfixing, please add the
corresponding regression test into `test/index.spec.js` accordingly.
#### Format and lint
```
$ npm run format
$ npm run lint
```
Formatting and linting by [prettier](https://github.com/prettier/prettier) and
[eslint](https://github.com/eslint/eslint) respectively.
#### Making changes to docs
Documentation is in the `/docs` folder in the form of `readme.md` files, and published on
[Github Pages](https://pages.github.com/). This setup is based on
[`zero-md-docs`](https://github.com/zerodevx/zero-md-docs).
To make changes to docs, simply raise a PR on any `readme.md` files should suffice.
## Changelog
Check out the [releases](https://github.com/zerodevx/zero-md/releases) page.
## License
ISC
## Acknowledgement
A big thank you to the following contributors and sponsors! :pray:
### Contributors
<!-- prettier-ignore -->
<kbd>[<img src="https://github.com/alifeee.png" width="60px;"/>](https://github.com/alifeee)</kbd> <kbd>[<img src="https://github.com/EmilePerron.png" width="60px;"/>](https://github.com/EmilePerron)</kbd> <kbd>[<img src="https://github.com/bennypowers.png" width="60px;"/>](https://github.com/bennypowers)</kbd> <kbd>[<img src="https://github.com/TheUnlocked.png" width="60px;"/>](https://github.com/TheUnlocked)</kbd> <kbd>[<img src="https://github.com/ernsheong.png" width="60px;"/>](https://github.com/ernsheong)</kbd>
### Sponsors
<!-- prettier-ignore -->
<kbd>[<img src="https://github.com/RootofalleviI.png" width="60px;"/>](https://github.com/RootofalleviI)</kbd><kbd>[<img src="https://github.com/alifeee.png" width="60px;"/>](https://github.com/alifeee)</kbd>

2
node_modules/zero-md/dist/zero-md.legacy.min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

1
node_modules/zero-md/dist/zero-md.legacy.min.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

2
node_modules/zero-md/dist/zero-md.min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

1
node_modules/zero-md/dist/zero-md.min.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

53
node_modules/zero-md/package.json generated vendored Normal file
View file

@ -0,0 +1,53 @@
{
"name": "zero-md",
"version": "2.5.4",
"description": "Ridiculously simple zero-config markdown displayer",
"author": "Jason Lee <jason@zerodevx.com>",
"type": "module",
"exports": "./src/index.js",
"scripts": {
"dev": "rollup -c -w",
"format": "prettier --write --ignore-path=.prettierignore .",
"lint": "prettier --check --ignore-path=.prettierignore . && eslint .",
"test": "npm run dev",
"build": "rollup -c",
"prepublishOnly": "npm run format && npm run lint && npm run build",
"docs:build": "zero-md-docs && sscli -b https://zerodevx.github.io/zero-md/ -r docs -i 'v1/**' --slash"
},
"devDependencies": {
"@babel/core": "^7.23.9",
"@babel/preset-env": "^7.23.9",
"@rollup/plugin-babel": "^6.0.4",
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-replace": "^5.0.5",
"@rollup/plugin-terser": "^0.4.4",
"chai": "^4.4.1",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"mocha": "^10.3.0",
"prettier": "^3.2.5",
"rollup": "^3.29.4",
"rollup-plugin-livereload": "^2.0.5",
"rollup-plugin-serve": "^2.0.3",
"static-sitemap-cli": "^2.2.3",
"zero-md-docs": "^0.1.8"
},
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"files": [
"src/",
"dist/"
],
"license": "ISC",
"repository": "github:zerodevx/zero-md",
"homepage": "https://zerodevx.github.io/zero-md/",
"keywords": [
"webcomponents",
"customelements",
"markdown-to-html",
"marked",
"prism"
]
}

353
node_modules/zero-md/src/index.js generated vendored Normal file
View file

@ -0,0 +1,353 @@
export class ZeroMd extends HTMLElement {
get src() {
return this.getAttribute('src')
}
set src(val) {
this.reflect('src', val)
}
get manualRender() {
return this.hasAttribute('manual-render')
}
set manualRender(val) {
this.reflect('manual-render', val)
}
reflect(name, val) {
if (val === false) {
this.removeAttribute(name)
} else {
this.setAttribute(name, val === true ? '' : val)
}
}
static get observedAttributes() {
return ['src']
}
attributeChangedCallback(name, old, val) {
if (name === 'src' && this.connected && !this.manualRender && val !== old) {
this.render()
}
}
constructor(defaults) {
super()
this.version = '$VERSION'
this.config = {
markedUrl: 'https://cdn.jsdelivr.net/gh/markedjs/marked@4/marked.min.js',
prismUrl: [
['https://cdn.jsdelivr.net/gh/PrismJS/prism@1/prism.min.js', 'data-manual'],
'https://cdn.jsdelivr.net/gh/PrismJS/prism@1/plugins/autoloader/prism-autoloader.min.js'
],
cssUrls: [
'https://cdn.jsdelivr.net/gh/sindresorhus/github-markdown-css@4/github-markdown.min.css',
'https://cdn.jsdelivr.net/gh/PrismJS/prism@1/themes/prism.min.css'
],
hostCss:
':host{display:block;position:relative;contain:content;}:host([hidden]){display:none;}',
...defaults,
...window.ZeroMdConfig
}
this.root = this.hasAttribute('no-shadow') ? this : this.attachShadow({ mode: 'open' })
this.root.prepend(
...this.makeNodes(`<div class="markdown-styles"></div><div class="markdown-body"></div>`)
)
if (!this.constructor.ready) {
this.constructor.ready = Promise.all([
!!window.marked || this.loadScript(this.config.markedUrl),
!!window.Prism || this.loadScript(this.config.prismUrl)
])
}
this.clicked = this.clicked.bind(this)
if (!this.manualRender) {
// Scroll to hash id after first render. However, `history.scrollRestoration` inteferes with this
// on refresh. It's much better to use a `setTimeout` rather than to alter the browser's behaviour.
this.render().then(() => setTimeout(() => this.goto(location.hash), 250))
}
this.observer = new MutationObserver(() => {
this.observeChanges()
if (!this.manualRender) this.render()
})
this.observer.observe(this, { childList: true })
this.observeChanges()
}
/**
* Start observing changes, if not already so, in `template` and `script`.
*/
observeChanges() {
this.querySelectorAll('template,script[type="text/markdown"]').forEach((n) => {
this.observer.observe(n.content || n, {
childList: true,
subtree: true,
attributes: true,
characterData: true
})
})
}
connectedCallback() {
this.connected = true
this.fire('zero-md-connected', {}, { bubbles: false, composed: false })
this.waitForReady().then(() => {
this.fire('zero-md-ready')
})
if (this.shadowRoot) {
this.shadowRoot.addEventListener('click', this.clicked)
}
}
disconnectedCallback() {
this.connected = false
if (this.shadowRoot) {
this.shadowRoot.removeEventListener('click', this.clicked)
}
}
waitForReady() {
const ready =
this.connected ||
new Promise((resolve) => {
this.addEventListener('zero-md-connected', function handler() {
this.removeEventListener('zero-md-connected', handler)
resolve()
})
})
return Promise.all([this.constructor.ready, ready])
}
fire(name, detail = {}, opts = { bubbles: true, composed: true }) {
if (detail.msg) {
console.warn(detail.msg)
}
this.dispatchEvent(
new CustomEvent(name, {
detail: { node: this, ...detail },
...opts
})
)
}
tick() {
return new Promise((resolve) => requestAnimationFrame(resolve))
}
// Coerce anything into an array
arrify(any) {
return any ? (Array.isArray(any) ? any : [any]) : []
}
// Promisify an element's onload callback
onload(node) {
return new Promise((resolve, reject) => {
node.onload = resolve
node.onerror = (err) => reject(err.path ? err.path[0] : err.composedPath()[0])
})
}
// Load a url or load (in order) an array of urls via <script> tags
loadScript(urls) {
return Promise.all(
this.arrify(urls).map((item) => {
const [url, ...attrs] = this.arrify(item)
const el = document.createElement('script')
el.src = url
el.async = false
attrs.forEach((attr) => el.setAttribute(attr, ''))
return this.onload(document.head.appendChild(el))
})
)
}
// Scroll to selected element
goto(sel) {
let el
try {
el = this.root.querySelector(sel)
} catch {}
if (el) el.scrollIntoView()
}
// Hijack same-doc anchor hash links
clicked(ev) {
if (ev.metaKey || ev.ctrlKey || ev.altKey || ev.shiftKey || ev.defaultPrevented) {
return
}
const a = ev.target.closest('a')
if (a && a.hash && a.host === location.host && a.pathname === location.pathname) {
this.goto(a.hash)
}
}
dedent(str) {
str = str.replace(/^\n/, '')
const match = str.match(/^\s+/)
return match ? str.replace(new RegExp(`^${match[0]}`, 'gm'), '') : str
}
getBaseUrl(src) {
const a = document.createElement('a')
a.href = src
return a.href.substring(0, a.href.lastIndexOf('/') + 1)
}
// Runs Prism highlight async; falls back to sync if Web Workers throw
highlight(container) {
return new Promise((resolve) => {
const unhinted = container.querySelectorAll('pre>code:not([class*="language-"])')
unhinted.forEach((n) => {
// Dead simple language detection :)
const lang = n.innerText.match(/^\s*</)
? 'markup'
: n.innerText.match(/^\s*(\$|#)/)
? 'bash'
: 'js'
n.classList.add(`language-${lang}`)
})
try {
window.Prism.highlightAllUnder(container, true, resolve())
} catch {
window.Prism.highlightAllUnder(container)
resolve()
}
})
}
/**
* Converts HTML string into HTMLCollection of nodes
* @param {string} html
* @returns {HTMLCollection}
*/
makeNodes(html) {
const tpl = document.createElement('template')
tpl.innerHTML = html
return tpl.content.children
}
/**
* Constructs the styles dom and returns HTML string
* @returns {string} `markdown-styles` string
*/
buildStyles() {
const get = (query) => {
const node = this.querySelector(query)
return node ? node.innerHTML || ' ' : ''
}
const urls = this.arrify(this.config.cssUrls)
const html = `<style>${this.config.hostCss}</style>${get('template[data-merge="prepend"]')}${
get('template:not([data-merge])') ||
urls.reduce((a, c) => `${a}<link rel="stylesheet" href="${c}">`, '')
}${get('template[data-merge="append"]')}`
return html
}
/**
* Constructs the markdown body nodes and returns HTML string
* @param {*} opts Markedjs options
* @returns {Promise<string>} `markdown-body` string
*/
async buildMd(opts = {}) {
const src = async () => {
if (!this.src) return ''
const resp = await fetch(this.src)
if (resp.ok) {
const md = await resp.text()
return window.marked.parse(md, {
baseUrl: this.getBaseUrl(this.src),
...opts
})
} else {
this.fire('zero-md-error', {
msg: `[zero-md] HTTP error ${resp.status} while fetching src`,
status: resp.status,
src: this.src
})
return ''
}
}
const script = () => {
const el = this.querySelector('script[type="text/markdown"]')
if (!el) return ''
const md = el.hasAttribute('data-dedent') ? this.dedent(el.text) : el.text
return window.marked.parse(md, opts)
}
return (await src()) || script()
}
/**
* Returns 32-bit DJB2a hash in base36
* @param {string} str
* @returns {string}
*/
getHash(str) {
let hash = 5381
for (let index = 0; index < str.length; index++) {
hash = ((hash << 5) + hash) ^ str.charCodeAt(index)
}
return (hash >>> 0).toString(36)
}
/**
* Insert or replace styles node in root from a HTML string. If there are external stylesheet
* links, wait for them to load.
* @param {string} html styles string
* @returns {Promise<boolean|undefined>} returns true if stamped
*/
async stampStyles(html) {
const hash = this.getHash(html)
const target = this.root.querySelector('.markdown-styles')
if (target.getAttribute('data-hash') !== hash) {
target.setAttribute('data-hash', hash)
const nodes = this.makeNodes(html)
const links = [...nodes].filter(
(i) => i.tagName === 'LINK' && i.getAttribute('rel') === 'stylesheet'
)
target.innerHTML = ''
target.append(...nodes)
await Promise.all(links.map((l) => this.onload(l))).catch((err) => {
this.fire('zero-md-error', {
msg: '[zero-md] An external stylesheet failed to load',
status: undefined,
src: err.href
})
})
return true
}
}
/**
* Insert or replace HTML body string into DOM
* @param {string} html markdown-body string
* @param {string[]} [classes] list of classes to apply to `.markdown-body` wrapper
* @returns {Promise<boolean|undefined>} returns true if stamped
*/
async stampBody(html, classes) {
const names = this.arrify(classes)
const hash = this.getHash(html + JSON.stringify(names))
const target = this.root.querySelector('.markdown-body')
if (target.getAttribute('data-hash') !== hash) {
target.setAttribute('data-hash', hash)
names.unshift('markdown-body')
target.setAttribute('class', names.join(' '))
const nodes = this.makeNodes(html)
target.innerHTML = ''
target.append(...nodes)
await this.highlight(target)
return true
}
}
async render(opts = {}) {
await this.waitForReady()
const pending = this.buildMd(opts)
const styles = await this.stampStyles(this.buildStyles())
await this.tick()
const body = await this.stampBody(await pending, opts.classes)
this.fire('zero-md-rendered', { node: this, stamped: { styles, body } })
}
}
customElements.define('zero-md', ZeroMd)