fix(markdown): keep hyphenated block attribute keys

The key pattern \w+ could not cross a hyphen, so data-config=foo was parsed as config=foo and the data- prefix was lost. Allow hyphens in keys, matching parseDirectiveAttrs.
This commit is contained in:
hyper
2026-09-12 23:44:43 +08:00
parent e838f9a4b1
commit 264038e27c
2 changed files with 18 additions and 2 deletions
@@ -239,6 +239,16 @@ describe("parseBlockAttrs", () => {
expect(attrs.extra).toEqual({ foo: "bar", baz: "42" });
});
test("keeps hyphenated attribute names intact", () => {
const attrs = parseBlockAttrs("yaml role=tag data-config=foo data-src=./x");
expect(attrs.extra).toEqual({ "data-config": "foo", "data-src": "./x" });
});
test("keeps hyphenated attribute names with quoted values", () => {
const attrs = parseBlockAttrs('yaml role=tag data-config="my config"');
expect(attrs.extra).toEqual({ "data-config": "my config" });
});
test("handles empty info string", () => {
const attrs = parseBlockAttrs("");
expect(attrs.lang).toBe("");
+8 -2
View File
@@ -14,10 +14,16 @@ export interface BlockAttrs {
extra: Record<string, string>;
}
/** Parse key="value" and key=value pairs from an attribute string. */
/**
* Parse key="value" and key=value pairs from an attribute string.
*
* Keys may contain hyphens (e.g. `data-config=...`); the key must start with a
* letter or underscore so a leading `-` is treated as part of a value, not a
* key.
*/
export function parseBlockAttrs(info: string): BlockAttrs {
const attrs: Record<string, string> = {};
const re = /(\w+)\s*=\s*("[^"]*"|\S+)/g;
const re = /([A-Za-z_][\w-]*)\s*=\s*("[^"]*"|\S+)/g;
let m: RegExpExecArray | null;
while ((m = re.exec(info)) !== null) {
attrs[m[1]] = m[2].replace(/^"|"$/g, "");