From 7361707b63d7ce77ccaafa36a271a45239d7620a Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Wed, 2 Dec 2026 12:20:30 +0900 Subject: [PATCH] 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 <26499420+wildcatDownstairs@users.noreply.github.com> --- src/editor/core/cm/astro/astro.test.ts | 142 ++++++++++++++++++++- src/editor/core/cm/astro/index.ts | 165 +++++++++++++++++++++++-- 2 files changed, 297 insertions(+), 10 deletions(-) diff --git a/src/editor/core/cm/astro/astro.test.ts b/src/editor/core/cm/astro/astro.test.ts index 11f0dca0b8..64e2a5079b 100644 --- a/src/editor/core/cm/astro/astro.test.ts +++ b/src/editor/core/cm/astro/astro.test.ts @@ -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", + '\n x\n', + ['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", + '

\n

{card.lead}

', + ['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", + 'z', + ['href={f("x y")}', 'title="t"'], + ["f:call", '"x y":str', '"t":value'], + ], + [ + "a spread and a shorthand", + "", + ["{...props}", "{name}", "client:load"], + ["props:var", "name:var", "client:load:attr"], + ], + [ + "nested braces and brackets", + '', + ['a={{ b: [1, { c: "d e" }] }}', 'f="g"'], + ['"d e":str', '"g":value'], + ], + ["a brace in a string", '"} b={x} />', ['a={"} >"}', "b={x}"], ['"} >":str', "x:var"]], + [ + "a brace in a template literal", + "`} c={d} />", + ["a={`} ${b + '}'} >`}", "c={d}"], + ["b:var", "'}':str", "d:var"], + ], + ["an escaped quote", '', ['a={"x \\" }"}', "b={y}"], ["y:var"]], + [ + "a comment with a quote", + "", + ["a={/* it's } */ x}", "b={y}"], + ["/* it's } */:comment", "x:var", "y:var"], + ], + [ + "an arrow function with markup", + "
  • {i > 1}
  • } />\n

    ok

    ", + ["render={(i) =>
  • {i > 1}
  • }"], + ["li:tag", "class:attr", ">:op", "p:tag"], + ], + [ + "an expression among quoted attributes", + '{t("img', + ['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 && {n}}', + ['class:list={["x y", c]}'], + ["ok:var", '"x y":str', "c:var", "n:var"], + ], + ["braces in a comment", '\n

    t

    ', [], ["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 = '
    {t}

    \nw'; + 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 = '\n\n

    '; + expect(maskTagExpressions(doc)).toBe(doc); + expect(maskTagExpressions('')).toBe(""); + }); + + it("reparses an edited tag expression like a fresh parse", () => { + const before = '

    \n

    {x}

    \ny'; + const parse = (doc: string) => astroLanguage.parser.parse(doc); + let tree = parse(before); + let doc = before; + // Type `{"m n"` then `}` after `

    { const out = tokens("\n"); 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(); diff --git a/src/editor/core/cm/astro/index.ts b/src/editor/core/cm/astro/index.ts index b8bd6886a8..0333e8ced0 100644 --- a/src/editor/core/cm/astro/index.ts +++ b/src/editor/core/cm/astro/index.ts @@ -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; `