@forgewp/compiler 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -5
- package/bin/analyze.js +158 -0
- package/bin/cli.js +29 -4
- package/bin/doctor.js +125 -11
- package/bin/export.js +20 -0
- package/bin/fresh.js +32 -343
- package/bin/i18n-extract.js +121 -0
- package/bin/i18n-translate.js +112 -0
- package/bin/make-block.js +27 -60
- package/bin/make-island.js +72 -0
- package/bin/make-post-type.js +6 -6
- package/bin/make-template.js +145 -0
- package/bin/repair.js +2 -2
- package/bin/sync-routes.js +28 -158
- package/define-config.d.ts +1 -0
- package/define-config.js +1 -0
- package/lib/adapters/html-adapter.js +65 -0
- package/lib/adapters/stub-adapter.js +49 -0
- package/lib/add-component.js +282 -183
- package/lib/asset-loader.js +27 -0
- package/lib/block-compiler.js +552 -0
- package/lib/blueprints.js +1459 -501
- package/lib/define-config.d.ts +3 -0
- package/lib/define-config.js +8 -0
- package/lib/diagnostics.js +798 -0
- package/lib/export-theme.js +81 -18
- package/lib/framework-adapter.js +34 -0
- package/lib/functions-builder.js +1801 -0
- package/lib/generate-theme.js +1019 -1352
- package/lib/hydration-scanner.js +516 -21
- package/lib/i18n/extractor.js +60 -0
- package/lib/i18n/providers.js +165 -0
- package/lib/index.d.ts +115 -3
- package/lib/index.js +19 -5
- package/lib/load-config.js +122 -6
- package/lib/markup-processor.js +584 -0
- package/lib/php-builders.js +381 -0
- package/lib/react-adapter.js +1336 -0
- package/lib/render-static.js +9 -82
- package/lib/render-theme.mts +526 -232
- package/lib/screenshot-fallback.png +0 -0
- package/lib/types.js +1 -0
- package/lib/validate-export.js +183 -0
- package/package.json +14 -3
- package/bin/make-component.js +0 -200
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
import {
|
|
2
|
+
existsSync,
|
|
3
|
+
mkdirSync,
|
|
4
|
+
readFileSync,
|
|
5
|
+
readdirSync,
|
|
6
|
+
statSync,
|
|
7
|
+
writeFileSync,
|
|
8
|
+
} from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
|
|
11
|
+
function parseAttributes(attrStr) {
|
|
12
|
+
const attrs = {};
|
|
13
|
+
const regex = /([a-zA-Z0-9_-]+)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|(?:\{([\s\S]*?)\}))|(?=\s|$))/gi;
|
|
14
|
+
let match;
|
|
15
|
+
while ((match = regex.exec(attrStr)) !== null) {
|
|
16
|
+
const key = match[1];
|
|
17
|
+
const val = match[2] || match[3] || match[4] || true;
|
|
18
|
+
attrs[key] = val;
|
|
19
|
+
}
|
|
20
|
+
return attrs;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function parseJsxToAst(jsx) {
|
|
24
|
+
const tokens = [];
|
|
25
|
+
let index = 0;
|
|
26
|
+
|
|
27
|
+
while (index < jsx.length) {
|
|
28
|
+
const char = jsx[index];
|
|
29
|
+
|
|
30
|
+
if (char === '<') {
|
|
31
|
+
let tagEnd = jsx.indexOf('>', index);
|
|
32
|
+
if (tagEnd === -1) break;
|
|
33
|
+
|
|
34
|
+
let tagStr = jsx.substring(index, tagEnd + 1);
|
|
35
|
+
const isClosing = tagStr.startsWith('</');
|
|
36
|
+
const isSelfClosing = tagStr.endsWith('/>');
|
|
37
|
+
|
|
38
|
+
const tagNameMatch = tagStr.match(/<\/?([a-zA-Z0-9_-]+)/);
|
|
39
|
+
const tagName = tagNameMatch ? tagNameMatch[1] : '';
|
|
40
|
+
|
|
41
|
+
tokens.push({
|
|
42
|
+
type: 'tag',
|
|
43
|
+
name: tagName,
|
|
44
|
+
raw: tagStr,
|
|
45
|
+
isClosing,
|
|
46
|
+
isSelfClosing
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
index = tagEnd + 1;
|
|
50
|
+
} else {
|
|
51
|
+
let nextTag = jsx.indexOf('<', index);
|
|
52
|
+
let text = nextTag === -1 ? jsx.substring(index) : jsx.substring(index, nextTag);
|
|
53
|
+
|
|
54
|
+
if (text.trim()) {
|
|
55
|
+
tokens.push({
|
|
56
|
+
type: 'text',
|
|
57
|
+
value: text
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
index = nextTag === -1 ? jsx.length : nextTag;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const root = { type: 'root', children: [] };
|
|
66
|
+
const stack = [root];
|
|
67
|
+
|
|
68
|
+
for (const token of tokens) {
|
|
69
|
+
if (token.type === 'tag') {
|
|
70
|
+
if (token.isClosing) {
|
|
71
|
+
if (stack.length > 1) {
|
|
72
|
+
stack.pop();
|
|
73
|
+
}
|
|
74
|
+
} else {
|
|
75
|
+
const node = {
|
|
76
|
+
type: 'element',
|
|
77
|
+
name: token.name,
|
|
78
|
+
attributes: parseAttributes(token.raw.substring(token.name.length + 1, token.raw.length - (token.isSelfClosing ? 2 : 1))),
|
|
79
|
+
children: []
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
stack[stack.length - 1].children.push(node);
|
|
83
|
+
|
|
84
|
+
if (!token.isSelfClosing && token.name !== 'img' && token.name !== 'input' && token.name !== 'br' && token.name !== 'hr') {
|
|
85
|
+
stack.push(node);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
} else {
|
|
89
|
+
stack[stack.length - 1].children.push({
|
|
90
|
+
type: 'text',
|
|
91
|
+
value: token.value
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return root;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function generateReactCreateElement(node) {
|
|
100
|
+
if (!node) return 'null';
|
|
101
|
+
|
|
102
|
+
if (node.type === 'root') {
|
|
103
|
+
if (node.children.length === 1) {
|
|
104
|
+
return generateReactCreateElement(node.children[0]);
|
|
105
|
+
}
|
|
106
|
+
return `[${node.children.map(generateReactCreateElement).join(', ')}]`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (node.type === 'text') {
|
|
110
|
+
const val = node.value.trim();
|
|
111
|
+
if (val.startsWith('{') && val.endsWith('}')) {
|
|
112
|
+
return val.slice(1, -1).trim();
|
|
113
|
+
}
|
|
114
|
+
return JSON.stringify(val);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (node.type === 'element') {
|
|
118
|
+
if (node.name === 'WpEditable') {
|
|
119
|
+
const tag = String(node.attributes.tagName || 'div').replace(/['"]/g, '').trim();
|
|
120
|
+
const valStr = String(node.attributes.value || '').trim();
|
|
121
|
+
|
|
122
|
+
let varName = 'value';
|
|
123
|
+
const varMatch = valStr.match(/(?:attributes|props)?\.?([a-zA-Z0-9_-]+)$/);
|
|
124
|
+
if (varMatch) {
|
|
125
|
+
varName = varMatch[1];
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const className = node.attributes.className
|
|
129
|
+
? (node.attributes.className.startsWith('{')
|
|
130
|
+
? node.attributes.className.slice(1, -1)
|
|
131
|
+
: JSON.stringify(node.attributes.className))
|
|
132
|
+
: '""';
|
|
133
|
+
|
|
134
|
+
return `createElement(wp.blockEditor.RichText, {
|
|
135
|
+
tagName: ${JSON.stringify(tag)},
|
|
136
|
+
value: attributes.${varName} || '',
|
|
137
|
+
onChange: function(val) { setAttributes({ ${varName}: val }); },
|
|
138
|
+
className: ${className}
|
|
139
|
+
})`;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const props = {};
|
|
143
|
+
for (const [key, val] of Object.entries(node.attributes)) {
|
|
144
|
+
const propKey = key === 'className' ? 'className' : key;
|
|
145
|
+
if (typeof val === 'string' && val.startsWith('{') && val.endsWith('}')) {
|
|
146
|
+
props[propKey] = val.slice(1, -1).trim();
|
|
147
|
+
} else {
|
|
148
|
+
props[propKey] = JSON.stringify(val);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const propsStr = Object.keys(props).length > 0
|
|
153
|
+
? `{ ${Object.entries(props).map(([k, v]) => `${k}: ${v}`).join(', ')} }`
|
|
154
|
+
: 'null';
|
|
155
|
+
|
|
156
|
+
const childrenStr = node.children.map(generateReactCreateElement).filter(Boolean).join(', ');
|
|
157
|
+
|
|
158
|
+
return `createElement(${JSON.stringify(node.name)}, ${propsStr}${childrenStr ? `, ${childrenStr}` : ''})`;
|
|
159
|
+
}
|
|
160
|
+
return 'null';
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function parseDefineBlock(code, blockSlug) {
|
|
164
|
+
const startIndex = code.indexOf('defineBlock(');
|
|
165
|
+
if (startIndex === -1) return null;
|
|
166
|
+
|
|
167
|
+
let depth = 1;
|
|
168
|
+
let i = startIndex + 'defineBlock('.length;
|
|
169
|
+
let blockContent = '';
|
|
170
|
+
|
|
171
|
+
while (i < code.length && depth > 0) {
|
|
172
|
+
const char = code[i];
|
|
173
|
+
if (char === '(') depth++;
|
|
174
|
+
else if (char === ')') depth--;
|
|
175
|
+
|
|
176
|
+
if (depth > 0) {
|
|
177
|
+
blockContent += char;
|
|
178
|
+
}
|
|
179
|
+
i++;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
let cleanBlockContent = blockContent;
|
|
183
|
+
|
|
184
|
+
cleanBlockContent = cleanBlockContent.replace(
|
|
185
|
+
/edit\s*:\s*([\s\S]*?)(?=,\s*(?:save|name|title|category|icon|attributes)\s*:|\s*\}$)/,
|
|
186
|
+
'edit: null'
|
|
187
|
+
);
|
|
188
|
+
cleanBlockContent = cleanBlockContent.replace(
|
|
189
|
+
/save\s*:\s*([\s\S]*?)(?=,\s*(?:edit|name|title|category|icon|attributes)\s*:|\s*\}$)/,
|
|
190
|
+
'save: null'
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
try {
|
|
194
|
+
const evalFn = new Function(`return ${cleanBlockContent};`);
|
|
195
|
+
return evalFn();
|
|
196
|
+
} catch (e) {
|
|
197
|
+
console.warn(`[Gutenberg Block Compiler] parseDefineBlock eval failed:`, e.message);
|
|
198
|
+
|
|
199
|
+
const nameMatch = blockContent.match(/name\s*:\s*["']([^"']+)["']/);
|
|
200
|
+
const titleMatch = blockContent.match(/title\s*:\s*["']([^"']+)["']/);
|
|
201
|
+
const categoryMatch = blockContent.match(/category\s*:\s*["']([^"']+)["']/);
|
|
202
|
+
const iconMatch = blockContent.match(/icon\s*:\s*["']([^"']+)["']/);
|
|
203
|
+
|
|
204
|
+
let attributes = {};
|
|
205
|
+
const attrMatch = blockContent.match(/attributes\s*:\s*(\{[\s\S]*?\})(?:\s*,\s*(?:edit|save)|\s*\})/);
|
|
206
|
+
if (attrMatch) {
|
|
207
|
+
try {
|
|
208
|
+
const attrEval = new Function(`return ${attrMatch[1]};`);
|
|
209
|
+
attributes = attrEval();
|
|
210
|
+
} catch {}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return {
|
|
214
|
+
name: nameMatch ? nameMatch[1] : blockSlug,
|
|
215
|
+
title: titleMatch ? titleMatch[1] : blockSlug,
|
|
216
|
+
category: categoryMatch ? categoryMatch[1] : 'design',
|
|
217
|
+
icon: iconMatch ? iconMatch[1] : 'info',
|
|
218
|
+
attributes
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function extractJsx(code, propertyName) {
|
|
224
|
+
const propIndex = code.indexOf(`${propertyName}:`);
|
|
225
|
+
if (propIndex === -1) return null;
|
|
226
|
+
|
|
227
|
+
const subCode = code.substring(propIndex);
|
|
228
|
+
const returnIndex = subCode.indexOf('return (');
|
|
229
|
+
if (returnIndex !== -1) {
|
|
230
|
+
let depth = 1;
|
|
231
|
+
let j = returnIndex + 'return ('.length;
|
|
232
|
+
let jsxContent = '';
|
|
233
|
+
while (j < subCode.length && depth > 0) {
|
|
234
|
+
const c = subCode[j];
|
|
235
|
+
if (c === '(') depth++;
|
|
236
|
+
else if (c === ')') depth--;
|
|
237
|
+
|
|
238
|
+
if (depth > 0) {
|
|
239
|
+
jsxContent += c;
|
|
240
|
+
}
|
|
241
|
+
j++;
|
|
242
|
+
}
|
|
243
|
+
return jsxContent.trim();
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const returnSingleIndex = subCode.indexOf('return ');
|
|
247
|
+
if (returnSingleIndex !== -1) {
|
|
248
|
+
const afterReturn = subCode.substring(returnSingleIndex + 'return '.length).trim();
|
|
249
|
+
if (afterReturn.startsWith('<')) {
|
|
250
|
+
const match = afterReturn.match(/^(<[\s\S]*?>)(?:\s*[,;\}]|\s*$)/);
|
|
251
|
+
if (match) {
|
|
252
|
+
return match[1].trim();
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const arrowIndex = subCode.indexOf('=>');
|
|
258
|
+
if (arrowIndex !== -1 && arrowIndex < 80) {
|
|
259
|
+
const afterArrow = subCode.substring(arrowIndex + 2).trim();
|
|
260
|
+
if (afterArrow.startsWith('(')) {
|
|
261
|
+
let depth = 1;
|
|
262
|
+
let j = 1;
|
|
263
|
+
let jsxContent = '';
|
|
264
|
+
while (j < afterArrow.length && depth > 0) {
|
|
265
|
+
const c = afterArrow[j];
|
|
266
|
+
if (c === '(') depth++;
|
|
267
|
+
else if (c === ')') depth--;
|
|
268
|
+
if (depth > 0) jsxContent += c;
|
|
269
|
+
j++;
|
|
270
|
+
}
|
|
271
|
+
return jsxContent.trim();
|
|
272
|
+
} else if (afterArrow.startsWith('<')) {
|
|
273
|
+
const match = afterArrow.match(/^(<[\s\S]*?>)(?:\s*[,;\}]|\s*$)/);
|
|
274
|
+
if (match) {
|
|
275
|
+
return match[1].trim();
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function parenthesizeTernaryExpression(expr) {
|
|
284
|
+
const questionCount = (expr.match(/\?/g) || []).length;
|
|
285
|
+
if (questionCount <= 1) return expr;
|
|
286
|
+
|
|
287
|
+
let depth = 0;
|
|
288
|
+
let firstQuestionIdx = -1;
|
|
289
|
+
let firstColonIdx = -1;
|
|
290
|
+
|
|
291
|
+
for (let i = 0; i < expr.length; i++) {
|
|
292
|
+
const char = expr[i];
|
|
293
|
+
if (char === '(' || char === '{' || char === '[') depth++;
|
|
294
|
+
else if (char === ')' || char === '}' || char === ']') depth--;
|
|
295
|
+
else if (depth === 0) {
|
|
296
|
+
if (char === '?' && firstQuestionIdx === -1) {
|
|
297
|
+
firstQuestionIdx = i;
|
|
298
|
+
} else if (char === ':' && firstQuestionIdx !== -1 && firstColonIdx === -1) {
|
|
299
|
+
firstColonIdx = i;
|
|
300
|
+
break;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
if (firstQuestionIdx === -1 || firstColonIdx === -1) {
|
|
306
|
+
return expr;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const cond = expr.substring(0, firstQuestionIdx).trim();
|
|
310
|
+
const truthy = expr.substring(firstQuestionIdx + 1, firstColonIdx).trim();
|
|
311
|
+
const falsy = expr.substring(firstColonIdx + 1).trim();
|
|
312
|
+
|
|
313
|
+
const newTruthy = parenthesizeTernaryExpression(truthy);
|
|
314
|
+
const newFalsy = parenthesizeTernaryExpression(falsy);
|
|
315
|
+
|
|
316
|
+
const wrapTruthy = (truthy.includes('?') && !truthy.startsWith('(')) ? `(${newTruthy})` : newTruthy;
|
|
317
|
+
const wrapFalsy = (falsy.includes('?') && !falsy.startsWith('(')) ? `(${newFalsy})` : newFalsy;
|
|
318
|
+
|
|
319
|
+
return `${cond} ? ${wrapTruthy} : ${wrapFalsy}`;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function translateJsExpressionToPhp(jsExpr) {
|
|
323
|
+
const phpExpr = jsExpr
|
|
324
|
+
.replace(/(?:attributes|props)\.([a-zA-Z0-9_-]+)/g, "$attributes['$1']")
|
|
325
|
+
.replace(/\b([a-zA-Z0-9_-]+)\b/g, (name) => {
|
|
326
|
+
return name;
|
|
327
|
+
});
|
|
328
|
+
return parenthesizeTernaryExpression(phpExpr);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Scans the `src/blocks/` folder, parses block settings and JSX content,
|
|
333
|
+
* and compiles them into official, dynamic WordPress blocks.
|
|
334
|
+
*
|
|
335
|
+
* @param {string} themeRoot
|
|
336
|
+
* @param {string} outDir
|
|
337
|
+
* @returns {string[]} Compiled block slugs
|
|
338
|
+
*/
|
|
339
|
+
export function compileBlocks(themeRoot, outDir) {
|
|
340
|
+
const blocksDir = path.join(themeRoot, 'src', 'blocks');
|
|
341
|
+
const blockSlugs = [];
|
|
342
|
+
|
|
343
|
+
if (!existsSync(blocksDir)) {
|
|
344
|
+
return blockSlugs;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const entries = readdirSync(blocksDir);
|
|
348
|
+
for (const entry of entries) {
|
|
349
|
+
const entryPath = path.join(blocksDir, entry);
|
|
350
|
+
let blockFile = '';
|
|
351
|
+
let blockSlug = '';
|
|
352
|
+
|
|
353
|
+
if (statSync(entryPath).isDirectory()) {
|
|
354
|
+
const indexPath = path.join(entryPath, 'index.tsx');
|
|
355
|
+
if (existsSync(indexPath)) {
|
|
356
|
+
blockFile = indexPath;
|
|
357
|
+
blockSlug = entry
|
|
358
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
359
|
+
.toLowerCase()
|
|
360
|
+
.replace(/[^a-z0-9]+/g, '-');
|
|
361
|
+
}
|
|
362
|
+
} else if (entry.endsWith('.tsx') || entry.endsWith('.jsx')) {
|
|
363
|
+
blockFile = entryPath;
|
|
364
|
+
blockSlug = entry
|
|
365
|
+
.replace(/\.(tsx|jsx)$/, '')
|
|
366
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
367
|
+
.toLowerCase()
|
|
368
|
+
.replace(/[^a-z0-9]+/g, '-');
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
if (blockFile) {
|
|
372
|
+
try {
|
|
373
|
+
const code = readFileSync(blockFile, 'utf8');
|
|
374
|
+
|
|
375
|
+
const settingsMatch = code.match(
|
|
376
|
+
/export\s+const\s+settings\s*=\s*(\{[\s\S]*?\});/,
|
|
377
|
+
);
|
|
378
|
+
let settings = {
|
|
379
|
+
apiVersion: 3,
|
|
380
|
+
name: `forgewp/${blockSlug}`,
|
|
381
|
+
title: blockSlug
|
|
382
|
+
.split('-')
|
|
383
|
+
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
|
384
|
+
.join(' '),
|
|
385
|
+
category: 'design',
|
|
386
|
+
icon: 'admin-generic',
|
|
387
|
+
attributes: {},
|
|
388
|
+
render: 'file:./render.php',
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
let parsedSettings = null;
|
|
392
|
+
if (code.includes('defineBlock(')) {
|
|
393
|
+
parsedSettings = parseDefineBlock(code, blockSlug);
|
|
394
|
+
} else if (settingsMatch) {
|
|
395
|
+
try {
|
|
396
|
+
const evalFn = new Function(`return ${settingsMatch[1]};`);
|
|
397
|
+
parsedSettings = evalFn();
|
|
398
|
+
} catch (e) {
|
|
399
|
+
console.warn(
|
|
400
|
+
`[Gutenberg Block Compiler] Error parsing legacy settings for ${blockSlug}:`,
|
|
401
|
+
e.message,
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
if (parsedSettings) {
|
|
407
|
+
settings = { ...settings, ...parsedSettings };
|
|
408
|
+
settings.name = settings.name ? (settings.name.includes('/') ? settings.name : `forgewp/${settings.name}`) : `forgewp/${blockSlug}`;
|
|
409
|
+
settings.apiVersion = 3;
|
|
410
|
+
settings.render = 'file:./render.php';
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// Extract JSX from save first, then edit as fallback
|
|
414
|
+
let jsx = '';
|
|
415
|
+
if (code.includes('save:')) {
|
|
416
|
+
jsx = extractJsx(code, 'save');
|
|
417
|
+
}
|
|
418
|
+
if (!jsx && code.includes('edit:')) {
|
|
419
|
+
jsx = extractJsx(code, 'edit');
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
if (!jsx) {
|
|
423
|
+
const returnMatch = code.match(/return\s*\(\s*(<[\s\S]*?>)\s*\)/);
|
|
424
|
+
if (returnMatch) {
|
|
425
|
+
jsx = returnMatch[1];
|
|
426
|
+
} else {
|
|
427
|
+
const returnMatchSingle = code.match(/return\s+(<[\s\S]*?>);/);
|
|
428
|
+
if (returnMatchSingle) {
|
|
429
|
+
jsx = returnMatchSingle[1];
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
if (!jsx) {
|
|
435
|
+
console.warn(
|
|
436
|
+
`[Gutenberg Block Compiler] Skipping block ${blockSlug}: No returning JSX element found.`,
|
|
437
|
+
);
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// Extract custom edit JSX for block-canvas high-fidelity controls using AST parser
|
|
442
|
+
let editJsx = '';
|
|
443
|
+
if (code.includes('edit:')) {
|
|
444
|
+
editJsx = extractJsx(code, 'edit');
|
|
445
|
+
}
|
|
446
|
+
if (editJsx) {
|
|
447
|
+
try {
|
|
448
|
+
const ast = parseJsxToAst(editJsx);
|
|
449
|
+
const customEditJsx = generateReactCreateElement(ast);
|
|
450
|
+
settings.customEditJsx = customEditJsx;
|
|
451
|
+
} catch (e) {
|
|
452
|
+
console.warn(`[Gutenberg Block Compiler] Failed to parse custom edit JSX for ${blockSlug}:`, e.message);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
let phpMarkup = jsx;
|
|
457
|
+
|
|
458
|
+
// Transpile <WpEditable> into standard JSX element so subsequent regexes can process it
|
|
459
|
+
phpMarkup = phpMarkup.replace(
|
|
460
|
+
/<WpEditable\s+([^>]*?)(?:\/>|>([\s\S]*?)<\/WpEditable>)/g,
|
|
461
|
+
(match, attrsStr, children) => {
|
|
462
|
+
const getAttr = (name) => {
|
|
463
|
+
const regex = new RegExp(
|
|
464
|
+
`${name}=(?:"([^"]*)"|'([^']*)'|\\{\\s*(?:attributes\\.|props\\.)?([a-zA-Z0-9_-]+)\\s*\\})`
|
|
465
|
+
);
|
|
466
|
+
const m = attrsStr.match(regex);
|
|
467
|
+
return m ? m[1] || m[2] || m[3] || '' : '';
|
|
468
|
+
};
|
|
469
|
+
|
|
470
|
+
const tag = getAttr('tagName') || 'div';
|
|
471
|
+
const valueVar = getAttr('value');
|
|
472
|
+
|
|
473
|
+
let cleanAttrs = attrsStr
|
|
474
|
+
.replace(/tagName=(?:"[^"]*"|'[^']*'|\{[^\}]*\})/g, '')
|
|
475
|
+
.replace(/value=(?:"[^"]*"|'[^']*'|\{[^\}]*\})/g, '')
|
|
476
|
+
.replace(/onChange=(?:"[^"]*"|'[^']*'|\{[^\}]*\})/g, '')
|
|
477
|
+
.trim();
|
|
478
|
+
|
|
479
|
+
if (cleanAttrs) cleanAttrs = ' ' + cleanAttrs;
|
|
480
|
+
|
|
481
|
+
const content = valueVar ? `{attributes.${valueVar}}` : (children || '');
|
|
482
|
+
|
|
483
|
+
return `<${tag}${cleanAttrs}>${content}</${tag}>`;
|
|
484
|
+
}
|
|
485
|
+
);
|
|
486
|
+
|
|
487
|
+
// className="..." -> class="..."
|
|
488
|
+
phpMarkup = phpMarkup.replace(/className=/g, 'class=');
|
|
489
|
+
|
|
490
|
+
// Transpile ES6 template literal conditional classes class={`...`}
|
|
491
|
+
phpMarkup = phpMarkup.replace(/class=\{\`([\s\S]*?)\`\}/g, (match, templateLiteralContent) => {
|
|
492
|
+
const processed = templateLiteralContent.replace(/\$\{\s*([\s\S]*?)\s*\}/g, (m, jsExpr) => {
|
|
493
|
+
const phpExpr = translateJsExpressionToPhp(jsExpr);
|
|
494
|
+
return `<?php echo esc_attr( ${phpExpr} ); ?>`;
|
|
495
|
+
});
|
|
496
|
+
return `class="${processed}"`;
|
|
497
|
+
});
|
|
498
|
+
|
|
499
|
+
// src={image} or src={attributes.image}
|
|
500
|
+
phpMarkup = phpMarkup.replace(
|
|
501
|
+
/(src|href|alt|title)=\{\s*(?:attributes\.|props\.)?([a-zA-Z0-9_-]+)\s*\}/gi,
|
|
502
|
+
(match, attr, varName) => {
|
|
503
|
+
const escFunc =
|
|
504
|
+
attr === 'href' || attr === 'src' ? 'esc_url' : 'esc_attr';
|
|
505
|
+
return `${attr}="<?php echo ${escFunc}( $attributes['${varName}'] ?? '' ); ?>"`;
|
|
506
|
+
},
|
|
507
|
+
);
|
|
508
|
+
|
|
509
|
+
// {title} or {props.title}
|
|
510
|
+
phpMarkup = phpMarkup.replace(
|
|
511
|
+
/\{\s*(?:attributes\.|props\.)?([a-zA-Z0-9_-]+)\s*\}/g,
|
|
512
|
+
(match, varName) => {
|
|
513
|
+
return `<?php echo esc_html( $attributes['${varName}'] ?? '' ); ?>`;
|
|
514
|
+
},
|
|
515
|
+
);
|
|
516
|
+
|
|
517
|
+
const renderPhpContent = `<?php
|
|
518
|
+
/**
|
|
519
|
+
* Gutenberg dynamic block template — ${settings.title}
|
|
520
|
+
* Autogenerated by ForgeWP Theme Compiler. Do not modify manually.
|
|
521
|
+
*/
|
|
522
|
+
?>
|
|
523
|
+
${phpMarkup}
|
|
524
|
+
`;
|
|
525
|
+
|
|
526
|
+
const blockOutDir = path.join(outDir, 'blocks', blockSlug);
|
|
527
|
+
mkdirSync(blockOutDir, { recursive: true });
|
|
528
|
+
|
|
529
|
+
// Write block.json and render.php
|
|
530
|
+
writeFileSync(
|
|
531
|
+
path.join(blockOutDir, 'block.json'),
|
|
532
|
+
JSON.stringify(settings, null, 2),
|
|
533
|
+
'utf8',
|
|
534
|
+
);
|
|
535
|
+
writeFileSync(
|
|
536
|
+
path.join(blockOutDir, 'render.php'),
|
|
537
|
+
renderPhpContent,
|
|
538
|
+
'utf8',
|
|
539
|
+
);
|
|
540
|
+
|
|
541
|
+
blockSlugs.push(settings);
|
|
542
|
+
} catch (e) {
|
|
543
|
+
console.error(
|
|
544
|
+
`[Gutenberg Block Compiler] Failed to compile block ${blockSlug}:`,
|
|
545
|
+
e.message,
|
|
546
|
+
);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
return blockSlugs;
|
|
552
|
+
}
|