Skip to content

Build your personal knowledge base with Trilium Notes

fix(client): keep appContext and froca across HMR updates

Elian Doran7fdb294906b0
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.ts
index b1ca8fb728..92560a549c 100644
--- a/apps/client/src/components/app_context.ts
+++ b/apps/client/src/components/app_context.ts
@@ -15,7 +15,7 @@ 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 from "../services/utils.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 { AddLinkOpts } from "../widgets/dialogs/add_link.jsx";
@@ -762,45 +762,51 @@ export class AppContext extends Component {
}
}
-const appContext = new AppContext(window.glob.isMainWindow);
+const appContext = reuseAcrossHotReloads(import.meta.hot, () => {
+ const context = new AppContext(window.glob.isMainWindow);
+ registerWindowHandlers(context);
+ return context;
+});
+
+export default appContext;
-// we should save all outstanding changes before the page/app is closed
-$(window).on("beforeunload", () => {
- let allSaved = true;
+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());
+ 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();
+ for (const listener of appContext.beforeUnloadListeners) {
+ if (typeof listener === "object") {
+ const component = listener.deref();
- if (!component) {
- continue;
- }
+ if (!component) {
+ continue;
+ }
- if (!component.beforeUnloadEvent()) {
- console.log(`Component ${component.componentId} is not finished saving its state.`);
+ if (!component.beforeUnloadEvent()) {
+ console.log(`Component ${component.componentId} is not finished saving its state.`);
+ allSaved = false;
+ }
+ } else if (!listener()) {
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 (!allSaved) {
+ toast.showMessage(t("app_context.please_wait_for_save"), 10000);
+ return "some string";
+ }
+ });
- if (notePath || ntxId) {
- appContext.tabManager.switchToNoteContext(ntxId, notePath, viewScope);
- } else if (searchString) {
- appContext.triggerCommand("searchNotes", { searchString });
- }
-});
+ $(window).on("hashchange", () => {
+ const { notePath, ntxId, viewScope, searchString } = linkService.parseNavigationStateFromUrl(window.location.href);
-export default appContext;
+ if (notePath || ntxId) {
+ appContext.tabManager.switchToNoteContext(ntxId, notePath, viewScope);
+ } else if (searchString) {
+ appContext.triggerCommand("searchNotes", { searchString });
+ }
+ });
+}
diff --git a/apps/client/src/services/froca.ts b/apps/client/src/services/froca.ts
index 8b3cd13be1..d39f524771 100644
--- a/apps/client/src/services/froca.ts
+++ b/apps/client/src/services/froca.ts
@@ -11,7 +11,7 @@ import FNote, { type FNoteRow } from "../entities/fnote.js";
import type { Bundle } from "./bundle.js";
import type { Froca, FrocaSource, NoteMapFilters, SavedAttachment, SubtreeResponse } from "./froca-interface.js";
import server from "./server.js";
-import { isPreAuthScreen } from "./utils.js";
+import { isPreAuthScreen, reuseAcrossHotReloads } from "./utils.js";
interface SearchNoteResponse {
@@ -495,6 +495,6 @@ const SERVER_SOURCE: FrocaSource = {
}
};
-const froca = new FrocaImpl();
+const froca = reuseAcrossHotReloads(import.meta.hot, () => new FrocaImpl());
export default froca;
diff --git a/apps/client/src/services/utils.spec.ts b/apps/client/src/services/utils.spec.ts
index c7393a4f41..b1f8ca4b06 100644
--- a/apps/client/src/services/utils.spec.ts
+++ b/apps/client/src/services/utils.spec.ts
@@ -1,3 +1,4 @@
+import type { ViteHotContext } from "vite/types/hot.js";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import utils, {
@@ -31,6 +32,7 @@ import utils, {
reloadFrontendApp,
replaceHtmlEscapedSlashes,
restartDesktopApp,
+ reuseAcrossHotReloads,
rootCauseMessage,
toggleBodyClass
} from "./utils.js";
@@ -1013,3 +1015,19 @@ describe("isPreAuthScreen", () => {
expect(isPreAuthScreen()).toBe(false);
});
});
+
+describe("reuseAcrossHotReloads", () => {
+ it("returns the stored instance on re-evaluation, and a fresh one without `hot.data`", () => {
+ const hot = { data: {} } as unknown as ViteHotContext;
+ const create = vi.fn(() => ({}));
+
+ const first = reuseAcrossHotReloads(hot, create);
+ expect(reuseAcrossHotReloads(hot, create)).toBe(first);
+ expect(create).toHaveBeenCalledTimes(1);
+
+ // Vitest's `import.meta.hot` stub has no `data`.
+ const stub = {} as unknown as ViteHotContext;
+ expect(reuseAcrossHotReloads(stub, create)).not.toBe(reuseAcrossHotReloads(stub, create));
+ expect(reuseAcrossHotReloads(undefined, create)).not.toBe(first);
+ });
+});
diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.ts
index 9dc34b3006..a9ce9240aa 100644
--- a/apps/client/src/services/utils.ts
+++ b/apps/client/src/services/utils.ts
@@ -1,4 +1,5 @@
import { dayjs, filterAttributeName, isValidAttributeName } from "@triliumnext/commons";
+import type { ViteHotContext } from "vite/types/hot.js";
import FNote from "../entities/fnote";
import { getNoteImageUrl } from "./image_urls.js";
@@ -959,6 +960,21 @@ export function* causeChain(e: unknown): Generator<unknown> {
}
}
+/**
+ * Returns the instance a previous evaluation of the calling module stored in `hot.data`, or
+ * creates and stores one. Pass `import.meta.hot` from a module that holds an app-wide
+ * singleton: an HMR update can import that module again under a new `?t=` URL, and without
+ * this the re-evaluated copy builds a second, uninitialized instance.
+ */
+export function reuseAcrossHotReloads<T>(hot: ViteHotContext | undefined, create: () => T): T {
+ const data = hot?.data as { instance?: T } | undefined;
+ if (!data) {
+ return create();
+ }
+ data.instance ??= create();
+ return data.instance;
+}
+
export function replaceHtmlEscapedSlashes(str: string) {
return str.replace(/&#x2F;/g, "/");
}