|
| 1 | +const fs = require('fs'); |
| 2 | + |
| 3 | +const colors = { |
| 4 | + '#486EC2': '--anatomy-gray-900', |
| 5 | + '#496EC2': '--anatomy-gray-800', |
| 6 | + '#4a6fc3': '--anatomy-gray-700', |
| 7 | + '#718dcf': '--anatomy-gray-600', |
| 8 | + '#a2b6e1': '--anatomy-gray-500', |
| 9 | + '#beccea': '--anatomy-gray-400', |
| 10 | + '#DAE2F4': '--anatomy-gray-300', |
| 11 | + '#E5EBF7': '--anatomy-gray-200', |
| 12 | + '#f4f6fc': '--anatomy-gray-100', |
| 13 | + '#FDFDFE': '--anatomy-gray-75', |
| 14 | + '#FFFFFF': '--anatomy-gray-50' |
| 15 | +}; |
| 16 | + |
| 17 | +let contents = fs.readFileSync(process.argv[process.argv.length - 1], 'utf8'); |
| 18 | +contents = contents.replace(/"(#[0-9a-f]{3,6})"/gi, (_, m) => { |
| 19 | + let c = nearestColor(hexToRgb(m)); |
| 20 | + if (c) { |
| 21 | + return '"var(' + c + ')"'; |
| 22 | + } else { |
| 23 | + console.log(m); |
| 24 | + return m; |
| 25 | + } |
| 26 | +}); |
| 27 | + |
| 28 | +contents = contents.replace(/(fill|stroke)="rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)"/g, (m, p, r, g, b, a) => { |
| 29 | + let color = { |
| 30 | + r: parseInt(r, 10), |
| 31 | + g: parseInt(g, 10), |
| 32 | + b: parseInt(b, 10) |
| 33 | + }; |
| 34 | + let nearest = nearestColor(color); |
| 35 | + if (nearest) { |
| 36 | + return `${p}="var(${nearest})" ${p}-opacity="${a}"`; |
| 37 | + } else { |
| 38 | + console.log(m); |
| 39 | + return m; |
| 40 | + } |
| 41 | +}); |
| 42 | + |
| 43 | +contents = contents.replace(/font-family="(.*?)"/g, 'font-family="Adobe-Clean"'); |
| 44 | + |
| 45 | +fs.writeFileSync(process.argv[process.argv.length - 1], contents); |
| 46 | + |
| 47 | +// Distance between 2 colors (in RGB) |
| 48 | +// https://stackoverflow.com/questions/23990802/find-nearest-color-from-a-colors-list |
| 49 | +function distance(a, b) { |
| 50 | + return Math.sqrt(Math.pow(a.r - b.r, 2) + Math.pow(a.g - b.g, 2) + Math.pow(a.b - b.b, 2)); |
| 51 | +} |
| 52 | + |
| 53 | +// return nearest color from array |
| 54 | +function nearestColor(target) { |
| 55 | + var lowest = Number.POSITIVE_INFINITY; |
| 56 | + var tmp; |
| 57 | + let res; |
| 58 | + for (let color in colors) { |
| 59 | + tmp = distance(target, hexToRgb(color)) |
| 60 | + if (tmp < lowest) { |
| 61 | + lowest = tmp; |
| 62 | + res = color; |
| 63 | + }; |
| 64 | + } |
| 65 | + return colors[res]; |
| 66 | + |
| 67 | +} |
| 68 | + |
| 69 | +function hexToRgb(hex) { |
| 70 | + var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; |
| 71 | + hex = hex.replace(shorthandRegex, function(m, r, g, b) { |
| 72 | + return r + r + g + g + b + b; |
| 73 | + }); |
| 74 | + |
| 75 | + var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); |
| 76 | + return result ? { |
| 77 | + r: parseInt(result[1], 16), |
| 78 | + g: parseInt(result[2], 16), |
| 79 | + b: parseInt(result[3], 16) |
| 80 | + } : null; |
| 81 | +} |
0 commit comments