Optimize CSS parser

This commit is contained in:
Mimi 2022-02-07 11:27:05 +08:00
parent 6fd36d9ab4
commit 2094a764d6

View File

@ -2,6 +2,7 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const css = require('css');
function resolve(name, file = '') { function resolve(name, file = '') {
let dir; let dir;
@ -15,20 +16,17 @@ function resolve(name, file = '') {
function highlightTheme(name) { function highlightTheme(name) {
const file = resolve('highlight.js', `styles/${name}.css`); const file = resolve('highlight.js', `styles/${name}.css`);
const css = fs.readFileSync(file).toString(); const content = fs.readFileSync(file, 'utf8');
let rule = '';
let background = ''; let background = '';
let foreground = ''; let foreground = '';
css.replace(/\.hljs(\s+|,[^{]+)\{(.*?)\}/sg, (match, $1, content) => { css.parse(content).stylesheet.rules
rule += content; .filter(rule => rule.type === 'rule' && rule.selectors.some(selector => selector.endsWith('.hljs')))
return match; .flatMap(rule => rule.declarations)
}); .forEach(declaration => {
const parse = (line, attr) => line.split(attr)[1].replace(';', '').trim(); if (declaration.property === 'background' || declaration.property === 'background-color') background = declaration.value;
rule.split('\n').forEach(line => { else if (declaration.property === 'color') foreground = declaration.value;
if (line.includes('background:')) background = parse(line, 'background:'); });
else if (line.includes('background-color:')) background = parse(line, 'background-color:');
else if (line.includes('color:')) foreground = parse(line, 'color:');
});
return { return {
file, file,
background, background,