fix(astro): keep tag expressions with quoted strings as one attribute (#7331)

Quoted strings inside an Astro tag expression split the expression into several attributes. The tokenizer now skips string literals inside braces.

Closes #7330

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-12-02 11:20:30 +08:00
1 джерело 8e56d3b73e
коміт 7361707b63
2 files changed
+297 -10

No files matched your search

+140 -2
Переглянути файл
@@ -7,7 +7,8 @@ import { buildParserFile } from "@lezer/generator";
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
import { findLanguageDescription, loadSupport } from "../languages";
import { pasteReindentFilter } from "../prefs";
import { astro, astroLanguage } from "./index";
import { TreeFragment, type Tree } from "@lezer/common";
import { astro, astroLanguage, maskTagExpressions } from "./index";
const highlighter = tagHighlighter([
{ tag: t.processingInstruction, class: "fence" },
@@ -36,6 +37,32 @@ function tokens(doc: string): string[] {
return out;
}
/** The text of each HTML attribute in `tree` of `doc`, expressions' trees left out. */
function attributesOf(tree: Tree, doc: string): string[] {
const out: string[] = [];
tree.iterate({
enter: (n) => {
if (n.name === "Attribute") out.push(doc.slice(n.from, n.to));
return n.name !== "Script";
},
});
return out;
}
const attributes = (doc: string) => attributesOf(astroLanguage.parser.parse(doc), doc);
/** Whether HTML marked anything in `doc` as an error. */
function htmlErrors(doc: string): boolean {
let found = false;
astroLanguage.parser.parse(doc).iterate({
enter: (n) => {
if (n.type.isError) found = true;
return n.name !== "Script";
},
});
return found;
}
/** A layout with what made HTML mode misread Astro components. */
const LAYOUT = `---
import '@/styles/global.css'
@@ -126,6 +153,114 @@ describe("Astro components", () => {
expect(out).toContain('"{literal}":value');
});
// Each case: the component, its HTML attributes, and tokens it must have.
const TAG_EXPRESSIONS: [string, string, string[], string[]][] = [
[
"the issue's multi-line class:list",
'<div\n class:list={[\n "relative flex w-full flex-col",\n card.textClass,\n ]}\n>\n <b>x</b>\n</div>',
['class:list={[\n "relative flex w-full flex-col",\n card.textClass,\n ]}'],
['"relative flex w-full flex-col":str', "card:var", "textClass:prop", "b:tag"],
],
[
"class:list and set:html in one tag",
'<h3 class:list={["font-bold", card.titleClass]} set:html={card.title} />\n<p>{card.lead}</p>',
['class:list={["font-bold", card.titleClass]}', "set:html={card.title}"],
['"font-bold":str', "titleClass:prop", "title:prop", "p:tag", "lead:prop"],
],
[
"a call with a quoted string",
'<a href={f("x y")} title="t">z</a>',
['href={f("x y")}', 'title="t"'],
["f:call", '"x y":str', '"t":value'],
],
[
"a spread and a shorthand",
"<C {...props} {name} client:load />",
["{...props}", "{name}", "client:load"],
["props:var", "name:var", "client:load:attr"],
],
[
"nested braces and brackets",
'<C a={{ b: [1, { c: "d e" }] }} f="g" />',
['a={{ b: [1, { c: "d e" }] }}', 'f="g"'],
['"d e":str', '"g":value'],
],
["a brace in a string", '<C a={"} >"} b={x} />', ['a={"} >"}', "b={x}"], ['"} >":str', "x:var"]],
[
"a brace in a template literal",
"<C a={`} ${b + '}'} >`} c={d} />",
["a={`} ${b + '}'} >`}", "c={d}"],
["b:var", "'}':str", "d:var"],
],
["an escaped quote", '<C a={"x \\" }"} b={y} />', ['a={"x \\" }"}', "b={y}"], ["y:var"]],
[
"a comment with a quote",
"<C a={/* it's } */ x} b={y} />",
["a={/* it's } */ x}", "b={y}"],
["/* it's } */:comment", "x:var", "y:var"],
],
[
"an arrow function with markup",
"<C render={(i) => <li class={i}>{i > 1}</li>} />\n<p>ok</p>",
["render={(i) => <li class={i}>{i > 1}</li>}"],
["li:tag", "class:attr", ">:op", "p:tag"],
],
[
"an expression among quoted attributes",
'<img src="a b.png" alt={t("img alt")} loading=\'lazy\' />',
['src="a b.png"', 'alt={t("img alt")}', "loading='lazy'"],
['"a b.png":value', '"img alt":str', "'lazy':value"],
],
[
"a tag expression in a text expression",
'{ok && <b class:list={["x y", c]}>{n}</b>}',
['class:list={["x y", c]}'],
["ok:var", '"x y":str', "c:var", "n:var"],
],
["braces in a comment", '<!-- <a b={"x y"}> -->\n<p>t</p>', [], ["p:tag"]],
];
it.each(TAG_EXPRESSIONS)("parses tag expressions: %s", (_, doc, attrs, toks) => {
expect(attributes(doc)).toEqual(attrs);
expect(tokens(doc)).toEqual(expect.arrayContaining(toks));
expect(htmlErrors(doc)).toBe(false);
});
it("leaves an unclosed tag expression to HTML, so the markup after it stays markup", () => {
const doc = '<div a={\n<p class="x">{t}</p>\n<b c={"y z"}>w</b>';
expect(attributes(doc)).toEqual(["a={", 'class="x"', 'c={"y z"}']);
expect(tokens(doc)).toEqual(expect.arrayContaining(["p:tag", "t:var", '"y z":str', "b:tag"]));
});
it("leaves script, style and attribute text unmasked", () => {
const doc = '<script>\n const s = "<a b={c d}>"\n</script>\n<style>a{b:c}</style>\n<p title="{x y}">';
expect(maskTagExpressions(doc)).toBe(doc);
expect(maskTagExpressions('<a b={c "d"}>')).toBe("<a b={c__d_}>");
});
it("reparses an edited tag expression like a fresh parse", () => {
const before = '<h3 class:list={["a", c]} />\n<p>{x}</p>\n<b>y</b>';
const parse = (doc: string) => astroLanguage.parser.parse(doc);
let tree = parse(before);
let doc = before;
// Type `{"m n"` then `}` after `<p `, then delete them again.
for (const [from, to, insert] of [
[before.indexOf("<p") + 2, before.indexOf("<p") + 2, ' a={"m n"'],
[before.indexOf("<p") + 11, before.indexOf("<p") + 11, "}"],
[before.indexOf("<p") + 2, before.indexOf("<p") + 12, ""],
] as const) {
const next = doc.slice(0, from) + insert + doc.slice(to);
const fragments = TreeFragment.applyChanges(TreeFragment.addTree(tree), [
{ fromA: from, toA: to, fromB: from, toB: from + insert.length },
]);
tree = astroLanguage.parser.parse(next, fragments);
doc = next;
expect(attributesOf(tree, doc)).toEqual(attributes(doc));
expect(tree.toString()).toBe(parse(doc).toString());
}
expect(doc).toBe(before);
});
it("parses scripts as TypeScript and leaves styles to CSS", () => {
const out = tokens("<script>\n const n: number = 1\n</script>\n<style>\n p { color: red; }\n</style>");
expect(out).toEqual(expect.arrayContaining(["const:def-kw", "number:type", "script:tag", "style:tag"]));
@@ -139,7 +274,10 @@ describe("Astro components", () => {
const state = EditorState.create({
extensions: [astro(), indentUnit.of(" "), EditorState.tabSize.of(2), pasteReindentFilter("indentEachLine")],
});
const pasted = state.update({ changes: { from: 0, insert: LAYOUT }, userEvent: "input.paste" }).state;
const pasted = state.update({
changes: { from: 0, insert: LAYOUT },
userEvent: "input.paste",
}).state;
expect(pasted.doc.toString()).toBe(LAYOUT);
} finally {
vi.useRealTimers();
+157 -8
Переглянути файл
@@ -7,7 +7,16 @@ import { LRLanguage, LanguageSupport } from "@codemirror/language";
import { html } from "@codemirror/lang-html";
import { tsxLanguage, typescriptLanguage } from "@codemirror/lang-javascript";
import { styleTags, tags as t } from "@lezer/highlight";
import { IterMode, parseMixed, type Input, type NestedParse, type SyntaxNodeRef } from "@lezer/common";
import {
IterMode,
Parser,
parseMixed,
type Input,
type NestedParse,
type PartialParse,
type SyntaxNodeRef,
type TreeFragment,
} from "@lezer/common";
import { JS_TAGS } from "../jsTags";
import { parser } from "./parser";
@@ -46,17 +55,16 @@ function pushRange(out: Range[], from: number, to: number) {
/**
* Appends to `out` the parts of `text`, which starts at `from`, inside `{…}`,
* braces included. Strings count only inside braces, so prose apostrophes
* stay text; in a tag (`attrQuotes`), quotes outside braces delimit attribute
* values, whose braces are literal.
* stay text.
*/
function scanBraces(text: string, from: number, scan: Scan, out: Range[], attrQuotes = false) {
function scanBraces(text: string, from: number, scan: Scan, out: Range[]) {
let start = scan.depth > 0 ? 0 : -1;
for (let i = 0; i < text.length; i++) {
const ch = text.charCodeAt(i);
if (scan.quote) {
if (ch === BACKSLASH && scan.depth > 0) i++;
else if (ch === scan.quote) scan.quote = 0;
} else if (QUOTES.has(ch) && (scan.depth > 0 || attrQuotes)) {
} else if (QUOTES.has(ch) && scan.depth > 0) {
scan.quote = ch;
} else if (ch === BRACE_L) {
if (scan.depth++ === 0) start = i;
@@ -95,10 +103,74 @@ function textExpressions(node: SyntaxNodeRef, input: Input): Range[] | null {
return out.length ? out : null;
}
/** The expressions in a tag: values, shorthands and spreads, also with spaces, which split HTML attributes. */
const SLASH = 47,
STAR = 42,
DOLLAR = 36,
BACKTICK = 96,
NEWLINE = 10;
/** What ends an HTML attribute name or unquoted value. */
const ATTR_BREAK = /[\s"'<>`=/]/g;
const TAG_NAME = /\/?([a-zA-Z][^\s/>]*)/y;
const RAW_TEXT = new Set(["script", "style", "textarea"]);
/**
* The end of the expression whose `{` is at `start`, past its `}`, or -1
* when it isn't closed. Strings and comments may hold braces; quoted strings
* end with their line, so an unclosed one doesn't run on.
*/
function expressionEnd(s: string, start: number): number {
// Open braces, and the template literals that `${` nests in.
const open: number[] = [];
for (let i = start; i < s.length; i++) {
const ch = s.charCodeAt(i);
if (open[open.length - 1] === BACKTICK) {
if (ch === BACKSLASH) i++;
else if (ch === BACKTICK) open.pop();
else if (ch === DOLLAR && s.charCodeAt(i + 1) === BRACE_L) {
open.push(BRACE_L);
i++;
}
} else if (ch === BRACE_L || ch === BACKTICK) {
open.push(ch);
} else if (ch === BRACE_R) {
open.pop();
if (!open.length) return i + 1;
} else if (ch === 34 || ch === 39) {
for (i++; i < s.length && s.charCodeAt(i) !== ch && s.charCodeAt(i) !== NEWLINE; i++) {
if (s.charCodeAt(i) === BACKSLASH) i++;
}
} else if (ch === SLASH && s.charCodeAt(i + 1) === SLASH) {
i = s.indexOf("\n", i);
if (i < 0) return -1;
} else if (ch === SLASH && s.charCodeAt(i + 1) === STAR) {
i = s.indexOf("*/", i + 2) + 1;
if (i <= 0) return -1;
}
}
return -1;
}
/**
* The expressions in a tag: values, shorthands and spreads. Quotes outside
* braces delimit attribute values, whose braces are literal; an unclosed
* expression runs to the end of the tag.
*/
function tagExpressions(node: SyntaxNodeRef, input: Input): Range[] | null {
const out: Range[] = [];
scanBraces(input.read(node.from, node.to), node.from, { depth: 0, quote: 0 }, out, true);
const text = input.read(node.from, node.to);
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (ch === '"' || ch === "'") {
i = text.indexOf(ch, i + 1);
if (i < 0) break;
} else if (ch === "{") {
const end = expressionEnd(text, i);
out.push({ from: node.from + i, to: node.from + (end < 0 ? text.length : end) });
if (end < 0) break;
i = end - 1;
}
}
return out.length ? out : null;
}
@@ -116,7 +188,84 @@ function mixExpressions(node: SyntaxNodeRef, input: Input): NestedParse | null {
return null;
}
const templateParser = (templateHTML.language as LRLanguage).parser.configure({ wrap: parseMixed(mixExpressions) });
/**
* `text` with each `{…}` in a tag made one HTML attribute name or value: the
* characters that would end one become `_`, keeping offsets. HTML would end
* `class:list={["a b"]}` at the quote and read the rest of the tag as text.
* An unclosed `{` is left alone, so typing one doesn't swallow the file.
*/
export function maskTagExpressions(text: string): string {
let out = "",
copied = 0;
for (let i = text.indexOf("<"); i >= 0; i = text.indexOf("<", i)) {
i++;
if (text.startsWith("!--", i)) {
i = text.indexOf("-->", i + 3);
if (i < 0) break;
continue;
}
TAG_NAME.lastIndex = i;
const name = TAG_NAME.exec(text);
if (!name) continue;
for (i = TAG_NAME.lastIndex; i < text.length; i++) {
const ch = text[i];
if (ch === ">" || ch === "<") break;
if (ch === '"' || ch === "'") {
i = text.indexOf(ch, i + 1);
if (i < 0) i = text.length;
} else if (ch === "{") {
const end = expressionEnd(text, i);
if (end < 0) continue;
out += text.slice(copied, i) + text.slice(i, end).replace(ATTR_BREAK, "_");
copied = end;
i = end - 1;
}
}
// Script, style and textarea text holds no tags; `<script />` holds none at all.
const tag = name[1]!.toLowerCase();
if (text[i] === ">" && text[i - 1] !== "/" && !name[0].startsWith("/") && RAW_TEXT.has(tag)) {
const close = text.toLowerCase().indexOf("</" + tag, i);
if (close < 0) break;
i = close;
}
}
return copied ? out + text.slice(copied) : text;
}
/** `base` with `text`, its masked template from `from`, in place of the template. */
function maskedInput(base: Input, from: number, text: string): Input {
const to = from + text.length;
return {
length: base.length,
lineChunks: false,
chunk: (pos) => (pos >= from && pos < to ? text.slice(pos - from) : base.chunk(pos)),
read: (a, b) => (a >= from && b <= to ? text.slice(a - from, b - from) : base.read(a, b)),
};
}
const htmlParser = (templateHTML.language as LRLanguage).parser;
const mixer = parseMixed(mixExpressions);
/**
* HTML reads the masked template, so expressions in tags are whole attributes,
* and the expressions mounted on its tree read the real text.
*/
class TemplateParser extends Parser {
createParse(
input: Input,
fragments: readonly TreeFragment[],
ranges: readonly { from: number; to: number }[],
): PartialParse {
// Masks the whole template on each parse, which is linear in its length.
const from = ranges[0]!.from,
text = input.read(from, ranges[ranges.length - 1]!.to),
masked = maskTagExpressions(text);
const htmlInput = masked === text ? input : maskedInput(input, from, masked);
return mixer(htmlParser.startParse(htmlInput, fragments, ranges), input, fragments, ranges);
}
}
const templateParser = new TemplateParser();
const componentParser = parser.configure({
props: [styleTags({ FrontmatterFence: t.processingInstruction })],