All files / apps/huella-legal/layers/articles/server/mappers note.ts

100% Statements 21/21
100% Branches 15/15
100% Functions 3/3
100% Lines 17/17

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 34 35 36 37 38 39 40 41 42 43 44 45          8x 8x   8x 22x   22x   6x             6x     8x 58x   58x 112x   72x   72x       112x   72x     58x   58x    
import type { Element, Root } from "hast";
import type { Note } from "../../shared/types/Note";
import { noteAnchor, noteReferenceAnchor } from "../../shared/utils/noteAnchors";
import { eachElement, stringifyNodes } from "../utils/hast";
 
const NOTE_REFERENCE = /^#_ftn(\d+)$/;
const NOTE_BACKLINK = /^#_ftnref(\d+)$/;
 
const toNoteReference = (element: Element): void => {
    const id = element.tagName === "a" && NOTE_REFERENCE.exec(String(element.properties.href))?.[1];
 
    if (!id) return;
 
    const link: Element = {
        type: "element",
        tagName: "a",
        properties: { href: `#${noteAnchor(id)}`, id: noteReferenceAnchor(id) },
        children: [{ type: "text", value: id }],
    };
 
    Object.assign(element, { tagName: "sup", properties: {}, children: [link] });
};
 
export const extractNotes = (tree: Root): Note[] => {
    const notes: Note[] = [];
 
    tree.children = tree.children.filter((node) => {
        if (node.type !== "element" || node.tagName !== "p") return true;
 
        const [marker] = node.children;
        const id =
            marker?.type === "element" &&
            marker.tagName === "a" &&
            NOTE_BACKLINK.exec(String(marker.properties.href))?.[1];
 
        if (id) notes.push({ id, html: stringifyNodes(node.children.slice(1)) });
 
        return !id;
    });
 
    if (notes.length) eachElement(tree, toNoteReference);
 
    return notes;
};