All files / picobel/src/js/markup utils.ts

100% Statements 16/16
90% Branches 9/10
100% Functions 3/3
100% Lines 16/16

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 46 47      10x 507x 507x 507x                   10x   38x     147x 116x 116x 116x       31x 21x 21x       21x           21x       38x    
import { type ComponentGroup } from "../types";
import * as componentConstructors from "./components";
 
export const createElement = (type = "div", className = "") => {
    const newElement = document.createElement(type);
    newElement.className = className;
    return newElement;
};
 
type BuildComponentsOptions = {
    key: number;
    container: HTMLElement;
    components: ComponentGroup[];
    namespace: string;
};
 
export const buildComponents = ({ key, container, components, namespace }: BuildComponentsOptions) => {
    // Add the components to the player in the order they are listed
    components.forEach(component => {
        // If the component is a string and we have a function to build it
        // then build it and add it to the player.
        if (typeof component === "string" && componentConstructors[component]) {
            const markup = componentConstructors[component](namespace, key);
            container.appendChild(markup);
            return;
        }
        // If the component is an array, build a wrapper and add each
        // component to the wrapper.
        if (Array.isArray(component) && component.length) {
            const classSuffix = component.flat().join("-");
            const wrapper = createElement(
                "div",
                `${namespace}__wrapper--${classSuffix}`
            );
            const wrapperWithComponents = buildComponents({
                key,
                container: wrapper,
                components: component,
                namespace
            });
            container.appendChild(wrapperWithComponents);
        }
    });
 
    return container;
};