Skip to content

Build your personal knowledge base with Trilium Notes

4.8 KB
Raw Blame
import type { ElectronWindowApi } from "@triliumnext/commons";

import appContext, { type CommandNames } from "./components/app_context.js";
import electronContextMenu from "./menus/electron_context_menu.js";
import { setupContextMenu as setupBrowserContextMenu } from "./menus/note_context_menu.js";
import bundleService from "./services/bundle.js";
import { setupClipboardImageEmbed } from "./services/clipboard_image_embed.js";
import glob from "./services/glob.js";
import { t } from "./services/i18n.js";
import { syncNativeWindowWithTheme } from "./services/native_window.js";
import noteTooltipService from "./services/note_tooltip.js";
import { onEffectiveThemeStyleChange, setBackgroundEffectsSuspended } from "./services/theme.js";
import toastService from "./services/toast.js";
import utils from "./services/utils.js";
import { preloadCommonNoteTypes } from "./widgets/note_types.js";

await appContext.earlyInit();

/**
 * Resolves once the layout is rendered and froca has the note tree. index.ts keeps the splash up
 * until then, so the bundle, layout and tree requests below are not made behind a blank page. A
 * failed start still resolves it: the toast that reports the failure has to become visible.
 */
export const ready = bundleService.getWidgetBundlesByParent().then(async (widgetBundles) => {
    // A dynamic import is required for layouts since they initialize components which require translations.
    const DesktopLayout = (await import("./layouts/desktop_layout.js")).default;

    appContext.setLayout(new DesktopLayout(widgetBundles));
    try {
        await appContext.start();
    } catch (e) {
        toastService.showPersistent({
            id: "critical-error",
            title: t("toast.critical-error.title"),
            icon: "alert",
            message: t("toast.critical-error.message", { message: e instanceof Error ? e.message : String(e) })
        });
        console.error("Critical error occured", e);
        return;
    }

    reportFullRenderStartupMetric();
    preloadCommonNoteTypes();
});

glob.setupGlobs();
initFullScreenDetection();

if (utils.isElectron()) {
    initOnElectron();
}

noteTooltipService.setupGlobalTooltip();

setupClipboardImageEmbed();

if (utils.isElectron()) {
    electronContextMenu.setupContextMenu();
} else {
    setupBrowserContextMenu();
}

function initOnElectron() {
    const api = window.electronApi;
    if (!api) return;

    const win = api.window;
    // The action name comes from the keyboard-actions registry in the main
    // process; runtime contract is that it's always a valid CommandNames key.
    win.onGlobalShortcut(async (actionName) => appContext.triggerCommand(actionName as CommandNames));
    win.onOpenInSameTab(async (noteId) => appContext.tabManager.openInSameTab(noteId));

    syncNativeWindowWithTheme();
    initDevToolsDockDetection(win);

    // With an "auto" theme the effective colors of background effects and the native title bar
    // follow the OS color scheme.
    onEffectiveThemeStyleChange(() => syncNativeWindowWithTheme());

    // Clear navigation history on frontend refresh.
    api.navigation.clearNavigationHistory();
}

/**
 * Tells the Electron main process that the client finished its initial render
 * (layout widgets attached, froca loaded, tab restoration started) so it gets
 * logged against the other startup metrics. The double requestAnimationFrame
 * defers the report until the browser has painted a frame of the rendered
 * layout, rather than measuring DOM construction only. No-op outside Electron.
 */
function reportFullRenderStartupMetric() {
    requestAnimationFrame(() => {
        requestAnimationFrame(() => {
            window.electronApi?.window.reportStartupMetric("client-full-render");
        });
    });
}

/** Sets `full-screen` on the body while the window, or the page in a browser, is full screen. */
function initFullScreenDetection() {
    const setFullScreen = (isFullScreen: boolean) => {
        document.body.classList.toggle("full-screen", isFullScreen);
    };

    const win = window.electronApi?.window;
    if (win) {
        setFullScreen(win.isFullScreen());
        win.onEnterFullScreen(() => setFullScreen(true));
        win.onLeaveFullScreen(() => setFullScreen(false));
        return;
    }

    document.addEventListener("fullscreenchange", () => {
        setFullScreen(document.fullscreenElement === document.documentElement);
    });
}

/**
 * Chromium disables the native window material (Mica / vibrancy) while DevTools is docked into
 * the window, which would leave the transparent background effects floating over a solid void —
 * suspend them for the duration. DevTools in a separate window does not affect the material.
 */
function initDevToolsDockDetection(win: ElectronWindowApi) {
    setBackgroundEffectsSuspended(win.isDevToolsDocked());
    win.onDevToolsDockChanged(setBackgroundEffectsSuspended);
}