File size: 9,174 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 |
#!/usr/bin/env node
/**
* The script looks for all colors used in the SVG images found in the repository
* and suggests Color Studio replacements for all non-standard values it finds.
*
* Please note that the suggestions are automatic and therefore not perfect
* in some edge cases. Make sure to manually review the files you edit.
*
* List all non-standard color values by image path:
* $ node ./bin/audit-svg-colors.js
*/
const { execSync } = require( 'child_process' );
const { readFileSync } = require( 'fs' );
const path = require( 'path' );
const PALETTE = require( '@automattic/color-studio' );
const chroma = require( 'chroma-js' );
/**
* Native Sort - replacement of _.sortBy Lodash function
* @returns Sorted array.
*/
const compareByName = ( objA, objB ) => {
if ( objA.to.name > objB.to.name ) {
return 1;
} else if ( objB.to.name > objA.to.name ) {
return -1;
}
return 0;
};
/**
* Palette color subsets
*/
/**
* pickBy function is a replacement for the Lodash _.pickby
*
*/
const pickBy = ( palette, fn ) =>
Object.keys( palette ?? {} )
.filter( ( key ) => fn( palette[ key ], key ) )
.reduce( ( acc, key ) => ( ( acc[ key ] = palette[ key ] ), acc ), {} );
// The subset of palette colors allowed in illustrations
const PALETTE_ILLUSTRATION_COLORS = pickBy( PALETTE.colors, ( colorValue, colorName ) => {
// Avoid using pure black
if ( colorValue === '#000' ) {
return;
}
// Avoid specific colors for illustration use
return ! colorName.startsWith( 'Simplenote Blue' );
} );
// The subset of palette colors used in app-related images is slightly wider
// than what we allow for in illustration use (the above)
const PALETTE_APP_COLORS = pickBy( PALETTE.colors, ( colorValue, colorName ) => {
// Avoid using pure black
if ( colorValue === '#000' ) {
return;
}
// Don’t use brand colors for any WordPress.com app images
return ! (
colorName.startsWith( 'Simplenote Blue' ) ||
colorName.startsWith( 'WooCommerce Purple' ) ||
colorName.startsWith( 'WordPress Blue' )
);
} );
// Making sure both sets contain only unique color values
// (the palette defines aliases for some colors)
const PALETTE_ILLUSTRATION_COLOR_VALUES = [
...new Set( Object.values( PALETTE_ILLUSTRATION_COLORS ) ),
];
const PALETTE_APP_COLOR_VALUES = [ ...new Set( Object.values( PALETTE_APP_COLORS ) ) ];
/**
* SVG image rules
*/
// The image paths that match the following patterns will not be processed
const SVG_IGNORE_PATHS = [
// Logos found in the repository
/(?:billcom|canva|evernote|facebook-messenger|fiverr|google-photos|monday|paypal|quickbooks|sendinblue|stripe|todoist|vaultpress)(-logo)?\.svg$/,
/images\/g-suite\/logo_/,
/images\/email-providers\/google-workspace/,
// Illustrations that contain logos
/images\/customer-home\/illustration--task-connect-social-accounts.svg/,
// Credit card and payment gateway logos (the disabled versions are allowed)
/upgrades\/cc-(?:amex|diners|discover|jcb|mastercard|unionpay|visa)\.svg$/,
/upgrades\/(?:alipay|bancontact|emergent-paywall|eps|ideal|netbanking|p24|paypal|paytm|sofort|tef|wechat|razorpay)/,
// Color scheme thumbnails that rely on .org colors
/color-scheme-thumbnail-(?:blue|classic-dark|coffee|ectoplasm|light|modern|ocean|sunrise)\.svg$/,
// Old WooCommerce mascotte
/ninja-joy\.svg$/,
// Specific images directories
/^static\/images\/marketing/,
/^static\/images\/me/,
/^static\/images\/illustrations\/illustration-woo-magic-link.svg/,
/^static\/images\/jetpack\/favicons/,
// Documentation
/^docs/,
/^client\/my-sites\/checkout\/docs/,
];
// The image paths that match the following patterns will use `PALETTE_APP_COLORS`,
// while all other paths with fall back to `PALETTE_ILLUSTRATION_COLORS`
const SVG_APP_PATHS = [
// Color scheme thumbnails
/color-scheme-thumbnail-[a-z-]+\.svg$/,
// Component icons
/^client\/components\/jetpack\/daily-backup-status\/status-card/,
// Plan icons
/^static\/images\/plans\//,
];
// The regular expressions used to identify color values
const SVG_VALUE_EXPRESSION =
/(?:fill|flood-color|lighting-color|stop-color|stroke)="([a-z0-9#]*?)"/gi;
const SVG_STYLE_EXPRESSION =
/(?:fill|flood-color|lighting-color|stop-color|stroke):\s*([a-z0-9#]*?)\s*[;}]/gi;
// The specific color values to ignore, including other variations of white
// primarily to decrease the amount of noise in the output
const SVG_IGNORE_VALUES = [ 'currentcolor', 'none', 'transparent', 'white', '#ffffff' ];
/**
* Other constants
*/
const ROOT_PATH = path.join( __dirname, '..' );
const GIT_DIR_PATH = path.join( ROOT_PATH, '.git' );
const SVG_FILES_TO_PROCESS = execSync( `git --git-dir="${ GIT_DIR_PATH }" ls-files "*.svg"` )
.toString()
.trim()
.split( /\s+/ )
.filter( excludeSelectedPaths );
const REPLACEMENT_RULES = [];
/**
* Perform the audit
*/
SVG_FILES_TO_PROCESS.forEach( ( imagePath ) => {
const targetPreset = isAppImagePath( imagePath ) ? 'app' : 'illustration';
const targetValues =
targetPreset === 'app' ? PALETTE_APP_COLOR_VALUES : PALETTE_ILLUSTRATION_COLOR_VALUES;
const imageContent = getFileContents( imagePath );
const matchedColorValues = matchColorValues( imageContent );
const colorValuesToReplace = [];
[ ...new Set( matchedColorValues ) ].forEach( ( value ) => {
if ( SVG_IGNORE_VALUES.includes( value ) ) {
return;
}
if ( targetValues.includes( value ) ) {
return;
}
if ( colorValuesToReplace.includes( value ) ) {
return;
}
colorValuesToReplace.push( value );
} );
if ( ! colorValuesToReplace.length ) {
return;
}
// There are SVG files where stroke value is 'null'.
// Added the filter before map() to ensure 'null' strings are filtered out.
REPLACEMENT_RULES.push( {
file: imagePath,
preset: targetPreset,
rules: colorValuesToReplace
.filter( ( val ) => val !== 'null' )
.map( ( value ) => {
const replacementValue = findClosestColor( value, targetValues );
const replacementName = findPaletteColorName( replacementValue );
return {
from: {
value,
},
to: {
value: replacementValue,
name: replacementName,
},
};
} ),
} );
} );
/**
* Output
*/
printReplacementRules( REPLACEMENT_RULES );
/**
* Utilities
*/
function excludeSelectedPaths( imagePath ) {
// Make sure none of the ignored paths match
return SVG_IGNORE_PATHS.every( ( ignoredPath ) => {
return ! ignoredPath.test( imagePath );
} );
}
function isAppImagePath( imagePath ) {
return SVG_APP_PATHS.some( ( appPath ) => {
return appPath.test( imagePath );
} );
}
function getFileContents( filePath ) {
return readFileSync( path.join( ROOT_PATH, filePath ) ).toString().trim();
}
function matchColorValues( content ) {
const values = [];
let match;
[ SVG_VALUE_EXPRESSION, SVG_STYLE_EXPRESSION ].forEach( ( expression ) => {
// `String.matchAll` is unsupported at the moment
while ( ( match = expression.exec( content ) ) !== null ) {
values.push( match[ 1 ].toLowerCase() );
}
} );
return values;
}
function findClosestColor( value, targetValues ) {
let closestValue = value;
let closestDistance = Infinity;
let targetValue;
for ( targetValue of targetValues ) {
const distance = chroma.distance( value, targetValue );
// This bit shortens existing variations of white to `#fff`
// for consitent notation that this script relies on
if ( distance === 0 ) {
closestValue = targetValue;
closestDistance = distance;
break;
}
// Unless white is explicitely used, let’s not convert darker colors to it
if ( targetValue === '#fff' ) {
continue;
}
if ( distance < closestDistance ) {
closestValue = targetValue;
closestDistance = distance;
}
}
return closestValue;
}
function findPaletteColorName( value ) {
// Iterating from right to make sure color name aliases aren’t caught
const name = Object.keys( PALETTE.colors ?? {} ).findLast( ( paletteColorName ) => {
return PALETTE.colors[ paletteColorName ] === value;
} );
return name;
}
function printReplacementRules( replacementObjects ) {
const count = replacementObjects.length;
if ( count <= 0 ) {
console.log(
`All the SVG illustration files in this repository seem to use correct color values. ✨`
);
} else {
console.log(
`Found ${ count } SVG images in this repository that use non-standard color values:`
);
replacementObjects.forEach( ( replacementObject ) => {
const replacementRules = formatReplacementRules( replacementObject.rules );
const replacementSuffix = getReplacementPrefixSuffix( replacementObject );
console.log(
`\n${ replacementObject.file }${ replacementSuffix }\n${ replacementRules.join( '\n' ) }`
);
} );
}
}
function formatReplacementRules( rules ) {
if ( rules && rules.length ) {
return [ ...rules ].sort( compareByName ).map( ( rule ) => {
const valueFrom = rule.from.value.padEnd( 7 );
const valueTo = rule.to.value.padEnd( 7 );
return `${ valueFrom } → ${ valueTo } (${ rule.to.name })`;
} );
}
return [];
}
function getReplacementPrefixSuffix( replacementObject ) {
const { preset } = replacementObject;
return preset === 'app' ? ' 🖥' : '';
}
|