dotfiles/build/util.js

97 lines
2.8 KiB
JavaScript

const convert = require( 'color-convert' );
const fs = require( 'fs' );
const path = require( 'path' );
/**
* Recursively find all files with extension in a directory
* @param {string} dir The directory to search. Either absolute or relative path
* @param {string} extension The file extension to look for
* @returns {string[]} returns a list of html files with their full path
*/
const treeWalker = ( dir, extension, ignoreList ) => {
const ls = fs.readdirSync( dir );
const fileList = [];
for ( let file in ls ) {
if ( fs.statSync( path.join( dir, ls[ file ] ) ).isDirectory() ) {
// Filter ignored directories
if ( ignoreList === undefined || !ignoreList.includes( ls[ file ] ) ) {
const newFiles = treeWalker( path.join( dir, ls[ file ] ), extension, ignoreList );
for (let file = 0; file < newFiles.length; file++) {
fileList.push( newFiles[ file ] );
}
}
} else if ( extension == '*' || ls[ file ].includes( extension ) ) {
if ( ignoreList === undefined || !ignoreList.includes( ls[ file ] ) ) {
fileList.push( path.join( dir, ls[ file ] ) );
}
}
}
return fileList;
}
const renderColourAsHex = ( colour ) => {
return '#' + convert.default.rgb.hex( colour[ 0 ], colour[ 1 ], colour[ 2 ] );
}
const renderColourAsRGB = ( colour ) => {
return `rgb( ${ colour[ 0 ] }, ${ colour[ 1 ] }, ${ colour[ 2 ] } )`
}
const renderColourAsRGBA = ( colour, ambiance ) => {
return `rgba( ${ colour[ 0 ] }, ${ colour[ 1 ] }, ${ colour[ 2 ] }, ${ ambiance } )`
}
/*
* Replace the colours with variable names
* #000 = @bg
* #111 = @bg_accent
* #222 = @bg_inactive
* #555A = @shadow_rgba
* #555 = @shadow
* #F00 = @accent
* #0F0 = @accent2
* #00F = @accent3
* #AAA = @inactive
* #FFF = @fg
*/
const replacements = {
'#000': '@bg',
'#111': '@bg_accent',
'#222': '@bg_inactive',
'#555A': '@shadow_rgba',
'#555': '@shadow',
'#F00': '@accent',
'#0F0': '@accent2',
'#00F': '@accent3',
'#AAA': '@inactive',
'#FFF': '@fg'
};
const themePreProcessor = ( file, replacement ) => {
const colours = Object.keys( replacements );
let data = '' + fs.readFileSync( file );
for (let index = 0; index < colours.length; index++) {
const colour = colours[index];
data = data.replaceAll(colour, replacements[ colour ]);
}
const outPath = file.replace( replacement, 'temp' );
try {
fs.mkdirSync( path.dirname( outPath ), {
recursive: true,
} );
} catch ( e ) {
console.error( e );
}
fs.writeFileSync( outPath, data );
}
module.exports = {
treeWalker,
renderColourAsHex,
renderColourAsRGB,
renderColourAsRGBA,
themePreProcessor
}