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(desktop): move custom_dictionary from server
Elian Doranebaa5a94baf6
diff --git a/apps/desktop/spec/setup.ts b/apps/desktop/spec/setup.tsnew file mode 100644index 0000000000..f23bfe40a9--- /dev/null+++ b/apps/desktop/spec/setup.ts@@ -0,0 +1,4 @@+// Reuse the server's full core initialization for desktop spec files that+// touch becca / sql — replicating it would mean dragging the entire provider+// stack over for one test fixture.+import "../../server/spec/setup.js";diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 2a6e0afcaa..bad10c438c 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -24,6 +24,7 @@ import { PRODUCT_NAME } from "./app-info";import IpcMessagingProvider from "./ipc_messaging_provider";import DesktopPlatformProvider from "./platform_provider";import { registerTriliumAppScheme } from "./protocol";+import { setupCustomDictionary } from "./services/custom_dictionary";import { setupSystemTray } from "./services/tray";async function main() {@@ -91,6 +92,7 @@ async function main() {});setupSystemTray();+ setupCustomDictionary();app.on("will-quit", () => {globalShortcut.unregisterAll();diff --git a/apps/server/src/services/custom_dictionary.spec.ts b/apps/desktop/src/services/custom_dictionary.spec.tssimilarity index 92%rename from apps/server/src/services/custom_dictionary.spec.tsrename to apps/desktop/src/services/custom_dictionary.spec.tsindex 0cc3933e2b..e048c9dcfb 100644--- a/apps/server/src/services/custom_dictionary.spec.ts+++ b/apps/desktop/src/services/custom_dictionary.spec.ts@@ -1,26 +1,17 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import becca from "../becca/becca.js";-import { buildNote } from "../test/becca_easy_mocking.js";-import customDictionary from "./custom_dictionary.js";+import { becca, becca_easy_mocking } from "@triliumnext/core";+import { beforeEach, describe, expect, it, vi } from "vitest";-vi.mock("./log.js", () => ({+import * as customDictionary from "./custom_dictionary.js";++const { buildNote } = becca_easy_mocking;++vi.mock("@triliumnext/server/src/services/log.js", () => ({default: {info: vi.fn(),error: vi.fn()}}));-vi.mock("./sql.js", () => ({- default: {- transactional: (cb: Function) => cb(),- execute: () => {},- replace: () => {},- getMap: () => {},- getValue: () => null,- upsert: () => {}- }-}));-function mockSession(localWords: string[] = []) {return {listWordsInSpellCheckerDictionary: vi.fn().mockResolvedValue(localWords),diff --git a/apps/server/src/services/custom_dictionary.ts b/apps/desktop/src/services/custom_dictionary.tssimilarity index 65%rename from apps/server/src/services/custom_dictionary.tsrename to apps/desktop/src/services/custom_dictionary.tsindex 6182c9884e..03d8401a6b 100644--- a/apps/server/src/services/custom_dictionary.ts+++ b/apps/desktop/src/services/custom_dictionary.ts@@ -1,10 +1,9 @@-import type { Session } from "electron";--import becca from "../becca/becca.js";-import cls from "./cls.js";-import log from "./log.js";+import { becca, cls, options as optionService, sql_init } from "@triliumnext/core";+import log from "@triliumnext/server/src/services/log.js";+import electron, { type Session } from "electron";const DICTIONARY_NOTE_ID = "_customDictionary";+const loadedSessions = new WeakSet<Session>();/*** Reads the custom dictionary words from the hidden note.@@ -31,7 +30,7 @@ function getWords(): Set<string> {* Saves the given words to the custom dictionary note, one per line.*/function saveWords(words: Set<string>) {- cls.init(() => {+ cls.getContext().init(() => {const note = becca.getNote(DICTIONARY_NOTE_ID);if (!note) {log.error("Custom dictionary note not found.");@@ -67,7 +66,7 @@ function clearFromLocalDictionary(session: Session, localWords: string[]) {* Loads the custom dictionary into Electron's spellchecker session,* performing a one-time import of locally stored words on first use.*/-async function loadForSession(session: Session) {+export async function loadForSession(session: Session) {const note = becca.getNote(DICTIONARY_NOTE_ID);if (!note) {log.error("Custom dictionary note not found.");@@ -105,9 +104,30 @@ async function loadForSession(session: Session) {}}-export default {- getWords,- saveWords,- addWord,- loadForSession-};+/**+ * Arms the custom dictionary to sync into every spellcheck-enabled renderer+ * session as it comes online, and to persist words the user accepts via the+ * renderer's context menu.+ *+ * Skipping while the DB is uninitialised avoids touching options/becca during+ * the setup wizard. The per-session WeakSet guard plus the shared session for+ * print windows mean repeated `web-contents-created` events (extra windows,+ * print preview) don't re-sync.+ */+export function setupCustomDictionary() {+ electron.app.on("web-contents-created", (_event, webContents) => {+ if (!sql_init.isDbInitialized()) return;+ if (!optionService.getOptionBool("spellCheckEnabled")) return;+ const session = webContents.session;+ if (loadedSessions.has(session)) return;+ loadedSessions.add(session);+ loadForSession(session).catch(err =>+ log.error(`Failed to load custom dictionary for spellcheck: ${err}`)+ );+ });++ electron.ipcMain.on("add-word-to-dictionary", (event, word: string) => {+ event.sender.session.addWordToSpellCheckerDictionary(word);+ addWord(word);+ });+}diff --git a/apps/desktop/vitest.config.mts b/apps/desktop/vitest.config.mtsindex c7d99f2cd4..705d3d115e 100644--- a/apps/desktop/vitest.config.mts+++ b/apps/desktop/vitest.config.mts@@ -7,7 +7,16 @@ export default defineConfig(() => ({test: {watch: false,globals: true,+ setupFiles: ["./spec/setup.ts"],environment: "node",+ env: {+ // Server initialization touches RESOURCE_DIR / utils.isDev at+ // module-load time; setting these here (not inside spec/setup.ts)+ // ensures they're in place before static imports resolve.+ NODE_ENV: "development",+ TRILIUM_INTEGRATION_TEST: "memory",+ TRILIUM_ENV: "dev"+ },include: ["src/**/*.spec.ts"],reporters: ["verbose"]}diff --git a/apps/server/src/services/window.ts b/apps/server/src/services/window.tsindex b12c096930..e286aa7ec6 100644--- a/apps/server/src/services/window.ts+++ b/apps/server/src/services/window.ts@@ -5,7 +5,6 @@ import url from "url";import app_info from "./app_info.js";import cls from "./cls.js";-import customDictionary from "./custom_dictionary.js";import dataDirs from "./data_dir.js";import keyboardActionsService from "./keyboard_actions.js";import log from "./log.js";@@ -133,11 +132,6 @@ electron.ipcMain.on("toggle-all-windows", () => {}});-electron.ipcMain.on("add-word-to-dictionary", (event, word: string) => {- event.sender.session.addWordToSpellCheckerDictionary(word);- customDictionary.addWord(word);-});-electron.ipcMain.on("get-available-spellchecker-languages", (event) => {event.returnValue = event.sender.session.availableSpellCheckerLanguages;});@@ -483,8 +477,6 @@ function setupSpellcheckForSession(session: Session) {.map((code) => code.trim());session.setSpellCheckerLanguages(languageCodes);- customDictionary.loadForSession(session)- .catch(err => log.error(`Failed to load custom dictionary for spellcheck: ${err}`));}}