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(i18n): name the language in force where a note says it has none
Elian Doran9a01332be8dd
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex c9bf6de3bf..625204d903 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3106,6 +3106,7 @@},"note_language": {"not_set": "No language set",+ "not_set_with_default": "No language set — {{- language}}","configure-languages": "Configure languages...","help-on-languages": "Help on content languages..."},diff --git a/apps/client/src/widgets/layout/StatusBar.tsx b/apps/client/src/widgets/layout/StatusBar.tsxindex 8b6858b07a..15ad91c29a 100644--- a/apps/client/src/widgets/layout/StatusBar.tsx+++ b/apps/client/src/widgets/layout/StatusBar.tsx@@ -174,15 +174,15 @@ function useConnectionsToggle(expandWidgetId: string) {function LanguageSwitcher({ note }: StatusBarContext) {const [ modalShown, setModalShown ] = useState(false);const noteType = useNoteProperty(note, "type");- const { locales, DEFAULT_LOCALE, currentNoteLanguage, setCurrentNoteLanguage } = useLanguageSwitcher(note);- const { activeLocale, processedLocales } = useProcessedLocales(locales, DEFAULT_LOCALE, currentNoteLanguage ?? DEFAULT_LOCALE.id);+ const { locales, DEFAULT_LOCALE, effectiveLocale, currentNoteLanguage, setCurrentNoteLanguage } = useLanguageSwitcher(note);+ const { processedLocales } = useProcessedLocales(locales, DEFAULT_LOCALE, currentNoteLanguage ?? DEFAULT_LOCALE.id);return (<>{noteType === "text" && <StatusBarDropdownicon="bx bx-globe"title={t("status_bar.language_title")}- text={<span dir={activeLocale?.rtl ? "rtl" : "ltr"}>{getLocaleName(activeLocale)}</span>}+ text={<span dir={effectiveLocale?.rtl ? "rtl" : "ltr"}>{getLocaleName(effectiveLocale)}</span>}>{processedLocales.map((locale, index) =>(typeof locale === "object") ? (diff --git a/apps/client/src/widgets/mobile_widgets/mobile_detail_menu.tsx b/apps/client/src/widgets/mobile_widgets/mobile_detail_menu.tsxindex d8e48d3d93..1c8065e31e 100644--- a/apps/client/src/widgets/mobile_widgets/mobile_detail_menu.tsx+++ b/apps/client/src/widgets/mobile_widgets/mobile_detail_menu.tsx@@ -121,13 +121,13 @@ export default function MobileDetailMenu() {}function ContentLanguageSelector({ note }: { note: FNote | null | undefined }) {- const { locales, DEFAULT_LOCALE, currentNoteLanguage, setCurrentNoteLanguage } = useLanguageSwitcher(note);- const { activeLocale, processedLocales } = useProcessedLocales(locales, DEFAULT_LOCALE, currentNoteLanguage ?? DEFAULT_LOCALE.id);+ const { locales, DEFAULT_LOCALE, effectiveLocale, currentNoteLanguage, setCurrentNoteLanguage } = useLanguageSwitcher(note);+ const { processedLocales } = useProcessedLocales(locales, DEFAULT_LOCALE, currentNoteLanguage ?? DEFAULT_LOCALE.id);return (<FormDropdownSubmenuicon="bx bx-globe"- title={t("mobile_detail_menu.content_language_switcher", { language: getLocaleName(activeLocale ?? DEFAULT_LOCALE) })}+ title={t("mobile_detail_menu.content_language_switcher", { language: getLocaleName(effectiveLocale ?? DEFAULT_LOCALE) })}>{processedLocales.map((locale, index) =>(typeof locale === "object") ? (diff --git a/apps/client/src/widgets/ribbon/BasicPropertiesTab.tsx b/apps/client/src/widgets/ribbon/BasicPropertiesTab.tsxindex d82b5446db..54e073e89f 100644--- a/apps/client/src/widgets/ribbon/BasicPropertiesTab.tsx+++ b/apps/client/src/widgets/ribbon/BasicPropertiesTab.tsx@@ -8,7 +8,8 @@ import FNote from "../../entities/fnote";import branches from "../../services/branches";import dialog from "../../services/dialog";import { isExperimentalFeatureEnabled } from "../../services/experimental_features";-import { getAvailableLocales, t } from "../../services/i18n";+import { getAvailableLocales, getLocaleById, t } from "../../services/i18n";+import { resolveContentLanguage } from "../../utils/formatters";import mime_types from "../../services/mime_types";import { NOTE_TYPES } from "../../services/note_types";import protected_session from "../../services/protected_session";@@ -391,9 +392,29 @@ export function NoteLanguageSelector({ note }: { note: FNote | null | undefinedexport function useLanguageSwitcher(note: FNote | null | undefined) {const [ languages ] = useTriliumOption("languages");+ // Subscribed to for the re-render alone — the values are read below through+ // `resolveContentLanguage`, which goes to the options store directly. Without these, changing+ // the default in the settings would leave the picker naming a stale language until reopened.+ useTriliumOption("defaultContentLanguage");+ useTriliumOption("locale");++ /**+ * The locale a note without a `#language` of its own is actually written in.+ *+ * Not memoized: it is a lookup over a two-dozen-entry catalog, and `resolveContentLanguage`+ * reads the options directly — so the subscriptions above, not a dependency array, are what+ * make this follow a change to the setting.+ */+ const resolvedDefaultLocale = getLocaleById(resolveContentLanguage(null));++ // Naming the resolved language here is the point: the entry used to read "No language set",+ // which denied the existence of the default that was in fact deciding text direction and+ // quotation marks. The id stays empty — it is the sentinel that clears the label.const DEFAULT_LOCALE = {id: "",- name: t("note_language.not_set")+ name: resolvedDefaultLocale+ ? t("note_language.not_set_with_default", { language: resolvedDefaultLocale.name })+ : t("note_language.not_set")};const [ currentNoteLanguage, setCurrentNoteLanguage ] = useNoteLabel(note, "language");const locales = useMemo(() => {@@ -401,7 +422,18 @@ export function useLanguageSwitcher(note: FNote | null | undefined) {const filteredLanguages = getAvailableLocales().filter((l) => typeof l !== "object" || enabledLanguages.includes(l.id));return filteredLanguages;}, [ languages ]);- return { locales, DEFAULT_LOCALE, currentNoteLanguage, setCurrentNoteLanguage };++ /**+ * The locale the note is actually written in — its own if it has one, the default otherwise.+ * What the compact displays (the status bar badge, the mobile submenu title) name, so that a+ * note without a `#language` reads as the language in force rather than as a bare dash.+ */+ const effectiveLocale = useMemo(+ () => (currentNoteLanguage ? getLocaleById(currentNoteLanguage) : resolvedDefaultLocale),+ [ currentNoteLanguage, resolvedDefaultLocale ]+ );++ return { locales, DEFAULT_LOCALE, resolvedDefaultLocale, effectiveLocale, currentNoteLanguage, setCurrentNoteLanguage };}export function ContentLanguagesModal({ modalShown, setModalShown }: { modalShown: boolean, setModalShown: (shown: boolean) => void }) {diff --git a/apps/client/src/widgets/ribbon/useLanguageSwitcher.spec.tsx b/apps/client/src/widgets/ribbon/useLanguageSwitcher.spec.tsxnew file mode 100644index 0000000000..352cae36fd--- /dev/null+++ b/apps/client/src/widgets/ribbon/useLanguageSwitcher.spec.tsx@@ -0,0 +1,105 @@+import { render } from "preact";+import { afterEach, describe, expect, it, vi } from "vitest";++/** The note's `#language`, which has no options entry to drive it through. */+const state = vi.hoisted(() => ({ noteLanguage: null as string | null }));++// The real hooks module pulls in app_context and the keyboard actions at module scope. Only the two+// readers the switcher uses matter here, so stub the module rather than boot half the app.+//+// `useTriliumOption` reads the real options store rather than a map of its own: `resolveContentLanguage`+// reads that store directly, and a separate fixture would let the two disagree — which is exactly the+// bug this suite would then fail to catch.+vi.mock("../react/hooks", async () => {+ const options = (await import("../../services/options")).default;+ type OptionNames = Parameters<typeof options.get>[0];+ return {+ useTriliumOption: (name: OptionNames) => [ options.get(name), vi.fn() ],+ useNoteLabel: () => [ state.noteLanguage, vi.fn() ],+ useNoteLabelBoolean: () => [ false, vi.fn() ],+ useNoteProperty: () => undefined,+ useTriliumEvent: () => {}+ };+});++// t() echoes the key with its interpolation, so assertions can name the resolved language without+// depending on the English wording.+vi.mock("../../services/i18n", async () => {+ const { LOCALES } = await import("@triliumnext/commons");+ return {+ t: (key: string, opts?: { language?: string }) => (opts?.language ? `${key}|${opts.language}` : key),+ getAvailableLocales: () => LOCALES,+ getLocaleById: (id: string | null | undefined) => LOCALES.find((l) => l.id === id) ?? null+ };+});++import options from "../../services/options";+import { useLanguageSwitcher } from "./BasicPropertiesTab";++type Switcher = ReturnType<typeof useLanguageSwitcher>;++/** Renders the hook and hands back what it returned. */+function runHook(): Switcher {+ let result: Switcher | undefined;+ function Probe() {+ result = useLanguageSwitcher(null);+ return null;+ }++ const container = document.createElement("div");+ render(<Probe />, container);+ render(null, container);++ if (!result) throw new Error("the hook did not run");+ return result;+}++afterEach(() => {+ state.noteLanguage = null;+ options.set("defaultContentLanguage", "");+ options.set("locale", "");+});++describe("useLanguageSwitcher", () => {+ it("names the resolved default in the entry that used to just say 'no language set'", () => {+ options.set("defaultContentLanguage", "de");++ // The interpolated name is the point: the entry has to say *which* language is in force.+ expect(runHook().DEFAULT_LOCALE.name).toBe("note_language.not_set_with_default|Deutsch");+ });++ it("follows the application's language when the default is the empty 'auto' entry", () => {+ options.set("defaultContentLanguage", "");+ options.set("locale", "fr");++ expect(runHook().DEFAULT_LOCALE.name).toBe("note_language.not_set_with_default|Français");+ });++ it("falls back to the bare wording when nothing resolves", () => {+ expect(runHook().DEFAULT_LOCALE.name).toBe("note_language.not_set");+ });++ it("keeps the empty id, which is the sentinel that clears the label", () => {+ options.set("defaultContentLanguage", "de");++ expect(runHook().DEFAULT_LOCALE.id).toBe("");+ });++ it("reports the effective locale as the note's own when it has one, else the default", () => {+ options.set("defaultContentLanguage", "de");++ // No `#language`: the note is written in the default.+ expect(runHook().effectiveLocale?.id).toBe("de");++ // An explicit language wins, and is not dragged to the default.+ state.noteLanguage = "fr";+ expect(runHook().effectiveLocale?.id).toBe("fr");+ });++ it("reports no effective locale for a language outside the catalog", () => {+ state.noteLanguage = "not-a-locale";++ // Better to render nothing than to claim the note is in the default language.+ expect(runHook().effectiveLocale).toBeNull();+ });+});