forked from Chalarangelo/30-seconds-of-css
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.js
70 lines (60 loc) · 2.24 KB
/
build.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const fs = require('fs')
const path = require('path')
const marked = require('marked')
const pretty = require('pretty')
const { JSDOM } = require('jsdom')
const caniuseDb = require('caniuse-db/data.json')
const { toKebabCase, emptyHTML } = require('../utils/utils.js')
const renderer = new marked.Renderer()
renderer.heading = (text, level) =>
level === 3
? `<h${level} id="${toKebabCase(text)}">${text}</h${level}>`
: `<h${level} data-type="${text}">${text}</h${level}>`
renderer.link = (url, _, text) => `<a href="${url}" target="_blank">${text || url}</a>`
const SNIPPETS_PATH = './snippets'
const SNIPPET_CONTAINER_SELECTOR = '.main > .container'
const createElement = str => {
const el = document.createElement('div')
el.innerHTML = str
return el.firstElementChild
}
const template = markdown => `
<div class="snippet">
${markdown}
</div>
`
const document = new JSDOM(fs.readFileSync('./index.html', 'utf8')).window.document
const snippetContainer = document.querySelector('.main > .container')
const sidebarLinks = document.querySelector('.sidebar__links')
emptyHTML(snippetContainer, sidebarLinks)
for (const snippetFile of fs.readdirSync(SNIPPETS_PATH)) {
const snippetPath = path.join(SNIPPETS_PATH, snippetFile)
const snippetData = fs.readFileSync(snippetPath, 'utf8')
const markdown = marked(snippetData, { renderer })
const snippetTemplate = template(markdown)
const el = createElement(snippetTemplate)
snippetContainer.append(el)
sidebarLinks.append(
createElement(
`<a class="sidebar__link" href="#${snippetFile.replace('.md', '')}">${
el.querySelector('h3').innerHTML
}</a>`
)
)
const featUsageShares = (snippetData.match(/https?:\/\/caniuse\.com\/#feat=.*/g) || []).map(
feat => {
const featData = caniuseDb.data[feat.match(/#feat=(.*)/)[1]]
return featData ? Number(featData.usage_perc_y + featData.usage_perc_a) : 100
}
)
el.querySelector('h4:last-of-type').after(
createElement(`
<div>
<div class="snippet__browser-support">
${featUsageShares.length ? Math.min(...featUsageShares).toPrecision(3) : '99+'}%
</div>
</div>
`)
)
}
fs.writeFileSync('./index.html', pretty(document.documentElement.outerHTML, { ocd: true }))