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", + '
{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", + "ok
", + ["render={(i) =>
',
+ ['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", '\nt
', [], ["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 = '';
+ expect(maskTagExpressions(doc)).toBe(doc);
+ expect(maskTagExpressions('')).toBe("");
+ });
+
+ it("reparses an edited tag expression like a fresh parse", () => {
+ const before = '\n {x} {
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; `` 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 })],