Skip to content

Build your personal knowledge base with Trilium Notes

8.4 KB
Raw Blame
import { MimeType, shouldSyntaxHighlight } from "@triliumnext/commons";
// highlight.js is heavy and this module is reachable from the startup graph (note tooltips →
// content renderer), so the library itself is only imported dynamically when highlighting runs.
import type { AutoHighlightResult, HighlightResult, Theme } from "@triliumnext/highlightjs";

import { copyText, copyTextWithToast } from "./clipboard_ext.js";
import { t } from "./i18n.js";
import mime_types from "./mime_types.js";
import options from "./options.js";
import { getEffectiveThemeStyle, onEffectiveThemeStyleChange } from "./theme.js";
import { isShare } from "./utils.js";

let highlightingLoaded = false;

function getEffectiveCodeBlockTheme(): string {
    const theme = options.get("codeBlockThemeMatchesApp") === "true"
        ? options.get(getEffectiveThemeStyle() === "dark" ? "codeBlockThemeDark" : "codeBlockThemeLight")
        : options.get("codeBlockTheme");
    // `options.get()` answers undefined until the options have loaded. String() would turn that
    // into the truthy "undefined", which `isSyntaxHighlightEnabled()` reads as a theme.
    return String(theme ?? "");
}

// Re-apply the highlight.js theme when the effective color scheme changes, so that
// "match app appearance" reacts in real time.
let colorSchemeListenerRegistered = false;
export function ensureColorSchemeListener() {
    if (colorSchemeListenerRegistered) return;
    colorSchemeListenerRegistered = true;

    onEffectiveThemeStyleChange(() => {
        if (highlightingLoaded && options.get("codeBlockThemeMatchesApp") === "true") {
            loadHighlightingTheme(getEffectiveCodeBlockTheme());
        }
    });
}

// Highlight.js can spend tens of milliseconds per block (php/c# are especially slow).
// The Markdown live preview replaces the entire rendered DOM on every keystroke, so the
// same unchanged code blocks would otherwise be re-highlighted continuously. Cache the
// output keyed by (language, text) so repeat renders short-circuit to a plain innerHTML
// assignment. FIFO eviction keeps memory bounded without needing an LRU.
const HIGHLIGHT_CACHE_MAX = 256;
const highlightCache = new Map<string, string>();

function getCachedHighlight(language: string, text: string) {
    return highlightCache.get(`${language}\x00${text}`);
}

function setCachedHighlight(language: string, text: string, value: string) {
    const key = `${language}\x00${text}`;
    if (highlightCache.size >= HIGHLIGHT_CACHE_MAX) {
        const oldest = highlightCache.keys().next().value;
        /* v8 ignore next -- size>=MAX guarantees a key exists; the undefined guard is defensive */
        if (oldest !== undefined) highlightCache.delete(oldest);
    }
    highlightCache.set(key, value);
}

/**
 * Identifies all the code blocks (as `pre code`) under the specified hierarchy and uses the highlight.js library to obtain the highlighted text which is then applied on to the code blocks.
 * Additionally, adds a "Copy to clipboard" button.
 *
 * @param $container the container under which to look for code blocks and to apply syntax highlighting to them.
 */
export async function formatCodeBlocks($container: JQuery<HTMLElement>) {
    const syntaxHighlightingEnabled = isSyntaxHighlightEnabled();

    const codeBlocks = $container.find("pre code");
    for (const codeBlock of codeBlocks) {
        const normalizedMimeType = extractLanguageFromClassList(codeBlock);
        if (!normalizedMimeType) {
            continue;
        }

        if (glob.device !== "print") {
            applyCopyToClipboardButton($(codeBlock));
        }

        if (syntaxHighlightingEnabled) {
            await applySingleBlockSyntaxHighlight($(codeBlock), normalizedMimeType);
        }
    }

    // Add click-to-copy for inline code (code elements not inside pre)
    if (glob.device !== "print") {
        const inlineCodeElements = $container.find("code:not(pre code)");
        for (const inlineCode of inlineCodeElements) {
            applyInlineCodeCopy($(inlineCode));
        }
    }
}

export function applyCopyToClipboardButton($codeBlock: JQuery<HTMLElement>) {
    const $copyButton = $("<button>")
        .addClass("bx component icon-action tn-tool-button bx-copy copy-button")
        .attr("title", t("code_block.copy_title"))
        .on("click", (e) => {
            e.stopPropagation();

            if (!isShare) {
                copyTextWithToast($codeBlock.text());
            } else {
                copyText($codeBlock.text());
            }
        });
    $codeBlock.parent().append($copyButton);
}

export function applyInlineCodeCopy($inlineCode: JQuery<HTMLElement>) {
    $inlineCode
        .addClass("copyable-inline-code")
        .attr("title", t("code_block.click_to_copy"))
        .off("click")
        .on("click", (e) => {
            e.stopPropagation();

            const text = $inlineCode.text();
            if (!isShare) {
                copyTextWithToast(text);
            } else {
                copyText(text);
            }
        });
}

/**
 * Applies syntax highlight to the given code block (assumed to be <pre><code>), using highlight.js.
 */
export async function applySingleBlockSyntaxHighlight($codeBlock: JQuery<HTMLElement>, normalizedMimeType: string) {
    $codeBlock.parent().toggleClass("hljs");
    const text = $codeBlock.text();
    if (!shouldSyntaxHighlight(text)) {
        return;
    }

    const cached = getCachedHighlight(normalizedMimeType, text);
    if (cached !== undefined) {
        $codeBlock.html(cached);
        return;
    }

    let highlightedText: HighlightResult | AutoHighlightResult | null = null;
    if (normalizedMimeType === mime_types.MIME_TYPE_AUTO && !isShare) {
        await ensureMimeTypesForHighlighting();
        const { highlightAuto } = await import("@triliumnext/highlightjs");
        highlightedText = highlightAuto(text);
    } else if (normalizedMimeType) {
        await ensureMimeTypesForHighlighting(normalizedMimeType);
        const { highlight } = await import("@triliumnext/highlightjs");
        try {
            highlightedText = highlight(text, { language: normalizedMimeType });
        } catch (e) {
            console.warn("Unable to apply syntax highlight.", e);
        }
    }

    if (highlightedText) {
        setCachedHighlight(normalizedMimeType, text, highlightedText.value);
        $codeBlock.html(highlightedText.value);
    }
}

export async function ensureMimeTypesForHighlighting(mimeTypeHint?: string) {
    if (!mimeTypeHint && highlightingLoaded) {
        return;
    }

    // Load theme.
    if (!highlightingLoaded) {
        await loadHighlightingTheme(getEffectiveCodeBlockTheme());
        ensureColorSchemeListener();
    }

    // Load mime types.
    let mimeTypes: MimeType[];

    if (mimeTypeHint) {
        mimeTypes = [
            {
                title: mimeTypeHint,
                enabled: true,
                mime: mimeTypeHint.replace("-", "/")
            }
        ];
    } else {
        mimeTypes = mime_types.getMimeTypes();
    }

    const { ensureMimeTypes } = await import("@triliumnext/highlightjs");
    await ensureMimeTypes(mimeTypes);

    highlightingLoaded = true;
}

export async function loadHighlightingTheme(themeName: string) {
    const { loadTheme, Themes } = await import("@triliumnext/highlightjs");
    const themePrefix = "default:";
    let theme: Theme | null = null;
    if (glob.device === "print") {
        theme = Themes.vs;
    } else if (themeName.includes(themePrefix)) {
        theme = Themes[themeName.substring(themePrefix.length)];
    }

    await loadTheme(theme ?? Themes.default);
}

/**
 * Indicates whether syntax highlighting should be enabled for code blocks, by querying the value of the `codeblockTheme` option.
 * @returns whether syntax highlighting should be enabled for code blocks.
 */
export function isSyntaxHighlightEnabled() {
    if (!isShare) {
        const theme = getEffectiveCodeBlockTheme();
        return !!theme && theme !== "none";
    }
    return true;

}

/**
 * Given a HTML element, tries to extract the `language-` class name out of it.
 *
 * @param el the HTML element from which to extract the language tag.
 * @returns the normalized MIME type (e.g. `text-css` instead of `language-text-css`).
 */
function extractLanguageFromClassList(el: HTMLElement) {
    const prefix = "language-";
    for (const className of el.classList) {
        if (className.startsWith(prefix)) {
            return className.substring(prefix.length);
        }
    }

    return null;
}