Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(client): ineffective dynamic imports
Elian Doran40e986b18894
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex d731f03382..1508ade084 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -5,6 +5,7 @@ import type { NativeImage, TouchBar } from "electron";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";@@ -578,7 +579,6 @@ export class AppContext extends Component {this.tabManager.loadTabs();- const bundleService = (await import("../services/bundle.js")).default;setTimeout(() => bundleService.executeStartupBundles(), 2000);}diff --git a/apps/client/src/entities/fnote.ts b/apps/client/src/entities/fnote.tsindex 12fd311bec..5fe7caf33c 100644--- a/apps/client/src/entities/fnote.ts+++ b/apps/client/src/entities/fnote.ts@@ -1,5 +1,6 @@import { getNoteIcon } from "@triliumnext/commons";+import bundleService from "../services/bundle.js";import cssClassManager from "../services/css_class_manager.js";import type { Froca } from "../services/froca-interface.js";import noteAttributeCache from "../services/note_attribute_cache.js";@@ -1014,7 +1015,6 @@ export default class FNote {const env = this.getScriptEnv();if (env === "frontend") {- const bundleService = (await import("../services/bundle.js")).default;return await bundleService.getAndExecuteBundle(this.noteId);} else if (env === "backend") {await server.post(`script/run/${this.noteId}`);diff --git a/apps/client/src/menus/electron_context_menu.ts b/apps/client/src/menus/electron_context_menu.tsindex 6baba6a951..547a26d3d8 100644--- a/apps/client/src/menus/electron_context_menu.ts+++ b/apps/client/src/menus/electron_context_menu.ts@@ -1,12 +1,14 @@-import utils from "../services/utils.js";-import options from "../services/options.js";+import type { BrowserWindow } from "electron";++import type { CommandNames } from "../components/app_context.js";+import appContext from "../components/app_context.js";import zoomService from "../components/zoom.js";-import contextMenu, { type MenuItem } from "./context_menu.js";+import * as clipboardExt from "../services/clipboard_ext.js";import { t } from "../services/i18n.js";+import options from "../services/options.js";import server from "../services/server.js";-import * as clipboardExt from "../services/clipboard_ext.js";-import type { BrowserWindow } from "electron";-import type { CommandNames, AppContext } from "../components/app_context.js";+import utils from "../services/utils.js";+import contextMenu, { type MenuItem } from "./context_menu.js";function setupContextMenu() {const electron = utils.dynamicRequire("electron");@@ -15,8 +17,6 @@ function setupContextMenu() {// FIXME: Remove typecast once Electron is properly integrated.const { webContents } = remote.getCurrentWindow() as BrowserWindow;- let appContext: AppContext;-webContents.on("context-menu", (event, params) => {const { editFlags } = params;const hasText = params.selectionText.trim().length > 0;@@ -141,7 +141,7 @@ function setupContextMenu() {}// Replace the placeholder with the real search keyword.- let searchUrl = searchEngineUrl.replace("{keyword}", encodeURIComponent(params.selectionText));+ const searchUrl = searchEngineUrl.replace("{keyword}", encodeURIComponent(params.selectionText));items.push({ kind: "separator" });@@ -155,10 +155,6 @@ function setupContextMenu() {title: t("electron_context_menu.search_in_trilium", { term: shortenedSelection }),uiIcon: "bx bx-search",handler: async () => {- if (!appContext) {- appContext = (await import("../components/app_context.js")).default;- }-await appContext.triggerCommand("searchNotes", {searchString: params.selectionText});diff --git a/apps/client/src/print.tsx b/apps/client/src/print.tsxindex dc7817d9b5..c943413c49 100644--- a/apps/client/src/print.tsx+++ b/apps/client/src/print.tsx@@ -4,6 +4,7 @@ import { useCallback, useLayoutEffect, useRef } from "preact/hooks";import FNote from "./entities/fnote";import content_renderer from "./services/content_renderer";import { applyInlineMermaid } from "./services/content_renderer_text";+import froca from "./services/froca";import { dynamicRequire, isElectron } from "./services/utils";import { CustomNoteList, useNoteViewType } from "./widgets/collections/NoteList";@@ -30,7 +31,6 @@ async function main() {if (!noteId) return;await import("./print.css");- const froca = (await import("./services/froca")).default;const note = await froca.getNote(noteId);const bodyWrapper = document.createElement("div");diff --git a/apps/client/src/services/bundle.ts b/apps/client/src/services/bundle.tsindex 7cee01812b..fdee38ba34 100644--- a/apps/client/src/services/bundle.ts+++ b/apps/client/src/services/bundle.ts@@ -26,7 +26,7 @@ type WithNoteId<T> = T & {};export type Widget = WithNoteId<(LegacyWidget | WidgetDefinitionWithType)>;-async function getAndExecuteBundle(noteId: string, originEntity = null, script = null, params = null) {+async function getAndExecuteBundle(noteId: string, originEntity: Entity | null = null, script: string | null = null, params: string | null = null) {const bundle = await server.post<Bundle>(`script/bundle/${noteId}`, {script,paramsdiff --git a/apps/client/src/services/clipboard_ext.ts b/apps/client/src/services/clipboard_ext.tsindex 9ab98af68f..16eea4ca49 100644--- a/apps/client/src/services/clipboard_ext.ts+++ b/apps/client/src/services/clipboard_ext.ts@@ -1,3 +1,6 @@+import { t } from "./i18n.js";+import toast from "./toast.js";+export function copyText(text: string) {if (!text) {return;@@ -6,29 +9,26 @@ export function copyText(text: string) {if (navigator.clipboard) {navigator.clipboard.writeText(text);return true;- } else {- // Fallback method: https://stackoverflow.com/a/72239825- const textArea = document.createElement("textarea");- textArea.value = text;- try {- document.body.appendChild(textArea);- textArea.focus();- textArea.select();- return document.execCommand('copy');- } finally {- document.body.removeChild(textArea);- }+ }+ // Fallback method: https://stackoverflow.com/a/72239825+ const textArea = document.createElement("textarea");+ textArea.value = text;+ try {+ document.body.appendChild(textArea);+ textArea.focus();+ textArea.select();+ return document.execCommand('copy');+ } finally {+ document.body.removeChild(textArea);}+} catch (e) {console.warn(e);return false;}}-export async function copyTextWithToast(text: string) {- const t = (await import("./i18n.js")).t;- const toast = (await import("./toast.js")).default;-+export function copyTextWithToast(text: string) {if (copyText(text)) {toast.showMessage(t("clipboard.copy_success"));} else {diff --git a/apps/client/src/services/dialog.ts b/apps/client/src/services/dialog.tsindex 8711ec1751..6888870fc9 100644--- a/apps/client/src/services/dialog.ts+++ b/apps/client/src/services/dialog.ts@@ -1,9 +1,11 @@import { Modal } from "bootstrap";+import appContext from "../components/app_context.js";import type { ConfirmDialogOptions, ConfirmDialogResult, ConfirmWithMessageOptions, MessageType } from "../widgets/dialogs/confirm.js";+import { InfoExtraProps } from "../widgets/dialogs/info.jsx";import type { PromptDialogOptions } from "../widgets/dialogs/prompt.js";import { focusSavedElement, saveFocusedElement } from "./focus.js";-import { InfoExtraProps } from "../widgets/dialogs/info.jsx";+import keyboardActionsService from "./keyboard_actions.js";export async function openDialog($dialog: JQuery<HTMLElement>, closeActDialog = true, config?: Partial<Modal.Options>) {if (closeActDialog) {@@ -25,7 +27,6 @@ export async function openDialog($dialog: JQuery<HTMLElement>, closeActDialog =}});- const keyboardActionsService = (await import("./keyboard_actions.js")).default;keyboardActionsService.updateDisplayedShortcuts($dialog);return $dialog;diff --git a/apps/client/src/services/froca_updater.ts b/apps/client/src/services/froca_updater.tsindex ca6c792746..8be1eceada 100644--- a/apps/client/src/services/froca_updater.ts+++ b/apps/client/src/services/froca_updater.ts@@ -1,14 +1,16 @@-import LoadResults from "./load_results.js";-import froca from "./froca.js";-import utils from "./utils.js";-import options from "./options.js";-import noteAttributeCache from "./note_attribute_cache.js";-import FBranch, { type FBranchRow } from "../entities/fbranch.js";-import FAttribute, { type FAttributeRow } from "../entities/fattribute.js";+import type { OptionNames } from "@triliumnext/commons";++import appContext from "../components/app_context.js";import FAttachment, { type FAttachmentRow } from "../entities/fattachment.js";+import FAttribute, { type FAttributeRow } from "../entities/fattribute.js";+import FBranch, { type FBranchRow } from "../entities/fbranch.js";import type { default as FNote, FNoteRow } from "../entities/fnote.js";import type { EntityChange } from "../server_types.js";-import type { OptionNames } from "@triliumnext/commons";+import froca from "./froca.js";+import LoadResults from "./load_results.js";+import noteAttributeCache from "./note_attribute_cache.js";+import options from "./options.js";+import utils from "./utils.js";async function processEntityChanges(entityChanges: EntityChange[]) {const loadResults = new LoadResults(entityChanges);@@ -63,7 +65,7 @@ async function processEntityChanges(entityChanges: EntityChange[]) {if (entityName === "branches" && !((entity as FBranchRow).parentNoteId in froca.notes)) {missingNoteIds.push((entity as FBranchRow).parentNoteId);} else if (entityName === "attributes") {- let attributeEntity = entity as FAttributeRow;+ const attributeEntity = entity as FAttributeRow;if (attributeEntity.type === "relation" && (attributeEntity.name === "template" || attributeEntity.name === "inherit") && !(attributeEntity.value in froca.notes)) {missingNoteIds.push(attributeEntity.value);}@@ -79,7 +81,6 @@ async function processEntityChanges(entityChanges: EntityChange[]) {noteAttributeCache.invalidate();}- const appContext = (await import("../components/app_context.js")).default;await appContext.triggerEvent("entitiesReloaded", { loadResults });}}diff --git a/apps/client/src/services/server.ts b/apps/client/src/services/server.tsindex 010b57cae1..1db7454182 100644--- a/apps/client/src/services/server.ts+++ b/apps/client/src/services/server.ts@@ -1,5 +1,8 @@+import { t } from "./i18n.js";+import toastService from "./toast.js";import utils, { isShare } from "./utils.js";import ValidationError from "./validation_error.js";+import { logError } from "./ws.js";type Headers = Record<string, string | null | undefined>;@@ -32,6 +35,7 @@ async function getHeaders(headers?: Headers) {return {};}+ // Dynamic import to avoid circular dependency (app_context imports froca which imports server).const appContext = (await import("../components/app_context.js")).default;const activeNoteContext = appContext.tabManager ? appContext.tabManager.getActiveContext() : null;@@ -344,8 +348,6 @@ async function reportError(method: string, url: string, statusCode: number, resp} catch (e) {}}- const toastService = (await import("./toast.js")).default;-const messageStr = (typeof message === "string" ? message : JSON.stringify(message)) || "-";if ([400, 404].includes(statusCode) && response && typeof response === "object") {@@ -357,7 +359,6 @@ async function reportError(method: string, url: string, statusCode: number, resp...response});} else {- const { t } = await import("./i18n.js");if (statusCode === 400 && (url.includes("%23") || url.includes("%2F"))) {toastService.showPersistent({id: "trafik-blocked",@@ -371,7 +372,6 @@ async function reportError(method: string, url: string, statusCode: number, respt("server.unknown_http_error_content", { statusCode, method, url, message: messageStr }),15_000);}- const { logError } = await import("./ws.js");logError(`${statusCode} ${method} ${url} - ${message}`);}}diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.tsindex 30b5e4eaf7..bcd817b6e2 100644--- a/apps/client/src/services/utils.ts+++ b/apps/client/src/services/utils.ts@@ -455,7 +455,7 @@ export function openInAppHelpFromUrl(inAppHelpPage: string) {export async function openInReusableSplit(targetNoteId: string, targetViewMode: ViewMode, openOpts: {hoistedNoteId?: string;} = {}) {- // Dynamic import to avoid import issues in tests.+ // Dynamic import to avoid circular dependency (app_context imports utils).const appContext = (await import("../components/app_context.js")).default;const activeContext = appContext.tabManager.getActiveContext();if (!activeContext) {diff --git a/apps/client/src/services/ws.ts b/apps/client/src/services/ws.tsindex 1002abe9f7..a68734a6c3 100644--- a/apps/client/src/services/ws.ts+++ b/apps/client/src/services/ws.ts@@ -1,13 +1,16 @@-import utils from "./utils.js";-import toastService from "./toast.js";-import server from "./server.js";-import options from "./options.js";-import frocaUpdater from "./froca_updater.js";+import { WebSocketMessage } from "@triliumnext/commons";+import appContext from "../components/app_context.js";-import { t } from "./i18n.js";import type { EntityChange } from "../server_types.js";-import { WebSocketMessage } from "@triliumnext/commons";+import bundleService from "./bundle.js";+import froca from "./froca.js";+import frocaUpdater from "./froca_updater.js";+import { t } from "./i18n.js";+import options from "./options.js";+import server from "./server.js";+import toastService from "./toast.js";import toast from "./toast.js";+import utils from "./utils.js";type MessageHandler = (message: WebSocketMessage) => void;let messageHandlers: MessageHandler[] = [];@@ -134,12 +137,6 @@ async function handleMessage(event: MessageEvent<any>) {} else if (message.type === "toast") {toastService.showMessage(message.message);} else if (message.type === "execute-script") {- // TODO: Remove after porting the file- // @ts-ignore- const bundleService = (await import("./bundle.js")).default as any;- // TODO: Remove after porting the file- // @ts-ignore- const froca = (await import("./froca.js")).default as any;const originEntity = message.originEntityId ? await froca.getNote(message.originEntityId) : null;bundleService.getAndExecuteBundle(message.currentNoteId, originEntity, message.script, message.params);@@ -161,7 +158,7 @@ function waitForEntityChangeId(desiredEntityChangeId: number) {return new Promise<void>((res, rej) => {entityChangeIdReachedListeners.push({- desiredEntityChangeId: desiredEntityChangeId,+ desiredEntityChangeId,resolvePromise: res,start: Date.now()});