gatsby-remark-jh-inline-svg
Advanced tools
Comparing version
48
index.js
@@ -6,32 +6,36 @@ const visit = require('unist-util-visit') | ||
const fetchImage = url => { | ||
return fs.readFileSync(path.join(__dirname, '../..', `/public${url}`), 'utf8') | ||
return fs.readFileSync(path.join(__dirname, '../..', `/public${url}`), 'utf8') | ||
} | ||
module.exports = ({ markdownAST }, pluginOptions) => { | ||
visit(markdownAST, 'image', (node) => { | ||
const { url, alt, title } = node | ||
visit(markdownAST, 'image', (node) => { | ||
const { url, alt, title } = node | ||
if (url.endsWith('.svg')) { | ||
let html = fetchImage(url) | ||
if (url.endsWith('.svg')) { | ||
let html = fetchImage(url) | ||
if (pluginOptions.colors) { | ||
Object.entries(pluginOptions.colors).forEach(([color, replacement]) => { | ||
const re = new RegExp(color, "g") | ||
html = html.replace(re, replacement) | ||
}) | ||
} | ||
if (pluginOptions.colors) { | ||
Object.entries(pluginOptions.colors).forEach(([color, replacement]) => { | ||
const re = new RegExp(color, 'g') | ||
html = html.replace(re, replacement) | ||
}) | ||
} | ||
if (alt) html = html.replace(/<title>.*<\/title>/, `<title>${alt}</title>`); | ||
const svgAttrsRe = new RegExp(/<svg(.*)>/) | ||
const [, svgAttrs] = html.match(svgAttrsRe) | ||
if (alt) html = html | ||
.replace(/<title>.*<\/title>/, `<title>${alt}</title>`) | ||
.replace(svgAttrs, `${svgAttrs} role="img"`) | ||
if (html) { | ||
node.type = 'html' | ||
node.value = `<figure> | ||
${html.trim()} | ||
${title ? `<figcaption>${title}</figcaption>` : ''} | ||
</figure>` | ||
} | ||
} | ||
}) | ||
if (html) { | ||
node.type = 'html' | ||
node.value = `<figure> | ||
${html.trim()} | ||
${title ? `<figcaption>${title}</figcaption>` : ''} | ||
</figure>` | ||
} | ||
} | ||
}) | ||
return markdownAST | ||
return markdownAST | ||
} |
{ | ||
"name": "gatsby-remark-jh-inline-svg", | ||
"version": "0.1.1", | ||
"version": "0.1.2", | ||
"description": "Gatsby plugin to inline SVGs in Jonathan Harrell's site", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
2524
9.93%33
13.79%