|
| 1 | +const chalk = require('chalk') |
| 2 | +const path = require('path') |
| 3 | +const fs = require('fs') |
| 4 | + |
| 5 | +const logId = '[' + chalk.blue('WebpackThemeJsonPlugin') + ']' |
| 6 | + |
| 7 | +class WebpackThemeJsonPlugin { |
| 8 | + /** |
| 9 | + * constructor |
| 10 | + * @param {Object} options = { |
| 11 | + * context: string - default: '../src/theme-json' |
| 12 | + * output: string - default: '../theme.json' |
| 13 | + * scssOutput: string - default: '../src/scss/00-variables/_theme-json.scss' |
| 14 | + * watch: boolean - default: false |
| 15 | + * } |
| 16 | + */ |
| 17 | + constructor(options) { |
| 18 | + // folders |
| 19 | + this._context = options.context || path.resolve(__dirname, '../src/theme-json') + '/' |
| 20 | + this._output = options.output || path.resolve(__dirname, '../theme.json') |
| 21 | + this._scssOutput = options.scssOutput || path.resolve(__dirname, '../src/scss/01-abstract/_theme-json.scss') |
| 22 | + |
| 23 | + if (options.watch) { |
| 24 | + fs.watch(this._context, () => { |
| 25 | + this.refresh() |
| 26 | + }) |
| 27 | + } |
| 28 | + |
| 29 | + this.refresh() |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * apply |
| 34 | + */ |
| 35 | + apply() {} |
| 36 | + |
| 37 | + /** |
| 38 | + * Generate theme json file |
| 39 | + */ |
| 40 | + generateThemeJson() { |
| 41 | + const jsonFiles = fs.readdirSync(this._context, { |
| 42 | + withFileTypes: true, |
| 43 | + }) |
| 44 | + const themeJson = {} |
| 45 | + |
| 46 | + jsonFiles.forEach((file) => { |
| 47 | + if (file.isFile() && file.name.endsWith('.json')) { |
| 48 | + let json = fs.readFileSync(this._context + file.name, 'utf8') |
| 49 | + |
| 50 | + try { |
| 51 | + json = JSON.parse(json) |
| 52 | + } catch (e) { |
| 53 | + // eslint-disable-next-line no-console |
| 54 | + console.error(logId, 'Error parsing JSON file:', file.name) |
| 55 | + } |
| 56 | + |
| 57 | + if (isPlainObject(json)) { |
| 58 | + extend(true, themeJson, json) |
| 59 | + } else { |
| 60 | + // eslint-disable-next-line no-console |
| 61 | + console.error(logId, 'JSON file is not a plain object:', file.name) |
| 62 | + } |
| 63 | + } |
| 64 | + }) |
| 65 | + |
| 66 | + fs.writeFileSync(this._output, JSON.stringify(themeJson, null, 2)) |
| 67 | + // eslint-disable-next-line no-console |
| 68 | + console.log(logId, 'JSON files successfully generated !') |
| 69 | + |
| 70 | + return this |
| 71 | + } |
| 72 | + |
| 73 | + /** |
| 74 | + * Generate scss variables file |
| 75 | + */ |
| 76 | + generateScssVariables() { |
| 77 | + const comment = [ |
| 78 | + '/**', |
| 79 | + ' * Theme JSON', |
| 80 | + ' * scss variables are extracted from theme.json', |
| 81 | + ' *', |
| 82 | + " * !!! DON'T EDIT THIS FILE !!!", |
| 83 | + ' *', |
| 84 | + ' */', |
| 85 | + ] |
| 86 | + const tasks = { |
| 87 | + 'settings-color-palette'(key, value) { |
| 88 | + let result = '' |
| 89 | + const palette = [] |
| 90 | + |
| 91 | + for (const color of value) { |
| 92 | + const colorVar = getVariableName('settings-color-' + color.slug) |
| 93 | + result += `${colorVar}: ${color.color};\n` |
| 94 | + palette.push(`${color.slug}: ${colorVar}`) |
| 95 | + } |
| 96 | + |
| 97 | + return result + `$settings-palette: (\n\t${palette.join(',\n\t')}\n);\n` |
| 98 | + }, |
| 99 | + 'settings-custom': 'default', |
| 100 | + 'settings-spacing-spacingSizes'(key, value) { |
| 101 | + let result = '' |
| 102 | + |
| 103 | + for (const spacing of value) { |
| 104 | + result += `${getVariableName('settings-spacing-' + spacing.slug)}: ${spacing.size};\n` |
| 105 | + } |
| 106 | + |
| 107 | + return result |
| 108 | + }, |
| 109 | + } |
| 110 | + // eslint-disable-next-line @wordpress/no-unused-vars-before-return |
| 111 | + const taskNames = Object.keys(tasks) |
| 112 | + let jsonFile = fs.readFileSync(this._output, 'utf8') |
| 113 | + |
| 114 | + // check if the theme.json file is valid |
| 115 | + try { |
| 116 | + jsonFile = JSON.parse(jsonFile) |
| 117 | + } catch (e) { |
| 118 | + // eslint-disable-next-line no-console |
| 119 | + console.error(logId, 'Error parsing JSON file:', this._output) |
| 120 | + return this |
| 121 | + } |
| 122 | + |
| 123 | + // format the scss variable name |
| 124 | + function getVariableName(id) { |
| 125 | + return `$${id.replace(/([A-Z])/g, '-$1').toLowerCase()}` |
| 126 | + } |
| 127 | + |
| 128 | + // traverse the theme.json file and generate the scss variables |
| 129 | + function traverse(obj, parents = [], result = '') { |
| 130 | + for (const key in obj) { |
| 131 | + const id = (parents.length > 0 ? parents.join('-') + '-' : '') + key |
| 132 | + const taskName = taskNames.filter((t) => (id.startsWith(t) ? t : null))[0] |
| 133 | + const task = taskName ? tasks[taskName] : null |
| 134 | + |
| 135 | + if (isPlainObject(obj[key])) { |
| 136 | + result += traverse(obj[key], [...parents, key]) |
| 137 | + } else if (task) { |
| 138 | + if (task === 'default' && typeof obj[key] === 'string') { |
| 139 | + result += `${getVariableName(id)}: ${obj[key]};\n` |
| 140 | + } else if (typeof task === 'function') { |
| 141 | + result += task(key, obj[key]) |
| 142 | + } |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + return result |
| 147 | + } |
| 148 | + |
| 149 | + fs.writeFileSync(this._scssOutput, comment.join('\n') + '\n' + traverse(jsonFile)) |
| 150 | + |
| 151 | + return this |
| 152 | + } |
| 153 | + |
| 154 | + /** |
| 155 | + * Refresh the theme json and scss variables files |
| 156 | + */ |
| 157 | + refresh() { |
| 158 | + this.generateThemeJson() |
| 159 | + this.generateScssVariables() |
| 160 | + return this |
| 161 | + } |
| 162 | +} |
| 163 | + |
| 164 | +// ---- |
| 165 | +// utils |
| 166 | +// ---- |
| 167 | +function isPlainObject(o) { |
| 168 | + return o?.constructor === Object || Object.getPrototypeOf(o ?? 0) === null |
| 169 | +} |
| 170 | + |
| 171 | +function extend() { |
| 172 | + const args = arguments |
| 173 | + const firstArgIsBool = typeof args[0] === 'boolean' |
| 174 | + const deep = firstArgIsBool ? args[0] : false |
| 175 | + const start = firstArgIsBool ? 1 : 0 |
| 176 | + const rt = isPlainObject(args[start]) ? args[start] : {} |
| 177 | + |
| 178 | + for (let i = start + 1; i < args.length; i++) { |
| 179 | + for (const prop in args[i]) { |
| 180 | + if (deep && isPlainObject(args[i][prop])) { |
| 181 | + rt[prop] = extend(true, {}, rt[prop], args[i][prop]) |
| 182 | + } else if (typeof args[i][prop] !== 'undefined') { |
| 183 | + rt[prop] = args[i][prop] |
| 184 | + } |
| 185 | + } |
| 186 | + } |
| 187 | + |
| 188 | + return rt |
| 189 | +} |
| 190 | + |
| 191 | +module.exports = WebpackThemeJsonPlugin |
0 commit comments