Work on inline attributes

This commit is contained in:
Zef Hemel
2023-07-24 19:54:31 +02:00
parent a1c623b1f5
commit 2b494f263e
12 changed files with 211 additions and 16 deletions
+39
View File
@@ -0,0 +1,39 @@
import { parse } from "../../common/markdown_parser/parse_tree.ts";
import buildMarkdown from "../../common/markdown_parser/parser.ts";
import { extractAttributes } from "$sb/lib/attribute.ts";
import { assertEquals } from "../../test_deps.ts";
import { renderToText } from "$sb/lib/tree.ts";
const inlineAttributeSample = `
# My document
Top level attributes: [name:: sup] [age:: 42]
* [ ] Attribute in a task [tag:: foo]
* Regular item [tag:: bar]
1. Itemized list [tag:: baz]
`;
const cleanedInlineAttributeSample = `
# My document
Top level attributes:
* [ ] Attribute in a task [tag:: foo]
* Regular item [tag:: bar]
1. Itemized list [tag:: baz]
`;
Deno.test("Test attribute extraction", () => {
const lang = buildMarkdown([]);
const tree = parse(lang, inlineAttributeSample);
const toplevelAttributes = extractAttributes(tree, false);
assertEquals(Object.keys(toplevelAttributes).length, 2);
assertEquals(toplevelAttributes.name, "sup");
assertEquals(toplevelAttributes.age, 42);
// Check if the attributes are still there
assertEquals(renderToText(tree), inlineAttributeSample);
// Now once again with cleaning
extractAttributes(tree, true);
assertEquals(renderToText(tree), cleanedInlineAttributeSample);
});
+51
View File
@@ -0,0 +1,51 @@
import {
findNodeOfType,
ParseTree,
replaceNodesMatching,
} from "$sb/lib/tree.ts";
export type Attribute = {
name: string;
value: string;
};
const numberRegex = /^-?\d+(\.\d+)?$/;
/**
* Extracts attributes from a tree, optionally cleaning them out of the tree.
* @param tree tree to extract attributes from
* @param clean whether or not to clean out the attributes from the tree
* @returns mapping from attribute name to attribute value
*/
export function extractAttributes(
tree: ParseTree,
clean: boolean,
): Record<string, any> {
const attributes: Record<string, any> = {};
replaceNodesMatching(tree, (n) => {
if (n.type === "ListItem") {
// Find top-level only, no nested lists
return n;
}
if (n.type === "Attribute") {
const nameNode = findNodeOfType(n, "AttributeName");
const valueNode = findNodeOfType(n, "AttributeValue");
if (nameNode && valueNode) {
let val: any = valueNode.children![0].text!;
if (numberRegex.test(val)) {
val = +val;
}
attributes[nameNode.children![0].text!] = val;
}
// Remove from tree
if (clean) {
return null;
} else {
return n;
}
}
// Go on...
return undefined;
});
return attributes;
}