presentation/renderers/definition.renderer.ts

presentation/renderers/definition.renderer.ts is a file in Bane's Lab Site. 56 lines of code and 7 definitions.

import {
    CODE_LINE_ATTRIBUTE,
    CODE_LINE_CLASS,
    CODE_LINE_MARKED_CLASS,
} from "#configuration/constants/syntax.constants";
import { DEFINITION_CITED_LEAD, DEFINITION_MISSING, SOURCE_LOADING } from "#configuration/strings/walk.strings";
import { renderServedSource, renderSource } from "#presentation/renderers/source.renderer";
import { ANATOMY_PAGE } from "#core/ids/page.ids";
import type { DefinitionBlock } from "#types/block.types";
import { SOURCE_LOADED_EVENT } from "#configuration/constants/anatomy.constants";
import { TEXT_LANGUAGE } from "#configuration/constants/code.constants";
import { TREE_TAB } from "#core/ids/anatomy.ids";
import { createElement } from "#core/factories/element.factory";
import { createPlainCodeBlock } from "#presentation/components/code.component";
import { isStaticRender } from "#core/predicates/document.predicate";
import { nodeHref } from "#domain/converters/source.converter";
import { tabLink } from "#core/assets/link.assets";

const citedHref = function citedHref(block: DefinitionBlock): string {
    return block.file === null || block.line === null
        ? tabLink(ANATOMY_PAGE, TREE_TAB)
        : nodeHref(block.file, block.line);
};

const focusLine = function focusLine(holder: HTMLElement, line: number): void {
    const span = holder.querySelector<HTMLElement>(`.${CODE_LINE_CLASS}[${CODE_LINE_ATTRIBUTE}="${String(line)}"]`);
    if (span === null) {
        return;
    }
    span.classList.add(CODE_LINE_MARKED_CLASS);
    holder.scrollTop = span.offsetTop;
};

export const renderDefinition = function renderDefinition(block: DefinitionBlock): Element {
    if (isStaticRender()) {
        return renderServedSource(DEFINITION_CITED_LEAD, citedHref(block), block.title);
    }
    const holder = createElement("div", {
        children: [createPlainCodeBlock(SOURCE_LOADING, block.title, TEXT_LANGUAGE)],
        className: "definition-holder",
    });
    void import("#domain/loaders/anatomy.loader").then((loader) => {
        const cited = loader.citedSource(block);
        if (cited === null) {
            holder.replaceChildren(createPlainCodeBlock(DEFINITION_MISSING, block.title, TEXT_LANGUAGE));
            return;
        }
        const source = renderSource(cited.block);
        source.addEventListener(
            SOURCE_LOADED_EVENT,
            () => {
                focusLine(holder, cited.location.line);
            },
            { once: true },
        );
        holder.replaceChildren(source);
    });
    return holder;
};