All files / apps/huella-legal/layers/articles/server/utils hast.ts

100% Statements 16/16
100% Branches 2/2
100% Functions 5/5
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33            31x 31x   818x   31x 135x   31x 742x 893x   516x 516x       813x   31x 42x            
import type { Element, Nodes, Root, RootContent } from "hast";
import { toText } from "hast-util-to-text";
import rehypeParse from "rehype-parse";
import rehypeStringify from "rehype-stringify";
import { unified } from "unified";
 
const parser = unified().use(rehypeParse, { fragment: true });
const stringifier = unified().use(rehypeStringify);
 
export const parseFragment = (html: string): Root => parser.parse(html);
 
export const stringifyNodes = (nodes: RootContent[]): string =>
    stringifier.stringify({ type: "root", children: nodes }).trim();
 
export const eachElement = (parent: Root | Element, visit: (element: Element) => void): void => {
    for (const node of parent.children) {
        if (node.type !== "element") continue;
 
        visit(node);
        eachElement(node, visit);
    }
};
 
export const textContent = (node: Nodes): string => toText(node).replace(/\s+/g, " ").trim();
 
export const slugify = (text: string): string =>
    text
        .normalize("NFD")
        .replace(/\p{M}/gu, "")
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, "-")
        .replace(/^-|-$/g, "");