@forgewp/compiler 0.4.3 → 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 +59 -0
- package/bin/add.js +20 -14
- package/bin/cli.js +145 -70
- package/bin/doctor.js +21 -12
- package/bin/export.js +69 -20
- package/bin/fresh.js +5 -0
- package/bin/i18n-extract.js +3 -10
- package/bin/i18n-translate.js +15 -24
- package/bin/make-block.js +13 -0
- package/bin/make-editable.js +166 -0
- package/bin/make-form.js +131 -0
- package/bin/make-loop.js +40 -43
- package/bin/make-mail.js +27 -0
- package/bin/make-post-type.js +57 -29
- package/bin/make-sandbox.js +62 -11
- 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 +5 -0
- package/lib/adapters/stub-adapter.js +4 -0
- package/lib/add-component.js +153 -92
- package/lib/asset-loader.js +313 -3
- 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 +31 -91
- 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 +1916 -339
- 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 +287 -8
- package/lib/index.js +2 -1
- package/lib/load-config.js +338 -242
- package/lib/mail-templates.js +37 -0
- package/lib/markup-processor.js +388 -102
- package/lib/node-runtime.js +7 -0
- package/lib/page-config-plugin.js +64 -20
- package/lib/php-builders.js +383 -44
- package/lib/react-adapter.js +983 -235
- package/lib/registration-metadata.js +11 -0
- package/lib/render-theme.mts +1410 -616
- 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 +2 -2
- package/lib/validate.js +27 -5
- package/lib/virtual-plugin.js +319 -0
- package/lib/walkthrough.md +26 -0
- package/package.json +16 -5
- 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/forgot-password-form-wrapper.tsx +10 -2
- package/templates/auth/components/login-form-wrapper.tsx +118 -21
- package/templates/auth/components/reset-password-form-wrapper.tsx +10 -2
- package/templates/auth/components/signup-form-wrapper.tsx +2 -2
- package/templates/auth/components/verify-email-view-wrapper.tsx +5 -5
- package/templates/auth/pages/DashboardPage.tsx +1 -4
- package/templates/auth/pages/ForgotPasswordPage.tsx +1 -4
- package/templates/auth/pages/LoginPage.tsx +1 -4
- package/templates/auth/pages/ResetPasswordPage.tsx +1 -4
- package/templates/auth/pages/SignUpPage.tsx +1 -4
- package/templates/auth/pages/VerifyEmailPage.tsx +1 -4
- 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/menus.json +12 -10
- package/templates/users.json +8 -4
- package/templates/wordpress.tsx +690 -245
- package/lib/block-compiler.js +0 -552
- package/lib/functions-builder.js +0 -2970
- package/lib/hydration-scanner.js +0 -833
|
@@ -0,0 +1,1229 @@
|
|
|
1
|
+
import { findHtmlTagEnd, resolveIconToSvgHtml } from "./shared-utils.js";
|
|
2
|
+
import { markLegacyFallback, tryParseSource } from "./ast-parser.js";
|
|
3
|
+
import { rewriteAttrRefsSafely } from "./source-sanitize.js";
|
|
4
|
+
|
|
5
|
+
const _iconResolveCache = new Map();
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Parse a JSX string into an AST for generateReactCreateElement to consume.
|
|
9
|
+
*
|
|
10
|
+
* Parses `jsx` with @babel/parser (see ast-parser.js) and, when it parses
|
|
11
|
+
* cleanly as a single JSX expression, returns the real JSXElement/JSXFragment
|
|
12
|
+
* node directly.
|
|
13
|
+
*
|
|
14
|
+
* `jsx` is sometimes not standalone-parseable — e.g. multiple adjacent root
|
|
15
|
+
* elements with no wrapping fragment, real JSX syntax forbids that — so a
|
|
16
|
+
* parse failure returns null. Callers that extract `jsx` as a sub-fragment of
|
|
17
|
+
* a larger snippet (rather than a whole customEditJsx tree) can retry by
|
|
18
|
+
* wrapping it in a synthetic `<>…</>` fragment before giving up.
|
|
19
|
+
*/
|
|
20
|
+
export function parseJsxToAst(jsx) {
|
|
21
|
+
if (typeof jsx === 'string' && jsx.trim()) {
|
|
22
|
+
const ast = tryParseSource(jsx);
|
|
23
|
+
const body = ast && ast.program.body;
|
|
24
|
+
if (body && body.length === 1 && body[0].type === 'ExpressionStatement') {
|
|
25
|
+
const expr = body[0].expression;
|
|
26
|
+
if (expr.type === 'JSXElement' || expr.type === 'JSXFragment') {
|
|
27
|
+
return { realAst: true, node: expr, source: jsx };
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
markLegacyFallback('editor-transpiler:parseJsxToAst-would-have-tried-legacy');
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function resolveIconToCreateElement(componentName, packageName, themeRoot, classNameStr) {
|
|
36
|
+
const cacheKey = `${packageName}::${componentName}::${classNameStr}`;
|
|
37
|
+
if (_iconResolveCache.has(cacheKey)) return _iconResolveCache.get(cacheKey);
|
|
38
|
+
|
|
39
|
+
const svgHtml = resolveIconToSvgHtml(componentName, packageName, themeRoot, classNameStr);
|
|
40
|
+
if (!svgHtml) {
|
|
41
|
+
_iconResolveCache.set(cacheKey, null);
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const result = svgHtmlToCreateElement(svgHtml, classNameStr);
|
|
46
|
+
_iconResolveCache.set(cacheKey, result);
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function svgHtmlToCreateElement(svgHtml, overrideClassName) {
|
|
51
|
+
function parseTagAttrs(attrStr) {
|
|
52
|
+
const obj = {};
|
|
53
|
+
const rx = /([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]*))/g;
|
|
54
|
+
let m;
|
|
55
|
+
while ((m = rx.exec(attrStr)) !== null) {
|
|
56
|
+
obj[m[1]] = m[2] !== undefined ? m[2] : m[3] !== undefined ? m[3] : m[4];
|
|
57
|
+
}
|
|
58
|
+
return obj;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function attrsToPropStr(attrs, overrideClass) {
|
|
62
|
+
const props = { ...attrs };
|
|
63
|
+
if (overrideClass !== undefined) props.className = overrideClass;
|
|
64
|
+
const renames = {
|
|
65
|
+
'class': 'className', 'stroke-width': 'strokeWidth', 'stroke-linecap': 'strokeLinecap',
|
|
66
|
+
'stroke-linejoin': 'strokeLinejoin', 'stroke-dasharray': 'strokeDasharray',
|
|
67
|
+
'stroke-dashoffset': 'strokeDashoffset', 'fill-rule': 'fillRule',
|
|
68
|
+
'clip-rule': 'clipRule', 'clip-path': 'clipPath', 'font-size': 'fontSize',
|
|
69
|
+
'text-anchor': 'textAnchor', 'dominant-baseline': 'dominantBaseline',
|
|
70
|
+
};
|
|
71
|
+
const out = {};
|
|
72
|
+
for (const [k, v] of Object.entries(props)) {
|
|
73
|
+
const key = renames[k] || k;
|
|
74
|
+
out[key] = v;
|
|
75
|
+
}
|
|
76
|
+
return JSON.stringify(out);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function parseChildren(html) {
|
|
80
|
+
const children = [];
|
|
81
|
+
let i = 0;
|
|
82
|
+
while (i < html.length) {
|
|
83
|
+
if (html[i] === '<') {
|
|
84
|
+
const tagEnd = html.indexOf('>', i);
|
|
85
|
+
if (tagEnd === -1) break;
|
|
86
|
+
const rawTag = html.slice(i + 1, tagEnd);
|
|
87
|
+
const selfClosing = rawTag.endsWith('/');
|
|
88
|
+
const cleanTag = selfClosing ? rawTag.slice(0, -1).trim() : rawTag.trim();
|
|
89
|
+
const spaceIdx = cleanTag.search(/\s/);
|
|
90
|
+
const tagName = spaceIdx === -1 ? cleanTag : cleanTag.slice(0, spaceIdx);
|
|
91
|
+
if (tagName.startsWith('/')) { break; }
|
|
92
|
+
const attrStr = spaceIdx === -1 ? '' : cleanTag.slice(spaceIdx + 1);
|
|
93
|
+
const attrs = parseTagAttrs(attrStr);
|
|
94
|
+
const propStr = attrsToPropStr(attrs);
|
|
95
|
+
let content = '';
|
|
96
|
+
if (!selfClosing && tagName !== 'br' && tagName !== 'hr' && tagName !== 'input') {
|
|
97
|
+
const closeTag = `</${tagName}>`;
|
|
98
|
+
const closeIdx = html.indexOf(closeTag, tagEnd + 1);
|
|
99
|
+
if (closeIdx !== -1) {
|
|
100
|
+
content = html.slice(tagEnd + 1, closeIdx);
|
|
101
|
+
i = closeIdx + closeTag.length;
|
|
102
|
+
} else {
|
|
103
|
+
i = tagEnd + 1;
|
|
104
|
+
}
|
|
105
|
+
} else {
|
|
106
|
+
i = tagEnd + 1;
|
|
107
|
+
}
|
|
108
|
+
const childCodes = content.trim() ? parseChildren(content) : [];
|
|
109
|
+
const childrenArg = childCodes.length > 0 ? ', ' + childCodes.join(', ') : '';
|
|
110
|
+
children.push(`createElement("${tagName}", ${propStr}${childrenArg})`);
|
|
111
|
+
} else {
|
|
112
|
+
const nextTag = html.indexOf('<', i);
|
|
113
|
+
const text = nextTag === -1 ? html.slice(i) : html.slice(i, nextTag);
|
|
114
|
+
const trimmed = text.trim();
|
|
115
|
+
if (trimmed) children.push(JSON.stringify(trimmed));
|
|
116
|
+
i = nextTag === -1 ? html.length : nextTag;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return children;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const svgOpenEnd = svgHtml.indexOf('>');
|
|
123
|
+
if (svgOpenEnd === -1) return null;
|
|
124
|
+
const svgTag = svgHtml.slice(1, svgOpenEnd);
|
|
125
|
+
const svgTagEnd = svgTag.search(/\s/);
|
|
126
|
+
const svgAttrs = svgTagEnd === -1 ? {} : parseTagAttrs(svgTag.slice(svgTagEnd + 1));
|
|
127
|
+
const svgCloseIdx = svgHtml.lastIndexOf('</svg>');
|
|
128
|
+
const svgInner = svgCloseIdx !== -1 ? svgHtml.slice(svgOpenEnd + 1, svgCloseIdx) : '';
|
|
129
|
+
const childCodes = parseChildren(svgInner);
|
|
130
|
+
const childrenArg = childCodes.length > 0 ? ', ' + childCodes.join(', ') : '';
|
|
131
|
+
const propStr = attrsToPropStr(svgAttrs, overrideClassName);
|
|
132
|
+
return `createElement("svg", ${propStr}${childrenArg})`;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Scans forward from an opening bracket at str[startIndex] and returns the index of its
|
|
137
|
+
* matching closing bracket, respecting nesting and string/template-literal boundaries.
|
|
138
|
+
* Returns -1 if unbalanced.
|
|
139
|
+
*/
|
|
140
|
+
function scanBalancedBrackets(str, startIndex, openChar, closeChar) {
|
|
141
|
+
let depth = 0;
|
|
142
|
+
let i = startIndex;
|
|
143
|
+
let inSingle = false;
|
|
144
|
+
let inDouble = false;
|
|
145
|
+
let inBacktick = false;
|
|
146
|
+
|
|
147
|
+
while (i < str.length) {
|
|
148
|
+
const c = str[i];
|
|
149
|
+
if (inSingle) {
|
|
150
|
+
if (c === '\\') { i += 2; continue; }
|
|
151
|
+
if (c === "'") inSingle = false;
|
|
152
|
+
} else if (inDouble) {
|
|
153
|
+
if (c === '\\') { i += 2; continue; }
|
|
154
|
+
if (c === '"') inDouble = false;
|
|
155
|
+
} else if (inBacktick) {
|
|
156
|
+
if (c === '\\') { i += 2; continue; }
|
|
157
|
+
if (c === '`') inBacktick = false;
|
|
158
|
+
} else {
|
|
159
|
+
if (c === "'") inSingle = true;
|
|
160
|
+
else if (c === '"') inDouble = true;
|
|
161
|
+
else if (c === '`') inBacktick = true;
|
|
162
|
+
else if (c === openChar) depth++;
|
|
163
|
+
else if (c === closeChar) {
|
|
164
|
+
depth--;
|
|
165
|
+
if (depth === 0) return i;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
i++;
|
|
169
|
+
}
|
|
170
|
+
return -1;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Parse `.map(…)` callback params after the array expression.
|
|
175
|
+
* Supports:
|
|
176
|
+
* (item) => (
|
|
177
|
+
* (item, index) => (
|
|
178
|
+
* item => (
|
|
179
|
+
* ({ a, b }) => (
|
|
180
|
+
* ({ a: A, b }) => (
|
|
181
|
+
* ({ a, b }, index) => (
|
|
182
|
+
*
|
|
183
|
+
* @returns {{ paramName: string, indexName?: string } | null}
|
|
184
|
+
*/
|
|
185
|
+
function matchMapCallbackParams(rest) {
|
|
186
|
+
const m = rest.match(/^\s*\.map\(\s*/);
|
|
187
|
+
if (!m) return null;
|
|
188
|
+
let i = m[0].length;
|
|
189
|
+
while (i < rest.length && /\s/.test(rest[i])) i++;
|
|
190
|
+
|
|
191
|
+
// Bare single param: item => (
|
|
192
|
+
if (/^[a-zA-Z_$]/.test(rest[i]) && rest[i] !== '(') {
|
|
193
|
+
const id = rest.slice(i).match(/^([a-zA-Z0-9_$]+)\s*=>\s*\(\s*$/);
|
|
194
|
+
if (!id) return null;
|
|
195
|
+
return { paramName: id[1] };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
if (rest[i] !== '(') return null;
|
|
199
|
+
// Param list: ( … ) => (
|
|
200
|
+
const closeParen = scanBalancedBrackets(rest, i, '(', ')');
|
|
201
|
+
if (closeParen === -1) return null;
|
|
202
|
+
const inside = rest.slice(i + 1, closeParen).trim();
|
|
203
|
+
const after = rest.slice(closeParen + 1);
|
|
204
|
+
if (!/^\s*=>\s*\(\s*$/.test(after)) return null;
|
|
205
|
+
|
|
206
|
+
// Object destructure: { a, b: B } or { a, b }, index
|
|
207
|
+
if (inside.startsWith('{')) {
|
|
208
|
+
const closeBrace = scanBalancedBrackets(inside, 0, '{', '}');
|
|
209
|
+
if (closeBrace === -1) return null;
|
|
210
|
+
const destructure = inside.slice(0, closeBrace + 1);
|
|
211
|
+
const tail = inside.slice(closeBrace + 1).trim();
|
|
212
|
+
let indexName;
|
|
213
|
+
if (tail.startsWith(',')) {
|
|
214
|
+
const idx = tail.slice(1).trim().match(/^([a-zA-Z0-9_$]+)\s*$/);
|
|
215
|
+
if (!idx) return null;
|
|
216
|
+
indexName = idx[1];
|
|
217
|
+
} else if (tail) {
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
return { paramName: destructure, indexName };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Simple: item or item, index
|
|
224
|
+
const simple = inside.match(
|
|
225
|
+
/^([a-zA-Z0-9_$]+)\s*(?:,\s*([a-zA-Z0-9_$]+)\s*)?$/,
|
|
226
|
+
);
|
|
227
|
+
if (!simple) return null;
|
|
228
|
+
return { paramName: simple[1], indexName: simple[2] };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Matches a `{ <arrayExpr>.map((param) => (` loop header text node, where <arrayExpr>
|
|
233
|
+
* is a bare dotted identifier chain (`items`, `foo.bar`), an arbitrary parenthesized
|
|
234
|
+
* expression (`(cond ? a : b)`, `(x || []).filter(y)`), or an array literal (`[1, 2, 3]`).
|
|
235
|
+
* The non-identifier forms let components inline a ternary/fallback/literal list directly
|
|
236
|
+
* into the `.map()` target — e.g. `{(categoryTerms.length > 0 ? A : B).map((tag) => (...))}`
|
|
237
|
+
* or `{[1, 2, 3].map((i) => (...))}` — without needing to be hoisted into a separate local
|
|
238
|
+
* variable just to satisfy this parser.
|
|
239
|
+
*
|
|
240
|
+
* Also supports object-destructure params: `.map(({ icon: Icon, label }) => (`.
|
|
241
|
+
*
|
|
242
|
+
* @returns {{ arrayExpr: string, paramName: string, indexName?: string } | null}
|
|
243
|
+
*/
|
|
244
|
+
function matchMapLoopHeader(cleanVal) {
|
|
245
|
+
if (!cleanVal.startsWith('{')) return null;
|
|
246
|
+
const body = cleanVal.slice(1).replace(/^\s+/, '');
|
|
247
|
+
|
|
248
|
+
// Parenthesized expression or array literal target — matched via a balanced-bracket
|
|
249
|
+
// scan since the expression itself may contain arbitrary nesting/strings.
|
|
250
|
+
if (body.startsWith('(') || body.startsWith('[')) {
|
|
251
|
+
const openChar = body[0];
|
|
252
|
+
const closeChar = openChar === '(' ? ')' : ']';
|
|
253
|
+
const closeIdx = scanBalancedBrackets(body, 0, openChar, closeChar);
|
|
254
|
+
if (closeIdx === -1) return null;
|
|
255
|
+
const arrayExpr = body.slice(0, closeIdx + 1);
|
|
256
|
+
const rest = body.slice(closeIdx + 1);
|
|
257
|
+
const cb = matchMapCallbackParams(rest);
|
|
258
|
+
if (!cb) return null;
|
|
259
|
+
return { arrayExpr, paramName: cb.paramName, indexName: cb.indexName };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// Bare identifier chain target: {items.map((x) => ( or {foo.bar.map(({a}) => (
|
|
263
|
+
const identPrefix = cleanVal.match(
|
|
264
|
+
/^\{\s*([a-zA-Z0-9_$]+(?:\.[a-zA-Z0-9_$]+)*)\s*(?=\.map\s*\()/,
|
|
265
|
+
);
|
|
266
|
+
if (!identPrefix) return null;
|
|
267
|
+
const arrayExpr = identPrefix[1];
|
|
268
|
+
const rest = cleanVal.slice(identPrefix[0].length);
|
|
269
|
+
const cb = matchMapCallbackParams(rest);
|
|
270
|
+
if (!cb) return null;
|
|
271
|
+
return { arrayExpr, paramName: cb.paramName, indexName: cb.indexName };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function transpileCurlyExpressions(val) {
|
|
275
|
+
const segments = [];
|
|
276
|
+
let i = 0;
|
|
277
|
+
while (i < val.length) {
|
|
278
|
+
if (val[i] === '{') {
|
|
279
|
+
let start = i;
|
|
280
|
+
let depth = 0;
|
|
281
|
+
const modes = [];
|
|
282
|
+
let curMode = 'code';
|
|
283
|
+
let j = start;
|
|
284
|
+
|
|
285
|
+
while (j < val.length) {
|
|
286
|
+
const c = val[j];
|
|
287
|
+
const next = val[j+1];
|
|
288
|
+
|
|
289
|
+
if (curMode === 'code') {
|
|
290
|
+
if (c === '"') curMode = 'double';
|
|
291
|
+
else if (c === "'") curMode = 'single';
|
|
292
|
+
else if (c === '`') curMode = 'backtick';
|
|
293
|
+
else if (c === '{') depth++;
|
|
294
|
+
else if (c === '}') {
|
|
295
|
+
depth--;
|
|
296
|
+
if (modes.length > 0) {
|
|
297
|
+
curMode = modes.pop();
|
|
298
|
+
} else if (depth === 0) {
|
|
299
|
+
j++;
|
|
300
|
+
break;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
} else if (curMode === 'double') {
|
|
304
|
+
if (c === '"' && val[j-1] !== '\\') curMode = 'code';
|
|
305
|
+
} else if (curMode === 'single') {
|
|
306
|
+
if (c === "'" && val[j-1] !== '\\') curMode = 'code';
|
|
307
|
+
} else if (curMode === 'backtick') {
|
|
308
|
+
if (c === '`' && val[j-1] !== '\\') curMode = 'code';
|
|
309
|
+
else if (c === '$' && next === '{') {
|
|
310
|
+
modes.push('backtick');
|
|
311
|
+
curMode = 'code';
|
|
312
|
+
depth++;
|
|
313
|
+
j++;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
j++;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
segments.push({
|
|
320
|
+
type: 'expression',
|
|
321
|
+
value: val.substring(start + 1, j - 1).trim()
|
|
322
|
+
});
|
|
323
|
+
i = j;
|
|
324
|
+
} else {
|
|
325
|
+
let start = i;
|
|
326
|
+
while (i < val.length && val[i] !== '{') {
|
|
327
|
+
i++;
|
|
328
|
+
}
|
|
329
|
+
segments.push({
|
|
330
|
+
type: 'text',
|
|
331
|
+
value: val.substring(start, i)
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (segments.length === 1 && segments[0].type === 'expression') {
|
|
337
|
+
return segments[0].value;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// Adjacent JSX expressions only (optional whitespace between), e.g.
|
|
341
|
+
// {cell(a)}{cell(b)}{cell(c)}
|
|
342
|
+
// Must NOT become a template string — React elements coerce to "[object Object]".
|
|
343
|
+
// Emit an array; React accepts arrays as createElement children.
|
|
344
|
+
const nonWsText = segments.filter(
|
|
345
|
+
(s) => s.type === 'text' && s.value.replace(/\s+/g, '').length > 0,
|
|
346
|
+
);
|
|
347
|
+
const exprs = segments.filter((s) => s.type === 'expression');
|
|
348
|
+
if (nonWsText.length === 0 && exprs.length > 0) {
|
|
349
|
+
if (exprs.length === 1) return exprs[0].value;
|
|
350
|
+
return `[${exprs.map((e) => e.value).join(', ')}]`;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const literalParts = [];
|
|
354
|
+
for (const seg of segments) {
|
|
355
|
+
if (seg.type === 'expression') {
|
|
356
|
+
literalParts.push(`\${${seg.value}}`);
|
|
357
|
+
} else {
|
|
358
|
+
literalParts.push(seg.value.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$/g, '\\$'));
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
return `\`${literalParts.join('')}\``;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function getJsxElementName(nameNode) {
|
|
365
|
+
if (nameNode.type === 'JSXIdentifier') return nameNode.name;
|
|
366
|
+
if (nameNode.type === 'JSXMemberExpression') {
|
|
367
|
+
return `${getJsxElementName(nameNode.object)}.${nameNode.property.name}`;
|
|
368
|
+
}
|
|
369
|
+
if (nameNode.type === 'JSXNamespacedName') {
|
|
370
|
+
return `${nameNode.namespace.name}:${nameNode.name.name}`;
|
|
371
|
+
}
|
|
372
|
+
return '';
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** `{name: value}` map from real JSXAttribute nodes — value is `true`
|
|
376
|
+
* (boolean shorthand), a string literal's value, or the `{...}` (braces
|
|
377
|
+
* included) source text of an expression attribute, which is the shape the
|
|
378
|
+
* WpIcon/WpEditable/prop-building logic below expects. */
|
|
379
|
+
function readRealJsxAttributes(openingElement, code) {
|
|
380
|
+
const attributes = {};
|
|
381
|
+
for (const attr of openingElement.attributes) {
|
|
382
|
+
if (attr.type !== 'JSXAttribute') continue; // spreads: legacy never modeled these either
|
|
383
|
+
const name = getJsxElementName(attr.name) || (attr.name.type === 'JSXIdentifier' ? attr.name.name : '');
|
|
384
|
+
if (!attr.value) {
|
|
385
|
+
attributes[name] = true;
|
|
386
|
+
} else if (attr.value.type === 'StringLiteral') {
|
|
387
|
+
attributes[name] = attr.value.value;
|
|
388
|
+
} else if (attr.value.type === 'JSXExpressionContainer') {
|
|
389
|
+
attributes[name] = code.slice(attr.value.start, attr.value.end);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
return attributes;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Rewrite bare block-attribute identifiers to `attributes.X` in a verbatim
|
|
397
|
+
* source slice (a ternary/`&&` condition, a `.map()` array target, …) —
|
|
398
|
+
* mirrors the narrower ad hoc regex the legacy children-loop applied to
|
|
399
|
+
* ternary/`&&` conditions specifically, generalized via the same safe
|
|
400
|
+
* rewriter index.js already uses for attribute-value expressions, and
|
|
401
|
+
* applied uniformly to every non-JSX expression this emitter passes through
|
|
402
|
+
* verbatim (also covers cases legacy's condition-only regex didn't reach,
|
|
403
|
+
* like a `.filter()` predicate).
|
|
404
|
+
*/
|
|
405
|
+
function rewriteBareAttrRefs(text, blockSettings) {
|
|
406
|
+
const attrKeys = Object.keys((blockSettings && blockSettings.attributes) || {});
|
|
407
|
+
if (attrKeys.length === 0) return text;
|
|
408
|
+
return rewriteAttrRefsSafely(text, attrKeys);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Emit a plain JS expression (a ternary condition, `.map()` callback body,
|
|
413
|
+
* `&&` right-hand side, arbitrary helper call, …) that may contain nested
|
|
414
|
+
* JSX anywhere inside it. Splices each outermost JSX subtree's byte range
|
|
415
|
+
* with its createElement(...) translation and leaves every other character —
|
|
416
|
+
* the ternary/`&&`/`.map()` shell itself — verbatim from the original
|
|
417
|
+
* source, then rewrites bare attribute references throughout. This is the
|
|
418
|
+
* generalized replacement for the old regex-matched ternary/`&&`/loop-header
|
|
419
|
+
* patterns: it works for any JS expression shape a real parser can produce,
|
|
420
|
+
* not just the handful the old patterns anticipated.
|
|
421
|
+
*/
|
|
422
|
+
/**
|
|
423
|
+
* Emit a plain JS expression (a ternary, `&&`, `.map()` call, arbitrary
|
|
424
|
+
* helper call, …) that may contain nested JSX anywhere inside it.
|
|
425
|
+
*
|
|
426
|
+
* Recursive emitters keyed on node.type for the shapes that need bare
|
|
427
|
+
* attr-key rewriting — ConditionalExpression and LogicalExpression rewrite
|
|
428
|
+
* only their own condition (`test/left`), exactly where legacy's phpCond
|
|
429
|
+
* regex applied it; a bare identifier BRANCH result (e.g. a local `const
|
|
430
|
+
* badge = badgeProp ?? badgeMeta` dual-host variable that happens to share
|
|
431
|
+
* its name with a block attribute key) must NOT be rewritten — legacy never
|
|
432
|
+
* touched branch content, only conditions, and conflating the two would
|
|
433
|
+
* silently replace an in-scope local variable read with the wrong value.
|
|
434
|
+
* CallExpression rewrites a bare attr-key `.map()`/`.filter()` array target
|
|
435
|
+
* the same way legacy's dedicated loop-header handling did. Everything else
|
|
436
|
+
* falls through to a generic "splice nested JSX, leave the rest verbatim"
|
|
437
|
+
* pass with no rewriting — the safe default for shapes with no known
|
|
438
|
+
* condition-like part (a plain identifier, a helper call, …).
|
|
439
|
+
*/
|
|
440
|
+
function emitExpressionWithNestedJsx(exprNode, code, blockSettings) {
|
|
441
|
+
if (exprNode.type === 'JSXElement' || exprNode.type === 'JSXFragment') {
|
|
442
|
+
return generateFromRealJsxNode(exprNode, code, blockSettings);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
if (exprNode.type === 'ConditionalExpression') {
|
|
446
|
+
const cond = rewriteBareAttrRefs(code.slice(exprNode.test.start, exprNode.test.end), blockSettings);
|
|
447
|
+
const trueCode = emitExpressionWithNestedJsx(exprNode.consequent, code, blockSettings);
|
|
448
|
+
const falseCode = emitExpressionWithNestedJsx(exprNode.alternate, code, blockSettings);
|
|
449
|
+
return `${cond} ? (${trueCode}) : (${falseCode})`;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
if (exprNode.type === 'LogicalExpression' && exprNode.operator === '&&') {
|
|
453
|
+
const cond = rewriteBareAttrRefs(code.slice(exprNode.left.start, exprNode.left.end), blockSettings);
|
|
454
|
+
const rightCode = emitExpressionWithNestedJsx(exprNode.right, code, blockSettings);
|
|
455
|
+
return `${cond} && (${rightCode})`;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
const spans = [];
|
|
459
|
+
collectOutermostJsx(exprNode, spans, code, blockSettings);
|
|
460
|
+
|
|
461
|
+
if (exprNode.type === 'CallExpression' && exprNode.callee.type === 'MemberExpression') {
|
|
462
|
+
const obj = exprNode.callee.object;
|
|
463
|
+
const objText = code.slice(obj.start, obj.end);
|
|
464
|
+
const rewrittenObj = rewriteBareAttrRefs(objText, blockSettings);
|
|
465
|
+
if (rewrittenObj !== objText) {
|
|
466
|
+
spans.push({ start: obj.start, end: obj.end, replacement: rewrittenObj });
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
if (spans.length === 0) {
|
|
471
|
+
return code.slice(exprNode.start, exprNode.end);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// Splice each span's replacement into the verbatim source, no further
|
|
475
|
+
// rewriting of the surrounding text (see function doc above).
|
|
476
|
+
spans.sort((a, b) => a.start - b.start);
|
|
477
|
+
let out = '';
|
|
478
|
+
let cursor = exprNode.start;
|
|
479
|
+
for (const span of spans) {
|
|
480
|
+
out += code.slice(cursor, span.start);
|
|
481
|
+
out += span.replacement;
|
|
482
|
+
cursor = span.end;
|
|
483
|
+
}
|
|
484
|
+
out += code.slice(cursor, exprNode.end);
|
|
485
|
+
return out;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
const AST_NODE_METADATA_KEYS = new Set([
|
|
489
|
+
'loc', 'start', 'end', 'range', 'extra', 'leadingComments',
|
|
490
|
+
'trailingComments', 'innerComments', 'comments',
|
|
491
|
+
]);
|
|
492
|
+
|
|
493
|
+
/** Find JSXElement/JSXFragment descendants without descending into ones already found. */
|
|
494
|
+
function collectOutermostJsx(node, out, code, blockSettings) {
|
|
495
|
+
if (!node || typeof node !== 'object' || typeof node.type !== 'string') return;
|
|
496
|
+
if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
|
|
497
|
+
out.push({
|
|
498
|
+
start: node.start,
|
|
499
|
+
end: node.end,
|
|
500
|
+
replacement: generateFromRealJsxNode(node, code, blockSettings),
|
|
501
|
+
});
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
for (const key of Object.keys(node)) {
|
|
505
|
+
if (AST_NODE_METADATA_KEYS.has(key)) continue;
|
|
506
|
+
const val = node[key];
|
|
507
|
+
if (Array.isArray(val)) {
|
|
508
|
+
for (const item of val) {
|
|
509
|
+
if (item && typeof item.type === 'string') collectOutermostJsx(item, out, code, blockSettings);
|
|
510
|
+
}
|
|
511
|
+
} else if (val && typeof val.type === 'string') {
|
|
512
|
+
collectOutermostJsx(val, out, code, blockSettings);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** Real JSXElement/JSXFragment children → array of createElement(...) arg code strings. */
|
|
518
|
+
function emitRealJsxChildren(children, code, blockSettings) {
|
|
519
|
+
const out = [];
|
|
520
|
+
for (const child of children) {
|
|
521
|
+
if (child.type === 'JSXText') {
|
|
522
|
+
const val = child.value.trim();
|
|
523
|
+
if (val) out.push(JSON.stringify(val));
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
if (child.type === 'JSXExpressionContainer') {
|
|
527
|
+
if (child.expression.type === 'JSXEmptyExpression') continue; // {/* comment */}
|
|
528
|
+
out.push(emitExpressionWithNestedJsx(child.expression, code, blockSettings));
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
531
|
+
if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
|
|
532
|
+
out.push(generateFromRealJsxNode(child, code, blockSettings));
|
|
533
|
+
continue;
|
|
534
|
+
}
|
|
535
|
+
if (child.type === 'JSXSpreadChild') {
|
|
536
|
+
out.push(emitExpressionWithNestedJsx(child.expression, code, blockSettings));
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
return out;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Emit createElement(...) code for a real JSXElement/JSXFragment node —
|
|
544
|
+
* WpIcon, WpImage, WpLink, and WpEditable get editor-safe runtime translations;
|
|
545
|
+
* everything else becomes a generic createElement(type, props, ...children) call.
|
|
546
|
+
*/
|
|
547
|
+
function generateFromRealJsxNode(node, code, blockSettings) {
|
|
548
|
+
if (node.type === 'JSXFragment') {
|
|
549
|
+
const childCodes = emitRealJsxChildren(node.children, code, blockSettings).filter(Boolean);
|
|
550
|
+
if (childCodes.length === 0) return 'null';
|
|
551
|
+
if (childCodes.length === 1) return childCodes[0];
|
|
552
|
+
return `createElement(wp.element.Fragment, null, ${childCodes.join(', ')})`;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
const tagName = getJsxElementName(node.openingElement.name);
|
|
556
|
+
const motionTag = tagName.match(/^motion\.([a-z][a-z0-9-]*)$/i);
|
|
557
|
+
const hostTagName = motionTag ? motionTag[1] : tagName;
|
|
558
|
+
const attributes = readRealJsxAttributes(node.openingElement, code);
|
|
559
|
+
|
|
560
|
+
// React short fragments <>…</>, and an explicit <Fragment> tag alike.
|
|
561
|
+
if (tagName === 'Fragment') {
|
|
562
|
+
const childCodes = emitRealJsxChildren(node.children, code, blockSettings).filter(Boolean);
|
|
563
|
+
if (childCodes.length === 0) return 'null';
|
|
564
|
+
if (childCodes.length === 1) return childCodes[0];
|
|
565
|
+
return `createElement(wp.element.Fragment, null, ${childCodes.join(', ')})`;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
// Dynamic icon from slug (repeater / attributes) — resolved at editor runtime via registry
|
|
569
|
+
if (tagName === 'WpIcon') {
|
|
570
|
+
let nameExpr = String(attributes.name || '""').trim();
|
|
571
|
+
if (nameExpr.startsWith('{') && nameExpr.endsWith('}')) {
|
|
572
|
+
nameExpr = nameExpr.slice(1, -1).trim();
|
|
573
|
+
} else if (!(nameExpr.startsWith('"') || nameExpr.startsWith("'") || nameExpr.startsWith('`'))) {
|
|
574
|
+
if (/^[a-zA-Z_$]/.test(nameExpr) && !nameExpr.includes('.')) {
|
|
575
|
+
nameExpr = JSON.stringify(nameExpr);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
if (blockSettings && blockSettings.attributes && /^[a-zA-Z_$][\w$]*$/.test(nameExpr)) {
|
|
579
|
+
if (Object.prototype.hasOwnProperty.call(blockSettings.attributes, nameExpr)) {
|
|
580
|
+
nameExpr = `attributes.${nameExpr}`;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
let classExpr = '""';
|
|
584
|
+
if (attributes.className) {
|
|
585
|
+
const raw = String(attributes.className).trim();
|
|
586
|
+
classExpr = raw.startsWith('{') && raw.endsWith('}')
|
|
587
|
+
? raw.slice(1, -1).trim()
|
|
588
|
+
: JSON.stringify(raw);
|
|
589
|
+
}
|
|
590
|
+
const providerRaw = String(attributes.provider || 'lucide').replace(/['"]/g, '');
|
|
591
|
+
return `forgeWpRenderIcon(${nameExpr}, ${classExpr}, ${JSON.stringify(providerRaw)})`;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
if (tagName === 'WpImage') {
|
|
595
|
+
const sourceRaw = String(attributes.src || '""').trim();
|
|
596
|
+
const sourceExpr =
|
|
597
|
+
sourceRaw.startsWith('{') && sourceRaw.endsWith('}')
|
|
598
|
+
? sourceRaw.slice(1, -1).trim()
|
|
599
|
+
: JSON.stringify(sourceRaw.replace(/^['"]|['"]$/g, ''));
|
|
600
|
+
const props = {};
|
|
601
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
602
|
+
if (key === 'src' || key === 'id' || key === 'field' || key === 'size' ||
|
|
603
|
+
key === 'priority' || key === 'optimize' || key === 'placeholder' ||
|
|
604
|
+
key === 'blurDataURL' || key === 'attachments') continue;
|
|
605
|
+
if (value === true || value === '') {
|
|
606
|
+
props[key] = 'true';
|
|
607
|
+
} else if (typeof value === 'string' && value.startsWith('{') && value.endsWith('}')) {
|
|
608
|
+
props[key] = value.slice(1, -1).trim();
|
|
609
|
+
} else {
|
|
610
|
+
props[key] = JSON.stringify(value);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
const formatPropKey = (key) =>
|
|
614
|
+
/^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key);
|
|
615
|
+
const propsStr = Object.keys(props).length > 0
|
|
616
|
+
? `{ ${Object.entries(props).map(([key, value]) => `${formatPropKey(key)}: ${value}`).join(', ')} }`
|
|
617
|
+
: '{}';
|
|
618
|
+
return `createElement("img", Object.assign(${propsStr}, { src: forgeWpResolveEditorImage(${sourceExpr}), alt: forgeWpEditorImageAlt(${sourceExpr}, ${props.alt || '""'}) }))`;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
if (tagName === 'WpLink') {
|
|
622
|
+
const props = {};
|
|
623
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
624
|
+
if (key === 'newTab' || key === 'prefetch') continue;
|
|
625
|
+
if (value === true || value === '') {
|
|
626
|
+
props[key] = 'true';
|
|
627
|
+
} else if (typeof value === 'string' && value.startsWith('{') && value.endsWith('}')) {
|
|
628
|
+
props[key] = value.slice(1, -1).trim();
|
|
629
|
+
} else {
|
|
630
|
+
props[key] = JSON.stringify(value);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
const childCodes = emitRealJsxChildren(node.children, code, blockSettings).filter(Boolean);
|
|
634
|
+
return emitEditorLink(props, childCodes.join(', '), blockSettings);
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
if (tagName === 'WpEditable') {
|
|
638
|
+
const tagRaw = String(attributes.tagName || 'div').trim();
|
|
639
|
+
let tagExpr;
|
|
640
|
+
let tagLiteral = 'div';
|
|
641
|
+
if (tagRaw.startsWith('{') && tagRaw.endsWith('}')) {
|
|
642
|
+
tagExpr = tagRaw.slice(1, -1).trim();
|
|
643
|
+
const lit = tagExpr.match(/^['"]([\w-]+)['"]$/);
|
|
644
|
+
if (lit) tagLiteral = lit[1];
|
|
645
|
+
else tagLiteral = '';
|
|
646
|
+
} else {
|
|
647
|
+
tagLiteral = tagRaw.replace(/['"]/g, '') || 'div';
|
|
648
|
+
tagExpr = JSON.stringify(tagLiteral);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
let valStr = String(attributes.value || '').trim();
|
|
652
|
+
if (valStr.startsWith('{') && valStr.endsWith('}')) {
|
|
653
|
+
valStr = valStr.slice(1, -1).trim();
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const isDotted = valStr.includes('.');
|
|
657
|
+
let varName = 'value';
|
|
658
|
+
const varMatch = valStr.match(/(?:attributes|props)?\.?([a-zA-Z0-9_-]+)$/);
|
|
659
|
+
if (varMatch) {
|
|
660
|
+
varName = varMatch[1];
|
|
661
|
+
}
|
|
662
|
+
const isAttrKey =
|
|
663
|
+
blockSettings &&
|
|
664
|
+
blockSettings.attributes &&
|
|
665
|
+
Object.prototype.hasOwnProperty.call(blockSettings.attributes, varName);
|
|
666
|
+
const valueExpr = isDotted
|
|
667
|
+
? valStr
|
|
668
|
+
: isAttrKey
|
|
669
|
+
? `attributes.${varName}`
|
|
670
|
+
: valStr;
|
|
671
|
+
|
|
672
|
+
const className = attributes.className
|
|
673
|
+
? (attributes.className.startsWith('{')
|
|
674
|
+
? attributes.className.slice(1, -1)
|
|
675
|
+
: JSON.stringify(attributes.className))
|
|
676
|
+
: '""';
|
|
677
|
+
|
|
678
|
+
const isLoopRowAccess = isDotted && !/^(?:attributes|props)\./.test(valStr);
|
|
679
|
+
const attrConfig = (!isLoopRowAccess && blockSettings && blockSettings.attributes) ? blockSettings.attributes[varName] : null;
|
|
680
|
+
|
|
681
|
+
const isSingleLine =
|
|
682
|
+
(tagLiteral && ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'span'].includes(tagLiteral)) ||
|
|
683
|
+
(attrConfig && attrConfig.control === 'text') ||
|
|
684
|
+
attributes.disableLineBreaks !== undefined;
|
|
685
|
+
|
|
686
|
+
const singleLineProps = isSingleLine
|
|
687
|
+
? ',\n disableLineBreaks: true,\n allowedFormats: []'
|
|
688
|
+
: '';
|
|
689
|
+
|
|
690
|
+
const isMultiParagraph = attrConfig && attrConfig.control === 'richText' &&
|
|
691
|
+
typeof attrConfig.default === 'string' && /<p[\s>]/i.test(attrConfig.default);
|
|
692
|
+
const multilineProps = isMultiParagraph ? ",\n multiline: 'p'" : '';
|
|
693
|
+
|
|
694
|
+
let rawOnChange = String(attributes.onChange || '').trim();
|
|
695
|
+
if (rawOnChange.startsWith('{') && rawOnChange.endsWith('}')) {
|
|
696
|
+
rawOnChange = rawOnChange.slice(1, -1).trim();
|
|
697
|
+
}
|
|
698
|
+
rawOnChange = rawOnChange.replace(/\(\s*([a-zA-Z0-9_$]+)\s*:\s*[^),]+\)\s*=>/, '($1) =>');
|
|
699
|
+
|
|
700
|
+
const standardSet =
|
|
701
|
+
rawOnChange.match(
|
|
702
|
+
/^\(\s*([a-zA-Z0-9_$]+)\s*\)\s*=>\s*setAttributes\s*\(\s*\{\s*([a-zA-Z0-9_$]+)\s*:\s*\1\s*\}\s*\)\s*$/,
|
|
703
|
+
) ||
|
|
704
|
+
rawOnChange.match(
|
|
705
|
+
/^\(\s*([a-zA-Z0-9_$]+)\s*\)\s*=>\s*setAttributes\s*&&\s*setAttributes\s*\(\s*\{\s*([a-zA-Z0-9_$]+)\s*:\s*\1\s*\}\s*\)\s*$/,
|
|
706
|
+
);
|
|
707
|
+
|
|
708
|
+
let onChangeExpr;
|
|
709
|
+
if (standardSet) {
|
|
710
|
+
const p = standardSet[1];
|
|
711
|
+
const field = standardSet[2];
|
|
712
|
+
onChangeExpr = `(${p}) => setAttributes({ ${field}: ${p} })`;
|
|
713
|
+
} else if (
|
|
714
|
+
rawOnChange &&
|
|
715
|
+
!/setAttributes\s*\(\s*\{\s*attributes\./.test(rawOnChange) &&
|
|
716
|
+
!/setAttributes\s*\(\s*\{\s*props\./.test(rawOnChange)
|
|
717
|
+
) {
|
|
718
|
+
onChangeExpr = rawOnChange;
|
|
719
|
+
} else {
|
|
720
|
+
onChangeExpr = `function(val) { setAttributes({ ${varName}: val }); }`;
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
return `createElement(wp.blockEditor.RichText, {
|
|
724
|
+
tagName: ${tagExpr},
|
|
725
|
+
value: (function(){ var __v = (${valueExpr}); if (__v == null) return ''; return (typeof __v === 'string' ? __v : String(__v)); })(),
|
|
726
|
+
onChange: ${onChangeExpr},
|
|
727
|
+
className: ${className}${singleLineProps}${multilineProps}
|
|
728
|
+
})`;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
const props = {};
|
|
732
|
+
for (const [key, val] of Object.entries(attributes)) {
|
|
733
|
+
if (
|
|
734
|
+
motionTag &&
|
|
735
|
+
[
|
|
736
|
+
'animate',
|
|
737
|
+
'drag',
|
|
738
|
+
'dragConstraints',
|
|
739
|
+
'exit',
|
|
740
|
+
'initial',
|
|
741
|
+
'layout',
|
|
742
|
+
'layoutId',
|
|
743
|
+
'onAnimationComplete',
|
|
744
|
+
'onUpdate',
|
|
745
|
+
'transition',
|
|
746
|
+
'variants',
|
|
747
|
+
'viewport',
|
|
748
|
+
'whileDrag',
|
|
749
|
+
'whileFocus',
|
|
750
|
+
'whileHover',
|
|
751
|
+
'whileInView',
|
|
752
|
+
'whileTap',
|
|
753
|
+
].includes(key)
|
|
754
|
+
) {
|
|
755
|
+
continue;
|
|
756
|
+
}
|
|
757
|
+
const propKey = key === 'className' ? 'className' : key;
|
|
758
|
+
if (val === true || val === '') {
|
|
759
|
+
props[propKey] = 'true';
|
|
760
|
+
} else if (typeof val === 'string' && val.startsWith('{') && val.endsWith('}')) {
|
|
761
|
+
// No bare-attr-ref rewriting here — matches legacy: attribute-value
|
|
762
|
+
// expressions are rewritten upstream (index.js's own `={...}` pass)
|
|
763
|
+
// before this ever runs; only child-position expressions (ternary/`&&`
|
|
764
|
+
// conditions, .map() targets) get rewritten at this level, same as
|
|
765
|
+
// legacy's own phpCond regex only applied there.
|
|
766
|
+
props[propKey] = val.slice(1, -1).trim();
|
|
767
|
+
} else {
|
|
768
|
+
props[propKey] = JSON.stringify(val);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
const formatPropKey = (k) =>
|
|
773
|
+
/^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k);
|
|
774
|
+
|
|
775
|
+
const propsStr = Object.keys(props).length > 0
|
|
776
|
+
? `{ ${Object.entries(props).map(([k, v]) => `${formatPropKey(k)}: ${v}`).join(', ')} }`
|
|
777
|
+
: 'null';
|
|
778
|
+
|
|
779
|
+
const childCodesList = emitRealJsxChildren(node.children, code, blockSettings).filter(Boolean);
|
|
780
|
+
const childrenStr = childCodesList.join(', ');
|
|
781
|
+
|
|
782
|
+
const isPascalCase = /^[A-Z]/.test(hostTagName);
|
|
783
|
+
if (isPascalCase && blockSettings && blockSettings.importMap && blockSettings.importMap[tagName] && blockSettings.themeRoot) {
|
|
784
|
+
const packageName = blockSettings.importMap[tagName];
|
|
785
|
+
const rawClassName = attributes.className || '';
|
|
786
|
+
const classNameStr = rawClassName.startsWith('{') && rawClassName.endsWith('}')
|
|
787
|
+
? rawClassName.slice(1, -1).trim()
|
|
788
|
+
: rawClassName;
|
|
789
|
+
const resolved = resolveIconToCreateElement(tagName, packageName, blockSettings.themeRoot, classNameStr);
|
|
790
|
+
if (resolved) return resolved;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
const isHost = !isPascalCase || hostTagName.includes('-') || hostTagName === 'Fragment';
|
|
794
|
+
if (hostTagName === 'a') {
|
|
795
|
+
return emitEditorLink(props, childrenStr, blockSettings);
|
|
796
|
+
}
|
|
797
|
+
const typeExpr = isHost ? JSON.stringify(hostTagName) : hostTagName;
|
|
798
|
+
return `createElement(${typeExpr}, ${propsStr}${childrenStr ? `, ${childrenStr}` : ''})`;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/**
|
|
802
|
+
* Emit a canvas link through the editor runtime's ForgeWpEditorLink so it never
|
|
803
|
+
* navigates away from wp-admin. When `href` reads a block attribute
|
|
804
|
+
* (`attributes.buyUrl`, optionally with a `|| '#fallback'`), also wire inline
|
|
805
|
+
* URL editing for that attribute. Loop-row hrefs (`item.url`) only get the
|
|
806
|
+
* navigation guard; their URLs remain editable in the sidebar repeater.
|
|
807
|
+
*
|
|
808
|
+
* @param {Record<string, string>} props prop name → JS expression
|
|
809
|
+
* @param {string} childrenStr
|
|
810
|
+
* @param {object} blockSettings
|
|
811
|
+
*/
|
|
812
|
+
function emitEditorLink(props, childrenStr, blockSettings) {
|
|
813
|
+
const linkProps = { ...props };
|
|
814
|
+
const hrefExpr = typeof props.href === 'string' ? props.href.trim() : '';
|
|
815
|
+
const bound = hrefExpr.match(/^\(?\s*attributes\.([A-Za-z_$][\w$]*)\s*\)?(?:\s*(?:\|\||\?\?)\s*[\s\S]+)?$/);
|
|
816
|
+
const attrKey = bound ? bound[1] : null;
|
|
817
|
+
const attrConfig =
|
|
818
|
+
attrKey && blockSettings && blockSettings.attributes
|
|
819
|
+
? blockSettings.attributes[attrKey]
|
|
820
|
+
: null;
|
|
821
|
+
if (attrConfig && (!attrConfig.type || attrConfig.type === 'string')) {
|
|
822
|
+
linkProps.forgeWpUrl = `attributes.${attrKey}`;
|
|
823
|
+
linkProps.forgeWpOnUrlChange =
|
|
824
|
+
`(typeof setAttributes === 'function' ? function(value) { setAttributes({ ${attrKey}: value }); } : undefined)`;
|
|
825
|
+
linkProps.forgeWpUrlLabel = JSON.stringify(attrConfig.label || 'Link URL');
|
|
826
|
+
}
|
|
827
|
+
const formatPropKey = (k) =>
|
|
828
|
+
/^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k);
|
|
829
|
+
const propsStr = `{ ${Object.entries(linkProps).map(([k, v]) => `${formatPropKey(k)}: ${v}`).join(', ')} }`;
|
|
830
|
+
return `createElement(ForgeWpEditorLink, ${propsStr}${childrenStr ? `, ${childrenStr}` : ''})`;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
export function generateReactCreateElement(node, blockSettings) {
|
|
834
|
+
if (!node) return 'null';
|
|
835
|
+
|
|
836
|
+
if (node.realAst) {
|
|
837
|
+
return generateFromRealJsxNode(node.node, node.source, blockSettings);
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
return 'null';
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/**
|
|
844
|
+
* Peel a trailing JSX control-flow header from a text node that may also hold
|
|
845
|
+
* prior complete expressions, e.g.:
|
|
846
|
+
* {editText(a, 'a', 'c', 'h2')}{setAttributes ? (
|
|
847
|
+
*
|
|
848
|
+
* @param {string} cleanVal
|
|
849
|
+
* @param {'ternary'|'and'} kind
|
|
850
|
+
* @returns {{ before: string, cond: string } | null}
|
|
851
|
+
*/
|
|
852
|
+
function peelTrailingControlHeader(cleanVal, kind) {
|
|
853
|
+
if (!cleanVal || typeof cleanVal !== 'string') return null;
|
|
854
|
+
let m;
|
|
855
|
+
if (kind === 'ternary') {
|
|
856
|
+
// Prefer end-anchored ternary header; before may be empty or prior `{…}` exprs
|
|
857
|
+
m = cleanVal.match(/^(?<before>[\s\S]*?)\{(?<cond>[^{}?:]+)\s*\?\s*\(\s*$/);
|
|
858
|
+
} else if (kind === 'and') {
|
|
859
|
+
m = cleanVal.match(/^(?<before>[\s\S]*?)\{(?<cond>[^{}]+)\s*&&\s*\(\s*$/);
|
|
860
|
+
}
|
|
861
|
+
if (!m || !m.groups) return null;
|
|
862
|
+
const cond = (m.groups.cond || '').trim();
|
|
863
|
+
if (!cond) return null;
|
|
864
|
+
// Avoid false positives: before must be empty or end with a complete `}`
|
|
865
|
+
const beforeTrimmed = (m.groups.before || '').trim();
|
|
866
|
+
if (beforeTrimmed && !beforeTrimmed.endsWith('}')) {
|
|
867
|
+
return null;
|
|
868
|
+
}
|
|
869
|
+
return { before: beforeTrimmed, cond };
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* Convert JSX still present in the editor IIFE preamble (helpers defined before
|
|
874
|
+
* `return`, e.g. `const cell = (… ) => (<div>…</div>)`) into createElement calls.
|
|
875
|
+
*
|
|
876
|
+
* Handles:
|
|
877
|
+
* - arrow paren bodies: `=> (<div/>)`
|
|
878
|
+
* - expression bodies with ternaries: `=> cond ? <A/> : <B/>`
|
|
879
|
+
* - residual JSX tags anywhere in the preamble after the arrow pass
|
|
880
|
+
*
|
|
881
|
+
* @param {string} preamble
|
|
882
|
+
* @param {object} blockSettings
|
|
883
|
+
* @returns {string}
|
|
884
|
+
*/
|
|
885
|
+
export function transpileJsxInPreamble(preamble, blockSettings) {
|
|
886
|
+
if (!preamble || typeof preamble !== 'string') return preamble;
|
|
887
|
+
if (!/<[A-Za-z/$]/.test(preamble) && !/<>/.test(preamble)) return preamble;
|
|
888
|
+
|
|
889
|
+
let result = '';
|
|
890
|
+
let i = 0;
|
|
891
|
+
while (i < preamble.length) {
|
|
892
|
+
const arrow = preamble.indexOf('=>', i);
|
|
893
|
+
if (arrow === -1) {
|
|
894
|
+
result += preamble.slice(i);
|
|
895
|
+
break;
|
|
896
|
+
}
|
|
897
|
+
result += preamble.slice(i, arrow + 2);
|
|
898
|
+
let j = arrow + 2;
|
|
899
|
+
while (j < preamble.length && /\s/.test(preamble[j])) j++;
|
|
900
|
+
|
|
901
|
+
if (preamble[j] !== '(') {
|
|
902
|
+
// Expression body (ternary, bare JSX, etc.) — leave for residual pass
|
|
903
|
+
i = arrow + 2;
|
|
904
|
+
continue;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
const close = findMatchingParen(preamble, j);
|
|
908
|
+
if (close === -1) {
|
|
909
|
+
i = arrow + 2;
|
|
910
|
+
continue;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
const inner = preamble.slice(j + 1, close).trim();
|
|
914
|
+
if (inner.startsWith('<') || inner.startsWith('<>')) {
|
|
915
|
+
// `inner` may be adjacent root elements with no wrapping fragment (real
|
|
916
|
+
// JSX syntax forbids that at the top level) — retry wrapped in a
|
|
917
|
+
// synthetic fragment before giving up on this arrow body.
|
|
918
|
+
const ast = parseJsxToAst(inner) || parseJsxToAst(`<>${inner}</>`);
|
|
919
|
+
if (ast) {
|
|
920
|
+
try {
|
|
921
|
+
const ce = generateReactCreateElement(ast, blockSettings);
|
|
922
|
+
if (ce && ce !== 'null') {
|
|
923
|
+
result += ` (${ce})`;
|
|
924
|
+
i = close + 1;
|
|
925
|
+
continue;
|
|
926
|
+
}
|
|
927
|
+
} catch {
|
|
928
|
+
// fall through — leave this fragment untranspiled rather than mangling it
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
// Paren group may still contain nested JSX in ternaries: (cond ? <A/> : <B/>)
|
|
934
|
+
const group = preamble.slice(j, close + 1);
|
|
935
|
+
if (/<[A-Za-z/$]/.test(group) || /<>/.test(group)) {
|
|
936
|
+
result += replaceJsxTagsWithCreateElement(group, blockSettings);
|
|
937
|
+
} else {
|
|
938
|
+
result += group;
|
|
939
|
+
}
|
|
940
|
+
i = close + 1;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
// Residual JSX outside paren-arrow forms (expression bodies, multi-line ternaries)
|
|
944
|
+
if (/<[A-Za-z/$]/.test(result) || /<>/.test(result)) {
|
|
945
|
+
result = replaceJsxTagsWithCreateElement(result, blockSettings);
|
|
946
|
+
}
|
|
947
|
+
return result;
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
/**
|
|
951
|
+
* Replace top-level JSX elements in a JS snippet with createElement(…) calls.
|
|
952
|
+
* Skips string/template contents and TypeScript-like generics (`Foo<Bar>`).
|
|
953
|
+
*/
|
|
954
|
+
function replaceJsxTagsWithCreateElement(code, blockSettings) {
|
|
955
|
+
let out = '';
|
|
956
|
+
let i = 0;
|
|
957
|
+
let inSingle = false;
|
|
958
|
+
let inDouble = false;
|
|
959
|
+
let inBacktick = false;
|
|
960
|
+
|
|
961
|
+
while (i < code.length) {
|
|
962
|
+
const c = code[i];
|
|
963
|
+
|
|
964
|
+
if (inSingle) {
|
|
965
|
+
out += c;
|
|
966
|
+
if (c === '\\') {
|
|
967
|
+
out += code[i + 1] || '';
|
|
968
|
+
i += 2;
|
|
969
|
+
continue;
|
|
970
|
+
}
|
|
971
|
+
if (c === "'") inSingle = false;
|
|
972
|
+
i++;
|
|
973
|
+
continue;
|
|
974
|
+
}
|
|
975
|
+
if (inDouble) {
|
|
976
|
+
out += c;
|
|
977
|
+
if (c === '\\') {
|
|
978
|
+
out += code[i + 1] || '';
|
|
979
|
+
i += 2;
|
|
980
|
+
continue;
|
|
981
|
+
}
|
|
982
|
+
if (c === '"') inDouble = false;
|
|
983
|
+
i++;
|
|
984
|
+
continue;
|
|
985
|
+
}
|
|
986
|
+
if (inBacktick) {
|
|
987
|
+
out += c;
|
|
988
|
+
if (c === '\\') {
|
|
989
|
+
out += code[i + 1] || '';
|
|
990
|
+
i += 2;
|
|
991
|
+
continue;
|
|
992
|
+
}
|
|
993
|
+
if (c === '`') inBacktick = false;
|
|
994
|
+
i++;
|
|
995
|
+
continue;
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
if (c === "'") {
|
|
999
|
+
inSingle = true;
|
|
1000
|
+
out += c;
|
|
1001
|
+
i++;
|
|
1002
|
+
continue;
|
|
1003
|
+
}
|
|
1004
|
+
if (c === '"') {
|
|
1005
|
+
inDouble = true;
|
|
1006
|
+
out += c;
|
|
1007
|
+
i++;
|
|
1008
|
+
continue;
|
|
1009
|
+
}
|
|
1010
|
+
if (c === '`') {
|
|
1011
|
+
inBacktick = true;
|
|
1012
|
+
out += c;
|
|
1013
|
+
i++;
|
|
1014
|
+
continue;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
// Potential JSX open
|
|
1018
|
+
if (c === '<' && i + 1 < code.length) {
|
|
1019
|
+
const next = code[i + 1];
|
|
1020
|
+
if (/[A-Za-z$]/.test(next) || next === '>') {
|
|
1021
|
+
// Skip TypeScript generics: Foo<Bar> — but NOT statement JSX like
|
|
1022
|
+
// `return <Icon />` / `throw <Err />` where the prev word is a keyword.
|
|
1023
|
+
let k = i - 1;
|
|
1024
|
+
while (k >= 0 && /\s/.test(code[k])) k--;
|
|
1025
|
+
if (k >= 0 && /[A-Za-z0-9_$]/.test(code[k])) {
|
|
1026
|
+
let start = k;
|
|
1027
|
+
while (start >= 0 && /[A-Za-z0-9_$]/.test(code[start])) start--;
|
|
1028
|
+
const prevWord = code.slice(start + 1, k + 1);
|
|
1029
|
+
const jsxAfterKeywords = new Set([
|
|
1030
|
+
'return',
|
|
1031
|
+
'throw',
|
|
1032
|
+
'yield',
|
|
1033
|
+
'case',
|
|
1034
|
+
'else',
|
|
1035
|
+
'default',
|
|
1036
|
+
'typeof',
|
|
1037
|
+
'delete',
|
|
1038
|
+
'void',
|
|
1039
|
+
'await',
|
|
1040
|
+
'new',
|
|
1041
|
+
'void',
|
|
1042
|
+
]);
|
|
1043
|
+
if (!jsxAfterKeywords.has(prevWord)) {
|
|
1044
|
+
out += c;
|
|
1045
|
+
i++;
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
const jsx = extractBalancedJsx(code, i);
|
|
1051
|
+
if (jsx) {
|
|
1052
|
+
const ast = parseJsxToAst(jsx) || parseJsxToAst(`<>${jsx}</>`);
|
|
1053
|
+
if (ast) {
|
|
1054
|
+
try {
|
|
1055
|
+
const ce = generateReactCreateElement(ast, blockSettings);
|
|
1056
|
+
if (ce && ce !== 'null') {
|
|
1057
|
+
out += ce;
|
|
1058
|
+
i += jsx.length;
|
|
1059
|
+
continue;
|
|
1060
|
+
}
|
|
1061
|
+
} catch {
|
|
1062
|
+
// fall through — leave this fragment untranspiled rather than mangling it
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
out += c;
|
|
1070
|
+
i++;
|
|
1071
|
+
}
|
|
1072
|
+
return out;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
/**
|
|
1076
|
+
* From an opening `<` at startIdx, extract a full JSX element/fragment string.
|
|
1077
|
+
*/
|
|
1078
|
+
function extractBalancedJsx(code, startIdx) {
|
|
1079
|
+
if (code[startIdx] !== '<') return null;
|
|
1080
|
+
|
|
1081
|
+
// Fragment <>…</>
|
|
1082
|
+
if (code.startsWith('<>', startIdx)) {
|
|
1083
|
+
const close = code.indexOf('</>', startIdx + 2);
|
|
1084
|
+
if (close === -1) return null;
|
|
1085
|
+
return code.slice(startIdx, close + 3);
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
const tagEnd = findHtmlTagEnd(code, startIdx);
|
|
1089
|
+
if (tagEnd === -1) return null;
|
|
1090
|
+
const openTag = code.slice(startIdx, tagEnd + 1);
|
|
1091
|
+
if (openTag.endsWith('/>')) {
|
|
1092
|
+
return openTag;
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
// Extract tag name
|
|
1096
|
+
const nameMatch = openTag.match(/^<\/?\s*([A-Za-z][\w.-]*)/);
|
|
1097
|
+
if (!nameMatch) return null;
|
|
1098
|
+
const tagName = nameMatch[1];
|
|
1099
|
+
const closeTag = `</${tagName}>`;
|
|
1100
|
+
|
|
1101
|
+
let depth = 1;
|
|
1102
|
+
let i = tagEnd + 1;
|
|
1103
|
+
while (i < code.length && depth > 0) {
|
|
1104
|
+
// Skip strings inside JSX text? Rare. Skip {…} expressions carefully.
|
|
1105
|
+
if (code[i] === '{') {
|
|
1106
|
+
const closeBrace = findMatchingBrace(code, i);
|
|
1107
|
+
if (closeBrace === -1) return null;
|
|
1108
|
+
i = closeBrace + 1;
|
|
1109
|
+
continue;
|
|
1110
|
+
}
|
|
1111
|
+
if (code[i] === '<') {
|
|
1112
|
+
if (code.startsWith(closeTag, i)) {
|
|
1113
|
+
depth--;
|
|
1114
|
+
if (depth === 0) {
|
|
1115
|
+
return code.slice(startIdx, i + closeTag.length);
|
|
1116
|
+
}
|
|
1117
|
+
i += closeTag.length;
|
|
1118
|
+
continue;
|
|
1119
|
+
}
|
|
1120
|
+
if (code.startsWith(`<${tagName}`, i) || code.match(new RegExp(`^<${tagName}[\\s/>]`, 'i'))) {
|
|
1121
|
+
// nested same tag
|
|
1122
|
+
const nestedEnd = findHtmlTagEnd(code, i);
|
|
1123
|
+
if (nestedEnd === -1) return null;
|
|
1124
|
+
const nested = code.slice(i, nestedEnd + 1);
|
|
1125
|
+
if (!nested.endsWith('/>')) depth++;
|
|
1126
|
+
i = nestedEnd + 1;
|
|
1127
|
+
continue;
|
|
1128
|
+
}
|
|
1129
|
+
// Other nested element
|
|
1130
|
+
if (/^<[A-Za-z$]/.test(code.slice(i))) {
|
|
1131
|
+
const nested = extractBalancedJsx(code, i);
|
|
1132
|
+
if (!nested) {
|
|
1133
|
+
i++;
|
|
1134
|
+
continue;
|
|
1135
|
+
}
|
|
1136
|
+
i += nested.length;
|
|
1137
|
+
continue;
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
i++;
|
|
1141
|
+
}
|
|
1142
|
+
return null;
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
function findMatchingBrace(code, openIdx) {
|
|
1146
|
+
let depth = 0;
|
|
1147
|
+
let inS = false;
|
|
1148
|
+
let inD = false;
|
|
1149
|
+
let inB = false;
|
|
1150
|
+
for (let i = openIdx; i < code.length; i++) {
|
|
1151
|
+
const c = code[i];
|
|
1152
|
+
if (inS) {
|
|
1153
|
+
if (c === '\\') {
|
|
1154
|
+
i++;
|
|
1155
|
+
continue;
|
|
1156
|
+
}
|
|
1157
|
+
if (c === "'") inS = false;
|
|
1158
|
+
continue;
|
|
1159
|
+
}
|
|
1160
|
+
if (inD) {
|
|
1161
|
+
if (c === '\\') {
|
|
1162
|
+
i++;
|
|
1163
|
+
continue;
|
|
1164
|
+
}
|
|
1165
|
+
if (c === '"') inD = false;
|
|
1166
|
+
continue;
|
|
1167
|
+
}
|
|
1168
|
+
if (inB) {
|
|
1169
|
+
if (c === '\\') {
|
|
1170
|
+
i++;
|
|
1171
|
+
continue;
|
|
1172
|
+
}
|
|
1173
|
+
if (c === '`') inB = false;
|
|
1174
|
+
continue;
|
|
1175
|
+
}
|
|
1176
|
+
if (c === "'") inS = true;
|
|
1177
|
+
else if (c === '"') inD = true;
|
|
1178
|
+
else if (c === '`') inB = true;
|
|
1179
|
+
else if (c === '{') depth++;
|
|
1180
|
+
else if (c === '}') {
|
|
1181
|
+
depth--;
|
|
1182
|
+
if (depth === 0) return i;
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
return -1;
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
function findMatchingParen(code, openIdx) {
|
|
1189
|
+
let depth = 0;
|
|
1190
|
+
let inSingle = false;
|
|
1191
|
+
let inDouble = false;
|
|
1192
|
+
let inBacktick = false;
|
|
1193
|
+
for (let i = openIdx; i < code.length; i++) {
|
|
1194
|
+
const c = code[i];
|
|
1195
|
+
if (inSingle) {
|
|
1196
|
+
if (c === '\\') {
|
|
1197
|
+
i++;
|
|
1198
|
+
continue;
|
|
1199
|
+
}
|
|
1200
|
+
if (c === "'") inSingle = false;
|
|
1201
|
+
continue;
|
|
1202
|
+
}
|
|
1203
|
+
if (inDouble) {
|
|
1204
|
+
if (c === '\\') {
|
|
1205
|
+
i++;
|
|
1206
|
+
continue;
|
|
1207
|
+
}
|
|
1208
|
+
if (c === '"') inDouble = false;
|
|
1209
|
+
continue;
|
|
1210
|
+
}
|
|
1211
|
+
if (inBacktick) {
|
|
1212
|
+
if (c === '\\') {
|
|
1213
|
+
i++;
|
|
1214
|
+
continue;
|
|
1215
|
+
}
|
|
1216
|
+
if (c === '`') inBacktick = false;
|
|
1217
|
+
continue;
|
|
1218
|
+
}
|
|
1219
|
+
if (c === "'") inSingle = true;
|
|
1220
|
+
else if (c === '"') inDouble = true;
|
|
1221
|
+
else if (c === '`') inBacktick = true;
|
|
1222
|
+
else if (c === '(') depth++;
|
|
1223
|
+
else if (c === ')') {
|
|
1224
|
+
depth--;
|
|
1225
|
+
if (depth === 0) return i;
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
return -1;
|
|
1229
|
+
}
|