-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathwebpack-theme-json-plugin.js
More file actions
191 lines (162 loc) · 4.91 KB
/
webpack-theme-json-plugin.js
File metadata and controls
191 lines (162 loc) · 4.91 KB
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
const chalk = require('chalk')
const path = require('path')
const fs = require('fs')
const logId = '[' + chalk.blue('WebpackThemeJsonPlugin') + ']'
class WebpackThemeJsonPlugin {
/**
* constructor
* @param {Object} options = {
* context: string - default: '../src/theme-json'
* output: string - default: '../theme.json'
* scssOutput: string - default: '../src/scss/00-variables/_theme-json.scss'
* watch: boolean - default: false
* }
*/
constructor(options) {
// folders
this._context = options.context || path.resolve(__dirname, '../src/theme-json') + '/'
this._output = options.output || path.resolve(__dirname, '../theme.json')
this._scssOutput = options.scssOutput || path.resolve(__dirname, '../src/scss/01-abstract/_theme-json.scss')
if (options.watch) {
fs.watch(this._context, () => {
this.refresh()
})
}
this.refresh()
}
/**
* apply
*/
apply() {}
/**
* Generate theme json file
*/
generateThemeJson() {
const jsonFiles = fs.readdirSync(this._context, {
withFileTypes: true,
})
const themeJson = {}
jsonFiles.forEach((file) => {
if (file.isFile() && file.name.endsWith('.json')) {
let json = fs.readFileSync(this._context + file.name, 'utf8')
try {
json = JSON.parse(json)
} catch (e) {
// eslint-disable-next-line no-console
console.error(logId, 'Error parsing JSON file:', file.name)
}
if (isPlainObject(json)) {
extend(true, themeJson, json)
} else {
// eslint-disable-next-line no-console
console.error(logId, 'JSON file is not a plain object:', file.name)
}
}
})
fs.writeFileSync(this._output, JSON.stringify(themeJson, null, 2))
// eslint-disable-next-line no-console
console.log(logId, 'JSON files successfully generated !')
return this
}
/**
* Generate scss variables file
*/
generateScssVariables() {
const comment = [
'/**',
' * Theme JSON',
' * scss variables are extracted from theme.json',
' *',
" * !!! DON'T EDIT THIS FILE !!!",
' *',
' */',
]
const tasks = {
'settings-color-palette'(key, value) {
let result = ''
const palette = []
for (const color of value) {
const colorVar = getVariableName('settings-color-' + color.slug)
result += `${colorVar}: ${color.color};\n`
palette.push(`${color.slug}: ${colorVar}`)
}
return result + `$settings-palette: (\n\t${palette.join(',\n\t')}\n);\n`
},
'settings-custom': 'default',
'settings-spacing-spacingSizes'(key, value) {
let result = ''
for (const spacing of value) {
result += `${getVariableName('settings-spacing-' + spacing.slug)}: ${spacing.size};\n`
}
return result
},
}
// eslint-disable-next-line @wordpress/no-unused-vars-before-return
const taskNames = Object.keys(tasks)
let jsonFile = fs.readFileSync(this._output, 'utf8')
// check if the theme.json file is valid
try {
jsonFile = JSON.parse(jsonFile)
} catch (e) {
// eslint-disable-next-line no-console
console.error(logId, 'Error parsing JSON file:', this._output)
return this
}
// format the scss variable name
function getVariableName(id) {
return `$${id.replace(/([A-Z])/g, '-$1').toLowerCase()}`
}
// traverse the theme.json file and generate the scss variables
function traverse(obj, parents = [], result = '') {
for (const key in obj) {
const id = (parents.length > 0 ? parents.join('-') + '-' : '') + key
const taskName = taskNames.filter((t) => (id.startsWith(t) ? t : null))[0]
const task = taskName ? tasks[taskName] : null
if (isPlainObject(obj[key])) {
result += traverse(obj[key], [...parents, key])
} else if (task) {
if (task === 'default' && typeof obj[key] === 'string') {
result += `${getVariableName(id)}: ${obj[key]};\n`
} else if (typeof task === 'function') {
result += task(key, obj[key])
}
}
}
return result
}
fs.writeFileSync(this._scssOutput, comment.join('\n') + '\n' + traverse(jsonFile))
return this
}
/**
* Refresh the theme json and scss variables files
*/
refresh() {
this.generateThemeJson()
this.generateScssVariables()
return this
}
}
// ----
// utils
// ----
function isPlainObject(o) {
return o?.constructor === Object || Object.getPrototypeOf(o ?? 0) === null
}
function extend() {
const args = arguments
const firstArgIsBool = typeof args[0] === 'boolean'
const deep = firstArgIsBool ? args[0] : false
const start = firstArgIsBool ? 1 : 0
const rt = isPlainObject(args[start]) ? args[start] : {}
for (let i = start + 1; i < args.length; i++) {
for (const prop in args[i]) {
if (deep && isPlainObject(args[i][prop])) {
rt[prop] = extend(true, {}, rt[prop], args[i][prop])
} else if (typeof args[i][prop] !== 'undefined') {
rt[prop] = args[i][prop]
}
}
}
return rt
}
module.exports = WebpackThemeJsonPlugin