@forgewp/compiler 0.4.2 → 0.4.4
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 +70 -3
- package/bin/add.js +30 -15
- package/bin/analyze.js +66 -1
- package/bin/cli.js +149 -70
- package/bin/doctor.js +21 -12
- package/bin/export.js +69 -20
- package/bin/fresh.js +6 -1
- package/bin/i18n-extract.js +3 -10
- package/bin/i18n-translate.js +15 -24
- package/bin/make-block.js +24 -0
- package/bin/make-editable.js +166 -0
- package/bin/make-form.js +131 -0
- package/bin/make-island.js +11 -0
- package/bin/make-loop.js +147 -0
- package/bin/make-mail.js +27 -0
- package/bin/make-page.js +83 -0
- package/bin/make-post-type.js +68 -29
- package/bin/make-sandbox.js +609 -0
- package/bin/make-section.js +221 -0
- package/bin/make-shell.js +375 -0
- package/bin/repair.js +14 -26
- package/bin/seed.js +119 -0
- package/bin/sync-routes.js +107 -85
- package/lib/adapters/html-adapter.js +13 -3
- package/lib/adapters/stub-adapter.js +10 -2
- package/lib/add-component.js +153 -92
- package/lib/asset-loader.js +333 -1
- package/lib/assets/asset-graph.js +432 -0
- package/lib/assets/asset-pipeline.js +125 -0
- package/lib/assets/diagnostics-report.js +345 -0
- package/lib/assets/external-fetcher.js +173 -0
- package/lib/assets/font-orchestrator.js +348 -0
- package/lib/assets/font-usage-scanner.js +242 -0
- package/lib/assets/image-optimizer.js +229 -0
- package/lib/assets/index.js +51 -0
- package/lib/assets/preload-generator.js +70 -0
- package/lib/assets/public-url.js +153 -0
- package/lib/block-authoring-help.js +11 -0
- package/lib/blocks/ast-parser.js +67 -0
- package/lib/blocks/discover-blocks.js +146 -0
- package/lib/blocks/editor-scope.js +733 -0
- package/lib/blocks/editor-transpiler.js +1229 -0
- package/lib/blocks/index.js +2838 -0
- package/lib/blocks/php-transpiler.js +4928 -0
- package/lib/blocks/scanner.js +1487 -0
- package/lib/blocks/shared-utils.js +290 -0
- package/lib/blocks/source-sanitize.js +1449 -0
- package/lib/blueprints.js +77 -5
- package/lib/build-assets.js +38 -33
- package/lib/collect-page-template-routes.js +102 -0
- package/lib/collect-static-routes.js +175 -0
- package/lib/diagnostics.js +58 -33
- package/lib/export-theme.js +84 -5
- package/lib/extract-template-content.js +90 -0
- package/lib/forms-preview.js +42 -0
- package/lib/functions/cpt-routing.js +69 -0
- package/lib/functions/forms.js +2461 -0
- package/lib/functions/hydration-enqueuer.js +400 -0
- package/lib/functions/index.js +1623 -0
- package/lib/functions/load-menus.js +112 -0
- package/lib/functions/load-translations.js +148 -0
- package/lib/functions/rest-endpoints.js +2923 -0
- package/lib/functions/routing.js +765 -0
- package/lib/functions/seed-mock-data.js +392 -0
- package/lib/functions/seed-products.js +481 -0
- package/lib/functions/settings-page.js +273 -0
- package/lib/functions/theme-setup.js +494 -0
- package/lib/generate-theme.js +2076 -303
- package/lib/hydration/editable-schemas.js +332 -0
- package/lib/hydration/enter-hidden-initial.js +65 -0
- package/lib/hydration/form-schemas.js +227 -0
- package/lib/hydration/index.js +12 -0
- package/lib/hydration/is-interactive.js +951 -0
- package/lib/hydration/island-split.js +1231 -0
- package/lib/hydration/islands-scanner.js +599 -0
- package/lib/hydration/resolve-island-chunk.js +103 -0
- package/lib/hydration/resolve-island-component.js +52 -0
- package/lib/hydration/rollup-inputs.js +81 -0
- package/lib/hydration/root-class-extractor.js +220 -0
- package/lib/hydration/scan-app-providers.js +154 -0
- package/lib/hydration/static-lint.js +382 -0
- package/lib/hydration/transform.js +257 -0
- package/lib/hydration/uses-block-area.js +49 -0
- package/lib/hydration/utils.js +119 -0
- package/lib/i18n/translation-cache.js +141 -0
- package/lib/icon-registry.js +72 -0
- package/lib/index.d.ts +324 -8
- package/lib/index.js +3 -2
- package/lib/load-config.js +338 -144
- package/lib/mail-templates.js +37 -0
- package/lib/markup-processor.js +483 -92
- package/lib/node-runtime.js +7 -0
- package/lib/page-config-plugin.js +84 -0
- package/lib/php-builders.js +383 -42
- package/lib/react-adapter.js +1053 -246
- package/lib/registration-metadata.js +11 -0
- package/lib/render-theme.mts +1410 -543
- package/lib/route-layout.js +76 -0
- package/lib/template-discovery.js +58 -0
- package/lib/theme-compatibility.js +32 -0
- package/lib/validate-export.js +51 -2
- package/lib/validate.js +27 -5
- package/lib/virtual-plugin.js +319 -0
- package/lib/walkthrough.md +26 -0
- package/package.json +17 -5
- package/templates/PresetsStyle.tsx +1 -1
- package/templates/auth/cms/email-logs.json +9 -0
- package/templates/auth/cms/menus.json +11 -0
- package/templates/auth/cms/mock-data.json +123 -0
- package/templates/auth/cms/roles.json +7 -0
- package/templates/auth/cms/sessions.json +1 -0
- package/templates/auth/cms/site-settings.json +28 -0
- package/templates/auth/cms/translations.json +4 -0
- package/templates/auth/cms/users.json +46 -0
- package/templates/auth/components/dashboard-view-wrapper.tsx +168 -0
- package/templates/auth/components/forgot-password-form-wrapper.tsx +141 -0
- package/templates/auth/components/login-form-wrapper.tsx +300 -0
- package/templates/auth/components/reset-password-form-wrapper.tsx +190 -0
- package/templates/auth/components/signup-form-wrapper.tsx +257 -0
- package/templates/auth/components/verify-email-view-wrapper.tsx +265 -0
- package/templates/auth/pages/DashboardPage.tsx +12 -0
- package/templates/auth/pages/ForgotPasswordPage.tsx +11 -0
- package/templates/auth/pages/LoginPage.tsx +11 -0
- package/templates/auth/pages/ResetPasswordPage.tsx +11 -0
- package/templates/auth/pages/SignUpPage.tsx +11 -0
- package/templates/auth/pages/VerifyEmailPage.tsx +11 -0
- package/templates/auth/ui/button.tsx +57 -0
- package/templates/auth/ui/card.tsx +76 -0
- package/templates/auth/ui/field.tsx +242 -0
- package/templates/auth/ui/input.tsx +22 -0
- package/templates/auth/ui/label.tsx +24 -0
- package/templates/auth/ui/separator.tsx +31 -0
- package/templates/forgewp-config.ts +70 -3
- package/templates/menus.json +12 -10
- package/templates/mock-data.json +122 -433
- package/templates/products.json +5 -0
- package/templates/roles.json +7 -0
- package/templates/sessions.json +1 -0
- package/templates/users.json +38 -0
- package/templates/wordpress.tsx +1835 -1297
- package/bin/make-template.js +0 -145
- package/lib/block-compiler.js +0 -552
- package/lib/functions-builder.js +0 -2044
- package/lib/hydration-scanner.js +0 -821
|
@@ -0,0 +1,2838 @@
|
|
|
1
|
+
import {
|
|
2
|
+
existsSync,
|
|
3
|
+
readdirSync,
|
|
4
|
+
readFileSync,
|
|
5
|
+
mkdirSync,
|
|
6
|
+
writeFileSync,
|
|
7
|
+
statSync,
|
|
8
|
+
} from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import {
|
|
11
|
+
scanAndGenerateBlocks,
|
|
12
|
+
parseDefineBlock,
|
|
13
|
+
parseDefineEditable,
|
|
14
|
+
mapEditableFieldToAttribute,
|
|
15
|
+
normalizeInnerBlocksConfig,
|
|
16
|
+
resolveComponentEditableSchema,
|
|
17
|
+
extractPickAttrMetaMap,
|
|
18
|
+
flushEditableIssues,
|
|
19
|
+
} from './scanner.js';
|
|
20
|
+
import {
|
|
21
|
+
findHtmlTagEnd,
|
|
22
|
+
resolveIconToSvgHtml,
|
|
23
|
+
warmupIconCache,
|
|
24
|
+
} from './shared-utils.js';
|
|
25
|
+
import {
|
|
26
|
+
generateReactCreateElement,
|
|
27
|
+
resolveIconToCreateElement,
|
|
28
|
+
parseJsxToAst,
|
|
29
|
+
transpileJsxInPreamble,
|
|
30
|
+
} from './editor-transpiler.js';
|
|
31
|
+
import {
|
|
32
|
+
extractJsx,
|
|
33
|
+
expandNestedComponentTags,
|
|
34
|
+
inlineIconWrapperTags,
|
|
35
|
+
transpileLoops,
|
|
36
|
+
transpileConditionals,
|
|
37
|
+
transpileTernaries,
|
|
38
|
+
transpileStaticArrayObjectMap,
|
|
39
|
+
translateStaticArrayLengthCheck,
|
|
40
|
+
translateJsExpressionToPhp,
|
|
41
|
+
extractCurlyExpression,
|
|
42
|
+
inlineJsxRenderHelperCalls,
|
|
43
|
+
generatePhpMarkupFromJsx,
|
|
44
|
+
} from './php-transpiler.js';
|
|
45
|
+
import {
|
|
46
|
+
stripTypeScriptSyntax,
|
|
47
|
+
extractSameFileHelpers,
|
|
48
|
+
jsHelperToPhpFunction,
|
|
49
|
+
jsxHelperToTemplate,
|
|
50
|
+
phpHelperName,
|
|
51
|
+
rewriteAttrRefsSafely,
|
|
52
|
+
stripTopLevelHelperDecl,
|
|
53
|
+
} from './source-sanitize.js';
|
|
54
|
+
import { buildEditorScopeInjections } from './editor-scope.js';
|
|
55
|
+
import { markLegacyFallback } from './ast-parser.js';
|
|
56
|
+
import {
|
|
57
|
+
isComponentInteractive,
|
|
58
|
+
isComponentEditorUnsafe,
|
|
59
|
+
readComponentSource,
|
|
60
|
+
} from '../hydration/is-interactive.js';
|
|
61
|
+
import { splitInteractiveIslands } from '../hydration/island-split.js';
|
|
62
|
+
|
|
63
|
+
export { scanAndGenerateBlocks, warmupIconCache, flushEditableIssues };
|
|
64
|
+
|
|
65
|
+
function findThemeCssFile(outDir) {
|
|
66
|
+
if (!outDir) return 'index.css';
|
|
67
|
+
const assetsDir = path.join(outDir, 'assets');
|
|
68
|
+
if (existsSync(assetsDir)) {
|
|
69
|
+
const files = readdirSync(assetsDir);
|
|
70
|
+
const cssFile = files.find(
|
|
71
|
+
(f) => f.startsWith('index-') && f.endsWith('.css'),
|
|
72
|
+
);
|
|
73
|
+
if (cssFile) {
|
|
74
|
+
return cssFile;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return 'index.css';
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Merge a class-attribute expression into the first opening tag found in
|
|
82
|
+
* `markup`. If that tag already has a class/className attribute, the new
|
|
83
|
+
* expression is appended inside the existing quotes; otherwise a new
|
|
84
|
+
* attribute is added. Used to apply paddingY/paddingX classes directly to a
|
|
85
|
+
* block's own top-level element without requiring any per-block wiring.
|
|
86
|
+
*/
|
|
87
|
+
function injectClassExprIntoFirstTag(markup, classExpr, attrName = 'class') {
|
|
88
|
+
const startMatch = markup.match(/<[a-zA-Z]/);
|
|
89
|
+
if (!startMatch) return markup;
|
|
90
|
+
const tagStart = startMatch.index;
|
|
91
|
+
|
|
92
|
+
// A naive [^<>]* attrs scan breaks the moment an attribute value contains an
|
|
93
|
+
// embedded <?php ... ?> block (the "<" of "<?php" looks like a new tag start),
|
|
94
|
+
// which is the common case here since the tag's own class attribute is often
|
|
95
|
+
// itself a PHP echo. findHtmlTagEnd already understands <?php ... ?> and
|
|
96
|
+
// quoted strings and is used for exactly this elsewhere in the compiler.
|
|
97
|
+
const tagEnd = findHtmlTagEnd(markup, tagStart);
|
|
98
|
+
if (tagEnd === -1) return markup;
|
|
99
|
+
|
|
100
|
+
const tagNameMatch = markup
|
|
101
|
+
.slice(tagStart + 1, tagEnd)
|
|
102
|
+
.match(/^([a-zA-Z][a-zA-Z0-9]*)/);
|
|
103
|
+
if (!tagNameMatch) return markup;
|
|
104
|
+
const tagName = tagNameMatch[1];
|
|
105
|
+
const attrsStr = markup.slice(tagStart + 1 + tagName.length, tagEnd);
|
|
106
|
+
|
|
107
|
+
const classAttrRegex = new RegExp(`\\s${attrName}=(["'])([\\s\\S]*?)\\1`);
|
|
108
|
+
const classAttrMatch = attrsStr.match(classAttrRegex);
|
|
109
|
+
let newAttrsStr;
|
|
110
|
+
if (classAttrMatch) {
|
|
111
|
+
const quote = classAttrMatch[1];
|
|
112
|
+
const existing = classAttrMatch[2];
|
|
113
|
+
const replacement = ` ${attrName}=${quote}${existing} ${classExpr}${quote}`;
|
|
114
|
+
newAttrsStr =
|
|
115
|
+
attrsStr.slice(0, classAttrMatch.index) +
|
|
116
|
+
replacement +
|
|
117
|
+
attrsStr.slice(classAttrMatch.index + classAttrMatch[0].length);
|
|
118
|
+
} else {
|
|
119
|
+
newAttrsStr = `${attrsStr} ${attrName}="${classExpr}"`;
|
|
120
|
+
}
|
|
121
|
+
const newTag = `<${tagName}${newAttrsStr}>`;
|
|
122
|
+
return markup.slice(0, tagStart) + newTag + markup.slice(tagEnd + 1);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function injectPaddingClassesIntoPhpMarkup(markup) {
|
|
126
|
+
return injectClassExprIntoFirstTag(
|
|
127
|
+
markup,
|
|
128
|
+
`<?php echo esc_attr( forgewp_padding_classes($attributes ?? array()) ); ?>`,
|
|
129
|
+
'class',
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Same token sets as forgewp_padding_classes() (PHP) and buildPaddingClassesJsExpr()
|
|
134
|
+
// (JS) below — keep all three in sync.
|
|
135
|
+
const PADDING_Y_TOKEN_PRESETS = [
|
|
136
|
+
['lg', ['py-12', 'sm:py-16']],
|
|
137
|
+
['md', ['py-8', 'sm:py-10']],
|
|
138
|
+
['sm', ['py-4', 'sm:py-6']],
|
|
139
|
+
];
|
|
140
|
+
const PADDING_X_TOKEN_PRESETS = [
|
|
141
|
+
['lg', ['px-4', 'sm:px-6', 'lg:px-8']],
|
|
142
|
+
['md', ['px-4', 'sm:px-6']],
|
|
143
|
+
['sm', ['px-4']],
|
|
144
|
+
];
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* A dev writes ordinary Tailwind padding classes (or none) on their block's own
|
|
148
|
+
* top-level element — no special convention required. If those classes exactly
|
|
149
|
+
* match one of the four padding presets, the compiler adopts it as that
|
|
150
|
+
* attribute's default (so retrofitting off hand-rolled padding doesn't silently
|
|
151
|
+
* reset a block's shipped appearance) and removes the literal tokens from the
|
|
152
|
+
* static className, so the sidebar-driven forgewp_padding_classes() call is the
|
|
153
|
+
* only thing controlling padding from then on — otherwise switching presets in
|
|
154
|
+
* the sidebar would layer the new classes on top of the never-changing old ones.
|
|
155
|
+
*/
|
|
156
|
+
function detectPresetMatch(classSet, presets) {
|
|
157
|
+
for (const [level, tokens] of presets) {
|
|
158
|
+
if (tokens.every((t) => classSet.has(t))) {
|
|
159
|
+
return { level, tokens };
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Find the first tag in `jsxText` and read its static className (plain string
|
|
167
|
+
* or a template literal with no ${} interpolation) — deliberately conservative;
|
|
168
|
+
* a dynamic className (computed, conditional, etc.) is left untouched and just
|
|
169
|
+
* yields no detected default (falls back to 'none'), since safely rewriting an
|
|
170
|
+
* arbitrary expression's literal text is out of scope here.
|
|
171
|
+
*/
|
|
172
|
+
function detectPaddingDefaultsFromJsx(jsxText) {
|
|
173
|
+
const empty = {
|
|
174
|
+
paddingY: 'none',
|
|
175
|
+
paddingX: 'none',
|
|
176
|
+
yTokens: [],
|
|
177
|
+
xTokens: [],
|
|
178
|
+
};
|
|
179
|
+
if (!jsxText) return empty;
|
|
180
|
+
const tagMatch = jsxText.match(/^\s*<[a-zA-Z][a-zA-Z0-9]*\b([^>]*)>/);
|
|
181
|
+
if (!tagMatch) return empty;
|
|
182
|
+
const attrsStr = tagMatch[1] || '';
|
|
183
|
+
const classMatch = attrsStr.match(
|
|
184
|
+
/className=(?:"([^"]*)"|'([^']*)'|\{`([^`$]*)`\})/,
|
|
185
|
+
);
|
|
186
|
+
const classStr = classMatch
|
|
187
|
+
? (classMatch[1] ?? classMatch[2] ?? classMatch[3] ?? '')
|
|
188
|
+
: '';
|
|
189
|
+
if (!classStr) return empty;
|
|
190
|
+
|
|
191
|
+
const classSet = new Set(classStr.split(/\s+/).filter(Boolean));
|
|
192
|
+
const yMatch = detectPresetMatch(classSet, PADDING_Y_TOKEN_PRESETS);
|
|
193
|
+
const xMatch = detectPresetMatch(classSet, PADDING_X_TOKEN_PRESETS);
|
|
194
|
+
return {
|
|
195
|
+
paddingY: yMatch ? yMatch.level : 'none',
|
|
196
|
+
paddingX: xMatch ? xMatch.level : 'none',
|
|
197
|
+
yTokens: yMatch ? yMatch.tokens : [],
|
|
198
|
+
xTokens: xMatch ? xMatch.tokens : [],
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Remove specific detected preset tokens (whole classes only, not substrings)
|
|
204
|
+
* from the first tag's className in `markup`, wherever that className lives —
|
|
205
|
+
* a plain string or a `<?php ... ?>`-embedded PHP echo of a static value.
|
|
206
|
+
*/
|
|
207
|
+
function stripPaddingTokensFromFirstTag(markup, tokens) {
|
|
208
|
+
if (!tokens || tokens.length === 0) return markup;
|
|
209
|
+
const startMatch = markup.match(/<[a-zA-Z]/);
|
|
210
|
+
if (!startMatch) return markup;
|
|
211
|
+
const tagStart = startMatch.index;
|
|
212
|
+
const tagEnd = findHtmlTagEnd(markup, tagStart);
|
|
213
|
+
if (tagEnd === -1) return markup;
|
|
214
|
+
|
|
215
|
+
let tag = markup.slice(tagStart, tagEnd + 1);
|
|
216
|
+
for (const token of tokens) {
|
|
217
|
+
const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
218
|
+
// Trailing boundary must NOT require whitespace/end-of-string — the token is
|
|
219
|
+
// almost always immediately followed by the class attribute's closing quote
|
|
220
|
+
// (e.g. `sm:py-10'`), which neither \s nor $ matches. A negative lookahead
|
|
221
|
+
// for "still part of a longer class-like token" is the correct boundary.
|
|
222
|
+
tag = tag
|
|
223
|
+
.replace(new RegExp(`(^|\\s)${escaped}(?![\\w:-])`, 'g'), '$1')
|
|
224
|
+
.replace(/ {2,}/g, ' ');
|
|
225
|
+
}
|
|
226
|
+
return markup.slice(0, tagStart) + tag + markup.slice(tagEnd + 1);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function buildPaddingClassesJsExpr() {
|
|
230
|
+
const py =
|
|
231
|
+
"({none:'',sm:'py-4 sm:py-6',md:'py-8 sm:py-10',lg:'py-12 sm:py-16'}[attributes.paddingY] || '')";
|
|
232
|
+
const px =
|
|
233
|
+
"({none:'',sm:'px-4',md:'px-4 sm:px-6',lg:'px-4 sm:px-6 lg:px-8'}[attributes.paddingX] || '')";
|
|
234
|
+
return `(${py} + ' ' + ${px}).trim()`;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Scan forward from `start` for the first top-level (depth-0) comma, respecting
|
|
239
|
+
* strings and nested (), [], {}. Returns -1 if none found before `end`.
|
|
240
|
+
*/
|
|
241
|
+
function findTopLevelComma(code, start, end) {
|
|
242
|
+
let depth = 0;
|
|
243
|
+
let inStr = null;
|
|
244
|
+
let esc = false;
|
|
245
|
+
for (let i = start; i < end; i++) {
|
|
246
|
+
const c = code[i];
|
|
247
|
+
if (inStr) {
|
|
248
|
+
if (esc) esc = false;
|
|
249
|
+
else if (c === '\\') esc = true;
|
|
250
|
+
else if (c === inStr) inStr = null;
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
if (c === '"' || c === "'" || c === '`') {
|
|
254
|
+
inStr = c;
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
if (c === '(' || c === '[' || c === '{') depth++;
|
|
258
|
+
else if (c === ')' || c === ']' || c === '}') {
|
|
259
|
+
if (depth === 0) return -1;
|
|
260
|
+
depth--;
|
|
261
|
+
} else if (c === ',' && depth === 0) {
|
|
262
|
+
return i;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return -1;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Remove specific whole-class tokens from a quoted JS string literal, leaving
|
|
270
|
+
* non-string-literal expressions (template literals, ternaries, …) untouched —
|
|
271
|
+
* safe no-op fallback rather than risking a mangled expression.
|
|
272
|
+
*/
|
|
273
|
+
function stripPaddingTokensFromJsStringLiteral(exprText, tokens) {
|
|
274
|
+
if (!tokens || tokens.length === 0) return exprText;
|
|
275
|
+
const m = exprText.match(/^(["'])([\s\S]*)\1$/);
|
|
276
|
+
if (!m) return exprText;
|
|
277
|
+
const quote = m[1];
|
|
278
|
+
let inner = m[2];
|
|
279
|
+
for (const token of tokens) {
|
|
280
|
+
const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
281
|
+
inner = inner
|
|
282
|
+
.replace(new RegExp(`(^|\\s)${escaped}(?![\\w:-])`, 'g'), '$1')
|
|
283
|
+
.replace(/ {2,}/g, ' ')
|
|
284
|
+
.trim();
|
|
285
|
+
}
|
|
286
|
+
return `${quote}${inner}${quote}`;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Merge computed paddingY/paddingX classes into the ROOT createElement call's
|
|
291
|
+
* props object in a generated customEditJsx string — mirrors
|
|
292
|
+
* injectPaddingClassesIntoPhpMarkup for the live editor-canvas path. Handles
|
|
293
|
+
* `createElement("tag", null, …)` and `createElement("tag", { ... }, …)`, with
|
|
294
|
+
* or without an existing className key. `tokensToStrip` removes any detected
|
|
295
|
+
* preset classes from the existing className first (see
|
|
296
|
+
* detectPaddingDefaultsFromJsx) so they don't linger alongside the new
|
|
297
|
+
* sidebar-driven computation once a preset is confirmed adopted as the default.
|
|
298
|
+
*/
|
|
299
|
+
function injectPaddingClassesIntoEditJsx(code, tokensToStrip = []) {
|
|
300
|
+
if (!code || !code.includes('createElement(')) return code;
|
|
301
|
+
const callIdx = code.indexOf('createElement(');
|
|
302
|
+
const argsStart = callIdx + 'createElement('.length;
|
|
303
|
+
|
|
304
|
+
const firstCommaIdx = findTopLevelComma(code, argsStart, code.length);
|
|
305
|
+
if (firstCommaIdx === -1) return code;
|
|
306
|
+
|
|
307
|
+
let propsStart = firstCommaIdx + 1;
|
|
308
|
+
while (propsStart < code.length && /\s/.test(code[propsStart])) propsStart++;
|
|
309
|
+
|
|
310
|
+
const paddingExpr = buildPaddingClassesJsExpr();
|
|
311
|
+
|
|
312
|
+
if (code.slice(propsStart, propsStart + 4) === 'null') {
|
|
313
|
+
return (
|
|
314
|
+
code.slice(0, propsStart) +
|
|
315
|
+
`{ className: ${paddingExpr} }` +
|
|
316
|
+
code.slice(propsStart + 4)
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
if (code[propsStart] !== '{') return code;
|
|
321
|
+
|
|
322
|
+
// Find the matching close brace for the props object
|
|
323
|
+
let depth = 0;
|
|
324
|
+
let inStr = null;
|
|
325
|
+
let esc = false;
|
|
326
|
+
let propsEnd = -1;
|
|
327
|
+
for (let i = propsStart; i < code.length; i++) {
|
|
328
|
+
const c = code[i];
|
|
329
|
+
if (inStr) {
|
|
330
|
+
if (esc) esc = false;
|
|
331
|
+
else if (c === '\\') esc = true;
|
|
332
|
+
else if (c === inStr) inStr = null;
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
if (c === '"' || c === "'" || c === '`') {
|
|
336
|
+
inStr = c;
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
if (c === '{') depth++;
|
|
340
|
+
else if (c === '}') {
|
|
341
|
+
depth--;
|
|
342
|
+
if (depth === 0) {
|
|
343
|
+
propsEnd = i;
|
|
344
|
+
break;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
if (propsEnd === -1) return code;
|
|
349
|
+
|
|
350
|
+
const propsText = code.slice(propsStart, propsEnd + 1);
|
|
351
|
+
const classNameMatch = propsText.match(/\bclassName\s*:\s*/);
|
|
352
|
+
let newPropsText;
|
|
353
|
+
if (classNameMatch) {
|
|
354
|
+
const valueStart = classNameMatch.index + classNameMatch[0].length;
|
|
355
|
+
const commaIdx = findTopLevelComma(
|
|
356
|
+
propsText,
|
|
357
|
+
valueStart,
|
|
358
|
+
propsText.length - 1,
|
|
359
|
+
);
|
|
360
|
+
const valueEnd = commaIdx === -1 ? propsText.length - 1 : commaIdx;
|
|
361
|
+
const existingValueExpr = stripPaddingTokensFromJsStringLiteral(
|
|
362
|
+
propsText.slice(valueStart, valueEnd).trim(),
|
|
363
|
+
tokensToStrip,
|
|
364
|
+
);
|
|
365
|
+
const merged = `((${existingValueExpr}) || '') + ' ' + ${paddingExpr}`;
|
|
366
|
+
newPropsText =
|
|
367
|
+
propsText.slice(0, valueStart) + merged + propsText.slice(valueEnd);
|
|
368
|
+
} else {
|
|
369
|
+
newPropsText = '{ className: ' + paddingExpr + ', ' + propsText.slice(1);
|
|
370
|
+
}
|
|
371
|
+
return code.slice(0, propsStart) + newPropsText + code.slice(propsEnd + 1);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Scans components and pages recursively for JSDoc annotated blocks,
|
|
376
|
+
* auto-generates wrapper block code inside src/blocks/generated/,
|
|
377
|
+
* then compiles both handcrafted and generated blocks into WordPress block files.
|
|
378
|
+
*
|
|
379
|
+
* @param {string} themeRoot
|
|
380
|
+
* @param {string} outDir
|
|
381
|
+
* @param {{ strict?: boolean }} [options] strict: fail export on from/pick issues
|
|
382
|
+
* @returns {string[]} Compiled block slugs
|
|
383
|
+
*/
|
|
384
|
+
export function compileBlocks(themeRoot, outDir, options = {}) {
|
|
385
|
+
// Auto-split components that mix static/attribute-driven content with
|
|
386
|
+
// genuine interactivity into a static shell + extracted islands, BEFORE
|
|
387
|
+
// anything below reads component source — readComponentSource (used by
|
|
388
|
+
// every readFileSync call in this function, and by isComponentInteractive)
|
|
389
|
+
// transparently returns the split shell instead of the dev's original,
|
|
390
|
+
// still-fully-interactive file content once this has run.
|
|
391
|
+
try {
|
|
392
|
+
splitInteractiveIslands(themeRoot);
|
|
393
|
+
} catch (err) {
|
|
394
|
+
console.warn(
|
|
395
|
+
'[ForgeWP Compiler] Error running splitInteractiveIslands:',
|
|
396
|
+
err.message,
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// Scan + generate wrappers; collect issues (flush after processDir so compile-time resolves are included)
|
|
401
|
+
scanAndGenerateBlocks(themeRoot, {
|
|
402
|
+
strict: false,
|
|
403
|
+
resetIssues: true,
|
|
404
|
+
flush: false,
|
|
405
|
+
});
|
|
406
|
+
|
|
407
|
+
const cssFile = findThemeCssFile(outDir);
|
|
408
|
+
|
|
409
|
+
const handcraftedDir = path.join(themeRoot, 'src', 'blocks');
|
|
410
|
+
const generatedDir = path.join(themeRoot, 'src', 'blocks', 'generated');
|
|
411
|
+
|
|
412
|
+
const blockSlugs = [];
|
|
413
|
+
const processedSlugs = new Set();
|
|
414
|
+
|
|
415
|
+
function processDir(dir) {
|
|
416
|
+
if (!existsSync(dir)) return;
|
|
417
|
+
const entries = readdirSync(dir);
|
|
418
|
+
for (const entry of entries) {
|
|
419
|
+
// Don't recurse into generated folder if processing handcrafted dir
|
|
420
|
+
if (dir === handcraftedDir && entry === 'generated') continue;
|
|
421
|
+
|
|
422
|
+
const entryPath = path.join(dir, entry);
|
|
423
|
+
let blockFile = '';
|
|
424
|
+
let blockSlug = '';
|
|
425
|
+
|
|
426
|
+
if (statSync(entryPath).isDirectory()) {
|
|
427
|
+
const indexPath = path.join(entryPath, 'index.tsx');
|
|
428
|
+
if (existsSync(indexPath)) {
|
|
429
|
+
blockFile = indexPath;
|
|
430
|
+
blockSlug = entry
|
|
431
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
432
|
+
.toLowerCase()
|
|
433
|
+
.replace(/[^a-z0-9]+/g, '-');
|
|
434
|
+
}
|
|
435
|
+
} else if (entry.endsWith('.tsx') || entry.endsWith('.jsx')) {
|
|
436
|
+
blockFile = entryPath;
|
|
437
|
+
blockSlug = entry
|
|
438
|
+
.replace(/\.(tsx|jsx)$/, '')
|
|
439
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
440
|
+
.toLowerCase()
|
|
441
|
+
.replace(/[^a-z0-9]+/g, '-');
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
if (blockFile && !processedSlugs.has(blockSlug)) {
|
|
445
|
+
processedSlugs.add(blockSlug);
|
|
446
|
+
try {
|
|
447
|
+
const code = readComponentSource(blockFile);
|
|
448
|
+
|
|
449
|
+
const importMap = {};
|
|
450
|
+
const importRx =
|
|
451
|
+
/import\s+(?:type\s+)?(?:\{([^}]+)\}|([A-Za-z0-9_$]+))\s+from\s+['"]([^'"]+)['"]/g;
|
|
452
|
+
let importMatch;
|
|
453
|
+
while ((importMatch = importRx.exec(code)) !== null) {
|
|
454
|
+
const namedImports = importMatch[1]; // e.g. "ArrowRight, Search, ChevronDown"
|
|
455
|
+
const defaultImport = importMatch[2]; // e.g. "React"
|
|
456
|
+
const fromPkg = importMatch[3]; // e.g. "lucide-react"
|
|
457
|
+
// Skip relative imports and known framework imports
|
|
458
|
+
if (
|
|
459
|
+
fromPkg.startsWith('.') ||
|
|
460
|
+
fromPkg.startsWith('@/') ||
|
|
461
|
+
fromPkg.startsWith('react') ||
|
|
462
|
+
fromPkg.startsWith('next')
|
|
463
|
+
)
|
|
464
|
+
continue;
|
|
465
|
+
if (namedImports) {
|
|
466
|
+
for (const name of namedImports.split(',')) {
|
|
467
|
+
const n = name.replace(/\s+as\s+\S+/, '').trim();
|
|
468
|
+
if (n && /^[A-Z]/.test(n)) importMap[n] = fromPkg;
|
|
469
|
+
}
|
|
470
|
+
} else if (defaultImport && /^[A-Z]/.test(defaultImport)) {
|
|
471
|
+
importMap[defaultImport] = fromPkg;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
const settingsMatch = code.match(
|
|
476
|
+
/export\s+const\s+settings\s*=\s*(\{[\s\S]*?\});/,
|
|
477
|
+
);
|
|
478
|
+
let settings = {
|
|
479
|
+
apiVersion: 3,
|
|
480
|
+
name: `forgewp/${blockSlug}`,
|
|
481
|
+
title: blockSlug
|
|
482
|
+
.split('-')
|
|
483
|
+
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
|
484
|
+
.join(' '),
|
|
485
|
+
category: 'design',
|
|
486
|
+
icon: 'admin-generic',
|
|
487
|
+
attributes: {},
|
|
488
|
+
supports: {
|
|
489
|
+
html: false,
|
|
490
|
+
},
|
|
491
|
+
editorStyle: `file:../../assets/${cssFile}`,
|
|
492
|
+
render: 'file:./render.php',
|
|
493
|
+
// Compile-time metadata used by generateReactCreateElement to resolve icon components
|
|
494
|
+
importMap,
|
|
495
|
+
themeRoot,
|
|
496
|
+
};
|
|
497
|
+
|
|
498
|
+
let parsedSettings = null;
|
|
499
|
+
if (code.includes('defineBlock(')) {
|
|
500
|
+
parsedSettings = parseDefineBlock(code, blockSlug);
|
|
501
|
+
} else if (settingsMatch) {
|
|
502
|
+
try {
|
|
503
|
+
const evalFn = new Function(`return ${settingsMatch[1]};`);
|
|
504
|
+
parsedSettings = evalFn();
|
|
505
|
+
} catch (e) {
|
|
506
|
+
console.warn(
|
|
507
|
+
`[Gutenberg Block Compiler] Error parsing legacy settings for ${blockSlug}:`,
|
|
508
|
+
e.message,
|
|
509
|
+
);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
if (parsedSettings) {
|
|
514
|
+
const parsedAttrs = parsedSettings.attributes || {};
|
|
515
|
+
settings = { ...settings, ...parsedSettings };
|
|
516
|
+
settings.attributes = {
|
|
517
|
+
...parsedAttrs,
|
|
518
|
+
};
|
|
519
|
+
if (!settings.supports) {
|
|
520
|
+
settings.supports = {};
|
|
521
|
+
}
|
|
522
|
+
settings.supports.html = false;
|
|
523
|
+
settings.editorStyle = `file:../../assets/${cssFile}`;
|
|
524
|
+
settings.name = settings.name
|
|
525
|
+
? settings.name.includes('/')
|
|
526
|
+
? settings.name
|
|
527
|
+
: `forgewp/${settings.name}`
|
|
528
|
+
: `forgewp/${blockSlug}`;
|
|
529
|
+
settings.apiVersion = 3;
|
|
530
|
+
settings.render = 'file:./render.php';
|
|
531
|
+
if (!settings.usesContext) {
|
|
532
|
+
settings.usesContext = [];
|
|
533
|
+
}
|
|
534
|
+
if (!settings.usesContext.includes('postId')) {
|
|
535
|
+
settings.usesContext.push('postId');
|
|
536
|
+
}
|
|
537
|
+
if (!settings.usesContext.includes('postType')) {
|
|
538
|
+
settings.usesContext.push('postType');
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// Editable schema: defineEditable / pickEditable / re-export / JSDoc from+pick
|
|
543
|
+
// Prefer the component source when this is a generated wrapper.
|
|
544
|
+
let editableSchema = resolveComponentEditableSchema(
|
|
545
|
+
code,
|
|
546
|
+
blockFile,
|
|
547
|
+
themeRoot,
|
|
548
|
+
);
|
|
549
|
+
let dualHostMeta = extractPickAttrMetaMap(code);
|
|
550
|
+
// Always resolve the component file for dualHostMeta (generated
|
|
551
|
+
// wrappers re-export editable but do not contain pickEditable maps).
|
|
552
|
+
const compImport = code.match(
|
|
553
|
+
/import\s+(?:(\w+)|\{[^}]*\b(\w+)\b[^}]*\})\s+from\s+['"](\.\.?\/[^'"]+)['"]/,
|
|
554
|
+
);
|
|
555
|
+
// Hoisted for the BAKED_PADDING lookup below — for a generated wrapper
|
|
556
|
+
// (src/blocks/generated/*.tsx), `code` is the wrapper's own text and
|
|
557
|
+
// never contains the component's module-level consts; the real source
|
|
558
|
+
// is only reachable through this same import resolution.
|
|
559
|
+
let resolvedComponentSource = code;
|
|
560
|
+
let resolvedComponentSourcePath = blockFile;
|
|
561
|
+
if (compImport) {
|
|
562
|
+
const importPath = compImport[3];
|
|
563
|
+
const extensions = ['.tsx', '.ts', '.jsx', '.js'];
|
|
564
|
+
for (const ext of extensions) {
|
|
565
|
+
const p = path.resolve(path.dirname(blockFile), importPath + ext);
|
|
566
|
+
if (existsSync(p)) {
|
|
567
|
+
const compCode = readComponentSource(p);
|
|
568
|
+
resolvedComponentSource = compCode;
|
|
569
|
+
resolvedComponentSourcePath = p;
|
|
570
|
+
if (!editableSchema) {
|
|
571
|
+
editableSchema = resolveComponentEditableSchema(
|
|
572
|
+
compCode,
|
|
573
|
+
p,
|
|
574
|
+
themeRoot,
|
|
575
|
+
);
|
|
576
|
+
}
|
|
577
|
+
if (!dualHostMeta) {
|
|
578
|
+
dualHostMeta = extractPickAttrMetaMap(compCode);
|
|
579
|
+
}
|
|
580
|
+
break;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
// Legacy direct defineEditable on the block file
|
|
585
|
+
if (!editableSchema && code.includes('defineEditable(')) {
|
|
586
|
+
editableSchema = parseDefineEditable(code);
|
|
587
|
+
}
|
|
588
|
+
if (dualHostMeta && Object.keys(dualHostMeta).length > 0) {
|
|
589
|
+
// attrKey → post meta key (ACF). Used on save_post so block edits
|
|
590
|
+
// update page meta that baked templates read via useWpMeta.
|
|
591
|
+
settings.dualHostMeta = dualHostMeta;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
if (editableSchema) {
|
|
595
|
+
if (!settings.attributes) {
|
|
596
|
+
settings.attributes = {
|
|
597
|
+
align: {
|
|
598
|
+
type: 'string',
|
|
599
|
+
default: 'full',
|
|
600
|
+
},
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
for (const [key, field] of Object.entries(editableSchema)) {
|
|
604
|
+
const mapped = mapEditableFieldToAttribute(field);
|
|
605
|
+
settings.attributes[key] = {
|
|
606
|
+
...(settings.attributes[key] || {}),
|
|
607
|
+
...mapped,
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// Every ForgeWP block ships with paddingY/paddingX by default — no
|
|
613
|
+
// per-block wiring needed. A dev writes normal Tailwind padding
|
|
614
|
+
// classes (or none) on their own top-level element; if they match a
|
|
615
|
+
// known preset exactly, the compiler adopts it as that attribute's
|
|
616
|
+
// default and strips the literal tokens from the static className
|
|
617
|
+
// (see stripPaddingTokensFromFirstTag below) so the sidebar-driven
|
|
618
|
+
// forgewp_padding_classes() call is the only thing controlling
|
|
619
|
+
// padding from then on. No dev code changes required either way.
|
|
620
|
+
if (!settings.attributes) settings.attributes = {};
|
|
621
|
+
const PADDING_OPTIONS = [
|
|
622
|
+
{ label: 'None', value: 'none' },
|
|
623
|
+
{ label: 'Small', value: 'sm' },
|
|
624
|
+
{ label: 'Medium', value: 'md' },
|
|
625
|
+
{ label: 'Large', value: 'lg' },
|
|
626
|
+
];
|
|
627
|
+
const detectedPadding = detectPaddingDefaultsFromJsx(
|
|
628
|
+
extractJsx(resolvedComponentSource) || '',
|
|
629
|
+
);
|
|
630
|
+
settings._detectedPaddingTokens = {
|
|
631
|
+
y: detectedPadding.yTokens,
|
|
632
|
+
x: detectedPadding.xTokens,
|
|
633
|
+
};
|
|
634
|
+
if (!settings.attributes.paddingY) {
|
|
635
|
+
settings.attributes.paddingY = {
|
|
636
|
+
type: 'string',
|
|
637
|
+
default: detectedPadding.paddingY,
|
|
638
|
+
control: 'select',
|
|
639
|
+
label: 'Vertical Padding',
|
|
640
|
+
options: PADDING_OPTIONS,
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
if (!settings.attributes.paddingX) {
|
|
644
|
+
settings.attributes.paddingX = {
|
|
645
|
+
type: 'string',
|
|
646
|
+
default: detectedPadding.paddingX,
|
|
647
|
+
control: 'select',
|
|
648
|
+
label: 'Horizontal Padding',
|
|
649
|
+
options: PADDING_OPTIONS,
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
if (settings.category) {
|
|
654
|
+
if (!settings.category.startsWith('forgewp-')) {
|
|
655
|
+
settings.category = `forgewp-${settings.category}`;
|
|
656
|
+
}
|
|
657
|
+
} else {
|
|
658
|
+
settings.category = 'forgewp-theme';
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
if (
|
|
662
|
+
settings.attributes &&
|
|
663
|
+
Object.keys(settings.attributes).length > 0
|
|
664
|
+
) {
|
|
665
|
+
settings.example = { attributes: {} };
|
|
666
|
+
for (const [key, attr] of Object.entries(settings.attributes)) {
|
|
667
|
+
settings.example.attributes[key] =
|
|
668
|
+
attr.default !== undefined && attr.default !== ''
|
|
669
|
+
? attr.default
|
|
670
|
+
: attr.type === 'number'
|
|
671
|
+
? 100
|
|
672
|
+
: attr.type === 'boolean'
|
|
673
|
+
? true
|
|
674
|
+
: `Sample ${key}`;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
// ── Parent shell blocks (InnerBlocks layout) ─────────────────────
|
|
679
|
+
// No content JSX required — shell + $content from child blocks.
|
|
680
|
+
if (settings.innerBlocks) {
|
|
681
|
+
const normalizedIb = normalizeInnerBlocksConfig(
|
|
682
|
+
settings.innerBlocks,
|
|
683
|
+
);
|
|
684
|
+
if (!normalizedIb) {
|
|
685
|
+
console.warn(
|
|
686
|
+
`[Gutenberg Block Compiler] Skipping parent shell ${blockSlug}: invalid innerBlocks config.`,
|
|
687
|
+
);
|
|
688
|
+
continue;
|
|
689
|
+
}
|
|
690
|
+
settings.isParentShell = true;
|
|
691
|
+
settings.innerBlocks = normalizedIb;
|
|
692
|
+
settings.shell =
|
|
693
|
+
settings.shell && typeof settings.shell === 'object'
|
|
694
|
+
? settings.shell
|
|
695
|
+
: {};
|
|
696
|
+
const shellClass = String(settings.shell.className || '').trim();
|
|
697
|
+
const gridClass = String(settings.shell.gridClassName || '').trim();
|
|
698
|
+
|
|
699
|
+
const blockFolderName = settings.name.replace('forgewp/', '');
|
|
700
|
+
const renderPhpContent = `<?php
|
|
701
|
+
/**
|
|
702
|
+
* Parent shell block — ${settings.title}
|
|
703
|
+
* Autogenerated by ForgeWP Theme Compiler. Do not modify manually.
|
|
704
|
+
*
|
|
705
|
+
* Layout-only wrapper. Child blocks are rendered into $content via InnerBlocks.
|
|
706
|
+
*/
|
|
707
|
+
$shell_class = ${JSON.stringify(shellClass ? `forgewp-block-shell ${shellClass}` : 'forgewp-block-shell')};
|
|
708
|
+
$grid_class = ${JSON.stringify(gridClass ? `forgewp-block-shell__grid ${gridClass}` : 'forgewp-block-shell__grid')};
|
|
709
|
+
?>
|
|
710
|
+
<div class="<?php echo esc_attr( $shell_class ); ?>">
|
|
711
|
+
<div class="<?php echo esc_attr( $grid_class ); ?>" style="min-width:0">
|
|
712
|
+
<?php echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- InnerBlocks HTML ?>
|
|
713
|
+
</div>
|
|
714
|
+
</div>
|
|
715
|
+
`;
|
|
716
|
+
|
|
717
|
+
const blockOutDir = path.join(outDir, 'blocks', blockFolderName);
|
|
718
|
+
mkdirSync(blockOutDir, { recursive: true });
|
|
719
|
+
|
|
720
|
+
const {
|
|
721
|
+
edit: _editShell,
|
|
722
|
+
customEditJsx: _cejShell,
|
|
723
|
+
importMap: _imShell,
|
|
724
|
+
themeRoot: _trShell,
|
|
725
|
+
isParentShell: _ips,
|
|
726
|
+
innerBlocks: _ibMeta,
|
|
727
|
+
shell: _shellMeta,
|
|
728
|
+
...blockJsonSettings
|
|
729
|
+
} = settings;
|
|
730
|
+
|
|
731
|
+
// Keep render + standard fields; drop compiler-only metadata from block.json
|
|
732
|
+
const jsonOut = {
|
|
733
|
+
apiVersion: 3,
|
|
734
|
+
name: settings.name,
|
|
735
|
+
title: settings.title,
|
|
736
|
+
category: settings.category,
|
|
737
|
+
icon: settings.icon,
|
|
738
|
+
description: settings.description || '',
|
|
739
|
+
attributes: settings.attributes || {},
|
|
740
|
+
supports: { html: false },
|
|
741
|
+
editorStyle: settings.editorStyle,
|
|
742
|
+
render: 'file:./render.php',
|
|
743
|
+
usesContext: settings.usesContext || ['postId', 'postType'],
|
|
744
|
+
};
|
|
745
|
+
|
|
746
|
+
writeFileSync(
|
|
747
|
+
path.join(blockOutDir, 'block.json'),
|
|
748
|
+
JSON.stringify(jsonOut, null, 2),
|
|
749
|
+
'utf8',
|
|
750
|
+
);
|
|
751
|
+
writeFileSync(
|
|
752
|
+
path.join(blockOutDir, 'render.php'),
|
|
753
|
+
renderPhpContent,
|
|
754
|
+
'utf8',
|
|
755
|
+
);
|
|
756
|
+
|
|
757
|
+
// forgeWpBlocks keeps full settings (isParentShell, innerBlocks, shell)
|
|
758
|
+
blockSlugs.push(settings);
|
|
759
|
+
console.log(
|
|
760
|
+
`[Gutenberg Block Compiler] Parent shell registered: ${settings.name}`,
|
|
761
|
+
);
|
|
762
|
+
continue;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
// Extract JSX from save first, then edit as fallback
|
|
766
|
+
let jsx = '';
|
|
767
|
+
if (code.includes('save:')) {
|
|
768
|
+
jsx = extractJsx(code, 'save');
|
|
769
|
+
}
|
|
770
|
+
if (!jsx && code.includes('edit:')) {
|
|
771
|
+
jsx = extractJsx(code, 'edit');
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
if (!jsx) {
|
|
775
|
+
const returnMatch = code.match(/return\s*\(\s*(<[\s\S]*?>)\s*\)/);
|
|
776
|
+
if (returnMatch) {
|
|
777
|
+
jsx = returnMatch[1];
|
|
778
|
+
} else {
|
|
779
|
+
const returnMatchSingle = code.match(/return\s+(<[\s\S]*?>);/);
|
|
780
|
+
if (returnMatchSingle) {
|
|
781
|
+
jsx = returnMatchSingle[1];
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
if (!jsx) {
|
|
787
|
+
console.warn(
|
|
788
|
+
`[Gutenberg Block Compiler] Skipping block ${blockSlug}: No returning JSX element found.`,
|
|
789
|
+
);
|
|
790
|
+
continue;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
let jsxSourceFile = blockFile;
|
|
794
|
+
let jsxSourceCode = code;
|
|
795
|
+
let resolvedComponentName = '';
|
|
796
|
+
if (jsx) {
|
|
797
|
+
const componentTagMatch = jsx
|
|
798
|
+
.trim()
|
|
799
|
+
.match(/^<([A-Z][a-zA-Z0-9_-]*)\s*([^>]*?)\/?>$/);
|
|
800
|
+
if (componentTagMatch) {
|
|
801
|
+
const compName = componentTagMatch[1];
|
|
802
|
+
resolvedComponentName = compName;
|
|
803
|
+
const importRegex = new RegExp(
|
|
804
|
+
`import\\s+(?:\\{\\s*${compName}\\s*\\}|${compName})\\s+from\\s+["']([^"']+)["']`,
|
|
805
|
+
);
|
|
806
|
+
const match = code.match(importRegex);
|
|
807
|
+
if (match) {
|
|
808
|
+
let importPath = match[1];
|
|
809
|
+
let resolvedPath = '';
|
|
810
|
+
if (importPath.startsWith('@/')) {
|
|
811
|
+
resolvedPath = path.resolve(
|
|
812
|
+
themeRoot,
|
|
813
|
+
importPath.replace('@/', './src/'),
|
|
814
|
+
);
|
|
815
|
+
} else {
|
|
816
|
+
resolvedPath = path.resolve(
|
|
817
|
+
path.dirname(blockFile),
|
|
818
|
+
importPath,
|
|
819
|
+
);
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
let finalPath = '';
|
|
823
|
+
for (const ext of [
|
|
824
|
+
'.tsx',
|
|
825
|
+
'.jsx',
|
|
826
|
+
'/index.tsx',
|
|
827
|
+
'/index.jsx',
|
|
828
|
+
]) {
|
|
829
|
+
if (existsSync(resolvedPath + ext)) {
|
|
830
|
+
finalPath = resolvedPath + ext;
|
|
831
|
+
break;
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
if (
|
|
835
|
+
existsSync(resolvedPath) &&
|
|
836
|
+
statSync(resolvedPath).isFile()
|
|
837
|
+
) {
|
|
838
|
+
finalPath = resolvedPath;
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
if (finalPath && existsSync(finalPath)) {
|
|
842
|
+
try {
|
|
843
|
+
const compContent = readComponentSource(finalPath);
|
|
844
|
+
const funcIndex = compContent.indexOf(
|
|
845
|
+
`function ${compName}`,
|
|
846
|
+
);
|
|
847
|
+
const constIndex = compContent.indexOf(`const ${compName}`);
|
|
848
|
+
const searchIndex =
|
|
849
|
+
funcIndex !== -1 ? funcIndex : constIndex;
|
|
850
|
+
|
|
851
|
+
let propKeys = [];
|
|
852
|
+
if (searchIndex !== -1) {
|
|
853
|
+
const sub = compContent.substring(searchIndex);
|
|
854
|
+
const paramMatch = sub.match(/\(\s*\{([\s\S]*?)\}/);
|
|
855
|
+
if (paramMatch) {
|
|
856
|
+
const paramBody = paramMatch[1];
|
|
857
|
+
const keyRegex = /([a-zA-Z0-9_-]+)(?:\s*=\s*[^,]+)?/g;
|
|
858
|
+
let kMatch;
|
|
859
|
+
while ((kMatch = keyRegex.exec(paramBody)) !== null) {
|
|
860
|
+
if (!kMatch[1].includes(':')) {
|
|
861
|
+
propKeys.push(kMatch[1].trim());
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
let compJsx = '';
|
|
868
|
+
if (searchIndex !== -1) {
|
|
869
|
+
compJsx =
|
|
870
|
+
extractJsx(
|
|
871
|
+
compContent.substring(searchIndex),
|
|
872
|
+
compName,
|
|
873
|
+
) || extractJsx(compContent, compName);
|
|
874
|
+
if (!compJsx) {
|
|
875
|
+
const sub = compContent.substring(searchIndex);
|
|
876
|
+
const returnMatch = sub.match(
|
|
877
|
+
/return\s*\(\s*(<[\s\S]*?>)\s*\)/,
|
|
878
|
+
);
|
|
879
|
+
if (returnMatch) {
|
|
880
|
+
compJsx = returnMatch[1];
|
|
881
|
+
} else {
|
|
882
|
+
const returnMatchSingle = sub.match(
|
|
883
|
+
/return\s+(<[\s\S]*?>);/,
|
|
884
|
+
);
|
|
885
|
+
if (returnMatchSingle) {
|
|
886
|
+
compJsx = returnMatchSingle[1];
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
if (compJsx) {
|
|
893
|
+
if (propKeys.length > 0) {
|
|
894
|
+
for (const key of propKeys) {
|
|
895
|
+
const rx = new RegExp(`\\{\\s*${key}\\s*\\}`, 'g');
|
|
896
|
+
compJsx = compJsx.replace(rx, `{attributes.${key}}`);
|
|
897
|
+
const attrRx = new RegExp(
|
|
898
|
+
`(src|href|alt|title)=\\{\\s*${key}\\s*\\}`,
|
|
899
|
+
'gi',
|
|
900
|
+
);
|
|
901
|
+
compJsx = compJsx.replace(
|
|
902
|
+
attrRx,
|
|
903
|
+
`$1={attributes.${key}}`,
|
|
904
|
+
);
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
jsx = compJsx;
|
|
908
|
+
jsxSourceFile = finalPath;
|
|
909
|
+
jsxSourceCode = compContent;
|
|
910
|
+
|
|
911
|
+
const compImportRx =
|
|
912
|
+
/import\s+(?:type\s+)?(?:\{([^}]+)\}|([A-Za-z0-9_$]+))\s+from\s+['"]([^'"]+)['"]/g;
|
|
913
|
+
let compImportMatch;
|
|
914
|
+
while (
|
|
915
|
+
(compImportMatch = compImportRx.exec(compContent)) !==
|
|
916
|
+
null
|
|
917
|
+
) {
|
|
918
|
+
const namedImports = compImportMatch[1];
|
|
919
|
+
const defaultImport = compImportMatch[2];
|
|
920
|
+
const fromPkg = compImportMatch[3];
|
|
921
|
+
if (
|
|
922
|
+
fromPkg.startsWith('.') ||
|
|
923
|
+
fromPkg.startsWith('@/') ||
|
|
924
|
+
fromPkg.startsWith('react') ||
|
|
925
|
+
fromPkg.startsWith('next')
|
|
926
|
+
)
|
|
927
|
+
continue;
|
|
928
|
+
if (namedImports) {
|
|
929
|
+
for (const name of namedImports.split(',')) {
|
|
930
|
+
const n = name.replace(/\s+as\s+\S+/, '').trim();
|
|
931
|
+
if (n && /^[A-Z]/.test(n)) importMap[n] = fromPkg;
|
|
932
|
+
}
|
|
933
|
+
} else if (
|
|
934
|
+
defaultImport &&
|
|
935
|
+
/^[A-Z]/.test(defaultImport)
|
|
936
|
+
) {
|
|
937
|
+
importMap[defaultImport] = fromPkg;
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
settings.importMap = importMap;
|
|
941
|
+
}
|
|
942
|
+
} catch (err) {
|
|
943
|
+
console.warn(
|
|
944
|
+
`[Gutenberg Block Compiler] Failed to resolve component source for ${compName}:`,
|
|
945
|
+
err.message,
|
|
946
|
+
);
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// Same-file "icon wrapper" helper components (e.g. ValueIcon) are
|
|
954
|
+
// invisible to expandNestedComponentTags (imports-only) — rewrite
|
|
955
|
+
// them to a direct <WpIcon> tag first so the dedicated WpIcon pass
|
|
956
|
+
// further down actually picks them up.
|
|
957
|
+
jsx = inlineIconWrapperTags(jsx, jsxSourceCode);
|
|
958
|
+
jsx = expandNestedComponentTags(
|
|
959
|
+
jsx,
|
|
960
|
+
jsxSourceCode,
|
|
961
|
+
jsxSourceFile,
|
|
962
|
+
themeRoot,
|
|
963
|
+
0,
|
|
964
|
+
'php',
|
|
965
|
+
);
|
|
966
|
+
|
|
967
|
+
// A block whose visitor component uses state, event handlers, or live-data
|
|
968
|
+
// hooks cannot be safely executed in the editor's generated IIFE. Let
|
|
969
|
+
// WordPress render its PHP output instead; authors can provide editorPreview
|
|
970
|
+
// when an interactive or live-data block needs a more representative view.
|
|
971
|
+
const isTopLevelLiveDataBlock =
|
|
972
|
+
isComponentInteractive(jsxSourceFile) &&
|
|
973
|
+
isComponentEditorUnsafe(jsxSourceFile);
|
|
974
|
+
const explicitEditorPreview = Object.prototype.hasOwnProperty.call(
|
|
975
|
+
settings,
|
|
976
|
+
'editorPreview',
|
|
977
|
+
)
|
|
978
|
+
? extractJsx(code, 'editorPreview')
|
|
979
|
+
: '';
|
|
980
|
+
const hasExplicitEditorPreview = Boolean(explicitEditorPreview);
|
|
981
|
+
const forceEditorPreview =
|
|
982
|
+
settings.editorPreviewMode === 'override' &&
|
|
983
|
+
hasExplicitEditorPreview;
|
|
984
|
+
let usesExplicitEditorPreview = false;
|
|
985
|
+
if (isTopLevelLiveDataBlock && !explicitEditorPreview) {
|
|
986
|
+
// Let WordPress render the generated PHP preview. React hooks,
|
|
987
|
+
// event handlers, and live data are not safe to execute in this
|
|
988
|
+
// compiler-generated editor component.
|
|
989
|
+
} else {
|
|
990
|
+
let editJsx = forceEditorPreview ? explicitEditorPreview : '';
|
|
991
|
+
usesExplicitEditorPreview = forceEditorPreview;
|
|
992
|
+
// paddingY/paddingX are excluded here — they're on every block by
|
|
993
|
+
// default and shouldn't by themselves flip a simple/static block from
|
|
994
|
+
// ServerSideRender (which just runs the real render.php for its editor
|
|
995
|
+
// preview) into the live customEditJsx canvas.
|
|
996
|
+
if (!editJsx && code.includes('edit:')) {
|
|
997
|
+
const sharedEdit = extractJsx(code, 'edit');
|
|
998
|
+
if (sharedEdit && sharedEdit.trim() !== 'null') {
|
|
999
|
+
editJsx = sharedEdit;
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
if (!editJsx && hasExplicitEditorPreview) {
|
|
1003
|
+
editJsx = explicitEditorPreview;
|
|
1004
|
+
usesExplicitEditorPreview = true;
|
|
1005
|
+
}
|
|
1006
|
+
if (editJsx) {
|
|
1007
|
+
try {
|
|
1008
|
+
editJsx = expandNestedComponentTags(
|
|
1009
|
+
editJsx,
|
|
1010
|
+
code,
|
|
1011
|
+
blockFile,
|
|
1012
|
+
themeRoot,
|
|
1013
|
+
0,
|
|
1014
|
+
'editor',
|
|
1015
|
+
);
|
|
1016
|
+
if (
|
|
1017
|
+
!usesExplicitEditorPreview &&
|
|
1018
|
+
hasExplicitEditorPreview &&
|
|
1019
|
+
editJsx.includes('forgewp-editor-island-placeholder')
|
|
1020
|
+
) {
|
|
1021
|
+
editJsx = expandNestedComponentTags(
|
|
1022
|
+
explicitEditorPreview,
|
|
1023
|
+
code,
|
|
1024
|
+
blockFile,
|
|
1025
|
+
themeRoot,
|
|
1026
|
+
0,
|
|
1027
|
+
'editor',
|
|
1028
|
+
);
|
|
1029
|
+
usesExplicitEditorPreview = true;
|
|
1030
|
+
}
|
|
1031
|
+
// Strip TS casts / annotations before AST → plain JS for new Function()
|
|
1032
|
+
editJsx = stripTypeScriptSyntax(editJsx);
|
|
1033
|
+
|
|
1034
|
+
const propKeys = Object.keys(settings.attributes || {});
|
|
1035
|
+
if (propKeys.length > 0) {
|
|
1036
|
+
for (const key of propKeys) {
|
|
1037
|
+
const rx = new RegExp(`\\{\\s*${key}\\s*\\}`, 'g');
|
|
1038
|
+
editJsx = editJsx.replace(rx, `{attributes.${key}}`);
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
// Rewrite bare attribute identifiers (and spread `...attr`) inside JSX
|
|
1042
|
+
// expression braces. Use balanced-brace scanning so nested objects
|
|
1043
|
+
// (e.g. setAttributes({ team: [...team, { ... }] })) are fully covered.
|
|
1044
|
+
// Spread must be handled first: `(?<![.\\w])team` fails on `...team`
|
|
1045
|
+
// because the last `.` of the spread looks like property access.
|
|
1046
|
+
const rewriteAttrRefsInExpr = (expr) =>
|
|
1047
|
+
rewriteAttrRefsSafely(expr, propKeys);
|
|
1048
|
+
|
|
1049
|
+
let rebuilt = '';
|
|
1050
|
+
let scan = 0;
|
|
1051
|
+
while (scan < editJsx.length) {
|
|
1052
|
+
const eqBrace = editJsx.indexOf('={', scan);
|
|
1053
|
+
if (eqBrace === -1) {
|
|
1054
|
+
rebuilt += editJsx.slice(scan);
|
|
1055
|
+
break;
|
|
1056
|
+
}
|
|
1057
|
+
rebuilt += editJsx.slice(scan, eqBrace + 2);
|
|
1058
|
+
let depth = 1;
|
|
1059
|
+
let pos = eqBrace + 2;
|
|
1060
|
+
let inSingle = false;
|
|
1061
|
+
let inDouble = false;
|
|
1062
|
+
let inBacktick = false;
|
|
1063
|
+
while (pos < editJsx.length && depth > 0) {
|
|
1064
|
+
const c = editJsx[pos];
|
|
1065
|
+
if (inSingle) {
|
|
1066
|
+
if (c === '\\') {
|
|
1067
|
+
pos += 2;
|
|
1068
|
+
continue;
|
|
1069
|
+
}
|
|
1070
|
+
if (c === "'") inSingle = false;
|
|
1071
|
+
} else if (inDouble) {
|
|
1072
|
+
if (c === '\\') {
|
|
1073
|
+
pos += 2;
|
|
1074
|
+
continue;
|
|
1075
|
+
}
|
|
1076
|
+
if (c === '"') inDouble = false;
|
|
1077
|
+
} else if (inBacktick) {
|
|
1078
|
+
if (c === '\\') {
|
|
1079
|
+
pos += 2;
|
|
1080
|
+
continue;
|
|
1081
|
+
}
|
|
1082
|
+
if (c === '`') inBacktick = false;
|
|
1083
|
+
} else {
|
|
1084
|
+
if (c === "'") inSingle = true;
|
|
1085
|
+
else if (c === '"') inDouble = true;
|
|
1086
|
+
else if (c === '`') inBacktick = true;
|
|
1087
|
+
else if (c === '{') depth++;
|
|
1088
|
+
else if (c === '}') depth--;
|
|
1089
|
+
}
|
|
1090
|
+
pos++;
|
|
1091
|
+
}
|
|
1092
|
+
const expr = editJsx.slice(eqBrace + 2, pos - 1);
|
|
1093
|
+
rebuilt += rewriteAttrRefsInExpr(expr) + '}';
|
|
1094
|
+
scan = pos;
|
|
1095
|
+
}
|
|
1096
|
+
editJsx = rebuilt;
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
const ast = parseJsxToAst(editJsx);
|
|
1100
|
+
if (!ast)
|
|
1101
|
+
throw new Error(
|
|
1102
|
+
'editJsx did not parse as a single JSX expression',
|
|
1103
|
+
);
|
|
1104
|
+
const customEditJsx = generateReactCreateElement(ast, settings);
|
|
1105
|
+
const paddingTokensToStrip = settings._detectedPaddingTokens
|
|
1106
|
+
? [
|
|
1107
|
+
...settings._detectedPaddingTokens.y,
|
|
1108
|
+
...settings._detectedPaddingTokens.x,
|
|
1109
|
+
]
|
|
1110
|
+
: [];
|
|
1111
|
+
settings.customEditJsx = injectPaddingClassesIntoEditJsx(
|
|
1112
|
+
customEditJsx,
|
|
1113
|
+
paddingTokensToStrip,
|
|
1114
|
+
);
|
|
1115
|
+
} catch (e) {
|
|
1116
|
+
console.warn(
|
|
1117
|
+
`[Gutenberg Block Compiler] Failed to parse custom edit JSX for ${blockSlug}:`,
|
|
1118
|
+
e.message,
|
|
1119
|
+
);
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
// Same-file helpers + TS-stripped locals for the editor IIFE / PHP render
|
|
1125
|
+
let hoistedHelperJs = '';
|
|
1126
|
+
let phpHelperDefinitions = '';
|
|
1127
|
+
const phpFreeFunctions = new Set();
|
|
1128
|
+
const helperNameToPhp = new Map();
|
|
1129
|
+
// JSX-returning helpers (e.g. `const cell = (a,b) => (<div>…)`) can't
|
|
1130
|
+
// become real PHP functions — jsHelperToPhpFunction rejects them —
|
|
1131
|
+
// so their call sites get inlined as literal JSX instead. Keyed by
|
|
1132
|
+
// helper name -> { params, jsxBody }.
|
|
1133
|
+
const jsxRenderHelperTemplates = new Map();
|
|
1134
|
+
const allSameFileHelperNames = new Set();
|
|
1135
|
+
|
|
1136
|
+
let phpVarDefinitions = '';
|
|
1137
|
+
let jsVarDefinitions = '';
|
|
1138
|
+
const localVars = new Set();
|
|
1139
|
+
const clientOnlyVars = new Set();
|
|
1140
|
+
if (!resolvedComponentName) {
|
|
1141
|
+
const funcMatch =
|
|
1142
|
+
jsxSourceCode.match(
|
|
1143
|
+
/(?:export\s+default\s+function|export\s+function|function)\s+([a-zA-Z0-9_$]+)/,
|
|
1144
|
+
) ||
|
|
1145
|
+
jsxSourceCode.match(
|
|
1146
|
+
/(?:export\s+const|const)\s+([A-Z][a-zA-Z0-9_$]*)/,
|
|
1147
|
+
);
|
|
1148
|
+
if (funcMatch && funcMatch[1] !== 'editable') {
|
|
1149
|
+
resolvedComponentName = funcMatch[1];
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
if (resolvedComponentName) {
|
|
1154
|
+
const funcIndex = jsxSourceCode.indexOf(
|
|
1155
|
+
`function ${resolvedComponentName}`,
|
|
1156
|
+
);
|
|
1157
|
+
const constIndex = jsxSourceCode.indexOf(
|
|
1158
|
+
`const ${resolvedComponentName}`,
|
|
1159
|
+
);
|
|
1160
|
+
const searchIndex = funcIndex !== -1 ? funcIndex : constIndex;
|
|
1161
|
+
if (searchIndex !== -1) {
|
|
1162
|
+
const sub = jsxSourceCode.substring(searchIndex);
|
|
1163
|
+
const returnMatch = sub.match(/return\s*\(?\s*</);
|
|
1164
|
+
const returnIdx = returnMatch ? returnMatch.index : -1;
|
|
1165
|
+
if (returnIdx !== -1) {
|
|
1166
|
+
const header = sub.substring(0, returnIdx);
|
|
1167
|
+
const attrKeys = Object.keys(settings.attributes || {});
|
|
1168
|
+
|
|
1169
|
+
const closeParenIdx = header.indexOf(')');
|
|
1170
|
+
const bodyBraceIdx = header.indexOf('{', closeParenIdx);
|
|
1171
|
+
let bodyHeader =
|
|
1172
|
+
bodyBraceIdx !== -1
|
|
1173
|
+
? header.substring(bodyBraceIdx + 1)
|
|
1174
|
+
: header;
|
|
1175
|
+
|
|
1176
|
+
bodyHeader = stripTypeScriptSyntax(bodyHeader);
|
|
1177
|
+
|
|
1178
|
+
// Rewrite bare attribute identifiers to attributes.X for the editor
|
|
1179
|
+
// IIFE — but NEVER rewrite binding names:
|
|
1180
|
+
// const title = … → must stay `const title`, not `const attributes.title`
|
|
1181
|
+
// (that produces "missing initializer in const declaration").
|
|
1182
|
+
bodyHeader = rewriteAttrRefsSafely(bodyHeader, attrKeys);
|
|
1183
|
+
|
|
1184
|
+
// Helpers defined before `return` may still contain JSX
|
|
1185
|
+
// (e.g. `const cell = () => (<div>…</div>)`). Convert those to
|
|
1186
|
+
// createElement so the editor IIFE is plain JS.
|
|
1187
|
+
if (/<[A-Za-z/$]/.test(bodyHeader) || /<>/.test(bodyHeader)) {
|
|
1188
|
+
bodyHeader = transpileJsxInPreamble(bodyHeader, settings);
|
|
1189
|
+
}
|
|
1190
|
+
jsVarDefinitions = bodyHeader;
|
|
1191
|
+
|
|
1192
|
+
// Optional `(?:\s*:\s*[^=]+?)?` after the name consumes (and discards) a
|
|
1193
|
+
// TypeScript type annotation — e.g. `const members: TeamMember[] = …` —
|
|
1194
|
+
// which the name charset itself can't include (no `:`). Without it the
|
|
1195
|
+
// whole declaration silently failed to match at all, so a repeater local
|
|
1196
|
+
// like `const members: TeamMember[] = Array.isArray(teamProp) ? …` never
|
|
1197
|
+
// even reached the value-translation logic below.
|
|
1198
|
+
const varRegex =
|
|
1199
|
+
/(?:const|let|var)\s+([a-zA-Z0-9_$,\s\[\]{}]+)(?:\s*:\s*[^=]+?)?\s*=\s*((?:[^;`"']|`(?:[^`\\]|\\.)*`|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')*?);/g;
|
|
1200
|
+
let vMatch;
|
|
1201
|
+
const reserved = [
|
|
1202
|
+
'setAttributes',
|
|
1203
|
+
'attributes',
|
|
1204
|
+
'clientId',
|
|
1205
|
+
'isSelected',
|
|
1206
|
+
'name',
|
|
1207
|
+
'context',
|
|
1208
|
+
'className',
|
|
1209
|
+
'attrs',
|
|
1210
|
+
];
|
|
1211
|
+
const phpStringLiteral = (s) =>
|
|
1212
|
+
`'${String(s).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
|
|
1213
|
+
|
|
1214
|
+
while ((vMatch = varRegex.exec(bodyHeader)) !== null) {
|
|
1215
|
+
const rawNames = vMatch[1];
|
|
1216
|
+
const varValue = vMatch[2].trim();
|
|
1217
|
+
const names =
|
|
1218
|
+
rawNames.match(/[a-zA-Z_$][a-zA-Z0-9_$]*/g) || [];
|
|
1219
|
+
if (names.length === 0) continue;
|
|
1220
|
+
|
|
1221
|
+
// useWpPageLink(slug, fallback) resolves to a real page URL server-side
|
|
1222
|
+
// via a dedicated PHP helper. Handled before the generic /useWp/ clientOnly
|
|
1223
|
+
// check below, which would otherwise silently drop it — leaving any
|
|
1224
|
+
// `href={pageLinkVar}` pointing at $attributes['pageLinkVar'] (undefined).
|
|
1225
|
+
const pageLinkMatch = varValue.match(
|
|
1226
|
+
/^useWpPageLink\(\s*(['"])((?:[^'"\\]|\\.)*)\1\s*(?:,\s*(['"])((?:[^'"\\]|\\.)*)\3\s*)?,?\s*\)$/,
|
|
1227
|
+
);
|
|
1228
|
+
if (
|
|
1229
|
+
pageLinkMatch &&
|
|
1230
|
+
names.length === 1 &&
|
|
1231
|
+
!reserved.includes(names[0])
|
|
1232
|
+
) {
|
|
1233
|
+
const slug = pageLinkMatch[2].replace(/\\(['"])/g, '$1');
|
|
1234
|
+
const fallback = (pageLinkMatch[4] || '').replace(
|
|
1235
|
+
/\\(['"])/g,
|
|
1236
|
+
'$1',
|
|
1237
|
+
);
|
|
1238
|
+
localVars.add(names[0]);
|
|
1239
|
+
phpVarDefinitions += `$${names[0]} = forgewp_resolve_page_link(${phpStringLiteral(slug)}, ${phpStringLiteral(fallback)});\n`;
|
|
1240
|
+
continue;
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
// useWpOption(name, default) reads a real WordPress site option —
|
|
1244
|
+
// trivially get_option() server-side. Without this dedicated case it
|
|
1245
|
+
// fell through to the generic /useWp/ clientOnly check below (which
|
|
1246
|
+
// exists for hooks that genuinely have no server twin, like useState),
|
|
1247
|
+
// silently dropping the value and everything derived from it — e.g.
|
|
1248
|
+
// ContactDetails' entire phone/email/address/hours list and social
|
|
1249
|
+
// links array are each `const x = useWpOption(...)`, so the whole
|
|
1250
|
+
// section rendered empty on the frontend even though these are plain,
|
|
1251
|
+
// always-available WordPress options.
|
|
1252
|
+
// Trailing comma (`,?` before the closing paren) covers the common
|
|
1253
|
+
// Prettier-formatted multi-line call — e.g. `useWpOption(\n 'x',\n 'y',\n)`
|
|
1254
|
+
// — which otherwise fails to match at all and silently drops the value.
|
|
1255
|
+
const wpOptionMatch = varValue.match(
|
|
1256
|
+
/^useWpOption\(\s*(['"])((?:[^'"\\]|\\.)*)\1\s*(?:,\s*(['"])((?:[^'"\\]|\\.)*)\3\s*,?\s*)?\)$/,
|
|
1257
|
+
);
|
|
1258
|
+
if (
|
|
1259
|
+
wpOptionMatch &&
|
|
1260
|
+
names.length === 1 &&
|
|
1261
|
+
!reserved.includes(names[0])
|
|
1262
|
+
) {
|
|
1263
|
+
const optionName = wpOptionMatch[2].replace(
|
|
1264
|
+
/\\(['"])/g,
|
|
1265
|
+
'$1',
|
|
1266
|
+
);
|
|
1267
|
+
const fallback = (wpOptionMatch[4] || '').replace(
|
|
1268
|
+
/\\(['"])/g,
|
|
1269
|
+
'$1',
|
|
1270
|
+
);
|
|
1271
|
+
localVars.add(names[0]);
|
|
1272
|
+
phpVarDefinitions += `$${names[0]} = get_option(${phpStringLiteral(optionName)}, ${phpStringLiteral(fallback)});\n`;
|
|
1273
|
+
continue;
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
// useWpMeta(key, default) reads a page/post meta field —
|
|
1277
|
+
// translates to forgewp_get_meta_value() server-side.
|
|
1278
|
+
// Trailing comma / multiline calls are handled via [\\s\\S]*? inside the regex.
|
|
1279
|
+
const wpMetaMatch = varValue.match(
|
|
1280
|
+
/^useWpMeta\(\s*(['"])((?:[^'"\\]|\\.)*)\1\s*,\s*([\s\S]*?)\s*\)$/,
|
|
1281
|
+
);
|
|
1282
|
+
if (
|
|
1283
|
+
wpMetaMatch &&
|
|
1284
|
+
names.length === 1 &&
|
|
1285
|
+
!reserved.includes(names[0])
|
|
1286
|
+
) {
|
|
1287
|
+
const metaKey = wpMetaMatch[2].replace(/\\(['"])/g, '$1');
|
|
1288
|
+
const rawFallback = wpMetaMatch[3]
|
|
1289
|
+
.trim()
|
|
1290
|
+
.replace(/,$/, '')
|
|
1291
|
+
.trim();
|
|
1292
|
+
let phpFallback = 'null';
|
|
1293
|
+
|
|
1294
|
+
// Section defaults are commonly imported with a local alias (for example, heroDefaults).
|
|
1295
|
+
const defaultsPropMatch = rawFallback.match(
|
|
1296
|
+
/^(?:defaults|[A-Za-z_$][A-Za-z0-9_$]*Defaults)\.([A-Za-z0-9_$]+)$/,
|
|
1297
|
+
);
|
|
1298
|
+
if (defaultsPropMatch) {
|
|
1299
|
+
const schemaKey = defaultsPropMatch[1];
|
|
1300
|
+
let attrKey = schemaKey;
|
|
1301
|
+
if (dualHostMeta) {
|
|
1302
|
+
for (const [aKey, mKey] of Object.entries(
|
|
1303
|
+
dualHostMeta,
|
|
1304
|
+
)) {
|
|
1305
|
+
if (mKey === schemaKey) {
|
|
1306
|
+
attrKey = aKey;
|
|
1307
|
+
break;
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
const attrDef = settings.attributes?.[attrKey];
|
|
1312
|
+
if (attrDef && typeof attrDef.default !== 'undefined') {
|
|
1313
|
+
phpFallback = phpStringLiteral(attrDef.default);
|
|
1314
|
+
}
|
|
1315
|
+
} else if (/^(['"])(.*?)\1$/.test(rawFallback)) {
|
|
1316
|
+
const stringLiteral = rawFallback
|
|
1317
|
+
.slice(1, -1)
|
|
1318
|
+
.replace(/\\(['"])/g, '$1');
|
|
1319
|
+
phpFallback = phpStringLiteral(stringLiteral);
|
|
1320
|
+
} else {
|
|
1321
|
+
phpFallback = translateJsExpressionToPhp(
|
|
1322
|
+
rawFallback,
|
|
1323
|
+
attrKeys,
|
|
1324
|
+
localVars,
|
|
1325
|
+
);
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
let isRichText = false;
|
|
1329
|
+
let attrKey = metaKey;
|
|
1330
|
+
if (dualHostMeta) {
|
|
1331
|
+
for (const [aKey, mKey] of Object.entries(dualHostMeta)) {
|
|
1332
|
+
if (mKey === metaKey) {
|
|
1333
|
+
attrKey = aKey;
|
|
1334
|
+
break;
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
const attrDefForRichText = settings.attributes?.[attrKey];
|
|
1339
|
+
if (
|
|
1340
|
+
attrDefForRichText &&
|
|
1341
|
+
(attrDefForRichText.control === 'richText' ||
|
|
1342
|
+
attrDefForRichText.control === 'wysiwyg')
|
|
1343
|
+
) {
|
|
1344
|
+
isRichText = true;
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
localVars.add(names[0]);
|
|
1348
|
+
phpVarDefinitions += `$${names[0]} = forgewp_get_meta_value(${phpStringLiteral(metaKey)}, ${phpFallback}, ${isRichText ? 'true' : 'false'}, null);\n`;
|
|
1349
|
+
continue;
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
// resolveBlockPaddingY(setAttributes, XProp, bakedDefault) — per
|
|
1353
|
+
// src/lib/section-padding.ts, "page host: always the baked default;
|
|
1354
|
+
// block host: attribute prop". render.php only ever renders a real,
|
|
1355
|
+
// active block (there is no "page host" render path here), so it
|
|
1356
|
+
// should always take the block-host branch: read the attribute,
|
|
1357
|
+
// fall back to the baked default. Previously this whole call fell
|
|
1358
|
+
// through to the generic unknownCall clientOnly check below, which
|
|
1359
|
+
// dropped it entirely — leaving padding permanently blank on the
|
|
1360
|
+
// frontend regardless of what the user picked in the sidebar.
|
|
1361
|
+
const paddingMatch = varValue.match(
|
|
1362
|
+
/^resolveBlockPaddingY\(\s*setAttributes\s*,\s*([A-Za-z_$][\w$]*)\s*,\s*([A-Za-z_$][\w$]*|'[^']*'|"[^"]*")\s*,?\s*\)$/,
|
|
1363
|
+
);
|
|
1364
|
+
if (
|
|
1365
|
+
paddingMatch &&
|
|
1366
|
+
names.length === 1 &&
|
|
1367
|
+
!reserved.includes(names[0])
|
|
1368
|
+
) {
|
|
1369
|
+
const propArg = paddingMatch[1];
|
|
1370
|
+
const attrKey = propArg.endsWith('Prop')
|
|
1371
|
+
? propArg.slice(0, -4)
|
|
1372
|
+
: propArg;
|
|
1373
|
+
let bakedDefault = paddingMatch[2];
|
|
1374
|
+
const bakedLiteralMatch =
|
|
1375
|
+
bakedDefault.match(/^['"]([^'"]*)['"]$/);
|
|
1376
|
+
if (bakedLiteralMatch) {
|
|
1377
|
+
bakedDefault = bakedLiteralMatch[1];
|
|
1378
|
+
} else {
|
|
1379
|
+
const constMatch = jsxSourceCode.match(
|
|
1380
|
+
new RegExp(
|
|
1381
|
+
`const\\s+${bakedDefault}\\s*=\\s*(['"])([^'"]*)\\1`,
|
|
1382
|
+
),
|
|
1383
|
+
);
|
|
1384
|
+
bakedDefault = constMatch ? constMatch[2] : 'md';
|
|
1385
|
+
}
|
|
1386
|
+
localVars.add(names[0]);
|
|
1387
|
+
phpVarDefinitions += `$${names[0]} = $attributes[${phpStringLiteral(attrKey)}] ?? ${phpStringLiteral(bakedDefault)};\n`;
|
|
1388
|
+
// sectionPaddingY(paddingY) — sibling helper, same file — gets a
|
|
1389
|
+
// real PHP twin too, via the same call-site rename used for
|
|
1390
|
+
// same-file hoisted helpers below.
|
|
1391
|
+
phpFreeFunctions.add('forgewp_section_padding_y');
|
|
1392
|
+
helperNameToPhp.set(
|
|
1393
|
+
'sectionPaddingY',
|
|
1394
|
+
'forgewp_section_padding_y',
|
|
1395
|
+
);
|
|
1396
|
+
continue;
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
// sectionPaddingY(paddingY) assigned to its own local var, e.g.
|
|
1400
|
+
// `const pad = sectionPaddingY(paddingY);` then `${pad}` later —
|
|
1401
|
+
// a second shape of the same helper pair (the other shape, inline
|
|
1402
|
+
// inside a class template literal, is handled by the
|
|
1403
|
+
// helperNameToPhp call-site rename below). Only reachable once the
|
|
1404
|
+
// paddingY-producing resolveBlockPaddingY() declaration above has
|
|
1405
|
+
// already run and registered the rename.
|
|
1406
|
+
const sectionPaddingCallMatch = varValue.match(
|
|
1407
|
+
/^sectionPaddingY\(\s*([A-Za-z_$][\w$]*)\s*\)$/,
|
|
1408
|
+
);
|
|
1409
|
+
if (
|
|
1410
|
+
sectionPaddingCallMatch &&
|
|
1411
|
+
names.length === 1 &&
|
|
1412
|
+
!reserved.includes(names[0])
|
|
1413
|
+
) {
|
|
1414
|
+
const argName = sectionPaddingCallMatch[1];
|
|
1415
|
+
const argRef = localVars.has(argName)
|
|
1416
|
+
? `$${argName}`
|
|
1417
|
+
: `($attributes[${phpStringLiteral(argName)}] ?? null)`;
|
|
1418
|
+
localVars.add(names[0]);
|
|
1419
|
+
phpVarDefinitions += `$${names[0]} = forgewp_section_padding_y(${argRef});\n`;
|
|
1420
|
+
continue;
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
// Dual-shape image/media fallback chain — the idiom used wherever
|
|
1424
|
+
// an "image" control attribute might be an object ({url, alt, id},
|
|
1425
|
+
// the shape the media picker actually saves) OR a plain string (a
|
|
1426
|
+
// baked default authored directly in block.json, e.g.
|
|
1427
|
+
// ContactHero/AboutHero's cardImage/image1/image2):
|
|
1428
|
+
// const cardImage = (cardImageProp && (cardImageProp as any).url)
|
|
1429
|
+
// || cardImageProp || cardImageMeta || '';
|
|
1430
|
+
// In JS, `(x as any).url` on a plain string just evaluates to
|
|
1431
|
+
// `undefined` — harmless. The naive PHP transpilation of `.url`
|
|
1432
|
+
// is unconditional array-index syntax (`$x['url']`), and PHP 8
|
|
1433
|
+
// throws a fatal TypeError indexing a string with a non-numeric
|
|
1434
|
+
// key ("Cannot access offset of type string on string") — turning
|
|
1435
|
+
// an untouched compile-time default into a site-breaking crash
|
|
1436
|
+
// the moment this block is actually inserted (WordPress applies
|
|
1437
|
+
// block.json's own default into $attributes even when nothing
|
|
1438
|
+
// was customized). Recognizing the idiom and guarding it with
|
|
1439
|
+
// is_array() preserves the same string-or-object either way.
|
|
1440
|
+
// Note: by the time this loop sees varValue, TypeScript `as`
|
|
1441
|
+
// casts have already been stripped upstream (stripAsCasts),
|
|
1442
|
+
// so `(cardImageProp as any).url` has already become plain
|
|
1443
|
+
// `(cardImageProp).url` here — the `as any` never survives
|
|
1444
|
+
// to this point, so the regex must not require it.
|
|
1445
|
+
const imageDualShapeMatch = varValue.match(
|
|
1446
|
+
/^\(\s*([A-Za-z_$][\w$]*)\s*&&\s*\(\s*\1\s*\)\.url\s*\)\s*\|\|\s*\1\s*\|\|\s*([A-Za-z_$][\w$]*)\s*\|\|\s*'([^']*)'$/,
|
|
1447
|
+
);
|
|
1448
|
+
if (
|
|
1449
|
+
imageDualShapeMatch &&
|
|
1450
|
+
names.length === 1 &&
|
|
1451
|
+
!reserved.includes(names[0])
|
|
1452
|
+
) {
|
|
1453
|
+
const propArg = imageDualShapeMatch[1];
|
|
1454
|
+
const metaArg = imageDualShapeMatch[2];
|
|
1455
|
+
const fallbackLiteral = imageDualShapeMatch[3];
|
|
1456
|
+
const attrKey = propArg.endsWith('Prop')
|
|
1457
|
+
? propArg.slice(0, -4)
|
|
1458
|
+
: propArg;
|
|
1459
|
+
if (attrKeys.includes(attrKey)) {
|
|
1460
|
+
const attrRef = `($attributes[${phpStringLiteral(attrKey)}] ?? null)`;
|
|
1461
|
+
const metaRef = localVars.has(metaArg)
|
|
1462
|
+
? `$${metaArg}`
|
|
1463
|
+
: `($attributes[${phpStringLiteral(metaArg)}] ?? null)`;
|
|
1464
|
+
localVars.add(names[0]);
|
|
1465
|
+
phpVarDefinitions += `$${names[0]} = (is_array(${attrRef}) ? (${attrRef}['url'] ?? '') : (${attrRef} ?? '')) ?: (${metaRef} ?: ${phpStringLiteral(fallbackLiteral)});\n`;
|
|
1466
|
+
continue;
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
// Array/repeater dual-host fallback chain — the idiom every
|
|
1471
|
+
// repeater-backed section uses (AboutTeam's `members`, AboutValues'
|
|
1472
|
+
// `rows`, AboutStats' `rows`, …):
|
|
1473
|
+
// const members = Array.isArray(teamProp) ? teamProp
|
|
1474
|
+
// : Array.isArray(teamMeta) ? teamMeta : (defaults.team_members as X[]);
|
|
1475
|
+
// The local var name (members) deliberately differs from the real
|
|
1476
|
+
// attribute key (team) for readability, but `.map()`'s loop-transpile
|
|
1477
|
+
// step (transpileLoops) just uses whatever identifier is literally
|
|
1478
|
+
// mapped-over as BOTH the attribute-key guess AND the local-var name
|
|
1479
|
+
// (`$attributes['members'] ?? $members ?? array()`) — it has no way
|
|
1480
|
+
// to know the JS variable's real data-flow origin. Since this whole
|
|
1481
|
+
// expression can't be `new Function()`-evaluated (teamProp/teamMeta/
|
|
1482
|
+
// defaults aren't defined in isolation) it fell through to the
|
|
1483
|
+
// generic bare-identifier fallback, producing `($teamProp ?? null)`
|
|
1484
|
+
// — always null — so the repeater silently rendered empty on the
|
|
1485
|
+
// frontend even though the block attribute had real rows. Recognizing
|
|
1486
|
+
// the idiom directly and resolving `teamProp` back to its attribute
|
|
1487
|
+
// key (strip the "Prop" suffix convention every dual-host component
|
|
1488
|
+
// uses) makes transpileLoops's own `?? $members` fallback pick up the
|
|
1489
|
+
// real value with no changes needed there.
|
|
1490
|
+
const arrayPropMetaMatch = varValue.match(
|
|
1491
|
+
/^Array\.isArray\(\s*([A-Za-z_$][\w$]*)\s*\)\s*\?\s*\1\s*:\s*Array\.isArray\(\s*[A-Za-z_$][\w$]*\s*\)\s*\?\s*[A-Za-z_$][\w$]*\s*:\s*\(?\s*defaults\.[A-Za-z_$][\w$]*\s*(?:as\s+[^)]+)?\)?$/,
|
|
1492
|
+
);
|
|
1493
|
+
if (
|
|
1494
|
+
arrayPropMetaMatch &&
|
|
1495
|
+
names.length === 1 &&
|
|
1496
|
+
!reserved.includes(names[0])
|
|
1497
|
+
) {
|
|
1498
|
+
const propArg = arrayPropMetaMatch[1];
|
|
1499
|
+
const attrKey = propArg.endsWith('Prop')
|
|
1500
|
+
? propArg.slice(0, -4)
|
|
1501
|
+
: propArg;
|
|
1502
|
+
if (attrKeys.includes(attrKey)) {
|
|
1503
|
+
localVars.add(names[0]);
|
|
1504
|
+
phpVarDefinitions += `$${names[0]} = $attributes[${phpStringLiteral(attrKey)}] ?? array();\n`;
|
|
1505
|
+
continue;
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
let referencesClientOnly = false;
|
|
1510
|
+
for (const clientVar of clientOnlyVars) {
|
|
1511
|
+
const rx = new RegExp(`\\b${clientVar}\\b`);
|
|
1512
|
+
if (rx.test(varValue)) {
|
|
1513
|
+
referencesClientOnly = true;
|
|
1514
|
+
break;
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
// Calls to imported/theme helpers (resolveBlockPaddingY, sectionPaddingY,
|
|
1519
|
+
// setState setters, DOM handlers, …) are not PHP-callable. Treat as
|
|
1520
|
+
// client-only so render.php never does ($fn ?? null)(...).
|
|
1521
|
+
const unknownCall = varValue.match(
|
|
1522
|
+
/^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/,
|
|
1523
|
+
);
|
|
1524
|
+
const knownPhpCall =
|
|
1525
|
+
unknownCall &&
|
|
1526
|
+
/^(Number|String|Boolean|parseInt|parseFloat|JSON\.parse|Math\.\w+|useWpPageLink|useWpMeta)$/.test(
|
|
1527
|
+
unknownCall[1],
|
|
1528
|
+
);
|
|
1529
|
+
const isClientOnly =
|
|
1530
|
+
referencesClientOnly ||
|
|
1531
|
+
/useRef|useState|useEffect|useMemo|useCallback|useWp|useIsEditorPreview|isEditorPreview|React\.|typeof\s+window|document\.|window\./.test(
|
|
1532
|
+
varValue,
|
|
1533
|
+
) ||
|
|
1534
|
+
varValue.includes('<') ||
|
|
1535
|
+
varValue.includes('>') ||
|
|
1536
|
+
(unknownCall && !knownPhpCall) ||
|
|
1537
|
+
// dual-host layout helpers take setAttributes — never SSR
|
|
1538
|
+
/\bsetAttributes\b/.test(varValue);
|
|
1539
|
+
|
|
1540
|
+
if (isClientOnly) {
|
|
1541
|
+
for (const name of names) {
|
|
1542
|
+
clientOnlyVars.add(name);
|
|
1543
|
+
}
|
|
1544
|
+
} else {
|
|
1545
|
+
for (const varName of names) {
|
|
1546
|
+
if (!reserved.includes(varName)) {
|
|
1547
|
+
localVars.add(varName);
|
|
1548
|
+
|
|
1549
|
+
let phpVal = '';
|
|
1550
|
+
if (
|
|
1551
|
+
varValue.startsWith('`') &&
|
|
1552
|
+
varValue.endsWith('`')
|
|
1553
|
+
) {
|
|
1554
|
+
const templateContent = varValue.slice(1, -1);
|
|
1555
|
+
const parts = [];
|
|
1556
|
+
let lastIdx = 0;
|
|
1557
|
+
const rx = /\$\{\s*([\s\S]*?)\s*\}/g;
|
|
1558
|
+
let m;
|
|
1559
|
+
while ((m = rx.exec(templateContent)) !== null) {
|
|
1560
|
+
const textBefore = templateContent.substring(
|
|
1561
|
+
lastIdx,
|
|
1562
|
+
m.index,
|
|
1563
|
+
);
|
|
1564
|
+
if (textBefore) {
|
|
1565
|
+
parts.push(JSON.stringify(textBefore));
|
|
1566
|
+
}
|
|
1567
|
+
const expr = translateJsExpressionToPhp(
|
|
1568
|
+
m[1],
|
|
1569
|
+
attrKeys,
|
|
1570
|
+
localVars,
|
|
1571
|
+
);
|
|
1572
|
+
parts.push(expr);
|
|
1573
|
+
lastIdx = rx.lastIndex;
|
|
1574
|
+
}
|
|
1575
|
+
const textAfter = templateContent.substring(lastIdx);
|
|
1576
|
+
if (textAfter) {
|
|
1577
|
+
parts.push(JSON.stringify(textAfter));
|
|
1578
|
+
}
|
|
1579
|
+
phpVal = parts.join(' . ');
|
|
1580
|
+
} else {
|
|
1581
|
+
let evaluatedVal;
|
|
1582
|
+
let evalSuccess = false;
|
|
1583
|
+
try {
|
|
1584
|
+
evaluatedVal = new Function(
|
|
1585
|
+
`return (${varValue});`,
|
|
1586
|
+
)();
|
|
1587
|
+
evalSuccess = true;
|
|
1588
|
+
} catch (e) {}
|
|
1589
|
+
|
|
1590
|
+
if (evalSuccess) {
|
|
1591
|
+
const convertJsValueToPhp = (val) => {
|
|
1592
|
+
if (val === null) return 'null';
|
|
1593
|
+
if (val === undefined) return 'null';
|
|
1594
|
+
if (typeof val === 'boolean')
|
|
1595
|
+
return val ? 'true' : 'false';
|
|
1596
|
+
if (typeof val === 'number') return String(val);
|
|
1597
|
+
if (typeof val === 'string')
|
|
1598
|
+
return JSON.stringify(val);
|
|
1599
|
+
if (Array.isArray(val)) {
|
|
1600
|
+
return (
|
|
1601
|
+
'[' +
|
|
1602
|
+
val.map(convertJsValueToPhp).join(', ') +
|
|
1603
|
+
']'
|
|
1604
|
+
);
|
|
1605
|
+
}
|
|
1606
|
+
if (typeof val === 'object') {
|
|
1607
|
+
const parts = Object.entries(val).map(
|
|
1608
|
+
([k, v]) => {
|
|
1609
|
+
return `${JSON.stringify(k)} => ${convertJsValueToPhp(v)}`;
|
|
1610
|
+
},
|
|
1611
|
+
);
|
|
1612
|
+
return '[' + parts.join(', ') + ']';
|
|
1613
|
+
}
|
|
1614
|
+
return 'null';
|
|
1615
|
+
};
|
|
1616
|
+
phpVal = convertJsValueToPhp(evaluatedVal);
|
|
1617
|
+
} else {
|
|
1618
|
+
phpVal = translateJsExpressionToPhp(
|
|
1619
|
+
varValue,
|
|
1620
|
+
attrKeys,
|
|
1621
|
+
localVars,
|
|
1622
|
+
);
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
// Last line of defense: never emit null callables
|
|
1627
|
+
if (
|
|
1628
|
+
/\(\s*\$\w+\s*\?\?\s*null\s*\)\s*\(/.test(phpVal) ||
|
|
1629
|
+
/\bnull\s*\(/.test(phpVal)
|
|
1630
|
+
) {
|
|
1631
|
+
clientOnlyVars.add(varName);
|
|
1632
|
+
localVars.delete(varName);
|
|
1633
|
+
continue;
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
phpVarDefinitions += `$${varName} = ${phpVal};\n`;
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
// Hoist same-file helpers referenced by the component (e.g. avatarUrl())
|
|
1646
|
+
// into the editor IIFE so developers can write normal TS modules.
|
|
1647
|
+
if (settings.customEditJsx || jsx) {
|
|
1648
|
+
const usageBlob = [
|
|
1649
|
+
settings.customEditJsx || '',
|
|
1650
|
+
jsx || '',
|
|
1651
|
+
jsVarDefinitions || '',
|
|
1652
|
+
].join('\n');
|
|
1653
|
+
const exclude = new Set(
|
|
1654
|
+
[
|
|
1655
|
+
resolvedComponentName,
|
|
1656
|
+
'defineEditable',
|
|
1657
|
+
'defineBlock',
|
|
1658
|
+
'editable',
|
|
1659
|
+
...Object.keys(settings.attributes || {}),
|
|
1660
|
+
].filter(Boolean),
|
|
1661
|
+
);
|
|
1662
|
+
const helpers = extractSameFileHelpers(
|
|
1663
|
+
jsxSourceCode,
|
|
1664
|
+
usageBlob,
|
|
1665
|
+
exclude,
|
|
1666
|
+
);
|
|
1667
|
+
for (const h of helpers) allSameFileHelperNames.add(h.name);
|
|
1668
|
+
if (helpers.length > 0) {
|
|
1669
|
+
// Helpers may return JSX (e.g. const cell = () => <div/>). Convert for editor.
|
|
1670
|
+
// If the same helper also lives in jsVarDefinitions (inline const before return),
|
|
1671
|
+
// drop the body copy so we don't double-declare in the IIFE.
|
|
1672
|
+
for (const h of helpers) {
|
|
1673
|
+
if (jsVarDefinitions) {
|
|
1674
|
+
jsVarDefinitions = stripTopLevelHelperDecl(
|
|
1675
|
+
jsVarDefinitions,
|
|
1676
|
+
h.name,
|
|
1677
|
+
);
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
hoistedHelperJs = helpers
|
|
1681
|
+
.map((h) => {
|
|
1682
|
+
let code = h.code;
|
|
1683
|
+
if (/<[A-Za-z/$]/.test(code) || /<>/.test(code)) {
|
|
1684
|
+
code = transpileJsxInPreamble(code, settings);
|
|
1685
|
+
}
|
|
1686
|
+
return code;
|
|
1687
|
+
})
|
|
1688
|
+
.join('\n\n');
|
|
1689
|
+
// Prefer defineBlock name (forgewp/slug) over generated wrapper file slug
|
|
1690
|
+
const helperSlug = (settings.name || blockSlug).replace(
|
|
1691
|
+
/^forgewp\//,
|
|
1692
|
+
'',
|
|
1693
|
+
);
|
|
1694
|
+
for (const h of helpers) {
|
|
1695
|
+
const phpName = phpHelperName(helperSlug, h.name);
|
|
1696
|
+
const phpFn = jsHelperToPhpFunction(phpName, h.code);
|
|
1697
|
+
if (phpFn) {
|
|
1698
|
+
phpHelperDefinitions += phpFn;
|
|
1699
|
+
phpFreeFunctions.add(phpName);
|
|
1700
|
+
helperNameToPhp.set(h.name, phpName);
|
|
1701
|
+
} else {
|
|
1702
|
+
const template = jsxHelperToTemplate(h.code);
|
|
1703
|
+
if (template) {
|
|
1704
|
+
jsxRenderHelperTemplates.set(h.name, template);
|
|
1705
|
+
} else {
|
|
1706
|
+
console.warn(
|
|
1707
|
+
`[Gutenberg Block Compiler] Could not convert helper "${h.name}" to PHP for block ${blockSlug}; editor still works.`,
|
|
1708
|
+
);
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
// The top-level live-data placeholder (set above when isTopLevelLiveDataBlock)
|
|
1716
|
+
// is a fully self-contained createElement(...) call — it references none of
|
|
1717
|
+
// the component's own local vars. jsVarDefinitions is extracted by cutting the
|
|
1718
|
+
// component body off right before its FIRST `return (<...`, which for a
|
|
1719
|
+
// component with an early-return branch (e.g. `if (loading) { return (...) }`)
|
|
1720
|
+
// is that branch's own return, not the top-level one — leaving the `if (loading) {`
|
|
1721
|
+
// opening brace hoisted into the preamble with no matching close. Safe for the
|
|
1722
|
+
// real editJsx path (whose FIRST return generally IS the top-level one), but
|
|
1723
|
+
// actively harmful here, so skip preamble injection entirely for this branch.
|
|
1724
|
+
if (
|
|
1725
|
+
settings.customEditJsx &&
|
|
1726
|
+
(!isTopLevelLiveDataBlock || hasExplicitEditorPreview)
|
|
1727
|
+
) {
|
|
1728
|
+
let preamble = usesExplicitEditorPreview
|
|
1729
|
+
? ''
|
|
1730
|
+
: [hoistedHelperJs, jsVarDefinitions]
|
|
1731
|
+
.filter(Boolean)
|
|
1732
|
+
.join('\n\n');
|
|
1733
|
+
// Final pass: any residual JSX in the combined preamble
|
|
1734
|
+
if (
|
|
1735
|
+
preamble &&
|
|
1736
|
+
(/<[A-Za-z/$]/.test(preamble) || /<>/.test(preamble))
|
|
1737
|
+
) {
|
|
1738
|
+
preamble = transpileJsxInPreamble(preamble, settings);
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
// Inject `defaults`, module consts (BAKED_PADDING), SECTION_PADDING_Y,
|
|
1742
|
+
// imported helpers, and dual-host prop aliases so the IIFE does not throw
|
|
1743
|
+
// "defaults is not defined" (no ESM in new Function).
|
|
1744
|
+
// Also attach settings.editorScope for a runtime second line of defense.
|
|
1745
|
+
const iifeProbe = `${preamble}\n${settings.customEditJsx}`;
|
|
1746
|
+
const scopeResult = buildEditorScopeInjections(
|
|
1747
|
+
usesExplicitEditorPreview ? code : jsxSourceCode || code,
|
|
1748
|
+
usesExplicitEditorPreview ? blockFile : jsxSourceFile || blockFile,
|
|
1749
|
+
themeRoot,
|
|
1750
|
+
iifeProbe,
|
|
1751
|
+
);
|
|
1752
|
+
const scopeInjections =
|
|
1753
|
+
typeof scopeResult === 'string'
|
|
1754
|
+
? scopeResult
|
|
1755
|
+
: (scopeResult && scopeResult.injections) || '';
|
|
1756
|
+
const editorScope =
|
|
1757
|
+
scopeResult &&
|
|
1758
|
+
typeof scopeResult === 'object' &&
|
|
1759
|
+
scopeResult.scope
|
|
1760
|
+
? scopeResult.scope
|
|
1761
|
+
: {};
|
|
1762
|
+
if (Object.keys(editorScope).length > 0) {
|
|
1763
|
+
settings.editorScope = editorScope;
|
|
1764
|
+
}
|
|
1765
|
+
if (scopeInjections) {
|
|
1766
|
+
preamble = [scopeInjections, preamble]
|
|
1767
|
+
.filter(Boolean)
|
|
1768
|
+
.join('\n\n');
|
|
1769
|
+
}
|
|
1770
|
+
|
|
1771
|
+
if (preamble) {
|
|
1772
|
+
settings.customEditJsx = `(() => {\n${preamble}\nreturn ${settings.customEditJsx};\n})()`;
|
|
1773
|
+
} else if (scopeInjections) {
|
|
1774
|
+
settings.customEditJsx = `(() => {\n${scopeInjections}\nreturn ${settings.customEditJsx};\n})()`;
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
// Older nested-island expansion can synthesize a text notice; require an
|
|
1779
|
+
// authored editorPreview when the shared edit component cannot be expanded.
|
|
1780
|
+
if (
|
|
1781
|
+
!usesExplicitEditorPreview &&
|
|
1782
|
+
settings.customEditJsx?.includes(
|
|
1783
|
+
'forgewp-editor-island-placeholder',
|
|
1784
|
+
)
|
|
1785
|
+
) {
|
|
1786
|
+
delete settings.customEditJsx;
|
|
1787
|
+
delete settings.editorScope;
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
let phpMarkup = jsx;
|
|
1791
|
+
|
|
1792
|
+
// Inline local JSX-returning render-helper calls (e.g. `{cell(a, b)}`)
|
|
1793
|
+
// before anything else touches phpMarkup — must run first so the
|
|
1794
|
+
// substituted JSX flows through the normal transpileConditionals/
|
|
1795
|
+
// transpileTernaries/etc. pipeline below like markup the dev wrote
|
|
1796
|
+
// directly inline, instead of surviving as literal, unexecuted JS text.
|
|
1797
|
+
if (jsxRenderHelperTemplates.size > 0) {
|
|
1798
|
+
phpMarkup = inlineJsxRenderHelperCalls(
|
|
1799
|
+
phpMarkup,
|
|
1800
|
+
jsxRenderHelperTemplates,
|
|
1801
|
+
);
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
// Rewrite helper calls to PHP function names before expression transpile
|
|
1805
|
+
if (helperNameToPhp.size > 0) {
|
|
1806
|
+
for (const [jsName, phpName] of helperNameToPhp) {
|
|
1807
|
+
phpMarkup = phpMarkup.replace(
|
|
1808
|
+
new RegExp(`\\b${jsName}\\s*\\(`, 'g'),
|
|
1809
|
+
`${phpName}(`,
|
|
1810
|
+
);
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
// AST-based markup emission (Phase 2 Step 4, PHP half): parses
|
|
1815
|
+
// phpMarkup once and emits render.php markup directly via
|
|
1816
|
+
// recursive node.type-keyed emitters — see generatePhpMarkupFromJsx's
|
|
1817
|
+
// doc comment in php-transpiler.js. Every text pass below this point
|
|
1818
|
+
// (icon/WpEditable/dangerouslySetInnerHTML substitution, attribute
|
|
1819
|
+
// escaping, className rename, ternary/conditional/loop transpile,
|
|
1820
|
+
// tag unwrapping, …) only matches specific literal patterns
|
|
1821
|
+
// (`<WpIcon`, `className=`, `{expr}`, …) that no longer appear in
|
|
1822
|
+
// this function's output for anything it successfully resolved —
|
|
1823
|
+
// so they remain safe, idempotent no-ops there, while still fully
|
|
1824
|
+
// processing the one thing it deliberately leaves as verbatim JSX
|
|
1825
|
+
// text: a `.map()` loop whose array target isn't a simple
|
|
1826
|
+
// attribute/local-var/split-string shape (a static array literal,
|
|
1827
|
+
// an `as const` cast, …), which needs transpileStaticArrayObjectMap's
|
|
1828
|
+
// cross-file resolution, not a property of the JSX subtree alone.
|
|
1829
|
+
const astPhpMarkup = generatePhpMarkupFromJsx(phpMarkup, settings, {
|
|
1830
|
+
localVars,
|
|
1831
|
+
freeFunctions: phpFreeFunctions,
|
|
1832
|
+
themeRoot,
|
|
1833
|
+
});
|
|
1834
|
+
if (astPhpMarkup === null) {
|
|
1835
|
+
markLegacyFallback('index:generatePhpMarkupFromJsx');
|
|
1836
|
+
}
|
|
1837
|
+
if (astPhpMarkup !== null) {
|
|
1838
|
+
phpMarkup = astPhpMarkup;
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
if (settings.importMap) {
|
|
1842
|
+
let startSearch = 0;
|
|
1843
|
+
while (true) {
|
|
1844
|
+
const match = phpMarkup
|
|
1845
|
+
.substring(startSearch)
|
|
1846
|
+
.match(
|
|
1847
|
+
/<([A-Z][a-zA-Z0-9]*)(?:\s+([^>]*?))?\s*(\/>|>([\s\S]*?)<\/\1>)/,
|
|
1848
|
+
);
|
|
1849
|
+
if (!match) break;
|
|
1850
|
+
|
|
1851
|
+
const fullTag = match[0];
|
|
1852
|
+
const compName = match[1];
|
|
1853
|
+
const attrsStr = match[2] || '';
|
|
1854
|
+
|
|
1855
|
+
const matchIndex = phpMarkup.indexOf(fullTag, startSearch);
|
|
1856
|
+
if (matchIndex === -1) {
|
|
1857
|
+
startSearch += 1;
|
|
1858
|
+
continue;
|
|
1859
|
+
}
|
|
1860
|
+
|
|
1861
|
+
if (settings.importMap[compName]) {
|
|
1862
|
+
const packageName = settings.importMap[compName];
|
|
1863
|
+
const svgHtml = resolveIconToSvgHtml(
|
|
1864
|
+
compName,
|
|
1865
|
+
packageName,
|
|
1866
|
+
themeRoot,
|
|
1867
|
+
'',
|
|
1868
|
+
);
|
|
1869
|
+
if (svgHtml) {
|
|
1870
|
+
let userClassPhp = '';
|
|
1871
|
+
const classAttrMatch = attrsStr.match(
|
|
1872
|
+
/class(?:Name)?=\s*(?:"([^"]*)"|'([^']*)'|\{)/i,
|
|
1873
|
+
);
|
|
1874
|
+
if (classAttrMatch) {
|
|
1875
|
+
if (classAttrMatch[1] !== undefined) {
|
|
1876
|
+
userClassPhp = classAttrMatch[1];
|
|
1877
|
+
} else if (classAttrMatch[2] !== undefined) {
|
|
1878
|
+
userClassPhp = classAttrMatch[2];
|
|
1879
|
+
} else {
|
|
1880
|
+
const braceStartIdx =
|
|
1881
|
+
classAttrMatch.index + classAttrMatch[0].length;
|
|
1882
|
+
const exprVal = extractCurlyExpression(
|
|
1883
|
+
attrsStr,
|
|
1884
|
+
braceStartIdx,
|
|
1885
|
+
);
|
|
1886
|
+
if (exprVal) {
|
|
1887
|
+
if (exprVal.startsWith('`') && exprVal.endsWith('`')) {
|
|
1888
|
+
const templateContent = exprVal.slice(1, -1);
|
|
1889
|
+
const parts = [];
|
|
1890
|
+
let lastIdx = 0;
|
|
1891
|
+
const rx = /\$\{\s*([\s\S]*?)\s*\}/g;
|
|
1892
|
+
let m;
|
|
1893
|
+
while ((m = rx.exec(templateContent)) !== null) {
|
|
1894
|
+
const textBefore = templateContent.substring(
|
|
1895
|
+
lastIdx,
|
|
1896
|
+
m.index,
|
|
1897
|
+
);
|
|
1898
|
+
if (textBefore) {
|
|
1899
|
+
parts.push(JSON.stringify(textBefore));
|
|
1900
|
+
}
|
|
1901
|
+
const expr = translateJsExpressionToPhp(
|
|
1902
|
+
m[1],
|
|
1903
|
+
Object.keys(settings.attributes || {}),
|
|
1904
|
+
localVars,
|
|
1905
|
+
phpFreeFunctions,
|
|
1906
|
+
);
|
|
1907
|
+
parts.push(expr);
|
|
1908
|
+
lastIdx = rx.lastIndex;
|
|
1909
|
+
}
|
|
1910
|
+
const textAfter = templateContent.substring(lastIdx);
|
|
1911
|
+
if (textAfter) {
|
|
1912
|
+
parts.push(JSON.stringify(textAfter));
|
|
1913
|
+
}
|
|
1914
|
+
userClassPhp =
|
|
1915
|
+
'<?php echo esc_attr(' +
|
|
1916
|
+
parts.join(' . ') +
|
|
1917
|
+
'); ?>';
|
|
1918
|
+
} else {
|
|
1919
|
+
const phpExpr = translateJsExpressionToPhp(
|
|
1920
|
+
exprVal,
|
|
1921
|
+
Object.keys(settings.attributes || {}),
|
|
1922
|
+
localVars,
|
|
1923
|
+
phpFreeFunctions,
|
|
1924
|
+
);
|
|
1925
|
+
userClassPhp =
|
|
1926
|
+
'<?php echo esc_attr(' + phpExpr + '); ?>';
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
let finalSvg = svgHtml;
|
|
1933
|
+
const classAttrRegex = /class="([^"]*)"/;
|
|
1934
|
+
const hasClassAttr = finalSvg.match(classAttrRegex);
|
|
1935
|
+
if (hasClassAttr) {
|
|
1936
|
+
const existingClasses = hasClassAttr[1];
|
|
1937
|
+
const combinedClass = (
|
|
1938
|
+
existingClasses +
|
|
1939
|
+
' ' +
|
|
1940
|
+
userClassPhp
|
|
1941
|
+
).trim();
|
|
1942
|
+
finalSvg = finalSvg.replace(
|
|
1943
|
+
classAttrRegex,
|
|
1944
|
+
`class="${combinedClass}"`,
|
|
1945
|
+
);
|
|
1946
|
+
} else {
|
|
1947
|
+
finalSvg = finalSvg.replace(
|
|
1948
|
+
'<svg',
|
|
1949
|
+
`<svg class="${userClassPhp.trim()}"`,
|
|
1950
|
+
);
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
phpMarkup =
|
|
1954
|
+
phpMarkup.substring(0, matchIndex) +
|
|
1955
|
+
finalSvg +
|
|
1956
|
+
phpMarkup.substring(matchIndex + fullTag.length);
|
|
1957
|
+
startSearch = matchIndex + finalSvg.length;
|
|
1958
|
+
continue;
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
|
|
1962
|
+
startSearch = matchIndex + fullTag.length;
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
// Dynamic <WpIcon name={...} className="..." /> → forgewp_render_theme_icon(...)
|
|
1967
|
+
let iconSearch = 0;
|
|
1968
|
+
while (true) {
|
|
1969
|
+
const iIndex = phpMarkup.indexOf('<WpIcon', iconSearch);
|
|
1970
|
+
if (iIndex === -1) break;
|
|
1971
|
+
const tagEnd = findHtmlTagEnd(phpMarkup, iIndex);
|
|
1972
|
+
if (tagEnd === -1) {
|
|
1973
|
+
iconSearch = iIndex + 7;
|
|
1974
|
+
continue;
|
|
1975
|
+
}
|
|
1976
|
+
const fullTagStr = phpMarkup.substring(iIndex, tagEnd + 1);
|
|
1977
|
+
const isSelfClosing = fullTagStr.endsWith('/>');
|
|
1978
|
+
let replacementEndIndex = tagEnd + 1;
|
|
1979
|
+
if (!isSelfClosing) {
|
|
1980
|
+
const closeTag = '</WpIcon>';
|
|
1981
|
+
const closeIndex = phpMarkup.indexOf(closeTag, tagEnd + 1);
|
|
1982
|
+
if (closeIndex !== -1) {
|
|
1983
|
+
replacementEndIndex = closeIndex + closeTag.length;
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
const attrsStr = isSelfClosing
|
|
1987
|
+
? fullTagStr.substring('<WpIcon'.length, fullTagStr.length - 2)
|
|
1988
|
+
: fullTagStr.substring('<WpIcon'.length, fullTagStr.length - 1);
|
|
1989
|
+
|
|
1990
|
+
const nameLit = attrsStr.match(
|
|
1991
|
+
/name\s*=\s*(?:"([^"]*)"|'([^']*)')/,
|
|
1992
|
+
);
|
|
1993
|
+
const nameExpr = attrsStr.match(/name\s*=\s*\{\s*([\s\S]*?)\s*\}/);
|
|
1994
|
+
const classLit = attrsStr.match(
|
|
1995
|
+
/class(?:Name)?\s*=\s*(?:"([^"]*)"|'([^']*)')/i,
|
|
1996
|
+
);
|
|
1997
|
+
const classExpr = attrsStr.match(
|
|
1998
|
+
/class(?:Name)?\s*=\s*\{\s*([\s\S]*?)\s*\}/i,
|
|
1999
|
+
);
|
|
2000
|
+
const providerMatch = attrsStr.match(
|
|
2001
|
+
/provider\s*=\s*(?:"([^"]*)"|'([^']*)')/,
|
|
2002
|
+
);
|
|
2003
|
+
const provider =
|
|
2004
|
+
(providerMatch && (providerMatch[1] || providerMatch[2])) ||
|
|
2005
|
+
'lucide';
|
|
2006
|
+
|
|
2007
|
+
let namePhp = "''";
|
|
2008
|
+
if (nameLit) {
|
|
2009
|
+
namePhp = JSON.stringify(nameLit[1] || nameLit[2] || '');
|
|
2010
|
+
} else if (nameExpr) {
|
|
2011
|
+
let expr = nameExpr[1].trim();
|
|
2012
|
+
// Already PHP from loop rewrite: $row['icon']
|
|
2013
|
+
if (/\$[a-zA-Z_]/.test(expr)) {
|
|
2014
|
+
namePhp = expr;
|
|
2015
|
+
} else if (/^(?:attributes|props)\./.test(expr)) {
|
|
2016
|
+
namePhp = translateJsExpressionToPhp(
|
|
2017
|
+
expr,
|
|
2018
|
+
Object.keys(settings.attributes || {}),
|
|
2019
|
+
localVars,
|
|
2020
|
+
phpFreeFunctions,
|
|
2021
|
+
);
|
|
2022
|
+
} else if (/^[a-zA-Z_][\w$]*\.[a-zA-Z_][\w$]*$/.test(expr)) {
|
|
2023
|
+
// row.icon — loop vars resolve in foreach; prefer $row['icon'] only
|
|
2024
|
+
const m = expr.match(/^([a-zA-Z_][\w$]*)\.([a-zA-Z_][\w$]*)$/);
|
|
2025
|
+
if (m) {
|
|
2026
|
+
namePhp = `($${m[1]}['${m[2]}'] ?? '')`;
|
|
2027
|
+
} else {
|
|
2028
|
+
namePhp = translateJsExpressionToPhp(
|
|
2029
|
+
expr,
|
|
2030
|
+
Object.keys(settings.attributes || {}),
|
|
2031
|
+
localVars,
|
|
2032
|
+
phpFreeFunctions,
|
|
2033
|
+
);
|
|
2034
|
+
}
|
|
2035
|
+
} else if (
|
|
2036
|
+
/^[a-zA-Z_][\w$]*\.[a-zA-Z_][\w$]*\s*\|\|\s*(?:'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")$/.test(
|
|
2037
|
+
expr,
|
|
2038
|
+
)
|
|
2039
|
+
) {
|
|
2040
|
+
// row.icon || 'default' — the same bare loop-var fast path as
|
|
2041
|
+
// above, extended with a literal fallback (produced by
|
|
2042
|
+
// inlineIconWrapperTags for a local icon-wrapper's default).
|
|
2043
|
+
const m2 = expr.match(
|
|
2044
|
+
/^([a-zA-Z_][\w$]*)\.([a-zA-Z_][\w$]*)\s*\|\|\s*('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")$/,
|
|
2045
|
+
);
|
|
2046
|
+
namePhp = `($${m2[1]}['${m2[2]}'] ?: ${m2[3]})`;
|
|
2047
|
+
} else if (/^[a-zA-Z_][\w$]*$/.test(expr)) {
|
|
2048
|
+
namePhp = localVars.has(expr)
|
|
2049
|
+
? `($${expr} ?? '')`
|
|
2050
|
+
: `($attributes['${expr}'] ?? '')`;
|
|
2051
|
+
} else {
|
|
2052
|
+
namePhp = translateJsExpressionToPhp(
|
|
2053
|
+
expr,
|
|
2054
|
+
Object.keys(settings.attributes || {}),
|
|
2055
|
+
localVars,
|
|
2056
|
+
phpFreeFunctions,
|
|
2057
|
+
);
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2061
|
+
let classPhp = "''";
|
|
2062
|
+
if (classLit) {
|
|
2063
|
+
classPhp = JSON.stringify(classLit[1] || classLit[2] || '');
|
|
2064
|
+
} else if (classExpr) {
|
|
2065
|
+
classPhp = translateJsExpressionToPhp(
|
|
2066
|
+
classExpr[1].trim(),
|
|
2067
|
+
Object.keys(settings.attributes || {}),
|
|
2068
|
+
localVars,
|
|
2069
|
+
phpFreeFunctions,
|
|
2070
|
+
);
|
|
2071
|
+
}
|
|
2072
|
+
|
|
2073
|
+
const replacement = `<?php forgewp_render_theme_icon( ${namePhp}, ${classPhp}, ${JSON.stringify(provider)} ); ?>`;
|
|
2074
|
+
phpMarkup =
|
|
2075
|
+
phpMarkup.substring(0, iIndex) +
|
|
2076
|
+
replacement +
|
|
2077
|
+
phpMarkup.substring(replacementEndIndex);
|
|
2078
|
+
iconSearch = iIndex + replacement.length;
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
let wStartSearch = 0;
|
|
2082
|
+
while (true) {
|
|
2083
|
+
const wIndex = phpMarkup.indexOf('<WpEditable', wStartSearch);
|
|
2084
|
+
if (wIndex === -1) break;
|
|
2085
|
+
|
|
2086
|
+
const tagEnd = findHtmlTagEnd(phpMarkup, wIndex);
|
|
2087
|
+
if (tagEnd === -1) {
|
|
2088
|
+
wStartSearch = wIndex + 11;
|
|
2089
|
+
continue;
|
|
2090
|
+
}
|
|
2091
|
+
|
|
2092
|
+
const fullTagStr = phpMarkup.substring(wIndex, tagEnd + 1);
|
|
2093
|
+
const isSelfClosing = fullTagStr.endsWith('/>');
|
|
2094
|
+
|
|
2095
|
+
const attrsStr = isSelfClosing
|
|
2096
|
+
? fullTagStr.substring(
|
|
2097
|
+
'<WpEditable'.length,
|
|
2098
|
+
fullTagStr.length - 2,
|
|
2099
|
+
)
|
|
2100
|
+
: fullTagStr.substring(
|
|
2101
|
+
'<WpEditable'.length,
|
|
2102
|
+
fullTagStr.length - 1,
|
|
2103
|
+
);
|
|
2104
|
+
|
|
2105
|
+
let children = '';
|
|
2106
|
+
let replacementEndIndex = tagEnd + 1;
|
|
2107
|
+
|
|
2108
|
+
if (!isSelfClosing) {
|
|
2109
|
+
const closeTag = '</WpEditable>';
|
|
2110
|
+
const closeIndex = phpMarkup.indexOf(closeTag, tagEnd + 1);
|
|
2111
|
+
if (closeIndex !== -1) {
|
|
2112
|
+
children = phpMarkup.substring(tagEnd + 1, closeIndex);
|
|
2113
|
+
replacementEndIndex = closeIndex + closeTag.length;
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
|
|
2117
|
+
const getAttr = (name) => {
|
|
2118
|
+
const regex = new RegExp(
|
|
2119
|
+
`${name}=(?:"([^"]*)"|'([^']*)'|\\{\\s*(?:attributes\\.|props\\.)?([a-zA-Z0-9_-]+)\\s*\\})`,
|
|
2120
|
+
);
|
|
2121
|
+
const m = attrsStr.match(regex);
|
|
2122
|
+
return m ? m[1] || m[2] || m[3] || '' : '';
|
|
2123
|
+
};
|
|
2124
|
+
|
|
2125
|
+
// Loop-variable property access, e.g. value={item.label} inside a repeater .map() body
|
|
2126
|
+
const getDottedAttr = (name) => {
|
|
2127
|
+
const regex = new RegExp(
|
|
2128
|
+
`${name}=\\{\\s*([a-zA-Z0-9_$]+)\\.([a-zA-Z0-9_$]+)\\s*\\}`,
|
|
2129
|
+
);
|
|
2130
|
+
const m = attrsStr.match(regex);
|
|
2131
|
+
return m ? { varName: m[1], prop: m[2] } : null;
|
|
2132
|
+
};
|
|
2133
|
+
|
|
2134
|
+
const tag = getAttr('tagName') || 'div';
|
|
2135
|
+
const valueVar = getAttr('value');
|
|
2136
|
+
const valueDotted = valueVar ? null : getDottedAttr('value');
|
|
2137
|
+
|
|
2138
|
+
let cleanAttrs = attrsStr
|
|
2139
|
+
.replace(/tagName=(?:"[^"]*"|'[^']*'|\{[^\}]*\})/g, '')
|
|
2140
|
+
.replace(/value=(?:"[^"]*"|'[^']*'|\{[^\}]*\})/g, '')
|
|
2141
|
+
.replace(
|
|
2142
|
+
/onChange=\{(?:[^{}]*|\{(?:[^{}]*|\{[^{}]*\})*\})*\}/g,
|
|
2143
|
+
'',
|
|
2144
|
+
)
|
|
2145
|
+
.trim();
|
|
2146
|
+
|
|
2147
|
+
if (cleanAttrs) cleanAttrs = ' ' + cleanAttrs;
|
|
2148
|
+
|
|
2149
|
+
const content = valueDotted
|
|
2150
|
+
? `<?php echo esc_html( $${valueDotted.varName}['${valueDotted.prop}'] ?? '' ); ?>`
|
|
2151
|
+
: valueVar
|
|
2152
|
+
? `{attributes.${valueVar}}`
|
|
2153
|
+
: children || '';
|
|
2154
|
+
|
|
2155
|
+
const replacement = `<${tag}${cleanAttrs}>${content}</${tag}>`;
|
|
2156
|
+
|
|
2157
|
+
phpMarkup =
|
|
2158
|
+
phpMarkup.substring(0, wIndex) +
|
|
2159
|
+
replacement +
|
|
2160
|
+
phpMarkup.substring(replacementEndIndex);
|
|
2161
|
+
wStartSearch = wIndex + replacement.length;
|
|
2162
|
+
}
|
|
2163
|
+
|
|
2164
|
+
// `dangerouslySetInnerHTML={{ __html: X }}` (the plain, non-WpEditable
|
|
2165
|
+
// side of a dual-host div, e.g. the "visitor" branch when the
|
|
2166
|
+
// WpEditable branch uses tagName="div") has no PHP/HTML translation
|
|
2167
|
+
// anywhere else in the pipeline — left alone, the attribute passes
|
|
2168
|
+
// through as literal, inert text and the actual HTML content is
|
|
2169
|
+
// never echoed at all, rendering blank. Always uses wp_kses_post
|
|
2170
|
+
// (not esc_html) since the whole point of dangerouslySetInnerHTML is
|
|
2171
|
+
// "this is HTML, don't escape it" — true regardless of whether the
|
|
2172
|
+
// backing attribute happens to be declared richText.
|
|
2173
|
+
let dsetSearch = 0;
|
|
2174
|
+
while (true) {
|
|
2175
|
+
const dIndex = phpMarkup.indexOf(
|
|
2176
|
+
'dangerouslySetInnerHTML',
|
|
2177
|
+
dsetSearch,
|
|
2178
|
+
);
|
|
2179
|
+
if (dIndex === -1) break;
|
|
2180
|
+
|
|
2181
|
+
const tagStart = phpMarkup.lastIndexOf('<', dIndex);
|
|
2182
|
+
const tagEnd =
|
|
2183
|
+
tagStart === -1 ? -1 : findHtmlTagEnd(phpMarkup, tagStart);
|
|
2184
|
+
if (tagStart === -1 || tagEnd === -1 || tagEnd < dIndex) {
|
|
2185
|
+
dsetSearch = dIndex + 'dangerouslySetInnerHTML'.length;
|
|
2186
|
+
continue;
|
|
2187
|
+
}
|
|
2188
|
+
|
|
2189
|
+
const fullTagStr = phpMarkup.substring(tagStart, tagEnd + 1);
|
|
2190
|
+
const dsetAttrMatch = fullTagStr.match(
|
|
2191
|
+
/dangerouslySetInnerHTML=\{\{\s*__html:\s*([a-zA-Z0-9_$]+)\s*\}\}/,
|
|
2192
|
+
);
|
|
2193
|
+
const tagNameMatch = fullTagStr.match(/^<([a-zA-Z][a-zA-Z0-9]*)/);
|
|
2194
|
+
if (!dsetAttrMatch || !tagNameMatch) {
|
|
2195
|
+
dsetSearch = dIndex + 'dangerouslySetInnerHTML'.length;
|
|
2196
|
+
continue;
|
|
2197
|
+
}
|
|
2198
|
+
|
|
2199
|
+
const tagName = tagNameMatch[1];
|
|
2200
|
+
const varName = dsetAttrMatch[1];
|
|
2201
|
+
const isSelfClosing = fullTagStr.endsWith('/>');
|
|
2202
|
+
|
|
2203
|
+
const cleanAttrs = fullTagStr
|
|
2204
|
+
.substring(
|
|
2205
|
+
tagName.length + 1,
|
|
2206
|
+
fullTagStr.length - (isSelfClosing ? 2 : 1),
|
|
2207
|
+
)
|
|
2208
|
+
.replace(/dangerouslySetInnerHTML=\{\{[\s\S]*?\}\}/, '')
|
|
2209
|
+
.trim();
|
|
2210
|
+
|
|
2211
|
+
const prefix = localVars.has(varName)
|
|
2212
|
+
? `$${varName}`
|
|
2213
|
+
: `$attributes['${varName}']`;
|
|
2214
|
+
const content = `<?php echo wp_kses_post( ${prefix} ?? '' ); ?>`;
|
|
2215
|
+
|
|
2216
|
+
let replacementEndIndex = tagEnd + 1;
|
|
2217
|
+
if (!isSelfClosing) {
|
|
2218
|
+
const closeTag = `</${tagName}>`;
|
|
2219
|
+
const closeIndex = phpMarkup.indexOf(closeTag, tagEnd + 1);
|
|
2220
|
+
if (closeIndex !== -1) {
|
|
2221
|
+
replacementEndIndex = closeIndex + closeTag.length;
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2224
|
+
|
|
2225
|
+
const replacement = `<${tagName}${cleanAttrs ? ' ' + cleanAttrs : ''}>${content}</${tagName}>`;
|
|
2226
|
+
phpMarkup =
|
|
2227
|
+
phpMarkup.substring(0, tagStart) +
|
|
2228
|
+
replacement +
|
|
2229
|
+
phpMarkup.substring(replacementEndIndex);
|
|
2230
|
+
dsetSearch = tagStart + replacement.length;
|
|
2231
|
+
}
|
|
2232
|
+
|
|
2233
|
+
phpMarkup = phpMarkup.replace(/\{\/\*[\s\S]*?\*\/\}/g, '');
|
|
2234
|
+
|
|
2235
|
+
phpMarkup = phpMarkup.replace(
|
|
2236
|
+
/style=\{\{\s*([\s\S]*?)\s*\}\}/g,
|
|
2237
|
+
(match, styleObjStr) => {
|
|
2238
|
+
try {
|
|
2239
|
+
const pairs = styleObjStr
|
|
2240
|
+
.split(',')
|
|
2241
|
+
.map((pair) => pair.trim())
|
|
2242
|
+
.filter(Boolean);
|
|
2243
|
+
const attrKeys = Object.keys(settings.attributes || {});
|
|
2244
|
+
const phpStyles = pairs
|
|
2245
|
+
.map((pair) => {
|
|
2246
|
+
const colonIndex = pair.indexOf(':');
|
|
2247
|
+
if (colonIndex === -1) return '';
|
|
2248
|
+
const prop = pair.substring(0, colonIndex).trim();
|
|
2249
|
+
const valExpr = pair.substring(colonIndex + 1).trim();
|
|
2250
|
+
|
|
2251
|
+
const kebabProp = prop
|
|
2252
|
+
.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2')
|
|
2253
|
+
.toLowerCase();
|
|
2254
|
+
|
|
2255
|
+
let phpExpr = valExpr
|
|
2256
|
+
.replace(
|
|
2257
|
+
/(?:attributes|props)\['([a-zA-Z0-9_-]+)'\]/g,
|
|
2258
|
+
"$attributes['$1']",
|
|
2259
|
+
)
|
|
2260
|
+
.replace(
|
|
2261
|
+
/(?:attributes|props)\.([a-zA-Z0-9_-]+)/g,
|
|
2262
|
+
"$attributes['$1']",
|
|
2263
|
+
);
|
|
2264
|
+
|
|
2265
|
+
phpExpr = phpExpr.replace(
|
|
2266
|
+
/(?<![.$'"\w])([a-zA-Z0-9_-]+)(?![.$'"\w])/g,
|
|
2267
|
+
(m, word) => {
|
|
2268
|
+
if (attrKeys.includes(word)) {
|
|
2269
|
+
return `$attributes['${word}']`;
|
|
2270
|
+
}
|
|
2271
|
+
return m;
|
|
2272
|
+
},
|
|
2273
|
+
);
|
|
2274
|
+
|
|
2275
|
+
phpExpr = phpExpr.replace(/\+/g, '.');
|
|
2276
|
+
|
|
2277
|
+
return `${kebabProp}: <?php echo esc_attr( ${phpExpr} ); ?>;`;
|
|
2278
|
+
})
|
|
2279
|
+
.filter(Boolean)
|
|
2280
|
+
.join(' ');
|
|
2281
|
+
return `style="${phpStyles}"`;
|
|
2282
|
+
} catch (err) {
|
|
2283
|
+
return match;
|
|
2284
|
+
}
|
|
2285
|
+
},
|
|
2286
|
+
);
|
|
2287
|
+
|
|
2288
|
+
const attrRegex =
|
|
2289
|
+
/\s+(?:on[A-Z][a-zA-Z]*|ref|disabled|checked)=\s*(\{)/g;
|
|
2290
|
+
let attrMatch;
|
|
2291
|
+
const attrMatches = [];
|
|
2292
|
+
while ((attrMatch = attrRegex.exec(phpMarkup)) !== null) {
|
|
2293
|
+
attrMatches.push(attrMatch);
|
|
2294
|
+
}
|
|
2295
|
+
for (let idx = attrMatches.length - 1; idx >= 0; idx--) {
|
|
2296
|
+
const m = attrMatches[idx];
|
|
2297
|
+
const startIndex = m.index;
|
|
2298
|
+
const braceIndex = startIndex + m[0].length - 1;
|
|
2299
|
+
let depth = 1;
|
|
2300
|
+
let pos = braceIndex + 1;
|
|
2301
|
+
while (pos < phpMarkup.length && depth > 0) {
|
|
2302
|
+
if (phpMarkup[pos] === '{') depth++;
|
|
2303
|
+
else if (phpMarkup[pos] === '}') depth--;
|
|
2304
|
+
pos++;
|
|
2305
|
+
}
|
|
2306
|
+
if (depth === 0) {
|
|
2307
|
+
phpMarkup =
|
|
2308
|
+
phpMarkup.substring(0, startIndex) + phpMarkup.substring(pos);
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
|
|
2312
|
+
// Runs before transpileLoops: an inline `(ARRAY_LITERAL as const).map(...)`
|
|
2313
|
+
// (a fixed set of static rows with dynamic values/icons — e.g. a
|
|
2314
|
+
// phone/email/address/hours details list) doesn't match any of
|
|
2315
|
+
// transpileLoops' bare-identifier-only patterns and would otherwise
|
|
2316
|
+
// render empty.
|
|
2317
|
+
//
|
|
2318
|
+
// A row value referencing a same-file helper (e.g. `getSocialHandle(...)`)
|
|
2319
|
+
// needs the SAME call-site rename applied to phpMarkup above (line ~1341)
|
|
2320
|
+
// applied here too — this reads straight from the original jsxSourceCode,
|
|
2321
|
+
// which still has the pre-rename JS name and would otherwise get the call
|
|
2322
|
+
// silently dropped as "unknown" once translated.
|
|
2323
|
+
let sourceCodeForStaticMap = jsxSourceCode;
|
|
2324
|
+
if (helperNameToPhp.size > 0) {
|
|
2325
|
+
for (const [jsName, phpName] of helperNameToPhp) {
|
|
2326
|
+
sourceCodeForStaticMap = sourceCodeForStaticMap.replace(
|
|
2327
|
+
new RegExp(`\\b${jsName}\\s*\\(`, 'g'),
|
|
2328
|
+
`${phpName}(`,
|
|
2329
|
+
);
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
phpMarkup = transpileStaticArrayObjectMap(
|
|
2333
|
+
phpMarkup,
|
|
2334
|
+
settings,
|
|
2335
|
+
themeRoot,
|
|
2336
|
+
localVars,
|
|
2337
|
+
sourceCodeForStaticMap,
|
|
2338
|
+
phpFreeFunctions,
|
|
2339
|
+
);
|
|
2340
|
+
// {socialList.length > 0 && (...)} guards a static-array-with-filter
|
|
2341
|
+
// header const the same way — its length can't be known at compile
|
|
2342
|
+
// time either, so re-express as "at least one row's own filter
|
|
2343
|
+
// condition holds" before the generic && handling below runs.
|
|
2344
|
+
const lengthCheckResult = translateStaticArrayLengthCheck(
|
|
2345
|
+
phpMarkup,
|
|
2346
|
+
sourceCodeForStaticMap,
|
|
2347
|
+
settings,
|
|
2348
|
+
localVars,
|
|
2349
|
+
phpFreeFunctions,
|
|
2350
|
+
);
|
|
2351
|
+
phpMarkup = lengthCheckResult.jsx;
|
|
2352
|
+
phpVarDefinitions += lengthCheckResult.prelude;
|
|
2353
|
+
|
|
2354
|
+
// Must run after transpileStaticArrayObjectMap/translateStaticArrayLengthCheck
|
|
2355
|
+
// above (which need to see a template literal's raw `${propName}`
|
|
2356
|
+
// text to inline that row's own static value) but before
|
|
2357
|
+
// transpileLoops/transpileConditionals/transpileTernaries below:
|
|
2358
|
+
// those scan for bare `{...}` JSX expression containers with no
|
|
2359
|
+
// awareness that a `${...}` inside a backtick template literal
|
|
2360
|
+
// isn't one — transpileTernaries in particular will happily "find"
|
|
2361
|
+
// the ternary inside e.g. `${cond ? 'a' : 'b'}`, transpile it in
|
|
2362
|
+
// place as if it were a real top-level JSX ternary, and leave the
|
|
2363
|
+
// surrounding backtick/`$` characters behind as broken literal text
|
|
2364
|
+
// (a stray `$` sitting right before the resulting <?php if (...): ?>
|
|
2365
|
+
// block). Resolving every remaining attr={`...`} template literal
|
|
2366
|
+
// into a plain PHP-interpolated string here removes the
|
|
2367
|
+
// backtick/${} syntax before those later passes can ever misread it.
|
|
2368
|
+
phpMarkup = phpMarkup.replace(
|
|
2369
|
+
/([a-zA-Z0-9_-]+)=\{\s*`([\s\S]*?)`\s*\}/g,
|
|
2370
|
+
(match, attr, templateLiteralContent) => {
|
|
2371
|
+
const escFunc =
|
|
2372
|
+
attr === 'href' || attr === 'src' ? 'esc_url' : 'esc_attr';
|
|
2373
|
+
const processed = templateLiteralContent.replace(
|
|
2374
|
+
/\$\{\s*([\s\S]*?)\s*\}/g,
|
|
2375
|
+
(m, jsExpr) => {
|
|
2376
|
+
const phpExpr = translateJsExpressionToPhp(
|
|
2377
|
+
jsExpr,
|
|
2378
|
+
Object.keys(settings.attributes || {}),
|
|
2379
|
+
localVars,
|
|
2380
|
+
phpFreeFunctions,
|
|
2381
|
+
);
|
|
2382
|
+
return `<?php echo ${escFunc}( ${phpExpr} ); ?>`;
|
|
2383
|
+
},
|
|
2384
|
+
);
|
|
2385
|
+
const attrName = attr === 'className' ? 'class' : attr;
|
|
2386
|
+
return `${attrName}="${processed}"`;
|
|
2387
|
+
},
|
|
2388
|
+
);
|
|
2389
|
+
|
|
2390
|
+
phpMarkup = transpileLoops(phpMarkup);
|
|
2391
|
+
phpMarkup = transpileConditionals(
|
|
2392
|
+
phpMarkup,
|
|
2393
|
+
Object.keys(settings.attributes || {}),
|
|
2394
|
+
);
|
|
2395
|
+
phpMarkup = transpileTernaries(
|
|
2396
|
+
phpMarkup,
|
|
2397
|
+
Object.keys(settings.attributes || {}),
|
|
2398
|
+
);
|
|
2399
|
+
|
|
2400
|
+
// React Fragment shorthand (`<>…</>`) has no PHP/HTML equivalent —
|
|
2401
|
+
// a Fragment's only job is "no wrapper element", so once the
|
|
2402
|
+
// ternary/conditional balancing above (which needs these markers
|
|
2403
|
+
// present to correctly track branch nesting — see
|
|
2404
|
+
// extractJsxByTagBalancing's <> handling) has finished, the tags
|
|
2405
|
+
// themselves are just deleted; the children were already carried
|
|
2406
|
+
// through as plain markup. Left unstripped, they show up as
|
|
2407
|
+
// literal, visible "<>" text on the rendered page.
|
|
2408
|
+
phpMarkup = phpMarkup.replace(/<>/g, '').replace(/<\/>/g, '');
|
|
2409
|
+
|
|
2410
|
+
phpMarkup = phpMarkup.replace(
|
|
2411
|
+
/(placeholder|label|title|alt|value)=\{\s*__\(\s*(['"])([\s\S]*?)\2\s*(?:,\s*['"][a-zA-Z0-9_-]+['"])?\s*,?\s*\)\s*\}/g,
|
|
2412
|
+
(match, attr, q1, text) => {
|
|
2413
|
+
const escaped = text
|
|
2414
|
+
.replace(/'/g, "\\'")
|
|
2415
|
+
.trim()
|
|
2416
|
+
.replace(/\s+/g, ' ');
|
|
2417
|
+
return `${attr}="<?php echo esc_attr( __('${escaped}', 'hotelchecker24') ); ?>"`;
|
|
2418
|
+
},
|
|
2419
|
+
);
|
|
2420
|
+
|
|
2421
|
+
phpMarkup = phpMarkup.replace(
|
|
2422
|
+
/\{\s*__\(\s*(['"])([\s\S]*?)\1\s*(?:,\s*['"][a-zA-Z0-9_-]+['"])?\s*,?\s*\)\s*\}/g,
|
|
2423
|
+
(match, q1, text) => {
|
|
2424
|
+
const escaped = text
|
|
2425
|
+
.replace(/'/g, "\\'")
|
|
2426
|
+
.trim()
|
|
2427
|
+
.replace(/\s+/g, ' ');
|
|
2428
|
+
return `<?php echo esc_html( __('${escaped}', 'hotelchecker24') ); ?>`;
|
|
2429
|
+
},
|
|
2430
|
+
);
|
|
2431
|
+
|
|
2432
|
+
phpMarkup = phpMarkup.replace(/className=/g, 'class=');
|
|
2433
|
+
|
|
2434
|
+
const attrKeysForPhp = Object.keys(settings.attributes || {});
|
|
2435
|
+
const toPhp = (expr) =>
|
|
2436
|
+
translateJsExpressionToPhp(
|
|
2437
|
+
expr,
|
|
2438
|
+
attrKeysForPhp,
|
|
2439
|
+
localVars,
|
|
2440
|
+
phpFreeFunctions,
|
|
2441
|
+
);
|
|
2442
|
+
|
|
2443
|
+
phpMarkup = phpMarkup.replace(
|
|
2444
|
+
/class=\{\`([\s\S]*?)\`\}/g,
|
|
2445
|
+
(match, templateLiteralContent) => {
|
|
2446
|
+
const processed = templateLiteralContent.replace(
|
|
2447
|
+
/\$\{\s*([\s\S]*?)\s*\}/g,
|
|
2448
|
+
(m, jsExpr) => {
|
|
2449
|
+
const phpExpr = toPhp(jsExpr);
|
|
2450
|
+
return `<?php echo esc_attr( ${phpExpr} ); ?>`;
|
|
2451
|
+
},
|
|
2452
|
+
);
|
|
2453
|
+
return `class="${processed}"`;
|
|
2454
|
+
},
|
|
2455
|
+
);
|
|
2456
|
+
|
|
2457
|
+
phpMarkup = phpMarkup.replace(
|
|
2458
|
+
/([a-zA-Z0-9_-]+)=\{\s*(?:attributes\.|props\.)?(?!(?:attributes|props)\b)([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\s*\}/gi,
|
|
2459
|
+
(match, attr, varName, prop) => {
|
|
2460
|
+
const escFunc =
|
|
2461
|
+
attr === 'href' || attr === 'src' ? 'esc_url' : 'esc_attr';
|
|
2462
|
+
const prefix = localVars.has(varName)
|
|
2463
|
+
? `$${varName}`
|
|
2464
|
+
: `$attributes['${varName}']`;
|
|
2465
|
+
return `${attr}="<?php echo ${escFunc}( ${prefix}['${prop}'] ?? '' ); ?>"`;
|
|
2466
|
+
},
|
|
2467
|
+
);
|
|
2468
|
+
|
|
2469
|
+
phpMarkup = phpMarkup.replace(
|
|
2470
|
+
/\{\s*(?:attributes\.|props\.)?(?!(?:attributes|props)\b)([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\s*\}/g,
|
|
2471
|
+
(match, varName, prop) => {
|
|
2472
|
+
const prefix = localVars.has(varName)
|
|
2473
|
+
? `$${varName}`
|
|
2474
|
+
: `$attributes['${varName}']`;
|
|
2475
|
+
return `<?php echo esc_html( ${prefix}['${prop}'] ?? '' ); ?>`;
|
|
2476
|
+
},
|
|
2477
|
+
);
|
|
2478
|
+
|
|
2479
|
+
phpMarkup = phpMarkup.replace(
|
|
2480
|
+
/([a-zA-Z0-9_-]+)=\{\s*(?:attributes\.|props\.)?([a-zA-Z0-9_-]+)\s*\}/gi,
|
|
2481
|
+
(match, attr, varName) => {
|
|
2482
|
+
const escFunc =
|
|
2483
|
+
attr === 'href' || attr === 'src' ? 'esc_url' : 'esc_attr';
|
|
2484
|
+
const prefix = localVars.has(varName)
|
|
2485
|
+
? `$${varName}`
|
|
2486
|
+
: `$attributes['${varName}']`;
|
|
2487
|
+
return `${attr}="<?php echo ${escFunc}( ${prefix} ?? '' ); ?>"`;
|
|
2488
|
+
},
|
|
2489
|
+
);
|
|
2490
|
+
|
|
2491
|
+
phpMarkup = phpMarkup.replace(
|
|
2492
|
+
/\{\s*(?:attributes\.|props\.)?([a-zA-Z0-9_-]+)\s*\}/g,
|
|
2493
|
+
(match, varName) => {
|
|
2494
|
+
const isRichText =
|
|
2495
|
+
settings.attributes &&
|
|
2496
|
+
settings.attributes[varName] &&
|
|
2497
|
+
settings.attributes[varName].control === 'richText';
|
|
2498
|
+
const escFunc = isRichText ? 'wp_kses_post' : 'esc_html';
|
|
2499
|
+
const prefix = localVars.has(varName)
|
|
2500
|
+
? `$${varName}`
|
|
2501
|
+
: `$attributes['${varName}']`;
|
|
2502
|
+
return `<?php echo ${escFunc}( ${prefix} ?? '' ); ?>`;
|
|
2503
|
+
},
|
|
2504
|
+
);
|
|
2505
|
+
|
|
2506
|
+
// Remaining attr={complexExpr} — helpers, ternaries, already-PHP loop args, etc.
|
|
2507
|
+
phpMarkup = phpMarkup.replace(
|
|
2508
|
+
/([a-zA-Z0-9_-]+)=\{([^{}]+)\}/g,
|
|
2509
|
+
(match, attr, expr) => {
|
|
2510
|
+
const trimmed = expr.trim();
|
|
2511
|
+
if (
|
|
2512
|
+
!trimmed ||
|
|
2513
|
+
trimmed.startsWith('/*') ||
|
|
2514
|
+
trimmed.includes('<?php')
|
|
2515
|
+
) {
|
|
2516
|
+
return match;
|
|
2517
|
+
}
|
|
2518
|
+
// Skip pure string literals
|
|
2519
|
+
if (/^['"`]/.test(trimmed) && !trimmed.includes('${')) {
|
|
2520
|
+
return match;
|
|
2521
|
+
}
|
|
2522
|
+
const escFunc =
|
|
2523
|
+
attr === 'href' || attr === 'src' ? 'esc_url' : 'esc_attr';
|
|
2524
|
+
// Already rewritten to PHP vars inside loop bodies (e.g. $row['avatar'])
|
|
2525
|
+
if (
|
|
2526
|
+
/\$[a-zA-Z_]/.test(trimmed) &&
|
|
2527
|
+
!/[a-zA-Z_]\(/.test(
|
|
2528
|
+
trimmed.replace(/forgewp_blk_\w+\s*\(/g, ''),
|
|
2529
|
+
)
|
|
2530
|
+
) {
|
|
2531
|
+
// May still contain helper calls: forgewp_blk_x($row['avatar'])
|
|
2532
|
+
if (
|
|
2533
|
+
trimmed.includes('forgewp_blk_') ||
|
|
2534
|
+
/\w+\s*\(/.test(trimmed)
|
|
2535
|
+
) {
|
|
2536
|
+
return `${attr}="<?php echo ${escFunc}( ${trimmed} ); ?>"`;
|
|
2537
|
+
}
|
|
2538
|
+
return `${attr}="<?php echo ${escFunc}( ${trimmed} ); ?>"`;
|
|
2539
|
+
}
|
|
2540
|
+
if (
|
|
2541
|
+
trimmed.includes('forgewp_blk_') ||
|
|
2542
|
+
/\$[a-zA-Z_]/.test(trimmed)
|
|
2543
|
+
) {
|
|
2544
|
+
return `${attr}="<?php echo ${escFunc}( ${trimmed} ); ?>"`;
|
|
2545
|
+
}
|
|
2546
|
+
try {
|
|
2547
|
+
const phpExpr = toPhp(trimmed);
|
|
2548
|
+
return `${attr}="<?php echo ${escFunc}( ${phpExpr} ); ?>"`;
|
|
2549
|
+
} catch {
|
|
2550
|
+
return match;
|
|
2551
|
+
}
|
|
2552
|
+
},
|
|
2553
|
+
);
|
|
2554
|
+
|
|
2555
|
+
phpMarkup = phpMarkup.replace(
|
|
2556
|
+
/\s+key=(?:\{(?:\?>|[^>])*?\}|"(?:\?>|[^>])*?"|'(?:\?>|[^>])*?')/g,
|
|
2557
|
+
'',
|
|
2558
|
+
);
|
|
2559
|
+
|
|
2560
|
+
phpMarkup = phpMarkup.replace(
|
|
2561
|
+
/<[A-Z][a-zA-Z0-9]*(?:\s(?:\?>|[^>])*?)?\/>/g,
|
|
2562
|
+
'',
|
|
2563
|
+
);
|
|
2564
|
+
|
|
2565
|
+
phpMarkup = phpMarkup.replace(
|
|
2566
|
+
/<([A-Z][a-zA-Z0-9]*)(?:\s(?:\?>|[^>])*?)?>([\s\S]*?)<\/\1>/g,
|
|
2567
|
+
(match, tagName, children) => {
|
|
2568
|
+
if (tagName === 'WpLink') {
|
|
2569
|
+
const hrefMatch = match.match(/href=(?:"([^"]*)"|'([^']*)')/);
|
|
2570
|
+
const classMatch = match.match(/class=(?:"([^"]*)"|'([^']*)')/);
|
|
2571
|
+
const href = hrefMatch ? hrefMatch[1] || hrefMatch[2] : '#';
|
|
2572
|
+
const cls = classMatch
|
|
2573
|
+
? ` class='${classMatch[1] || classMatch[2]}'`
|
|
2574
|
+
: '';
|
|
2575
|
+
return `<a href="${href}"${cls}>${children}</a>`;
|
|
2576
|
+
}
|
|
2577
|
+
if (tagName === 'Button') {
|
|
2578
|
+
const classMatch = match.match(/class=(?:"([^"]*)"|'([^']*)')/);
|
|
2579
|
+
const cls = classMatch
|
|
2580
|
+
? ` class='${classMatch[1] || classMatch[2]}'`
|
|
2581
|
+
: '';
|
|
2582
|
+
return `<button${cls}>${children}</button>`;
|
|
2583
|
+
}
|
|
2584
|
+
return children;
|
|
2585
|
+
},
|
|
2586
|
+
);
|
|
2587
|
+
|
|
2588
|
+
// Safety net for client-only JS expressions (e.g., .map, =>, etc.)
|
|
2589
|
+
let braceIdx = phpMarkup.length;
|
|
2590
|
+
while (true) {
|
|
2591
|
+
const openBrace = phpMarkup.lastIndexOf('{', braceIdx);
|
|
2592
|
+
if (openBrace === -1) break;
|
|
2593
|
+
|
|
2594
|
+
const lastPhpStart = phpMarkup.lastIndexOf('<?php', openBrace);
|
|
2595
|
+
const lastPhpEnd = phpMarkup.lastIndexOf('?>', openBrace);
|
|
2596
|
+
if (lastPhpStart !== -1 && lastPhpStart > lastPhpEnd) {
|
|
2597
|
+
braceIdx = openBrace - 1;
|
|
2598
|
+
continue;
|
|
2599
|
+
}
|
|
2600
|
+
|
|
2601
|
+
let depth = 1;
|
|
2602
|
+
let closeBrace = -1;
|
|
2603
|
+
let inQuote = null;
|
|
2604
|
+
let esc = false;
|
|
2605
|
+
for (let j = openBrace + 1; j < phpMarkup.length; j++) {
|
|
2606
|
+
const c = phpMarkup[j];
|
|
2607
|
+
if (inQuote) {
|
|
2608
|
+
if (esc) {
|
|
2609
|
+
esc = false;
|
|
2610
|
+
} else if (c === '\\') {
|
|
2611
|
+
esc = true;
|
|
2612
|
+
} else if (c === inQuote) {
|
|
2613
|
+
inQuote = null;
|
|
2614
|
+
}
|
|
2615
|
+
continue;
|
|
2616
|
+
}
|
|
2617
|
+
if (c === "'" || c === '"' || c === '`') {
|
|
2618
|
+
inQuote = c;
|
|
2619
|
+
continue;
|
|
2620
|
+
}
|
|
2621
|
+
if (c === '{') depth++;
|
|
2622
|
+
else if (c === '}') {
|
|
2623
|
+
depth--;
|
|
2624
|
+
if (depth === 0) {
|
|
2625
|
+
closeBrace = j;
|
|
2626
|
+
break;
|
|
2627
|
+
}
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
|
|
2631
|
+
if (closeBrace !== -1) {
|
|
2632
|
+
const braceContent = phpMarkup.substring(
|
|
2633
|
+
openBrace + 1,
|
|
2634
|
+
closeBrace,
|
|
2635
|
+
);
|
|
2636
|
+
if (
|
|
2637
|
+
/(?:=>|\.map\s*\(|\.find\s*\(|\.filter\s*\(|\.slice\s*\(|\.split\s*\(|setState|setSearch|setSelected|setCategory|setCountry|setAttributes|setFilter|&&)/.test(
|
|
2638
|
+
braceContent,
|
|
2639
|
+
)
|
|
2640
|
+
) {
|
|
2641
|
+
phpMarkup =
|
|
2642
|
+
phpMarkup.substring(0, openBrace) +
|
|
2643
|
+
'' +
|
|
2644
|
+
phpMarkup.substring(closeBrace + 1);
|
|
2645
|
+
braceIdx = openBrace - 1;
|
|
2646
|
+
continue;
|
|
2647
|
+
}
|
|
2648
|
+
}
|
|
2649
|
+
braceIdx = openBrace - 1;
|
|
2650
|
+
}
|
|
2651
|
+
|
|
2652
|
+
phpMarkup = phpMarkup.replace(
|
|
2653
|
+
/\{[a-zA-Z_$][a-zA-Z0-9_$]*\s*&&\s*\([\s\S]*?\)\s*\}/g,
|
|
2654
|
+
'',
|
|
2655
|
+
);
|
|
2656
|
+
|
|
2657
|
+
phpMarkup = phpMarkup.replace(/^\s*\)\}\s*$/gm, '');
|
|
2658
|
+
|
|
2659
|
+
const allowedSelfClosing = [
|
|
2660
|
+
'area',
|
|
2661
|
+
'base',
|
|
2662
|
+
'br',
|
|
2663
|
+
'col',
|
|
2664
|
+
'embed',
|
|
2665
|
+
'hr',
|
|
2666
|
+
'img',
|
|
2667
|
+
'input',
|
|
2668
|
+
'link',
|
|
2669
|
+
'meta',
|
|
2670
|
+
'param',
|
|
2671
|
+
'source',
|
|
2672
|
+
'track',
|
|
2673
|
+
'wbr',
|
|
2674
|
+
'path',
|
|
2675
|
+
'circle',
|
|
2676
|
+
'rect',
|
|
2677
|
+
'line',
|
|
2678
|
+
'polygon',
|
|
2679
|
+
'polyline',
|
|
2680
|
+
'ellipse',
|
|
2681
|
+
'stop',
|
|
2682
|
+
'use',
|
|
2683
|
+
];
|
|
2684
|
+
phpMarkup = phpMarkup.replace(
|
|
2685
|
+
/<([a-zA-Z0-9-]+)(?:\s+([^>]*?))?\s*\/>/g,
|
|
2686
|
+
(match, tagName, attrs) => {
|
|
2687
|
+
if (allowedSelfClosing.includes(tagName.toLowerCase())) {
|
|
2688
|
+
return match;
|
|
2689
|
+
}
|
|
2690
|
+
const attrsStr = attrs ? ` ${attrs}` : '';
|
|
2691
|
+
return `<${tagName}${attrsStr}></${tagName}>`;
|
|
2692
|
+
},
|
|
2693
|
+
);
|
|
2694
|
+
|
|
2695
|
+
// Safety net: any remaining call to a known local same-file helper
|
|
2696
|
+
// that wasn't converted to a real PHP function nor inlined as a JSX
|
|
2697
|
+
// template (e.g. a render-helper with statements before its JSX
|
|
2698
|
+
// return) must never leak into the page as literal, unexecuted JS
|
|
2699
|
+
// text — drop the call site instead.
|
|
2700
|
+
for (const helperName of allSameFileHelperNames) {
|
|
2701
|
+
if (
|
|
2702
|
+
helperNameToPhp.has(helperName) ||
|
|
2703
|
+
jsxRenderHelperTemplates.has(helperName)
|
|
2704
|
+
)
|
|
2705
|
+
continue;
|
|
2706
|
+
const leftoverCallRegex = new RegExp(
|
|
2707
|
+
`\\{\\s*${helperName}\\s*\\([^{}]*\\)\\s*\\}`,
|
|
2708
|
+
'g',
|
|
2709
|
+
);
|
|
2710
|
+
if (leftoverCallRegex.test(phpMarkup)) {
|
|
2711
|
+
console.warn(
|
|
2712
|
+
`[Gutenberg Block Compiler] Dropping unconvertible helper call "${helperName}(...)" from render.php for block ${blockSlug} — content will be blank on the frontend for this call site.`,
|
|
2713
|
+
);
|
|
2714
|
+
phpMarkup = phpMarkup.replace(leftoverCallRegex, '');
|
|
2715
|
+
}
|
|
2716
|
+
}
|
|
2717
|
+
|
|
2718
|
+
if (settings._detectedPaddingTokens) {
|
|
2719
|
+
phpMarkup = stripPaddingTokensFromFirstTag(
|
|
2720
|
+
phpMarkup,
|
|
2721
|
+
settings._detectedPaddingTokens.y,
|
|
2722
|
+
);
|
|
2723
|
+
phpMarkup = stripPaddingTokensFromFirstTag(
|
|
2724
|
+
phpMarkup,
|
|
2725
|
+
settings._detectedPaddingTokens.x,
|
|
2726
|
+
);
|
|
2727
|
+
}
|
|
2728
|
+
phpMarkup = injectPaddingClassesIntoPhpMarkup(phpMarkup);
|
|
2729
|
+
|
|
2730
|
+
const blockFolderName = settings.name.replace('forgewp/', '');
|
|
2731
|
+
// Only components isComponentInteractive() flags get a client-side hydration
|
|
2732
|
+
// bundle (see islands-scanner.js) — a data-forgewp-hydrate wrapper on anything
|
|
2733
|
+
// else is a dead attribute: the hydrator finds no manifest entry for it, never
|
|
2734
|
+
// mounts, and logs a console.error on every page load for no reason. Omitting
|
|
2735
|
+
// the wrapper for non-interactive blocks also removes any possibility of a
|
|
2736
|
+
// future hydration bundle silently re-rendering over (and discarding) this
|
|
2737
|
+
// server-computed markup — the exact bug class that caused paddingY/paddingX
|
|
2738
|
+
// to work in SSR but get clobbered the instant a needless hydration ran.
|
|
2739
|
+
const isHydratedBlock = isComponentInteractive(
|
|
2740
|
+
jsxSourceFile,
|
|
2741
|
+
);
|
|
2742
|
+
const hydrationIslandName =
|
|
2743
|
+
isHydratedBlock &&
|
|
2744
|
+
resolvedComponentName &&
|
|
2745
|
+
jsxSourceFile !== blockFile
|
|
2746
|
+
? resolvedComponentName
|
|
2747
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
2748
|
+
.replace(/[^a-zA-Z0-9-]+/g, '-')
|
|
2749
|
+
.replace(/^-|-$/g, '')
|
|
2750
|
+
.toLowerCase()
|
|
2751
|
+
: blockFolderName;
|
|
2752
|
+
const hydrationWrapperOpen = isHydratedBlock
|
|
2753
|
+
? `<div data-forgewp-hydrate="${hydrationIslandName}" data-forgewp-trigger="visible" data-forgewp-props="<?php echo esc_attr( json_encode( $attributes ?? array() ) ); ?>" style="display:block">\n`
|
|
2754
|
+
: '';
|
|
2755
|
+
const hydrationWrapperClose = isHydratedBlock ? '\n</div>\n' : '\n';
|
|
2756
|
+
const renderPhpContent = `<?php
|
|
2757
|
+
/**
|
|
2758
|
+
* Gutenberg dynamic block template — ${settings.title}
|
|
2759
|
+
* Autogenerated by ForgeWP Theme Compiler. Do not modify manually.
|
|
2760
|
+
*/
|
|
2761
|
+
$loading = true;
|
|
2762
|
+
$isLoading = true;
|
|
2763
|
+
$hotels = array();
|
|
2764
|
+
$posts = array();
|
|
2765
|
+
$listicles = array();
|
|
2766
|
+
$destinations = array();
|
|
2767
|
+
${phpHelperDefinitions}${phpVarDefinitions}?>
|
|
2768
|
+
${hydrationWrapperOpen}${phpMarkup}${hydrationWrapperClose}`;
|
|
2769
|
+
|
|
2770
|
+
const blockOutDir = path.join(outDir, 'blocks', blockFolderName);
|
|
2771
|
+
mkdirSync(blockOutDir, { recursive: true });
|
|
2772
|
+
|
|
2773
|
+
const {
|
|
2774
|
+
edit: _edit,
|
|
2775
|
+
save: _save,
|
|
2776
|
+
editorPreview: _editorPreview,
|
|
2777
|
+
editorPreviewMode: _editorPreviewMode,
|
|
2778
|
+
customEditJsx: _customEditJsx,
|
|
2779
|
+
editorScope: _editorScope,
|
|
2780
|
+
dualHostMeta: _dualHostMeta,
|
|
2781
|
+
...blockJsonSettings
|
|
2782
|
+
} = settings;
|
|
2783
|
+
if (blockJsonSettings.attributes) {
|
|
2784
|
+
const cleanedAttrs = {};
|
|
2785
|
+
for (const [key, attr] of Object.entries(
|
|
2786
|
+
blockJsonSettings.attributes,
|
|
2787
|
+
)) {
|
|
2788
|
+
if (attr && typeof attr === 'object') {
|
|
2789
|
+
// Strip editor-only metadata (controls, labels, repeater mode/fields, etc.)
|
|
2790
|
+
const {
|
|
2791
|
+
control,
|
|
2792
|
+
label,
|
|
2793
|
+
options,
|
|
2794
|
+
min,
|
|
2795
|
+
max,
|
|
2796
|
+
mode,
|
|
2797
|
+
fields,
|
|
2798
|
+
provider,
|
|
2799
|
+
...wpAttr
|
|
2800
|
+
} = attr;
|
|
2801
|
+
cleanedAttrs[key] = wpAttr;
|
|
2802
|
+
} else {
|
|
2803
|
+
cleanedAttrs[key] = attr;
|
|
2804
|
+
}
|
|
2805
|
+
}
|
|
2806
|
+
blockJsonSettings.attributes = cleanedAttrs;
|
|
2807
|
+
}
|
|
2808
|
+
|
|
2809
|
+
writeFileSync(
|
|
2810
|
+
path.join(blockOutDir, 'block.json'),
|
|
2811
|
+
JSON.stringify(blockJsonSettings, null, 2),
|
|
2812
|
+
'utf8',
|
|
2813
|
+
);
|
|
2814
|
+
writeFileSync(
|
|
2815
|
+
path.join(blockOutDir, 'render.php'),
|
|
2816
|
+
renderPhpContent,
|
|
2817
|
+
'utf8',
|
|
2818
|
+
);
|
|
2819
|
+
|
|
2820
|
+
blockSlugs.push(settings);
|
|
2821
|
+
} catch (e) {
|
|
2822
|
+
console.error(
|
|
2823
|
+
`[Gutenberg Block Compiler] Failed to compile block ${blockSlug}:`,
|
|
2824
|
+
e.message,
|
|
2825
|
+
);
|
|
2826
|
+
}
|
|
2827
|
+
}
|
|
2828
|
+
}
|
|
2829
|
+
}
|
|
2830
|
+
|
|
2831
|
+
processDir(handcraftedDir);
|
|
2832
|
+
processDir(generatedDir);
|
|
2833
|
+
|
|
2834
|
+
// Default: warn only. `forgewp export --strict` fails the export.
|
|
2835
|
+
flushEditableIssues({ strict: !!options.strict });
|
|
2836
|
+
|
|
2837
|
+
return blockSlugs;
|
|
2838
|
+
}
|