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
fix(share): mark shared pages with their language and write the date in it
Elian Doran4d2d2f99acbd
diff --git a/apps/client/src/utils/formatters.ts b/apps/client/src/utils/formatters.tsindex eb06f930e3..7f2a55a133 100644--- a/apps/client/src/utils/formatters.ts+++ b/apps/client/src/utils/formatters.ts@@ -1,6 +1,8 @@-import { normalizeLocale } from "@triliumnext/commons";+import {+ isRightToLeftLanguage, normalizeLocale, resolveContentLanguage as resolveLanguage+} from "@triliumnext/commons";-import { getLocaleById, t } from "../services/i18n";+import { t } from "../services/i18n";import options from "../services/options";import type { MeasurementSystem } from "./units";@@ -198,12 +200,12 @@ function parseDate(date: string | Date | number): Date {* setting promises to affect — text direction, typographic quotes — actually follows it everywhere.*/export function resolveContentLanguage(noteLanguage: string | null | undefined): string | null {- return noteLanguage || options.get("defaultContentLanguage") || options.get("locale") || null;+ return resolveLanguage(noteLanguage, options.get("defaultContentLanguage"), options.get("locale"));}/** Whether a note's resolved language is written right-to-left. */export function isContentRightToLeft(noteLanguage: string | null | undefined): boolean {- return getLocaleById(resolveContentLanguage(noteLanguage))?.rtl ?? false;+ return isRightToLeftLanguage(resolveContentLanguage(noteLanguage));}/**diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.htmlindex 3076cb41f5..58630219ae 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html@@ -15,7 +15,11 @@ class="image"><li>Customizable logo.</li><li>Toggle button for dark/light mode, which also stores the user preferences.</li><li>Quick navigation buttons (previous and next note).</li>- <li>Displaying the date of the last update of the note.</li>+ <li>Displaying the date of the last update of the note, written out in the+ application's language.</li>+ <li>Marking the page with the application's language and its text direction,+ and the content of the note with its own <a href="#root/_help_veGu4faJErEM">content language</a>,+ for screen readers and right-to-left text.</li></ul><h3>By note type</h3><figure class="table">diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.htmlindex cae8d362f2..869cfdc650 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.html@@ -96,6 +96,19 @@<td>The pages before and after the note in the navigation tree, as <code>previous</code> and <code>next</code>,each with <code>title</code> and <code>href</code>, or <code>null</code>.</td></tr>+ <tr>+ <td><code>language</code>+ </td>+ <td>The languages of the page: <code>page</code> with the <code>lang</code> and <code>dir</code> of+ the application's language, and <code>content</code> with those of the note's+ content language, or <code>null</code> when they are the same.</td>+ </tr>+ <tr>+ <td><code>lastUpdated</code>+ </td>+ <td>When the note was last changed, as <code>iso</code> for a <code><time></code> element+ and as <code>text</code> in the application's language, or <code>null</code>.</td>+ </tr><tr><td><code>snippets</code></td>diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Content language & Right-to-left support.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Content language & Right-to-left support.htmlindex e6b24111fa..277e62a28c 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Content language & Right-to-left support.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Content language & Right-to-left support.html@@ -13,6 +13,9 @@set to <em>Based on note's content language</em>.</li><li>Which languages are offered by the <a class="reference-link" href="#root/_help_VRoP0g1uHHc2">In-editor AI assistant</a> fortranslation.</li>+ <li>The language and the text direction the content is marked with on a <a+ href="#root/_help_R9pX4DGra2Vt">shared page</a>, which screen readers and+ browsers follow.</li></ul><h2>Setting the language of a single note</h2><p>To set the language of the content of a <a class="reference-link"diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.mdindex cac46c7d2a..714efcc651 100644--- a/docs/User Guide/User Guide/Advanced Usage/Sharing.md+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing.md@@ -12,7 +12,8 @@ Trilium allows you to share selected notes as **publicly accessible** read-only* Customizable logo.* Toggle button for dark/light mode, which also stores the user preferences.* Quick navigation buttons (previous and next note).-* Displaying the date of the last update of the note.+* Displaying the date of the last update of the note, written out in the application's language.+* Marking the page with the application's language and its text direction, and the content of the note with its own [content language](../Note%20Types/Text/Content%20language%20%26%20Right-to-left%20support.md), for screen readers and right-to-left text.### By note typediff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.md b/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.mdindex a38c44a106..eb0beb2003 100644--- a/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.md+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.md@@ -35,6 +35,8 @@ Your template is rendered with a context object exposing the note and its render| `navigation` | The navigation tree of the site: its visible pages, each with `title`, `href`, `isExternal`, `type`, `icon`, `isActive` (the page being shown), `isExpanded` (that page or one of its ancestors) and `children`. || `childLinks` | The links to the note's visible children, each with `title`, `href`, `isExternal` and `type`. || `prevNext` | The pages before and after the note in the navigation tree, as `previous` and `next`, each with `title` and `href`, or `null`. |+| `language` | The languages of the page: `page` with the `lang` and `dir` of the application's language, and `content` with those of the note's content language, or `null` when they are the same. |+| `lastUpdated` | When the note was last changed, as `iso` for a `<time>` element and as `text` in the application's language, or `null`. || `snippets` | The HTML of the `~shareHtml` snippets for each location, such as `snippets["head:end"]`. Every location is present, empty when no snippet goes there. || `subRoot` | The root of the shared subtree as `{ note, branch }` — handy for a site-wide title or logo. || `cssToLoad` / `jsToLoad` | Arrays of stylesheet / script URLs the default theme would inject (includes anything added via `~shareCss` / `~shareJs`). |diff --git a/docs/User Guide/User Guide/Note Types/Text/Content language & Right-to-left support.md b/docs/User Guide/User Guide/Note Types/Text/Content language & Right-to-left support.mdindex c3d29e7ef3..4c181413e2 100644--- a/docs/User Guide/User Guide/Note Types/Text/Content language & Right-to-left support.md+++ b/docs/User Guide/User Guide/Note Types/Text/Content language & Right-to-left support.md@@ -7,6 +7,7 @@ The content language determines:* Whether the text is displayed from right-to-left, for languages such as Arabic, Hebrew, etc.* How typed quotes are [automatically replaced](Automatic%20replacements.md) (e.g. English uses `“text”`, whereas some languages use `«text»`). This applies only if <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Text_ → _Single/Double quotation marks_ is set to _Based on note's content language_.* Which languages are offered by the <a class="reference-link" href="In-editor%20AI%20assistant.md">In-editor AI assistant</a> for translation.+* The language and the text direction the content is marked with on a [shared page](../../Advanced%20Usage/Sharing.md), which screen readers and browsers follow.## Setting the language of a single notediff --git a/packages/commons/src/lib/i18n.spec.ts b/packages/commons/src/lib/i18n.spec.tsindex 14f643b9cc..b879b12ba2 100644--- a/packages/commons/src/lib/i18n.spec.ts+++ b/packages/commons/src/lib/i18n.spec.ts@@ -4,8 +4,11 @@ import {getEnglishName,getTesseractCode,isDisplayableLocale,+ isRightToLeftLanguage,LOCALES,- normalizeLocale+ normalizeLocale,+ resolveContentLanguage,+ toLanguageTag} from "./i18n.js";describe("getTesseractCode", () => {@@ -111,3 +114,32 @@ describe("normalizeLocale", () => {expect(normalizeLocale("en")).toBe("en");});});++describe("toLanguageTag", () => {+ it("turns a locale id into a canonical language tag", () => {+ expect([ "cn", "tw", "pt_br", "en-GB", "ar" ].map(toLanguageTag))+ .toStrictEqual([ "zh-CN", "zh-TW", "pt-BR", "en-GB", "ar" ]);+ });++ it("falls back to the language part, then to English, for an id that is no valid tag", () => {+ expect(toLanguageTag("en_rtl")).toBe("en");+ expect(toLanguageTag("!!")).toBe("en");+ expect(toLanguageTag("")).toBe("en");+ });+});++describe("resolveContentLanguage", () => {+ it("takes the note's language, then the default content language, then the display language", () => {+ expect(resolveContentLanguage("de", "fr", "en")).toBe("de");+ expect(resolveContentLanguage("", "fr", "en")).toBe("fr");+ expect(resolveContentLanguage(null, null, "en")).toBe("en");+ expect(resolveContentLanguage(undefined, "", null)).toBeNull();+ });+});++describe("isRightToLeftLanguage", () => {+ it("tells the languages written right to left", () => {+ expect([ "ar", "he", "en_rtl", "en", "fr", "unknown", null ].map(isRightToLeftLanguage))+ .toStrictEqual([ true, true, true, false, false, false, false ]);+ });+});diff --git a/packages/commons/src/lib/i18n.ts b/packages/commons/src/lib/i18n.tsindex 35b6e818c9..6992ba1e3f 100644--- a/packages/commons/src/lib/i18n.ts+++ b/packages/commons/src/lib/i18n.ts@@ -154,6 +154,42 @@ export function normalizeLocale(locale: string) {}}+/**+ * Turns a Trilium locale id into a canonical BCP 47 tag, for a `lang` attribute or `Intl`. An id+ * that gives no valid tag, such as `en_rtl`, falls back to its language part, then to `en`.+ */+export function toLanguageTag(localeId: string) {+ const tag = normalizeLocale(localeId);+ for (const candidate of [ tag, tag.split("-")[0] ]) {+ try {+ const [ canonical ] = Intl.getCanonicalLocales(candidate);+ if (canonical) {+ return canonical;+ }+ } catch {+ // `Intl` throws a RangeError on a malformed tag; the next candidate is tried.+ }+ }+ return "en";+}++/**+ * Returns the language of a note's content: its `#language` label, otherwise the+ * `defaultContentLanguage` option, otherwise the display language (the `locale` option).+ */+export function resolveContentLanguage(+ noteLanguage: string | null | undefined,+ defaultContentLanguage: string | null | undefined,+ displayLanguage: string | null | undefined+): string | null {+ return noteLanguage || defaultContentLanguage || displayLanguage || null;+}++/** Whether the language of the locale id is written right to left. */+export function isRightToLeftLanguage(localeId: string | null | undefined) {+ return LOCALES.find((locale) => locale.id === localeId)?.rtl ?? false;+}+/*** Locale ids that are not BCP-47 tags, mapped to one.*diff --git a/packages/share-theme/src/model/page.spec.ts b/packages/share-theme/src/model/page.spec.tsindex 289f68ab48..4aeb780af4 100644--- a/packages/share-theme/src/model/page.spec.ts+++ b/packages/share-theme/src/model/page.spec.ts@@ -1,8 +1,9 @@import { describe, expect, it } from "vitest";import {- getChildLinks, getHtmlSnippets, getNavigationTree, getPageHead, getPrevNextLinks, getShareLink, getSiteAncestorIds,- getSiteLogo, getTableOfContents, type NavigationItem, type PageHeading, type ShareNote+ getChildLinks, getHtmlSnippets, getLastUpdated, getNavigationTree, getPageHead, getPageLanguages,+ getPrevNextLinks, getShareLink, getSiteAncestorIds, getSiteLogo, getTableOfContents,+ type NavigationItem, type PageHeading, type ShareNote} from "./page.js";describe("getPageHead", () => {@@ -313,6 +314,41 @@ describe("getNavigationTree", () => {});});+describe("getPageLanguages", () => {+ const languages = (noteLanguage: string | null, displayLanguage: string, defaultContentLanguage?: string) =>+ getPageLanguages(+ fakeNote({ noteId: "page", labels: noteLanguage ? { language: noteLanguage } : {} }),+ { displayLanguage, defaultContentLanguage });++ it("gives the page the display language and its direction", () => {+ expect(languages(null, "pt_br").page).toStrictEqual({ lang: "pt-BR", dir: "ltr" });+ expect(languages(null, "ar").page).toStrictEqual({ lang: "ar", dir: "rtl" });+ expect(languages(null, "en_rtl").page).toStrictEqual({ lang: "en", dir: "rtl" });+ });++ it("gives the content its own language only where it differs from the page's", () => {+ expect(languages(null, "en").content).toBeNull();+ expect(languages("en", "en", "de").content).toBeNull();+ expect(languages(null, "en", "de").content).toStrictEqual({ lang: "de", dir: "ltr" });+ expect(languages("he", "en").content).toStrictEqual({ lang: "he", dir: "rtl" });+ });+});++describe("getLastUpdated", () => {+ it("gives the modification date as an ISO date and as text in the display language", () => {+ const modified = (utcDateModified?: string) => ({ ...fakeNote({ noteId: "page" }), utcDateModified });++ expect(getLastUpdated(modified("2026-10-09 12:00:00.000Z"), "en")).toStrictEqual({+ iso: "2026-10-09T12:00:00.000Z",+ text: "October 9, 2026"+ });+ expect(getLastUpdated(modified("2026-10-09 12:00:00.000Z"), "de")?.text).toBe("9. Oktober 2026");+ expect(getLastUpdated(modified("2026-10-09 12:00:00.000Z"), "en_rtl")?.text).toBe("October 9, 2026");+ expect(getLastUpdated(modified(undefined), "en")).toBeNull();+ expect(getLastUpdated(modified("never"), "en")).toBeNull();+ });+});+describe("getChildLinks", () => {it("links to the visible children of a note, in order", () => {const parent = fakeNote({ noteId: "parent" });diff --git a/packages/share-theme/src/model/page.ts b/packages/share-theme/src/model/page.tsindex 5aea21a5b6..76c968729e 100644--- a/packages/share-theme/src/model/page.ts+++ b/packages/share-theme/src/model/page.ts@@ -3,11 +3,17 @@* `~shareTemplate` templates receive them too.*/+import {+ isRightToLeftLanguage, resolveContentLanguage, toLanguageTag+} from "@triliumnext/commons/src/lib/i18n.js";+/** The parts of a note the page model reads; core's `SNote` and `BNote` both provide them. */export interface ShareNote {noteId: string;shareId: string;title: string;+ /** When the note was last changed, as Trilium stores it (`2026-10-09 12:00:00.000Z`). */+ utcDateModified?: string;getLabelValue(name: string): string | null | undefined;hasLabel(name: string): boolean;getRelationValue(name: string): string | null | undefined;@@ -154,6 +160,52 @@ function getMetaTags(title: string, description: string | null, openGraph: PageH(content ? [ { attribute, key, content } ] : []));}+/** A language and its writing direction, for the `lang` and `dir` attributes of an element. */+export interface PageLanguage {+ lang: string;+ dir: "ltr" | "rtl";+}++/** The languages Trilium is set to, as the `locale` and `defaultContentLanguage` options give them. */+export interface LanguageSettings {+ displayLanguage: string;+ defaultContentLanguage?: string | null;+}++/**+ * Returns the language of the page, which is the display language its own texts are translated+ * to, and the language of the note's content when it is another: the note's `#language`,+ * otherwise the default content language.+ */+export function getPageLanguages(note: ShareNote, settings: LanguageSettings) {+ const page = toPageLanguage(settings.displayLanguage);+ const content = toPageLanguage(resolveContentLanguage(note.getLabelValue("language"),+ settings.defaultContentLanguage, settings.displayLanguage) ?? settings.displayLanguage);+ return {+ page,+ content: content.lang === page.lang && content.dir === page.dir ? null : content+ };+}++function toPageLanguage(localeId: string): PageLanguage {+ return { lang: toLanguageTag(localeId), dir: isRightToLeftLanguage(localeId) ? "rtl" : "ltr" };+}++/**+ * Returns when `note` was last changed, as an ISO date for a `<time>` element and as a date+ * written out in the display language, or `null` when the note has no valid date.+ */+export function getLastUpdated(note: ShareNote, displayLanguage: string) {+ const date = new Date(note.utcDateModified ?? Number.NaN);+ if (Number.isNaN(date.getTime())) {+ return null;+ }+ return {+ iso: date.toISOString(),+ text: new Intl.DateTimeFormat(toLanguageTag(displayLanguage), { dateStyle: "long" }).format(date)+ };+}+/** Returns the trimmed value of the label, or `null` when it is missing or blank. */function readLabel(note: ShareNote, name: string) {return note.getLabelValue(name)?.trim() || null;diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejsindex 6e01a1d1f1..a86b7407fb 100644--- a/packages/share-theme/src/templates/page.ejs+++ b/packages/share-theme/src/templates/page.ejs@@ -1,5 +1,5 @@<!DOCTYPE html>-<html lang="en">+<html lang="<%= language.page.lang %>" dir="<%= language.page.dir %>"><head><% const hasTree = subRoot.note.hasVisibleChildren(); %><%- snippets["head:start"] %>@@ -73,7 +73,7 @@</div><div id="right-pane"><div id="main">- <div id="content" class="type-<%= note.type %><% if (note.type === "text" || (note.type === "code" && note.mime === "text/x-markdown")) { %> ck-content<% } %><% if (isEmpty) { %> no-content<% } %>" data-tab-title-placeholder="<%= t("share_theme.tab-title") %>">+ <div id="content" class="type-<%= note.type %><% if (note.type === "text" || (note.type === "code" && note.mime === "text/x-markdown")) { %> ck-content<% } %><% if (isEmpty) { %> no-content<% } %>"<% if (language.content) { %> lang="<%= language.content.lang %>" dir="<%= language.content.dir %>"<% } %> data-tab-title-placeholder="<%= t("share_theme.tab-title") %>"><%- snippets["content:start"] %><h1 id="title"><%= note.title %></h1><% if (isEmpty && (!note.hasVisibleChildren() && note.type !== "book")) { %>@@ -101,10 +101,9 @@<% } %><footer id="content-footer">- <% if (!isEmpty && !isStatic) { %>+ <% if (!isEmpty && !isStatic && lastUpdated) { %><div class="updated">- <% const lastUpdated = new Date(note.utcDateModified); %>- <%- t("share_theme.last-updated", { date: `<time datetime="${lastUpdated.toISOString()}">${lastUpdated.toLocaleDateString("en-US")}</time>`}) %>+ <%- t("share_theme.last-updated", { date: `<time datetime="${lastUpdated.iso}">${lastUpdated.text}</time>` }) %></div><% } %>diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 261d726afc..18d9290ae8 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -397,6 +397,29 @@ describe("content_renderer", () => {]));});+ it("declares the display language on the page and the note's own on its content", () => {+ const getOption = options.getOptionOrNull.bind(options);+ vi.spyOn(options, "getOptionOrNull").mockImplementation((name) =>+ (name === "locale" ? "de" : getOption(name)));+ const shareRootNote = buildShareNote({+ id: shareRoot.SHARE_ROOT_NOTE_ID,+ children: [ { "id": "hebrewPage", "content": "<p>שלום</p>", "#language": "he" } ]+ });++ const page = parse(String(renderNoteContent(shareRootNote.getChildNotes()[0])));+ vi.restoreAllMocks();++ const language = (selector: string) => [ "lang", "dir" ]+ .map((name) => page.querySelector(selector)?.getAttribute(name));+ expect(language("html")).toStrictEqual([ "de", "ltr" ]);+ expect(language("#content")).toStrictEqual([ "he", "rtl" ]);++ const time = page.querySelector(".updated time");+ expect(time).toBeTruthy();+ expect(time?.text).toBe(new Intl.DateTimeFormat("de", { dateStyle: "long" })+ .format(new Date(time?.getAttribute("datetime") ?? "")));+ });+it("keeps the alt text of an image on the page", () => {const shareRootNote = buildShareNote({id: shareRoot.SHARE_ROOT_NOTE_ID,@@ -1216,6 +1239,8 @@ describe("content_renderer", () => {prevNext: getPrevNextLinks(note, note),navigation: [],childLinks: getChildLinks(note, sanitize.sanitizeUrl),+ language: { page: { lang: "en", dir: "ltr" }, content: null },+ lastUpdated: null,headings: [],toc: []}, {diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 887baa744e..136360b051 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -8,8 +8,9 @@ import { renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons/src/limport { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";import { getLanguage, highlight, highlightAuto, syncMimeTypes } from "@triliumnext/highlightjs";import {- getChildLinks, getHtmlSnippets, getNavigationTree, getPageHead, getPrevNextLinks, getShareLink,- getSiteAncestorIds, getSiteLogo, getTableOfContents, type PageHeading+ getChildLinks, getHtmlSnippets, getLastUpdated, getNavigationTree, getPageHead, getPageLanguages,+ getPrevNextLinks, getShareLink, getSiteAncestorIds, getSiteLogo, getTableOfContents,+ type PageHeading} from "@triliumnext/share-theme/model/page";import ejs from "ejs";import escapeHtml from "escape-html";@@ -208,6 +209,7 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)});const showLoginInShareTheme = options.getOptionBool("showLoginInShareTheme");const siteRoot = renderArgs.subRoot.note ?? note;+ const displayLanguage = options.getOptionOrNull("locale") || "en";const opts = {note,header,@@ -229,6 +231,11 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)iconPackPrefixes: renderArgs.iconPackSupportedPrefixes}),childLinks: getChildLinks(note, sanitize.sanitizeUrl),+ language: getPageLanguages(note, {+ displayLanguage,+ defaultContentLanguage: options.getOptionOrNull("defaultContentLanguage")+ }),+ lastUpdated: getLastUpdated(note, displayLanguage),...renderArgs,};