Skip to content

Instantly share code, notes, and snippets.

@Rarst
Last active April 28, 2020 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rarst/aed61335fc68694a84f0a1131a4ef5fd to your computer and use it in GitHub Desktop.
Save Rarst/aed61335fc68694a84f0a1131a4ef5fd to your computer and use it in GitHub Desktop.
Automagically add Tailwind–like CSS from Frontend Mentor style guide files. https://www.frontendmentor.io/
fetch('style-guide.md')
.then((response) => {
return response.text();
})
.then((markdown) => {
parseMarkdown(markdown)
});
function parseMarkdown(markdown) {
let css = '';
const colors = parseColors(markdown);
colors.forEach(color => {
css += `.text-${color.cssName} { color: ${color.value} }
.bg-${color.cssName} { background-color: ${color.value} }
.border-${color.cssName} { border-color: ${color.value} }\n`;
})
const fonts = parseFonts(markdown);
fonts.forEach(font => {
let urlSafeName = font.name.replace(/ /g, '+');
let weights = font.weights.join(';');
let url = `https://fonts.googleapis.com/css2?family=${urlSafeName}:wght@${weights}&display=swap`;
addStyleLink(url);
css += `.font-${font.cssName} { font-family: '${font.name}' }\n`;
});
addStyleTag(css);
}
function parseColors(markdown) {
const colorRegex = /-\s*(?<name>[\s\w]+)\s*:\s*(?<value>hsl\(.+\))/g;
let colors = markdown.matchAll(colorRegex);
let output = [];
for (let {groups: {name, value}} of colors) {
output.push({name, cssName: parseColorName(name), value});
}
return output;
}
function parseColorName(colorName) {
colorName = colorName.toLowerCase();
let parts = colorName.split(' ');
if (2 > parts.length) {
return colorName;
}
parts.unshift(parts.pop())
return parts.join('-');
}
function parseFonts(markdown) {
const fontRegex = /Family\s*:\s*\[(?<name>[\s\w]+)].+?Weights:\s*(?<weights>[\s\d,]+)/gms;
let fonts = markdown.matchAll(fontRegex);
let output = [];
for (let {groups: {name, weights}} of fonts) {
let cssName = name.toLowerCase().replace(/ /g, '-');
weights = weights.replace(/\s/g, '').split(',');
output.push({name, cssName, weights});
}
return output;
}
function addStyleTag(css) {
let style = document.createElement('style');
style["type"] = 'text/css';
style.innerHTML = css;
document.getElementsByTagName('head')[0].appendChild(style);
}
function addStyleLink(url) {
let link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', url);
document.getElementsByTagName('head')[0].appendChild(link);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment