Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert ERB octicon() helpers to inline SVG on the fly #847

Merged
merged 17 commits into from
Aug 7, 2019
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions lib/erb-to-html.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/* eslint-disable no-console */
const visit = require('unist-util-visit')
const cache = new Map()
const ERB_BLOCK_PATTERN = /<%=[^%]+%>/g

module.exports = options => {
const convert = converter(options)
return tree => {
visit(tree, 'code', node => {
const match = node.lang ? node.lang.match(/^[a-z]+/) : null
const lang = match ? match[0] : null
if (lang === 'erb' || lang === 'html') {
const erb = node.value
const html = convert(erb)
const remaining = html ? html.match(ERB_BLOCK_PATTERN) : null
if (html && !remaining) {
node.value = html
node.lang = node.lang.replace(/^erb/, 'html')
} else if (remaining) {
console.warn(`Unable to convert ${remaining.length} ERB blocks:\n ${remaining.join(' \n')}`)
} else {
// console.warn(`No conversions made in: ${erb}`)
}
} else {
console.warn(`Unknown code block lang: ${node.lang}`)
}
})
}
}

function converter({methods = {}}) {
return erb => {
const blocks = erb.match(ERB_BLOCK_PATTERN)
if (blocks && blocks.length) {
let html = erb
console.warn(`Replacing ${blocks.length} ERB block(s)...`)
for (const block of blocks) {
const output = convert(block)
if (output !== block) {
const count = html.split(block).length - 1
console.warn(` found ${count} instances of "${block}"`)
html = replaceAll(html, block, output)
console.warn(html)
}
}
return html
}
}

function convert(block) {
if (cache.has(block)) {
return cache.get(block)
}

// eslint-disable-next-line no-unused-vars
const [_, method, argString] = block.match(/<%= *(\w+)[ (]([^)]+)\)? *%>/)
const parts = argString.split(/, */)
const args = []
const kwargs = {}
let match
for (const part of parts) {
if ((match = part.match(/^:(.+) => (.+)$/))) {
kwargs[unquote(match[1])] = unquote(match[2])
} else if ((match = part.match(/^(.+): (.+)$/))) {
kwargs[unquote(match[1])] = unquote(match[2])
} else {
args.push(unquote(part))
}
}

if (typeof methods[method] === 'function') {
let output = methods[method](args, kwargs)
console.warn(`converted: ${block} -> ${output}`)
const escaped = block.replace('<', '').replace('>', '')
output = `<!--${escaped}-->\n${output}`
cache.set(block, output)
return output
} else {
console.warn(`No such ERB method implemented: "${method}"`)
return block
}
}
}

function replaceAll(str, input, output) {
return str.split(input).join(output)
}

function unquote(str) {
return str.replace(/^\s*"([^"]+)"\s*$/, (_, value) => value)
}
27 changes: 26 additions & 1 deletion lib/mdx-loader.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
const {getOptions} = require('loader-utils')
const mdx = require('@mdx-js/mdx')
const octicons = require('@primer/octicons')

const emoji = require('remark-emoji')
const images = require('remark-images')
const rehypePrism = require('./rehype-prism')
const textr = require('remark-textr')
const toc = require('remark-toc')
const erbToHTML = require('./erb-to-html')

const mdxExportJSONByDefault = require('mdx-constant')
const grayMatter = require('gray-matter')
Expand All @@ -22,7 +24,30 @@ module.exports = async function(source) {
[toc, {heading: '(table of|section)? contents'}],
images,
emoji,
[textr, {plugins: [typographicBase]}]
[textr, {plugins: [typographicBase]}],
[
erbToHTML,
{
methods: {
octicon: ([icon], attrs) => {
if (octicons[icon]) {
return octicons[icon].toSVG(attrs)
} else {
throw new Error(`No such octicon: "${icon}"`)
}
},
// eslint-disable-next-line camelcase
avatar_for: ([username, size], kwargs) => {
const name = username === 'current_user' ? 'github' : username
const attrs = Object.entries(kwargs)
.map(([key, value]) => ` ${key}="${value}"`)
.join(' ')
const s = size * 2
return `<img src="https://github.com/${name}.png?s=${s}" width="${size}" height="${size}"${attrs}>`
}
}
}
]
],
hastPlugins: [rehypePrism],
compilers: [mdxExportJSONByDefault('frontMatter', data)]
Expand Down
Loading