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
feat(spellcheck): basic logic to save words
Elian Doranad9707186280
diff --git a/apps/server/src/services/custom_dictionary.spec.ts b/apps/server/src/services/custom_dictionary.spec.tsnew file mode 100644index 0000000000..56b54bad2b--- /dev/null+++ b/apps/server/src/services/custom_dictionary.spec.ts@@ -0,0 +1,114 @@+import { describe, it, expect, vi, beforeEach } from "vitest";++vi.mock("./log.js", () => ({+ default: {+ info: vi.fn(),+ error: vi.fn()+ }+}));++const mockNote = {+ getContent: vi.fn(),+ setContent: vi.fn()+};++vi.mock("../becca/becca.js", () => ({+ default: {+ getNote: vi.fn()+ }+}));++import becca from "../becca/becca.js";+import customDictionary from "./custom_dictionary.js";++function mockSession(localWords: string[] = []) {+ return {+ listWordsInSpellCheckerDictionary: vi.fn().mockResolvedValue(localWords),+ addWordToSpellCheckerDictionary: vi.fn()+ } as any;+}++describe("custom_dictionary", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(becca.getNote).mockReturnValue(mockNote as any);+ });++ describe("loadForSession", () => {+ it("does nothing when note is empty and no local words", async () => {+ mockNote.getContent.mockReturnValue("");+ const session = mockSession();++ await customDictionary.loadForSession(session);++ expect(session.addWordToSpellCheckerDictionary).not.toHaveBeenCalled();+ expect(mockNote.setContent).not.toHaveBeenCalled();+ });++ it("imports local words when note is empty (one-time import)", async () => {+ mockNote.getContent.mockReturnValue("");+ const session = mockSession(["hello", "world"]);++ await customDictionary.loadForSession(session);++ expect(mockNote.setContent).toHaveBeenCalledWith("hello\nworld");+ expect(session.addWordToSpellCheckerDictionary).toHaveBeenCalledTimes(2);+ expect(session.addWordToSpellCheckerDictionary).toHaveBeenCalledWith("hello");+ expect(session.addWordToSpellCheckerDictionary).toHaveBeenCalledWith("world");+ });++ it("loads note words into session when no local words exist", async () => {+ mockNote.getContent.mockReturnValue("apple\nbanana");+ const session = mockSession();++ await customDictionary.loadForSession(session);++ expect(mockNote.setContent).not.toHaveBeenCalled();+ expect(session.addWordToSpellCheckerDictionary).toHaveBeenCalledTimes(2);+ expect(session.addWordToSpellCheckerDictionary).toHaveBeenCalledWith("apple");+ expect(session.addWordToSpellCheckerDictionary).toHaveBeenCalledWith("banana");+ });++ it("merges note and local words when both have content", async () => {+ mockNote.getContent.mockReturnValue("apple\nbanana");+ const session = mockSession(["banana", "cherry"]);++ await customDictionary.loadForSession(session);++ // Should save the merged set (apple + banana + cherry), sorted+ expect(mockNote.setContent).toHaveBeenCalledWith("apple\nbanana\ncherry");+ expect(session.addWordToSpellCheckerDictionary).toHaveBeenCalledTimes(3);+ });++ it("does not save when local words are a subset of note words", async () => {+ mockNote.getContent.mockReturnValue("apple\nbanana\ncherry");+ const session = mockSession(["apple", "banana"]);++ await customDictionary.loadForSession(session);++ expect(mockNote.setContent).not.toHaveBeenCalled();+ expect(session.addWordToSpellCheckerDictionary).toHaveBeenCalledTimes(3);+ });++ it("handles note with whitespace and blank lines", async () => {+ mockNote.getContent.mockReturnValue(" apple \n\n banana \n\n");+ const session = mockSession();++ await customDictionary.loadForSession(session);++ expect(session.addWordToSpellCheckerDictionary).toHaveBeenCalledTimes(2);+ expect(session.addWordToSpellCheckerDictionary).toHaveBeenCalledWith("apple");+ expect(session.addWordToSpellCheckerDictionary).toHaveBeenCalledWith("banana");+ });++ it("handles missing dictionary note gracefully", async () => {+ vi.mocked(becca.getNote).mockReturnValue(null as any);+ const session = mockSession(["hello"]);++ await customDictionary.loadForSession(session);++ // Can't save, but shouldn't crash+ expect(session.addWordToSpellCheckerDictionary).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/services/custom_dictionary.ts b/apps/server/src/services/custom_dictionary.tsnew file mode 100644index 0000000000..1b48b2210d--- /dev/null+++ b/apps/server/src/services/custom_dictionary.ts@@ -0,0 +1,100 @@+import type { Session } from "electron";++import becca from "../becca/becca.js";+import log from "./log.js";++const DICTIONARY_NOTE_ID = "_customDictionary";++/**+ * Reads the custom dictionary words from the hidden note.+ */+function getWords(): Set<string> {+ const note = becca.getNote(DICTIONARY_NOTE_ID);+ if (!note) {+ return new Set();+ }++ const content = note.getContent();+ if (typeof content !== "string" || !content.trim()) {+ return new Set();+ }++ return new Set(+ content.split("\n")+ .map((w) => w.trim())+ .filter((w) => w.length > 0)+ );+}++/**+ * Saves the given words to the custom dictionary note, one per line.+ */+function saveWords(words: Set<string>) {+ const note = becca.getNote(DICTIONARY_NOTE_ID);+ if (!note) {+ log.error("Custom dictionary note not found.");+ return;+ }++ const sorted = [...words].sort((a, b) => a.localeCompare(b));+ note.setContent(sorted.join("\n"));+}++/**+ * Adds a single word to the custom dictionary note.+ */+function addWord(word: string) {+ const words = getWords();+ words.add(word);+ saveWords(words);+}++/**+ * 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) {+ const note = becca.getNote(DICTIONARY_NOTE_ID);+ if (!note) {+ log.error("Custom dictionary note not found.");+ return;+ }++ const noteWords = getWords();+ const localWords = await session.listWordsInSpellCheckerDictionary();++ let merged = noteWords;++ // One-time import: if the note is empty but there are local words, import them.+ if (noteWords.size === 0 && localWords.length > 0) {+ log.info(`Importing ${localWords.length} words from local spellchecker dictionary.`);+ merged = new Set(localWords);+ saveWords(merged);+ } else if (noteWords.size > 0 && localWords.length > 0) {+ // Merge both sources so no words are lost.+ const before = noteWords.size;+ for (const w of localWords) {+ merged.add(w);+ }+ if (merged.size > before) {+ log.info(`Merged ${merged.size - before} new words from local dictionary.`);+ saveWords(merged);+ }+ }++ // Load all words into Electron's spellchecker.+ for (const word of merged) {+ session.addWordToSpellCheckerDictionary(word);+ }++ if (merged.size > 0) {+ log.info(`Loaded ${merged.size} custom dictionary words into spellchecker.`);+ }+}++export default {+ getWords,+ saveWords,+ addWord,+ loadForSession+};diff --git a/apps/server/src/services/window.ts b/apps/server/src/services/window.tsindex c3af7620cb..350b39fa2a 100644--- a/apps/server/src/services/window.ts+++ b/apps/server/src/services/window.ts@@ -6,6 +6,7 @@ import url from "url";import app_info from "./app_info.js";import cls from "./cls.js";+import customDictionary from "./custom_dictionary.js";import keyboardActionsService from "./keyboard_actions.js";import log from "./log.js";import optionService from "./options.js";@@ -381,6 +382,7 @@ async function configureWebContents(webContents: WebContents, spellcheckEnabled:.map((code) => code.trim());webContents.session.setSpellCheckerLanguages(languageCodes);+ customDictionary.loadForSession(webContents.session);}}