Skip to content

Build your personal knowledge base with Trilium Notes

7.4 KB
Raw Blame
import { afterEach, describe, expect, it, vi } from "vitest";

import attributes from "./attributes.js";
import getSharedBootstrapItems, { getIconConfig } from "./bootstrap_utils.js";
import * as cls from "./context.js";
import notes from "./notes.js";
import options from "./options.js";
import { getPlatform } from "./platform.js";
import { enterSetupMode, leaveSetupMode } from "./setup_mode.js";
import sqlInit from "./sql_init.js";

const ASSET_PATH = "assets-x";

function withTheme<T>(theme: string, fn: () => T): T {
    const previous = options.getOption("theme");
    try {
        cls.init(() => options.setOption("theme", theme));
        return fn();
    } finally {
        cls.init(() => options.setOption("theme", previous));
    }
}

/** Returns the bootstrap payload for an initialized DB, narrowed to the full shape. */
function fullPayload(theme: string) {
    const items = withTheme(theme, () => getSharedBootstrapItems(ASSET_PATH, true));
    if (!("customThemeCssUrl" in items)) {
        throw new Error("Expected the initialized bootstrap payload");
    }
    return items;
}

describe("bootstrap_utils (real DB)", () => {
    afterEach(() => cls.reset());

    it("returns the minimal setup payload before the DB is initialized", () => {
        const items = getSharedBootstrapItems(ASSET_PATH, false);

        expect(items.dbInitialized).toBe(false);
        expect(items.theme).toBe("next");
        expect(items.themeCssUrl).toBe(false);
        expect(items.appCssNoteIds).toEqual([]);
        // Common items + icon config are always present.
        expect(items.assetPath).toBe(ASSET_PATH);
        expect(items.iconRegistry).toBeTruthy();
        expect(typeof items.iconPackCss).toBe("string");
    });

    it("flags syncInProgress for a not-yet-initialized DB only when the schema already exists", () => {
        const schemaSpy = vi.spyOn(sqlInit, "schemaExists");
        try {
            // Schema present but DB not initialized = a sync that was interrupted → resume it.
            schemaSpy.mockReturnValue(true);
            expect(getSharedBootstrapItems(ASSET_PATH, false).syncInProgress).toBe(true);

            // No schema yet = a fresh install → start the setup wizard from the top.
            schemaSpy.mockReturnValue(false);
            expect(getSharedBootstrapItems(ASSET_PATH, false).syncInProgress).toBe(false);
        } finally {
            schemaSpy.mockRestore();
        }
    });

    it("tells the wizard where to open, and that it has a database to go back to", () => {
        const schemaSpy = vi.spyOn(sqlInit, "schemaExists").mockReturnValue(true);
        try {
            // A first run: nowhere in particular to go, and nothing behind the wizard.
            expect(getSharedBootstrapItems(ASSET_PATH, false)).toMatchObject({
                hasExistingData: false, setupTargetScreen: undefined
            });

            enterSetupMode({ lang: "ro", targetScreen: "restore-backup" });
            const items = getSharedBootstrapItems(ASSET_PATH, false);

            expect(items).toMatchObject({ hasExistingData: true, setupTargetScreen: "restore-backup" });
            // The schema of a finished database says nothing about an interrupted sync, so the
            // wizard must not be sent to the sync-progress screen instead of the one asked for.
            expect(items.syncInProgress).toBe(false);
        } finally {
            leaveSetupMode();
            schemaSpy.mockRestore();
        }
    });

    it("returns the full payload once the DB is initialized, including app CSS note ids", () => {
        const appCssNoteId = cls.init(() => {
            const { note } = notes.createNewNote({
                parentNoteId: "root",
                title: "App CSS",
                content: "body {}",
                type: "code",
                mime: "text/css"
            });
            attributes.createLabel(note.noteId, "appCss", "");
            return note.noteId;
        });

        const items = fullPayload("next");

        expect(items.dbInitialized).toBe(true);
        expect(typeof items.maxEntityChangeIdAtLoad).toBe("number");
        expect(typeof items.maxEntityChangeSyncIdAtLoad).toBe("number");
        expect(items.isProtectedSessionAvailable).toBe(false);
        expect(items.theme).toBe("next");
        expect(items.appCssNoteIds).toContain(appCssNoteId);
    });

    it("maps each built-in theme to its stylesheet URL", () => {
        const expectations: Record<string, string | false> = {
            auto: `${ASSET_PATH}/stylesheets/theme.css`,
            light: false,
            dark: `${ASSET_PATH}/stylesheets/theme-dark.css`,
            next: `${ASSET_PATH}/stylesheets/theme-next.css`,
            "next-light": `${ASSET_PATH}/stylesheets/theme-next-light.css`,
            "next-dark": `${ASSET_PATH}/stylesheets/theme-next-dark.css`
        };

        for (const [theme, expected] of Object.entries(expectations)) {
            const items = fullPayload(theme);
            expect(items.themeCssUrl, `theme=${theme}`).toBe(expected);
            // Built-in themes never expose a custom CSS URL.
            expect(items.customThemeCssUrl, `theme=${theme}`).toBeUndefined();
        }
    });

    it("resolves a custom theme note to a download URL", () => {
        const noteId = cls.init(() => {
            const { note } = notes.createNewNote({
                parentNoteId: "root",
                title: "Custom Theme",
                content: "body {}",
                type: "code",
                mime: "text/css"
            });
            attributes.createLabel(note.noteId, "appTheme", "myCustomTheme");
            attributes.createLabel(note.noteId, "appThemeBase", "next-dark");
            return note.noteId;
        });

        const items = fullPayload("myCustomTheme");
        expect(items.themeCssUrl).toBe(`api/notes/download/${noteId}`);
        expect(items.customThemeCssUrl).toBe(`api/notes/download/${noteId}`);
        expect(items.themeBase).toBe("next-dark");
    });

    it("withholds both custom theme URLs in safe mode", () => {
        cls.init(() => {
            const { note } = notes.createNewNote({
                parentNoteId: "root",
                title: "Custom Theme",
                content: "body {}",
                type: "code",
                mime: "text/css"
            });
            attributes.createLabel(note.noteId, "appTheme", "mySafeModeTheme");
        });

        // Safe mode reaches core through the platform provider rather than `process.env`: the
        // browser build has no `process` and takes the value from a `?safeMode` URL parameter.
        const envSpy = vi.spyOn(getPlatform(), "getEnv")
            .mockImplementation((key) => (key === "TRILIUM_SAFE_MODE" ? "1" : undefined));
        try {
            const items = fullPayload("mySafeModeTheme");
            expect(items.themeCssUrl).toBe(false);
            expect(items.customThemeCssUrl).toBeUndefined();
        } finally {
            envSpy.mockRestore();
        }
    });

    it("falls back to the baseline light theme for an unknown theme with no matching note", () => {
        const items = fullPayload("ghostThemeWithoutNote");
        expect(items.themeCssUrl).toBe(false);
        expect(items.customThemeCssUrl).toBeUndefined();
    });

    it("getIconConfig produces an icon registry and CSS", () => {
        const config = getIconConfig(ASSET_PATH);
        expect(config.iconRegistry).toBeTruthy();
        expect(typeof config.iconPackCss).toBe("string");
    });
});