[FIX] compiler: add support for #{...} in string interpolation

This commit is contained in:
Géry Debongnie
2022-06-07 17:25:23 +02:00
committed by Sam Degueldre
parent a3111eb9ca
commit 385e118e58
7 changed files with 68 additions and 14 deletions
+9 -6
View File
@@ -1,4 +1,10 @@
import { compileExpr, compileExprToArray, interpolate, INTERP_REGEXP } from "./inline_expressions";
import {
compileExpr,
compileExprToArray,
interpolate,
INTERP_REGEXP,
replaceDynamicParts,
} from "./inline_expressions";
import {
AST,
ASTComment,
@@ -606,11 +612,8 @@ export class CodeGenerator {
this.target.hasRef = true;
const isDynamic = INTERP_REGEXP.test(ast.ref);
if (isDynamic) {
const str = ast.ref.replace(
INTERP_REGEXP,
(expr) => "${" + this.captureExpression(expr.slice(2, -2), true) + "}"
);
const idx = block!.insertData(`(el) => refs[\`${str}\`] = el`, "ref");
const str = replaceDynamicParts(ast.ref, (expr) => this.captureExpression(expr, true));
const idx = block!.insertData(`(el) => refs[${str}] = el`, "ref");
attrs["block-ref"] = String(idx);
} else {
let name = ast.ref;
+10 -5
View File
@@ -355,15 +355,20 @@ export function compileExpr(expr: string): string {
.join("");
}
export const INTERP_REGEXP = /\{\{.*?\}\}/g;
const INTERP_GROUP_REGEXP = /\{\{.*?\}\}/g;
export const INTERP_REGEXP = /\{\{.*?\}\}|\#\{.*?\}/g;
export function interpolate(s: string): string {
export function replaceDynamicParts(s: string, replacer: (s: string) => string) {
let matches = s.match(INTERP_REGEXP);
if (matches && matches[0].length === s.length) {
return `(${compileExpr(s.slice(2, -2))})`;
return `(${replacer(s.slice(2, matches[0][0] === "{" ? -2 : -1))})`;
}
let r = s.replace(INTERP_GROUP_REGEXP, (s) => "${" + compileExpr(s.slice(2, -2)) + "}");
let r = s.replace(
INTERP_REGEXP,
(s) => "${" + replacer(s.slice(2, s[0] === "{" ? -2 : -1)) + "}"
);
return "`" + r + "`";
}
export function interpolate(s: string): string {
return replaceDynamicParts(s, compileExpr);
}