719
Le
lextide / files
lextide / test / language-test-helpers.ts
1.6 KB
1import type { ElementContent, Root } from "../src/index"; 2 3export function collectClasses(root: Root): string[] { 4 const classes: string[] = []; 5 6 visit(root.children, (node) => { 7 if (node.type === "element") { 8 classes.push(...node.properties.className); 9 } 10 }); 11 12 return classes; 13} 14 15export function plainText(root: Root): string { 16 return root.children.map((child) => nodeText(child)).join(""); 17} 18 19export function simplifyChildren( 20 children: readonly ElementContent[], 21): unknown[] { 22 return children.map((child) => simplifyNode(child)); 23} 24 25export function textForClass(root: Root, className: string): string { 26 return textsForClass(root, className).join(""); 27} 28 29export function textsForClass(root: Root, className: string): string[] { 30 const values: string[] = []; 31 32 visit(root.children, (node) => { 33 if ( 34 node.type === "element" && 35 node.properties.className.includes(className) 36 ) { 37 values.push(node.children.map((child) => nodeText(child)).join("")); 38 } 39 }); 40 41 return values; 42} 43 44function nodeText(node: ElementContent): string { 45 if (node.type === "text") { 46 return node.value; 47 } 48 49 return node.children.map((child) => nodeText(child)).join(""); 50} 51 52function simplifyNode(node: ElementContent): unknown[] { 53 if (node.type === "text") { 54 return ["text", node.value]; 55 } 56 57 return [ 58 "span", 59 node.properties.className, 60 node.children.map((child) => 61 child.type === "text" ? child.value : simplifyNode(child), 62 ), 63 ]; 64} 65 66function visit( 67 children: readonly ElementContent[], 68 visitor: (node: ElementContent) => void, 69): void { 70 for (const child of children) { 71 visitor(child); 72 73 if (child.type === "element") { 74 visit(child.children, visitor); 75 } 76 } 77}