presentation/widgets/menu.widget.ts

presentation/widgets/menu.widget.ts is a file in Bane's Lab Site. 30 lines of code and 7 definitions.

import { PAGE_ATTRIBUTE, createMenuButton } from "#presentation/components/menu.component";
import { ACTIVE_CLASS } from "#configuration/constants/element.constants";
import type { Disposer } from "#types/base.types";
import { MAIN_NAVIGATION_LABEL } from "#configuration/strings/menu.strings";
import { ROUTE_CHANGED } from "#core/ids/route.ids";
import { attachSearchToggle } from "#presentation/components/search.component";
import { createElement } from "#core/factories/element.factory";
import { listPages } from "#domain/registries/page.registry";
import { subscribeEvent } from "#core/buses/base.bus";

const markActive = function markActive(buttons: readonly Element[], page: string): void {
    for (const item of buttons) {
        const active = item.getAttribute(PAGE_ATTRIBUTE) === page;
        item.classList.toggle(ACTIVE_CLASS, active);
        item.setAttribute("aria-current", active ? "page" : "false");
    }
};

export const mountMenu = function mountMenu(container: HTMLElement): Disposer {
    const buttons = listPages().map(createMenuButton);
    const bar = createElement("nav", { attributes: { "aria-label": MAIN_NAVIGATION_LABEL }, className: "tab-bar" });
    const search = attachSearchToggle(bar, buttons);
    container.replaceChildren(bar);
    const unsubscribe = subscribeEvent(ROUTE_CHANGED, (event) => {
        markActive(buttons, event.page);
    });
    return () => {
        unsubscribe();
        search.dispose();
        container.replaceChildren();
    };
};