|
| 1 | +const VariablesMap = new Map(); |
| 2 | +const History = []; |
| 3 | +let Variables = -1; |
| 4 | +let Skips = []; |
| 5 | +/** |
| 6 | + * @param {string} val |
| 7 | + */ |
| 8 | +function shouldRun (val) { |
| 9 | + if (History.indexOf(val) > -1) { |
| 10 | + return false; |
| 11 | + } |
| 12 | + return true; |
| 13 | +} |
| 14 | + |
| 15 | +function increase () { |
| 16 | + Variables = Variables + 1; |
| 17 | + let temp = Variables.toString(36); |
| 18 | + Skips.forEach(E => { |
| 19 | + if (E === temp) { |
| 20 | + temp = Variables.toString(36); |
| 21 | + Variables = Variables + 1; |
| 22 | + } |
| 23 | + }); |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * @param {string} match |
| 28 | + */ |
| 29 | +function replacer (match) { |
| 30 | + |
| 31 | + if (!shouldRun(match)) return match; |
| 32 | + let exist = VariablesMap.get(match); |
| 33 | + |
| 34 | + if (!exist) { |
| 35 | + exist = '--' + (Variables).toString(36); |
| 36 | + increase(); |
| 37 | + VariablesMap.set(match, exist); |
| 38 | + History.push(exist); |
| 39 | + } |
| 40 | + |
| 41 | + return exist; |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * @param {import('postcss').Declaration} j |
| 46 | + */ |
| 47 | +function looker (j) { |
| 48 | + |
| 49 | + let prop = j.prop; |
| 50 | + |
| 51 | + if (j.variable && shouldRun(prop)) { |
| 52 | + let old = prop; |
| 53 | + let exist = VariablesMap.get(old); |
| 54 | + if (!exist) { |
| 55 | + exist = '--' + Variables.toString(36); |
| 56 | + increase(); |
| 57 | + VariablesMap.set(old, exist); |
| 58 | + History.push(exist); |
| 59 | + } |
| 60 | + prop = exist; |
| 61 | + } |
| 62 | + |
| 63 | + let value = j.value.replace(/--[\w-_]{1,1000}/g, replacer); |
| 64 | + |
| 65 | + if (prop) j.prop = prop; |
| 66 | + if (value) j.value = value; |
| 67 | + |
| 68 | +} |
| 69 | + |
| 70 | +/** |
| 71 | + * @param {string[]} opts |
| 72 | + */ |
| 73 | +module.exports = (opts = []) => { |
| 74 | + |
| 75 | + opts.forEach(E => VariablesMap.set(E, E)); |
| 76 | + opts.forEach(E => Skips.push(E.replace('--', ''))); |
| 77 | + |
| 78 | + increase(); |
| 79 | + |
| 80 | + return { |
| 81 | + postcssPlugin: 'postcss-variable-compress', |
| 82 | + Declaration: { |
| 83 | + '*': looker |
| 84 | + } |
| 85 | + }; |
| 86 | +}; |
| 87 | + |
| 88 | +module.exports.postcss = true; |
0 commit comments