Skip to content

Build your personal knowledge base with Trilium Notes

29.8 KB
Raw Blame
import type { CKTextEditor } from "@triliumnext/ckeditor5";
import type CodeMirror from "@triliumnext/codemirror";
import { type LOCALE_IDS, SqlExecuteResponse } from "@triliumnext/commons";
import { ColumnComponent } from "tabulator-tables";

import type { Attribute } from "../services/attribute_parser.js";
import bundleService from "../services/bundle.js";
import froca from "../services/froca.js";
import { initLocale, t } from "../services/i18n.js";
import keyboardActionsService from "../services/keyboard_actions.js";
import linkService, { type HashPane, type ViewScope } from "../services/link.js";
import type LoadResults from "../services/load_results.js";
import type { CreateNoteOpts } from "../services/note_create.js";
import options from "../services/options.js";
import type { ShortcutHintSection } from "../services/shortcut_hints.js";
import { reportSplashPhase } from "../services/splash.js";
import toast from "../services/toast.js";
import utils, { reuseAcrossHotReloads } from "../services/utils.js";
import { ReactWrappedWidget } from "../widgets/basic_widget.js";
import type RootContainer from "../widgets/containers/root_container.js";
import type { ConfirmWithMessageOptions, ConfirmWithTitleOptions } from "../widgets/dialogs/confirm.js";
import { ContentEmbedOpts } from "../widgets/dialogs/content_embed.jsx";
import type { ResolveOptions } from "../widgets/dialogs/delete_notes.js";
import { EditLinkOpts } from "../widgets/dialogs/edit_link.jsx";
import { IconPickerOpts } from "../widgets/dialogs/icon_picker.jsx";
import type { InfoProps } from "../widgets/dialogs/info.jsx";
import type { ResourceDownloadDialogOptions } from "../widgets/dialogs/resource_download.jsx";
import type { LightboxOptions } from "../widgets/dialogs/lightbox.jsx";
import type { MarkdownImportOpts } from "../widgets/dialogs/markdown_import.jsx";
import { ChooseNoteTypeCallback } from "../widgets/dialogs/note_type_chooser.jsx";
import type { PrintPreviewData } from "../widgets/dialogs/print_preview.jsx";
import type { NotePickerDialogOptions } from "../widgets/dialogs/note_picker.js";
import type { ItemPickerDialogOptions } from "../widgets/dialogs/item_picker.js";
import type { PromptDialogOptions } from "../widgets/dialogs/prompt.js";
import type { YouTubeVideoOpts } from "../widgets/dialogs/youtube_video.js";
import type NoteTreeWidget from "../widgets/note_tree.js";
import type { PaneId, PaneMode } from "../widgets/react/peek_pane.js";
import type { RightPaneTabId } from "../widgets/sidebar/RightPaneTabs.jsx";
import type { ToolCall } from "../widgets/type_widgets/llm_chat/llm_chat_types.js";
import Component from "./component.js";
import Entrypoints from "./entrypoints.js";
import MainTreeExecutors from "./main_tree_executors.js";
import MobileScreenSwitcherExecutor, { type Screen } from "./mobile_screen_switcher.js";
import type { default as NoteContext, GetTextEditorCallback } from "./note_context.js";
import RootCommandExecutor from "./root_command_executor.js";
import ShortcutComponent from "./shortcut_component.js";
import { StartupChecks } from "./startup_checks.js";
import TabManager from "./tab_manager.js";
import zoomComponent from "./zoom.js";

interface Layout {
    getRootWidget: (appContext: AppContext) => RootContainer;
}

export interface BeforeUploadListener extends Component {
    beforeUnloadEvent(): boolean;
}

/**
 * Base interface for the data/arguments for a given command (see {@link CommandMappings}).
 */
export interface CommandData {
    ntxId?: string | null;
}

/**
 * Represents a set of commands that are triggered from the context menu, providing information such as the selected note.
 */
export interface ContextMenuCommandData extends CommandData {
    /**
     * Fancytree node for the target when the command originated from the
     * Fancytree-based note tree. Omitted when dispatched from node-free UIs
     * (e.g. the mobile drill-down navigator) — handlers should prefer the
     * explicit `noteId` / `branchId` / `notePath` fields below.
     */
    node?: Fancytree.FancytreeNode;
    notePath?: string;
    noteId?: string;
    branchId?: string;
    selectedOrActiveBranchIds: string[];
    selectedOrActiveNoteIds?: string[];
}

export interface NoteCommandData extends CommandData {
    notePath?: string | null;
    hoistedNoteId?: string | null;
    viewScope?: ViewScope;
    /**
     * Panes to open beside `notePath`, in order — how a tab moved or copied into a window of its own
     * takes its splits along. Honoured only while booting a detached window.
     */
    splits?: HashPane[] | null;
    /** Index into `[main pane, ...splits]` of the pane to focus. Defaults to the main pane. */
    activeSplit?: number;
}

/** The note a quick-edit popup opens, and how. */
export interface OpenInPopupData extends CommandData {
    noteIdOrPath: string;
    viewScope?: ViewScope;
    /** Offers the note type switcher while the note is still blank, as the tab layout does. */
    showNoteTypeSwitcher?: boolean;
    /** Focuses the title with all of it selected instead of the content, for a note to name. */
    selectTitle?: boolean;
}

export interface ExecuteCommandData<T> extends CommandData {
    resolve: (data: T) => void;
}

export interface NoteSwitchedContext {
    noteContext: NoteContext;
    notePath: string | null | undefined;
}

/**
 * The keys represent the different commands that can be triggered via {@link AppContext#triggerCommand} (first argument), and the values represent the data or arguments definition of the given command. All data for commands must extend {@link CommandData}.
 */
export type CommandMappings = {
    "api-log-messages": CommandData;
    focusTree: CommandData;
    focusOnTitle: CommandData;
    focusOnDetail: CommandData & {
        /**
         * When set, instead of merely focusing the editor, an empty paragraph is inserted at the very
         * top of the document and the cursor is placed there (Notion-like behavior when pressing Enter
         * in the title). Only honored by text notes. If the first block is already an empty paragraph,
         * the cursor is placed in it rather than stacking another empty paragraph.
         */
        insertNewlineAtTop?: boolean;
    };
    searchNotes: CommandData & {
        searchString?: string;
        ancestorNoteId?: string | null;
    };
    closeTocCommand: CommandData;
    closeHlt: CommandData;
    showLaunchBarSubtree: CommandData;
    showHiddenSubtree: CommandData;
    showSQLConsoleHistory: CommandData;
    logout: CommandData;
    switchToMobileVersion: CommandData;
    switchToDesktopVersion: CommandData;
    showRevisions: CommandData & {
        noteId?: string | null;
    };
    showOptions: CommandData & {
        section?: string;
    };
    showContentLanguagesDialog: CommandData;
    showExportDialog: CommandData & {
        notePath: string;
        defaultType: "single" | "subtree";
    };
    showDeleteNotesDialog: CommandData & {
        branchIdsToDelete: string[];
        callback: (value: ResolveOptions) => void;
        forceDeleteAllClones: boolean;
    };
    showConfirmDeleteNoteBoxWithNoteDialog: ConfirmWithTitleOptions;
    focusAndSelectTitle: CommandData & {
        isNewNote?: boolean;
    };
    showPromptDialog: PromptDialogOptions;
    showItemPickerDialog: ItemPickerDialogOptions;
    showNotePickerDialog: NotePickerDialogOptions;
    showInfoDialog: InfoProps;
    showLightbox: LightboxOptions;
    showToolCallDetails: { toolCall: ToolCall };
    showConfirmDialog: ConfirmWithMessageOptions;
    showResourceDownloadDialog: ResourceDownloadDialogOptions;
    showRecentChanges: CommandData & { ancestorNoteId: string };
    showDeletedNotes: CommandData & { ancestorNoteId?: string };
    showImportDialog: CommandData & { noteId: string };
    openNewNoteSplit: NoteCommandData;
    openInWindow: NoteCommandData;
    /** Opens a note in the quick-edit popup. A `viewScope` carrying an `attachmentId` opens that attachment instead of the note itself. */
    openInPopup: OpenInPopupData;
    /** Opens a note in a second quick-edit popup, over the first one, such as a help page asked for from within it. */
    openInNestedPopup: OpenInPopupData;
    /** Dismisses the quick-edit popup, for something within it that has sent the reader elsewhere. Does nothing if it isn't open. */
    closePopupEditor: CommandData;
    openInTreePopup: CommandData & { noteIdOrPath: string; hoistedNoteId: string; };
    openNoteInNewTab: CommandData;
    openNoteInNewSplit: CommandData;
    openNoteInNewWindow: CommandData;
    openAboutDialog: CommandData;
    hideLeftPane: CommandData;
    showCpuArchWarning: CommandData;
    showLeftPane: CommandData;
    showAttachments: CommandData;
    showNoteAttributes: CommandData;
    showSearchHistory: CommandData;
    showShareSubtree: CommandData;
    hoistNote: CommandData & { noteId: string };
    leaveProtectedSession: CommandData;
    enterProtectedSession: CommandData;
    noteContextReorder: CommandData & {
        ntxIdsInOrder: string[];
        oldMainNtxId?: string | null;
        newMainNtxId?: string | null;
    };
    openNote: ContextMenuCommandData;
    openInTab: ContextMenuCommandData;
    openNoteInSplit: ContextMenuCommandData;
    openNoteInWindow: ContextMenuCommandData;
    openNoteInPopup: ContextMenuCommandData;
    toggleNoteHoisting: ContextMenuCommandData;
    insertNoteAfter: ContextMenuCommandData;
    insertChildNote: ContextMenuCommandData;
    delete: ContextMenuCommandData;
    editNoteTitle: {};
    protectSubtree: ContextMenuCommandData;
    unprotectSubtree: ContextMenuCommandData;
    openBulkActionsDialog:
    | ContextMenuCommandData
    | {
        selectedOrActiveNoteIds?: string[];
    };
    editBranchPrefix: ContextMenuCommandData;
    convertNoteToAttachment: ContextMenuCommandData;
    duplicateSubtree: ContextMenuCommandData;
    duplicateNote: ContextMenuCommandData;
    expandSubtree: ContextMenuCommandData;
    collapseSubtree: ContextMenuCommandData;
    toggleArchivedNotes: CommandData;
    sortChildNotes: ContextMenuCommandData;
    copyNotePathToClipboard: ContextMenuCommandData;
    recentChangesInSubtree: ContextMenuCommandData;
    cutNotesToClipboard: ContextMenuCommandData;
    copyNotesToClipboard: ContextMenuCommandData;
    pasteNotesFromClipboard: ContextMenuCommandData;
    pasteNotesAfterFromClipboard: ContextMenuCommandData;
    moveNotesTo: ContextMenuCommandData;
    cloneNotesTo: ContextMenuCommandData;
    deleteNotes: ContextMenuCommandData;
    importIntoNote: ContextMenuCommandData;
    exportNote: ContextMenuCommandData;
    searchInSubtree: CommandData & { notePath: string; };
    moveNoteUp: ContextMenuCommandData;
    moveNoteDown: ContextMenuCommandData;
    moveNoteUpInHierarchy: ContextMenuCommandData;
    moveNoteDownInHierarchy: ContextMenuCommandData;
    selectAllNotesInParent: ContextMenuCommandData;

    createNoteIntoInbox: CommandData;

    addNoteLauncher: ContextMenuCommandData;
    addScriptLauncher: ContextMenuCommandData;
    addWidgetLauncher: ContextMenuCommandData;
    addSpacerLauncher: ContextMenuCommandData;
    moveLauncherToVisible: ContextMenuCommandData;
    moveLauncherToAvailable: ContextMenuCommandData;
    resetLauncher: ContextMenuCommandData;

    executeInActiveNoteDetailWidget: CommandData & {
        callback: (value: ReactWrappedWidget) => void;
    };
    executeWithTextEditor: CommandData &
    ExecuteCommandData<CKTextEditor> & {
        callback?: GetTextEditorCallback;
    };
    executeWithCodeEditor: CommandData & ExecuteCommandData<CodeMirror>;
    /**
     * Called upon when attempting to retrieve the content element of a {@link NoteContext}.
     * Generally should not be invoked manually, as it is used by {@link NoteContext.getContentElement}.
     */
    executeWithContentElement: CommandData & ExecuteCommandData<JQuery<HTMLElement>>;
    executeWithTypeWidget: CommandData & ExecuteCommandData<ReactWrappedWidget | null>;
    addTextToActiveEditor: CommandData & {
        text: string;
    };
    /** Works only in the electron context menu. */
    replaceMisspelling: CommandData;

    showPasswordNotSet: CommandData;
    showProtectedSessionPasswordDialog: CommandData;
    showUploadAttachmentsDialog: CommandData & { noteId: string };
    showContentEmbedDialog: CommandData & ContentEmbedOpts;
    showEditLinkDialog: CommandData & EditLinkOpts;
    showIconPickerDialog: CommandData & IconPickerOpts;
    showYouTubeVideoDialog: CommandData & YouTubeVideoOpts;
    showPasteMarkdownDialog: CommandData & MarkdownImportOpts;
    closeProtectedSessionPasswordDialog: CommandData;
    copyImageReferenceToClipboard: CommandData;
    copyImageToClipboard: CommandData;
    updateAttributesList: {
        attributes: Attribute[];
    };

    addNewLabel: CommandData;
    addNewRelation: CommandData;
    addNewLabelDefinition: CommandData;
    addNewRelationDefinition: CommandData;

    cloneNoteIdsTo: CommandData & {
        noteIds: string[];
    };
    moveBranchIdsTo: CommandData & {
        branchIds: string[];
    };
    /** Sets the active {@link Screen} (e.g. to toggle the tree sidebar). It triggers the {@link EventMappings.activeScreenChanged} event, but only if the provided <em>screen</em> is different than the current one. */
    setActiveScreen: CommandData & {
        screen: Screen;
    };
    closeTab: CommandData;
    closeToc: CommandData;
    closeOtherTabs: CommandData;
    closeRightTabs: CommandData;
    closeAllTabs: CommandData;
    pinTab: CommandData;
    unpinTab: CommandData;
    reopenLastTab: CommandData;
    moveTabToNewWindow: CommandData;
    copyTabToNewWindow: CommandData;
    closeActiveTab: CommandData & {
        $el: JQuery<HTMLElement>;
    };
    setZoomFactorAndSave: {
        zoomFactor: string;
    };

    runActiveNote: CommandData;
    scrollContainerTo: CommandData & {
        position: number;
    };
    scrollToEnd: CommandData;
    closeThisNoteSplit: CommandData;
    moveThisNoteSplit: CommandData & { isMovingLeft: boolean };
    /**
     * Keyboard-action counterparts of the pane buttons. The buttons bubble `closeThisNoteSplit` /
     * `moveThisNoteSplit` up from the pane they sit in; these are dispatched from `appContext`,
     * which has no pane to start from and so distributes them downwards as events instead.
     */
    closeActiveNoteSplit: CommandData;
    moveActiveNoteSplitLeft: CommandData;
    moveActiveNoteSplitRight: CommandData;
    focusNoteSplitLeft: CommandData;
    focusNoteSplitRight: CommandData;
    jumpToNote: CommandData;
    openTodayNote: CommandData;
    commandPalette: CommandData;

    // Keyboard shortcuts
    backInNoteHistory: CommandData;
    forwardInNoteHistory: CommandData;
    forceSaveRevision: CommandData;
    saveNamedRevision: CommandData;
    scrollToActiveNote: CommandData;
    quickSearch: CommandData;
    collapseTree: CommandData;
    createNoteAfter: CommandData;
    createNoteInto: CommandData;
    addNoteAboveToSelection: CommandData;
    addNoteBelowToSelection: CommandData;
    openNewTab: CommandData;
    activateNextTab: CommandData;
    activatePreviousTab: CommandData;
    openNewWindow: CommandData;
    toggleTray: CommandData;
    firstTab: CommandData;
    secondTab: CommandData;
    thirdTab: CommandData;
    fourthTab: CommandData;
    fifthTab: CommandData;
    sixthTab: CommandData;
    seventhTab: CommandData;
    eigthTab: CommandData;
    ninthTab: CommandData;
    lastTab: CommandData;
    showNoteSource: CommandData;
    showNoteOCRText: CommandData;
    showOcrTextDialog: CommandData & {
        textUrl: string;
        processUrl: string;
    };
    showSQLConsole: CommandData;
    showBackendLog: CommandData;
    showSpaceUsage: CommandData;
    showCheatsheet: CommandData;
    showShortcutHints: CommandData;
    showHelp: CommandData;
    addLinkToText: CommandData;
    followLinkUnderCursor: CommandData;
    insertDateTimeToText: CommandData;
    pasteMarkdownIntoText: CommandData;
    cutIntoNote: CommandData;
    saveNoteDetailNow: CommandData;
    addIncludeNoteToText: CommandData;
    editReadOnlyNote: CommandData;
    toggleRibbonTabClassicEditor: CommandData;
    toggleRibbonTabBasicProperties: CommandData;
    toggleRibbonTabBookProperties: CommandData;
    toggleRibbonTabFileProperties: CommandData;
    toggleRibbonTabImageProperties: CommandData;
    toggleRibbonTabOwnedAttributes: CommandData;
    toggleRibbonTabInheritedAttributes: CommandData;
    toggleRibbonTabPromotedAttributes: CommandData;
    toggleRibbonTabNoteMap: CommandData;
    toggleRibbonTabNoteInfo: CommandData;
    toggleRibbonTabNotePaths: CommandData;
    toggleRibbonTabSimilarNotes: CommandData;
    toggleRightPane: CommandData;
    peekRightPane: CommandData;
    /** Shows the given tab of the right pane, opening the pane if it is closed. */
    selectRightPaneTab: CommandData & {
        tabId: RightPaneTabId;
        /**
         * Peek the pane rather than dock it when it is closed, for an entry point that is only a glance
         * at the tab and shouldn't reflow the content around it. An already docked pane stays docked.
         */
        peek?: boolean;
        /**
         * The id of a widget of that tab (see `RightPanelWidget`) to expand, so that an entry point
         * aimed at one widget doesn't land on it collapsed.
         */
        expandWidgetId?: string;
    };
    printActiveNote: CommandData;
    exportAsPdf: CommandData;
    showPrintPreview: PrintPreviewData;
    openNoteExternally: CommandData;
    openNoteCustom: CommandData;
    openNoteOnServer: CommandData;
    renderActiveNote: CommandData;
    unhoist: CommandData;
    reloadFrontendApp: CommandData;
    openDevTools: CommandData;
    findInText: CommandData & { searchTerms?: string[] };
    toggleLeftPane: CommandData;
    peekLeftPane: CommandData;
    toggleFullscreen: CommandData;
    zoomOut: CommandData;
    zoomIn: CommandData;
    zoomReset: CommandData;
    copyWithoutFormatting: CommandData;

    toggleZenMode: CommandData;

    updateAttributeList: CommandData & { attributes: Attribute[] };
    saveAttributes: CommandData;
    reloadAttributes: CommandData;
    refreshNoteList: CommandData & { noteId: string };

    refreshResults: {};
    refreshSearchDefinition: {};

    geoMapCreateChildNote: CommandData;

    // Table view
    addNewRow: CommandData & {
        customOpts: CreateNoteOpts;
        parentNotePath?: string;
    };
    addNewTableColumn: CommandData & {
        columnToEdit?: ColumnComponent;
        referenceColumn?: ColumnComponent;
        direction?: "before" | "after";
        type?: "label" | "relation";
    };
    deleteTableColumn: CommandData & {
        columnToDelete?: ColumnComponent;
    };

    reloadTextEditor: CommandData;
    chooseNoteType: CommandData & {
        callback: ChooseNoteTypeCallback
    };
    customDownload: CommandData;
};

type EventMappings = {
    initialRenderComplete: {};
    frocaReloaded: {};
    setLeftPaneVisibility: {
        leftPaneVisible: boolean | null;
    }
    /** Raised by a side pane after it is closed, peeked or docked. See `peek_pane.ts`. */
    paneModeChanged: {
        pane: PaneId;
        mode: PaneMode;
    }
    protectedSessionStarted: {};
    notesReloaded: {
        noteIds: string[];
    };
    refreshEmbeddedNote: {
        noteId: string;
    };
    apiLogMessages: {
        noteId: string;
        messages: string[];
    };
    entitiesReloaded: {
        loadResults: LoadResults;
    };
    addNewLabel: CommandData;
    addNewRelation: CommandData;
    sqlQueryResults: CommandData & {
        response: SqlExecuteResponse;
    };
    readOnlyTemporarilyDisabled: {
        noteContext: NoteContext;
    };
    /** Triggered when the {@link CommandMappings.setActiveScreen} command is invoked. */
    activeScreenChanged: {
        activeScreen: Screen;
    };
    /** Triggered when the active theme changes (theme option swap or, for auto themes, the OS light/dark flip),
     * once the new stylesheet is applied. Lets widgets that read CSS variables in JS (e.g. canvas renderers)
     * re-read them. Consume with {@link useTriliumEvent}("themeChanged") or the {@link useColorScheme} hook. */
    themeChanged: {
        themeStyle: "light" | "dark";
    };
    activeContextChanged: {
        noteContext: NoteContext;
    };
    /** Emitted with the hints collected from the focused component chain (via the
     * {@link CommandMappings.showShortcutHints} handler) or from a widget's help button, for the
     * shortcut-hints pane to render. When `anchor` is set the pane opens as a dropdown by it;
     * otherwise it opens in the bottom-right corner. */
    shortcutHintsRequested: {
        sections: ShortcutHintSection[];
        anchor?: HTMLElement | null;
    };
    beforeNoteSwitch: {
        noteContext: NoteContext;
    };
    beforeNoteContextRemove: {
        ntxIds: string[];
    };
    noteSwitched: NoteSwitchedContext;
    noteSwitchedAndActivated: NoteSwitchedContext;
    setNoteContext: {
        noteContext: NoteContext;
    };
    showSearchError: {
        error: string;
    };
    searchRefreshed: { ntxId?: string | null };
    textEditorRefreshed: { ntxId?: string | null, editor: CKTextEditor };
    contentElRefreshed: { ntxId?: string | null, contentEl: HTMLElement };
    hoistedNoteChanged: {
        noteId: string;
        ntxId: string | null;
    };
    contextsReopened: {
        ntxId?: string;
        mainNtxId: string | null;
        tabPosition: number;
        afterNtxId?: string;
    };
    noteDetailRefreshed: {
        ntxId?: string | null;
    };
    noteContextReorder: {
        oldMainNtxId: string;
        newMainNtxId: string;
        ntxIdsInOrder: string[];
    };
    newNoteContextCreated: {
        noteContext: NoteContext;
    };
    noteContextRemoved: {
        ntxIds: string[];
    };
    contextDataChanged: {
        noteContext: NoteContext;
        key: string;
        value: unknown;
    };
    exportSvg: { ntxId: string | null | undefined; };
    exportPng: { ntxId: string | null | undefined; };
    exportXlsx: { ntxId: string | null | undefined; };
    exportCsv: { ntxId: string | null | undefined; };
    geoMapCreateChildNote: {
        ntxId: string | null | undefined; // TODO: deduplicate ntxId
    };
    /** Opens the properties dialog of a board or calendar, which only the view itself can show. */
    showCollectionProperties: { ntxId: string | null | undefined; };
    /** Opens the properties dialog of a template note. */
    showTemplateProperties: { noteId: string; };
    tabReorder: {
        ntxIdsInOrder: string[];
    };
    tabPinStateChanged: {
        ntxId: string | null;
        pinned: boolean;
    };
    refreshNoteList: {
        noteId: string;
    };
    noteTypeMimeChanged: { noteId: string };
    zenModeChanged: { isEnabled: boolean };
    activeNoteChanged: {ntxId: string | null | undefined};
    showEditLinkDialog: EditLinkOpts;
    showContentEmbedDialog: ContentEmbedOpts;
    openBulkActionsDialog: {
        selectedOrActiveNoteIds: string[];
    };
    cloneNoteIdsTo: {
        noteIds: string[];
    };
    refreshData: { ntxId: string | null | undefined };
};

export type EventListener<T extends EventNames> = {
    [key in T as `${key}Event`]: (data: EventData<T>) => void;
};

export type CommandListener<T extends CommandNames> = {
    [key in T as `${key}Command`]: (data: CommandListenerData<T>) => void;
};

export type CommandListenerData<T extends CommandNames> = CommandMappings[T];

type CommandAndEventMappings = CommandMappings & EventMappings;
type EventOnlyNames = keyof EventMappings;
export type EventNames = CommandNames | EventOnlyNames;
export type EventData<T extends EventNames> = CommandAndEventMappings[T];

/**
 * This type is a discriminated union which contains all the possible commands that can be triggered via {@link AppContext.triggerCommand}.
 */
export type CommandNames = keyof CommandMappings;

type FilterByValueType<T, ValueType> = { [K in keyof T]: T[K] extends ValueType ? K : never }[keyof T];

/**
 * Generic which filters {@link CommandNames} to provide only those commands that take in as data the desired implementation of {@link CommandData}. Mostly useful for contextual menu, to enforce consistency in the commands.
 */
export type FilteredCommandNames<T extends CommandData> = keyof Pick<CommandMappings, FilterByValueType<CommandMappings, T>>;

export class AppContext extends Component {
    isMainWindow: boolean;
    components: Component[];
    beforeUnloadListeners: (WeakRef<BeforeUploadListener> | (() => boolean))[];
    tabManager!: TabManager;
    layout?: Layout;
    noteTreeWidget?: NoteTreeWidget;

    lastSearchString?: string;

    constructor(isMainWindow: boolean) {
        super();

        this.isMainWindow = isMainWindow;
        // non-widget/layout components needed for the application
        this.components = [];
        this.beforeUnloadListeners = [];
    }

    /**
     * Must be called as soon as possible, before the creation of any components since this method is in charge of initializing the locale. Any attempts to read translation before this method is called will result in `undefined`.
     */
    async earlyInit() {
        await options.initializedPromise;
        await initLocale((options.get("locale") || "en") as LOCALE_IDS);
    }

    setLayout(layout: Layout) {
        this.layout = layout;
    }

    async start() {
        this.initComponents();
        this.renderWidgets();

        reportSplashPhase("notes");
        await froca.initializedPromise;

        this.tabManager.loadTabs();

        setTimeout(() => bundleService.executeStartupBundles(), 2000);
    }

    initComponents() {
        this.tabManager = new TabManager();

        this.components = [
            this.tabManager,
            new RootCommandExecutor(),
            new Entrypoints(),
            new MainTreeExecutors(),
            new ShortcutComponent(),
            new StartupChecks()
        ];

        if (utils.isMobile()) {
            this.components.push(new MobileScreenSwitcherExecutor());
        }

        for (const component of this.components) {
            this.child(component);
        }

        if (utils.isElectron()) {
            this.child(zoomComponent);
        }

        void keyboardActionsService.setupWindowShortcuts();
    }

    renderWidgets() {
        if (!this.layout) {
            throw new Error("Missing layout.");
        }

        const rootWidget = this.layout.getRootWidget(this);
        const $renderedWidget = rootWidget.render();

        keyboardActionsService.updateDisplayedShortcuts($renderedWidget);

        $("body").append($renderedWidget);

        $renderedWidget.on("click", "[data-trigger-command]", function () {
            if ($(this).hasClass("disabled")) {
                return;
            }

            const commandName = $(this).attr("data-trigger-command");
            const $component = $(this).closest(".component");
            const component = $component.prop("component");

            component.triggerCommand(commandName, { $el: $(this) });
        });

        this.child(rootWidget as Component);

        this.triggerEvent("initialRenderComplete", {});
    }

    triggerEvent<K extends EventNames>(name: K, data: EventData<K>) {
        return this.handleEvent(name, data);
    }

    triggerCommand<K extends CommandNames>(name: K, _data?: CommandMappings[K]) {
        const data = _data || {};
        for (const executor of this.components) {
            const fun = (executor as any)[`${name}Command`];

            if (fun) {
                return executor.callMethod(fun, data);
            }
        }

        // this might hint at error, but sometimes this is used by components which are at different places
        // in the component tree to communicate with each other
        console.debug(`Unhandled command ${name}, converting to event.`);

        return this.triggerEvent(name, data as CommandAndEventMappings[K]);
    }

    getComponentByEl(el: HTMLElement) {
        return $(el).closest("[data-component-id]").prop("component");
    }

    addBeforeUnloadListener(obj: BeforeUploadListener | (() => boolean)) {
        if (typeof WeakRef !== "function") {
            // older browsers don't support WeakRef
            return;
        }

        if (typeof obj === "object") {
            this.beforeUnloadListeners.push(new WeakRef<BeforeUploadListener>(obj));
        } else {
            this.beforeUnloadListeners.push(obj);
        }
    }

    removeBeforeUnloadListener(listener: (() => boolean)) {
        this.beforeUnloadListeners = this.beforeUnloadListeners.filter(l => l !== listener);
    }
}

const appContext = reuseAcrossHotReloads(import.meta.hot, () => {
    const context = new AppContext(window.glob.isMainWindow);
    registerWindowHandlers(context);
    return context;
});

export default appContext;

function registerWindowHandlers(appContext: AppContext) {
    // we should save all outstanding changes before the page/app is closed
    $(window).on("beforeunload", () => {
        let allSaved = true;

        appContext.beforeUnloadListeners = appContext.beforeUnloadListeners.filter((wr) => typeof wr === "function" || !!wr.deref());

        for (const listener of appContext.beforeUnloadListeners) {
            if (typeof listener === "object") {
                const component = listener.deref();

                if (!component) {
                    continue;
                }

                if (!component.beforeUnloadEvent()) {
                    console.log(`Component ${component.componentId} is not finished saving its state.`);
                    allSaved = false;
                }
            } else if (!listener()) {
                allSaved = false;
            }
        }

        if (!allSaved) {
            toast.showMessage(t("app_context.please_wait_for_save"), 10000);
            return "some string";
        }
    });

    $(window).on("hashchange", () => {
        const { notePath, ntxId, viewScope, searchString } = linkService.parseNavigationStateFromUrl(window.location.href);

        if (notePath || ntxId) {
            appContext.tabManager.switchToHistoryEntry(ntxId, notePath, viewScope);
        } else if (searchString) {
            appContext.triggerCommand("searchNotes", { searchString });
        }
    });
}