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
client/text editor/tables: add support for sorting tables
Adorian Doranebec338cde06
diff --git a/apps/client/src/menus/note_context_menu.spec.ts b/apps/client/src/menus/note_context_menu.spec.tsindex 469722d269..1f94f11490 100644--- a/apps/client/src/menus/note_context_menu.spec.ts+++ b/apps/client/src/menus/note_context_menu.spec.ts@@ -222,6 +222,7 @@ describe("buildNoteContextMenuItems", () => {const cell = document.createElement("td");vi.mocked(buildTableContextMenuSections).mockResolvedValueOnce({main: [ { title: "T1" }, { kind: "separator" }, { title: "T2" } ],+ sort: { title: "S" },delete: [ { title: "D1" }, { title: "D2" } ]} as TableMenuSections);const host = browserLikeHost({@@ -242,6 +243,8 @@ describe("buildNoteContextMenuItems", () => {"electron_context_menu.paste","electron_context_menu.paste-as-plain-text","---",+ "S",+ "---","D1","D2","---",@@ -274,6 +277,7 @@ describe("buildNoteContextMenuItems", () => {const cell = document.createElement("td");vi.mocked(buildTableContextMenuSections).mockResolvedValue({main: [ { title: "T1" } ],+ sort: { title: "S" },delete: []} as TableMenuSections);@@ -297,6 +301,7 @@ describe("buildNoteContextMenuItems", () => {const cell = document.createElement("td");vi.mocked(buildTableContextMenuSections).mockResolvedValueOnce({main: [ { title: "T1" } ],+ sort: { title: "S" },delete: []} as TableMenuSections);vi.mocked(hasTableCellSelection).mockResolvedValueOnce(true);@@ -387,6 +392,7 @@ describe("setupContextMenu (browser)", () => {setSelection(null, "", "");vi.mocked(buildTableContextMenuSections).mockResolvedValueOnce({main: [ { title: "table_context_menu.merge_cells" } ],+ sort: { title: "S" },delete: []} as TableMenuSections);diff --git a/apps/client/src/menus/note_context_menu.ts b/apps/client/src/menus/note_context_menu.tsindex 36b5196bfd..83eab2e9dc 100644--- a/apps/client/src/menus/note_context_menu.ts+++ b/apps/client/src/menus/note_context_menu.ts@@ -225,7 +225,8 @@ export async function buildNoteContextMenuItems(}if (tableSections) {- items.push({ kind: "separator" }, ...tableSections.delete);+ items.push({ kind: "separator" }, tableSections.sort, { kind: "separator" },+ ...tableSections.delete);}if (hasText) {diff --git a/apps/client/src/menus/table_context_menu.spec.ts b/apps/client/src/menus/table_context_menu.spec.tsindex 5d4f919f9f..7053e344e3 100644--- a/apps/client/src/menus/table_context_menu.spec.ts+++ b/apps/client/src/menus/table_context_menu.spec.ts@@ -26,6 +26,11 @@ const MAIN_TITLES = ["table_context_menu.distribute_columns"];+const SORT_TITLES = [+ "table_context_menu.sort_ascending",+ "table_context_menu.sort_descending"+];+const DELETE_TITLES = ["table_context_menu.delete_rows","table_context_menu.delete_columns",@@ -42,6 +47,8 @@ describe("buildTableMenuSections", () => {expect(syncSelectionToDomTarget).toHaveBeenCalledWith(element);expect(titles(sections?.main ?? [])).toEqual(MAIN_TITLES);expect(titles(sections?.delete ?? [])).toEqual(DELETE_TITLES);+ expect(titles(sections ? [sections.sort] : [])).toEqual(["table_context_menu.sort"]);+ expect(titles(sortSubmenu(sections))).toEqual(SORT_TITLES);const splitRow = findItem(sections?.main ?? [], "table_context_menu.split_cells");const submenu = splitRow?.items ?? [];@@ -55,7 +62,8 @@ describe("buildTableMenuSections", () => {it("executes the mapped command and refocuses the editor", () => {const { editor, executed, focus } = stubEditor();- const items = allItems(buildTableMenuSections(editor, cellElement()));+ const sections = buildTableMenuSections(editor, cellElement());+ const items = allItems(sections);const submenu = findItem(items, "table_context_menu.split_cells")?.items ?? [];for (const title of titles(items).filter((t) => t !== "---")) {@@ -64,6 +72,9 @@ describe("buildTableMenuSections", () => {run(submenu, "table_context_menu.split_vertically");run(submenu, "table_context_menu.split_horizontally");run(submenu, "table_context_menu.split_reset");+ for (const title of SORT_TITLES) {+ run(sortSubmenu(sections), title);+ }expect(executed).toEqual(["triliumInsertTableRowsAbove",@@ -77,7 +88,9 @@ describe("buildTableMenuSections", () => {"triliumDeleteTable","splitTableCellVertically","splitTableCellHorizontally",- "triliumResetTableCellSpans"+ "triliumResetTableCellSpans",+ "triliumSortTableRowsAscending",+ "triliumSortTableRowsDescending"]);expect(focus).toHaveBeenCalledTimes(executed.length);});@@ -118,6 +131,24 @@ describe("buildTableMenuSections", () => {expect(splitRow(SPLIT_COMMANDS)).toBe(false);});+ it("enables the sort submenu while either direction is enabled", () => {+ const SORT_COMMANDS = ["triliumSortTableRowsAscending", "triliumSortTableRowsDescending"];+ const sortRow = (disabled: string[]) => {+ const { editor } = stubEditor(disabled);+ const sections = buildTableMenuSections(editor, cellElement());+ return (sections?.sort as MenuCommandItem<any> | undefined)?.enabled;+ };++ expect(sortRow([])).toBe(true);+ expect(sortRow([SORT_COMMANDS[0]])).toBe(true);+ expect(sortRow(SORT_COMMANDS)).toBe(false);++ const { editor } = stubEditor([SORT_COMMANDS[1]]);+ const submenu = sortSubmenu(buildTableMenuSections(editor, cellElement()));+ expect(findItem(submenu, SORT_TITLES[0])?.enabled).toBe(true);+ expect(findItem(submenu, SORT_TITLES[1])?.enabled).toBe(false);+ });+it("returns null without the plugin or a table cell at the target", () => {const { editor: withoutPlugin } = stubEditor([], { hasPlugin: false });expect(buildTableMenuSections(withoutPlugin, cellElement())).toBeNull();@@ -233,6 +264,10 @@ function allItems(sections: TableMenuSections | null) {return [...(sections?.main ?? []), ...(sections?.delete ?? [])];}+function sortSubmenu(sections: TableMenuSections | null): MenuItem<any>[] {+ return (sections?.sort as MenuCommandItem<any> | undefined)?.items ?? [];+}+/** The titles of `items`, with separators rendered as "---" so ordering stays readable. */function titles(items: MenuItem<any>[]) {return items.map((item) => ("kind" in item && item.kind === "separator"diff --git a/apps/client/src/menus/table_context_menu.ts b/apps/client/src/menus/table_context_menu.tsindex c0cd05887c..15aee4bff8 100644--- a/apps/client/src/menus/table_context_menu.ts+++ b/apps/client/src/menus/table_context_menu.ts@@ -53,6 +53,12 @@ export function buildTableMenuSections(];const unmergeItem = commandItem(t("table_context_menu.split_reset"), "bx bx-reset","triliumResetTableCellSpans");+ const sortItems = [+ commandItem(t("table_context_menu.sort_ascending"), "bx bx-sort-a-z",+ "triliumSortTableRowsAscending"),+ commandItem(t("table_context_menu.sort_descending"), "bx bx-sort-z-a",+ "triliumSortTableRowsDescending")+ ];return {main: [@@ -77,6 +83,12 @@ export function buildTableMenuSections(commandItem(t("table_context_menu.distribute_columns"), "bx bx-move-horizontal","triliumDistributeTableColumns")],+ sort: {+ title: t("table_context_menu.sort"),+ uiIcon: "bx bx-sort",+ enabled: sortItems.some((item) => item.enabled),+ items: sortItems+ },delete: [commandItem(t("table_context_menu.delete_rows"), "bx bx-trash", "removeTableRow"),commandItem(t("table_context_menu.delete_columns"), "bx bx-trash",@@ -93,6 +105,8 @@ export interface TableMenuSections {* and equal widths for the spanned columns. Shown above the clipboard.*/main: MenuItem<CommandNames>[];+ /** Sorting of the rows by the column of the selection. Shown above the deletion rows. */+ sort: MenuItem<CommandNames>;/** Deletion of the spanned rows or columns, or of the table. Shown below the clipboard. */delete: MenuItem<CommandNames>[];}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 1089c3197f..62e4c9755f 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3515,7 +3515,10 @@"split_cells": "Split cell","split_vertically": "Vertically","split_horizontally": "Horizontally",- "split_reset": "Unmerge cells"+ "split_reset": "Unmerge cells",+ "sort": "Sort",+ "sort_ascending": "Ascending",+ "sort_descending": "Descending"},"board_view": {"delete-note": "Delete note...",@@ -4373,7 +4376,11 @@"date-time": "Date/time","distribute-columns-evenly": "Distribute columns evenly","merge-selected-cells": "Merge selected cells",- "unmerge-cells": "Unmerge cells"+ "unmerge-cells": "Unmerge cells",+ "sort": "Sort",+ "ascending": "Ascending",+ "descending": "Descending",+ "some-rows-were-sorted-together-because-merged-cells-tie-them-to-each-other": "Some rows were sorted together because merged cells tie them to each other"},"task-state-dropped-title": "Invalid task states","task-state-dropped-message_one": "A custom task state definition is invalid and was ignored.",diff --git a/apps/client/src/utils/formatters.spec.ts b/apps/client/src/utils/formatters.spec.tsindex 655d47124f..4fd9b1ec1f 100644--- a/apps/client/src/utils/formatters.spec.ts+++ b/apps/client/src/utils/formatters.spec.ts@@ -16,7 +16,7 @@ vi.mock("../services/i18n", async () => {import { LOCALES } from "@triliumnext/commons";import options from "../services/options";-import { formatDateNumeric, formatDateTime, formatDuration, getMeasurementSystem, isContentRightToLeft, normalizeLocale, resolveContentLanguage } from "./formatters";+import { formatDateNumeric, formatDateTime, formatDuration, getMeasurementSystem, isContentRightToLeft, resolveContentLanguage } from "./formatters";describe("formatters", () => {it("tolerates incorrect locale", () => {@@ -37,14 +37,6 @@ describe("formatters", () => {expect(formatDateTime(new Date(), "none", "full")).toBeTruthy();});- it("normalizes locale", () => {- expect(normalizeLocale("zh_CN")).toBe("zh-CN");- expect(normalizeLocale("cn")).toBe("zh-CN");- expect(normalizeLocale("tw")).toBe("zh-TW");- // The default branch returns the (underscore-normalized) locale unchanged.- expect(normalizeLocale("en_US")).toBe("en-US");- });-it("returns an empty string for falsy dates", () => {expect(formatDateTime(null)).toBe("");expect(formatDateTime(undefined)).toBe("");diff --git a/apps/client/src/utils/formatters.ts b/apps/client/src/utils/formatters.tsindex 59f41a0dac..717d397799 100644--- a/apps/client/src/utils/formatters.ts+++ b/apps/client/src/utils/formatters.ts@@ -1,3 +1,5 @@+import { normalizeLocale } from "@triliumnext/commons";+import { getLocaleById, t } from "../services/i18n";import options from "../services/options";import type { MeasurementSystem } from "./units";@@ -184,15 +186,6 @@ function parseDate(date: string | Date | number): Date {throw new TypeError(`Invalid type for the "date" argument.`);}-export function normalizeLocale(locale: string) {- locale = locale.replaceAll("_", "-");- switch (locale) {- case "cn": return "zh-CN";- case "tw": return "zh-TW";- default: return locale;- }-}-/*** The language a note is written in.*diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsxindex 4bb47f3438..eb4d26b67d 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx@@ -47,6 +47,7 @@ interface CKEditorWithWatchdogProps extends Pick<HTMLProps<HTMLDivElement>, "clawatchdogRef: RefObject<EditorWatchdog>;watchdogConfig?: WatchdogConfig;onNotificationWarning?: (evt: NotificationEventInfo, data: NotificationEventData) => void;+ onNotificationInfo?: (evt: NotificationEventInfo, data: NotificationEventData) => void;onWatchdogStateChange?: (watchdog: EditorWatchdog) => void;onChange: () => void;/** Called upon whenever a new CKEditor instance is initialized, whether it's the first initialization, after a crash or after a config change that requires it (e.g. content language). */@@ -56,7 +57,7 @@ interface CKEditorWithWatchdogProps extends Pick<HTMLProps<HTMLDivElement>, "clacontainerRef?: RefObject<HTMLDivElement>;}-export default function CKEditorWithWatchdog({ containerRef: externalContainerRef, contentLanguage, className, tabIndex, isClassicEditor, watchdogRef: externalWatchdogRef, watchdogConfig, onNotificationWarning, onWatchdogStateChange, onChange, onEditorInitialized, editorApi, templates }: CKEditorWithWatchdogProps) {+export default function CKEditorWithWatchdog({ containerRef: externalContainerRef, contentLanguage, className, tabIndex, isClassicEditor, watchdogRef: externalWatchdogRef, watchdogConfig, onNotificationWarning, onNotificationInfo, onWatchdogStateChange, onChange, onEditorInitialized, editorApi, templates }: CKEditorWithWatchdogProps) {const containerRef = useSyncedRef<HTMLDivElement>(externalContainerRef, null);const watchdogRef = useRef<EditorWatchdog>(null);// Serializes editor build/teardown so overlapping effect runs never operate on the same@@ -386,6 +387,13 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRereturn () => notificationPlugin.off("show:warning", onNotificationWarning);}, [ editor, onNotificationWarning ]);+ useEffect(() => {+ if (!onNotificationInfo || !editor) return;+ const notificationPlugin = editor.plugins.get("Notification");+ notificationPlugin.on("show:info", onNotificationInfo);+ return () => notificationPlugin.off("show:info", onNotificationInfo);+ }, [ editor, onNotificationInfo ]);+// React to on change listener.useEffect(() => {if (!editor) return;diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.tsindex 7dfc629e16..c4e5f5e7b2 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts@@ -10,12 +10,15 @@ import { describe, expect, it, vi } from "vitest";const showError = vi.hoisted(() => vi.fn());const showErrorTitleAndMessage = vi.hoisted(() => vi.fn());-vi.mock("../../../services/toast", () => ({ default: { showError, showErrorTitleAndMessage } }));+const showMessage = vi.hoisted(() => vi.fn());+vi.mock("../../../services/toast", () => ({+ default: { showError, showErrorTitleAndMessage, showMessage }+}));// Imported by EditableText for editor types and content styles; irrelevant (and heavy) here.vi.mock("@triliumnext/ckeditor5", () => ({}));-const { onNotificationWarning } = await import("./EditableText");+const { onNotificationInfo, onNotificationWarning } = await import("./EditableText");describe("onNotificationWarning", () => {/** The payload `Notification#_showNotification` builds, with the `EventInfo` before it. */@@ -56,3 +59,14 @@ describe("onNotificationWarning", () => {expect(evt.stop).toHaveBeenCalledOnce();});});++describe("onNotificationInfo", () => {+ it("shows the message as a toast and leaves the event running", () => {+ vi.clearAllMocks();+ const evt = { stop: vi.fn() };+ onNotificationInfo(evt, { type: "info", message: "Rows sorted.", title: "" });++ expect(showMessage).toHaveBeenCalledWith("Rows sorted.");+ expect(evt.stop).not.toHaveBeenCalled();+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 009e08f4e4..e03c891f12 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -484,6 +484,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext}}templates={templates}onNotificationWarning={onNotificationWarning}+ onNotificationInfo={onNotificationInfo}onWatchdogStateChange={onWatchdogStateChange}onChange={() => spacedUpdate.scheduleUpdate()}onEditorInitialized={(editor) => {@@ -642,3 +643,11 @@ export function onNotificationWarning(evt: NotificationEventInfo, data: Notificaevt.stop();}+/**+ * Shows a CKEditor info notification, such as the notice after sorting a table, as a Trilium toast.+ *+ * Exported for testing.+ */+export function onNotificationInfo(_evt: NotificationEventInfo, data: NotificationEventData) {+ toast.showMessage(data.message);+}diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex da4ba37e74..2002d7bfe9 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -313,6 +313,22 @@ describe("CK config - HTML support", () => {});});+describe("CK config - tables", () => {+ it("offers the Sort dropdown just before the table properties", async () => {+ const toolbar = (await buildConfig(baseOpts())).table?.contentToolbar ?? [];+ expect(toolbar).toContain("tableSort");+ expect(toolbar.indexOf("tableSort")).toBe(toolbar.indexOf("tableProperties") - 1);+ });++ it("hands the user's date format to table sorting", async () => {+ expect((await buildConfig(baseOpts())).autoSort).toEqual({ dateFormats: [] });++ optionsState.map.customDateTimeFormat = "DD.MM.YYYY HH:mm";+ expect((await buildConfig(baseOpts())).autoSort)+ .toEqual({ dateFormats: ["DD.MM.YYYY HH:mm"] });+ });+});+describe("CK config - licensing", () => {it("always runs under the open-source license, with no premium plugins", async () => {// Every premium plugin Trilium used has an in-tree GPL replacement, so there is nodiff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 8cc257684a..59dacd0eef 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -146,7 +146,10 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi]},table: {- contentToolbar: ["tableColumn", "tableRow", "mergeTableCells", "tableProperties", "tableCellProperties", "toggleTableCaption"]+ contentToolbar: [+ "tableColumn", "tableRow", "mergeTableCells", "tableSort", "tableProperties",+ "tableCellProperties", "toggleTableCaption"+ ]},list: {properties: {@@ -269,6 +272,10 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfiembedImage: (src: string) => imageService.embedReferenceImageAsDataUrl(src)};+ // Table sorting reads dates inserted in the user's own format.+ const customDateTimeFormat = options.get("customDateTimeFormat");+ config.autoSort = { dateFormats: customDateTimeFormat ? [customDateTimeFormat] : [] };+// The language this note is written in, which governs both its text direction and which// typographic quotes typing produces.//diff --git a/apps/client/src/widgets/type_widgets/text/quotes.ts b/apps/client/src/widgets/type_widgets/text/quotes.tsindex 139fff5f9b..d5bd700ce2 100644--- a/apps/client/src/widgets/type_widgets/text/quotes.ts+++ b/apps/client/src/widgets/type_widgets/text/quotes.ts@@ -1,6 +1,5 @@import type { TextTypingTransformationDescription } from "@triliumnext/ckeditor5";--import { normalizeLocale } from "../../../utils/formatters.js";+import { normalizeLocale } from "@triliumnext/commons";/** The opening and closing mark of one quotation level — what a single quote key produces. */export type QuoteMarks = readonly [open: string, close: string];diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.htmlindex 18d26ad285..c664112f7f 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html@@ -54,9 +54,12 @@ src="3_Tables_image.png" width="384" height="100">header row is emitted, since Markdown tables require one.</li></ul></li>- <li><em>Delete row</em> and <em>Delete column</em>, below the clipboard section,- remove every row or column the selection touches, even when only some of- their cells are selected.</li>+ <li><em>Sort</em>, below the clipboard section, sorts the rows by the column+ of the current cell, in <em>Ascending</em> or <em>Descending</em> order. See <a+ href="#sorting-rows">Sorting rows</a>.</li>+ <li><em>Delete row</em> and <em>Delete column</em>, below <em>Sort</em>, remove+ every row or column the selection touches, even when only some of their+ cells are selected.</li><li><em>Delete table</em> removes the whole table and leaves an empty paragraphin its place. In a table nested inside another, only the inner table isremoved.</li>@@ -141,6 +144,90 @@ src="3_Tables_image.png" width="384" height="100"><p>Outside of tables, <kbd>Alt</kbd>+<kbd>Left</kbd> and <kbd>Alt</kbd>+<kbd>Right</kbd> keepnavigating the note history, and <kbd>Alt</kbd>+<kbd>Up</kbd> and <kbd>Alt</kbd>+<kbd>Down</kbd> keepmoving the current paragraph.</p>+<h2>Sorting rows</h2>+<p>Since v0.107.0, the rows of a table can be sorted by the values of one+ column:</p>+<ul>+ <li>To sort all the rows, place the cursor in any cell of the column to sort+ by, then select <em>Sort</em> → <em>Ascending</em> or <em>Descending</em> from+ the <a href="#context-menu">context menu</a>. The same items are in the <span+ class="tn-icon bx bx-sort"></span> button of the formatting toolbar.</li>+ <li>To sort only some of the rows, select their cells in the column to sort+ by, then sort the same way. Sorting is not available while the selection+ spans more than one column.</li>+</ul>+<p>Header rows always stay at the top of the table and are never sorted.+ A sort can be undone with <kbd>Ctrl</kbd>+<kbd>Z</kbd>.</p>+<h3>How values are compared</h3>+<p>Each cell is read as plain text, so formatting does not affect the order.+ Trilium then detects what kind of value the cell holds:</p>+<figure class="table">+ <table>+ <thead>+ <tr>+ <th>Kind</th>+ <th>Examples</th>+ <th>Compared by</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <td>Time</td>+ <td><code>15:02</code>, <code>15:02:38</code>, <code>3:02 PM</code>+ </td>+ <td>The time of day.</td>+ </tr>+ <tr>+ <td>Date</td>+ <td><code>2026-09-30</code>, <code>2026-09-30 15:02</code>, <code>30 September 2026</code>, <code>Wednesday, 30 September 2026</code>, <code>2026-09-30T15:02:38+03:00</code>+ </td>+ <td>The date and time.</td>+ </tr>+ <tr>+ <td>Number</td>+ <td><code>12</code>, <code>-3.5</code>, <code>1,234.56</code>, <code>$ 12.04</code>, <code>21 RON</code>, <code>24.5m</code>+ </td>+ <td>The numeric value.</td>+ </tr>+ <tr>+ <td>Text</td>+ <td>Anything else.</td>+ <td>Alphabetically, with numbers inside the text in numeric order (<code>Item 9</code> before <code>Item 10</code>).</td>+ </tr>+ <tr>+ <td>Empty</td>+ <td>An empty cell, or one holding only spaces.</td>+ <td>Not compared. Empty cells always go last.</td>+ </tr>+ </tbody>+ </table>+</figure>+<p>Ascending order puts times first, then dates, numbers and text. Descending+ order reverses it. Empty cells go last in both directions, and rows with+ equal values keep their relative order.</p>+<ul>+ <li>Dates are also recognized in the formats of the note's language, such+ as <code>30.09.2026</code> or <code>30. September 2026</code> for German, and+ in the format chosen in <a class="reference-link" href="#root/_help_4TIF1oA4VQRO">Options</a> → <em>Text Notes</em> → <em>Editor</em> → <em>Date/time format</em> for <a+ href="#root/_help_CohkqWQC1iBv">inserting the date and time</a>.</li>+ <li>A number can start with a currency symbol, such as <code>$</code>, <code>€</code> or <code>£</code>.+ Whatever follows the number, such as a unit, is ignored, so units are not+ converted: <code>1 km</code> sorts before <code>500 m</code>. A cell that+ starts with letters, such as <code>RON 21</code>, is text.</li>+ <li>The decimal separator follows the language of the note: <code>1.500</code> is+ one and a half in English, but one thousand five hundred in German. A comma+ or period that is not followed by exactly three digits is always read as+ a decimal separator, so <code>1,5</code> is one and a half in either language.</li>+ <li>The language of the note is the one set in its Basic Properties, or else+ the default content language. See <a class="reference-link" href="#root/_help_veGu4faJErEM">Content language & Right-to-left support</a>.</li>+</ul>+<h3>Merged cells</h3>+<p>Rows joined by a merged cell are kept together and move as one block.+ The block is sorted by the value in its first row. When the block has more+ than one cell in the sorted column, the other cells do not affect the order,+ and a message says so: <em>Some rows were sorted together because merged cells tie them to each other</em>.</p>+<p>When the selection covers only part of such a block, the whole block is+ sorted.</p><h2>Merging cells</h2><p>To merge two or more cells together, simply select them via drag &drop and press the <span class="tn-icon cke cke-table-merge-cell"></span> buttondiff --git a/docs/User Guide/User Guide/Note Types/Text/Tables.md b/docs/User Guide/User Guide/Note Types/Text/Tables.mdindex 0fc2485722..b2d9c5125e 100644--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md@@ -31,7 +31,8 @@ Since v0.106.0, right-clicking anywhere inside a table opens a context menu with* _Cut_, _Copy_ and _Copy as Markdown_ act on the selected cells:* Cutting or copying produces a smaller table holding just the selected cells. Pasting it over a cell selection replaces those cells; pasting elsewhere inserts it as a table of its own. Cutting clears the cells without removing rows or columns.* _Copy as Markdown_ converts the selected cells to a Markdown table. A selected header row becomes the Markdown header; without one, an empty header row is emitted, since Markdown tables require one.-* _Delete row_ and _Delete column_, below the clipboard section, remove every row or column the selection touches, even when only some of their cells are selected.+* _Sort_, below the clipboard section, sorts the rows by the column of the current cell, in _Ascending_ or _Descending_ order. See [Sorting rows](#sorting-rows).+* _Delete row_ and _Delete column_, below _Sort_, remove every row or column the selection touches, even when only some of their cells are selected.* _Delete table_ removes the whole table and leaves an empty paragraph in its place. In a table nested inside another, only the inner table is removed.Right-clicking a cell that is not part of the current selection moves the cursor there first, so the menu always applies to the cell under the pointer.@@ -78,6 +79,40 @@ When the table has a header row, a header row moved below the header area becomeOutside of tables, <kbd>Alt</kbd>+<kbd>Left</kbd> and <kbd>Alt</kbd>+<kbd>Right</kbd> keep navigating the note history, and <kbd>Alt</kbd>+<kbd>Up</kbd> and <kbd>Alt</kbd>+<kbd>Down</kbd> keep moving the current paragraph.+## Sorting rows++Since v0.107.0, the rows of a table can be sorted by the values of one column:++* To sort all the rows, place the cursor in any cell of the column to sort by, then select _Sort_ → _Ascending_ or _Descending_ from the [context menu](#context-menu). The same items are in the <span class="tn-icon bx bx-sort"></span> button of the formatting toolbar.+* To sort only some of the rows, select their cells in the column to sort by, then sort the same way. Sorting is not available while the selection spans more than one column.++Header rows always stay at the top of the table and are never sorted. A sort can be undone with <kbd>Ctrl</kbd>+<kbd>Z</kbd>.++### How values are compared++Each cell is read as plain text, so formatting does not affect the order. Trilium then detects what kind of value the cell holds:++| Kind | Examples | Compared by |+| --- | --- | --- |+| Time | `15:02`, `15:02:38`, `3:02 PM` | The time of day. |+| Date | `2026-09-30`, `2026-09-30 15:02`, `30 September 2026`, `Wednesday, 30 September 2026`, `2026-09-30T15:02:38+03:00` | The date and time. |+| Number | `12`, `-3.5`, `1,234.56`, `$ 12.04`, `21 RON`, `24.5m` | The numeric value. |+| Text | Anything else. | Alphabetically, with numbers inside the text in numeric order (`Item 9` before `Item 10`). |+| Empty | An empty cell, or one holding only spaces. | Not compared. Empty cells always go last. |++Ascending order puts times first, then dates, numbers and text. Descending order reverses it. Empty cells go last in both directions, and rows with equal values keep their relative order.++* Dates are also recognized in the formats of the note's language, such as `30.09.2026` or `30. September 2026` for German, and in the format chosen in <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Text Notes_ → _Editor_ → _Date/time format_ for [inserting the date and time](Insert%20buttons.md).+* A number can start with a currency symbol, such as `$`, `€` or `£`. Whatever follows the number, such as a unit, is ignored, so units are not converted: `1 km` sorts before `500 m`. A cell that starts with letters, such as `RON 21`, is text.+* The decimal separator follows the language of the note: `1.500` is one and a half in English, but one thousand five hundred in German. A comma or period that is not followed by exactly three digits is always read as a decimal separator, so `1,5` is one and a half in either language.+* The language of the note is the one set in its Basic Properties, or else the default content language. See <a class="reference-link" href="Content%20language%20%26%20Right-to-left%20support.md">Content language & Right-to-left support</a>.++### Merged cells++Rows joined by a merged cell are kept together and move as one block. The block is sorted by the value in its first row. When the block has more than one cell in the sorted column, the other cells do not affect the order, and a message says so: _Some rows were sorted together because merged cells tie them to each other_.++When the selection covers only part of such a block, the whole block is sorted.+## Merging cellsTo merge two or more cells together, simply select them via drag & drop and press the <span class="tn-icon cke cke-table-merge-cell"></span> button from the formatting toolbar.diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 82f85071cb..ecf2b46035 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -106,6 +106,10 @@ declare module "ckeditor5" {*/copyHtml?(html: string, plainText: string): void;},- clipboardImageEmbed?: ClipboardImageEmbedConfig+ clipboardImageEmbed?: ClipboardImageEmbedConfig,+ autoSort?: {+ /** More date formats for table sorting to recognize, in Day.js syntax. */+ dateFormats?: string[];+ }}}diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.tsindex f5d35f4f7f..f09ad8a614 100644--- a/packages/ckeditor5/src/plugins.ts+++ b/packages/ckeditor5/src/plugins.ts@@ -59,6 +59,7 @@ import CollapsibleListItems from "./plugins/collapsible_list_items.js";import TableIndent from "./plugins/table_indent.js";import TableContextMenu from "./plugins/table_context_menu.js";import TableMove from "./plugins/table_move/table_move.js";+import TableSort from "./plugins/table_sort.js";import TableInsertUI from "./plugins/table_insert/table_insert_ui.js";import TableToolbarDropdowns from "./plugins/table_toolbar_dropdowns.js";import ToolbarGroupMenu from "./plugins/toolbar_group_menu.js";@@ -99,6 +100,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [TableIndent,TableContextMenu,TableMove,+ TableSort,TableInsertUI,TableToolbarDropdowns,ToolbarGroupMenu,diff --git a/packages/ckeditor5/src/plugins/table_move/table_move_groups.spec.ts b/packages/ckeditor5/src/plugins/table_move/table_move_groups.spec.tsindex f375fb2de9..437563e293 100644--- a/packages/ckeditor5/src/plugins/table_move/table_move_groups.spec.ts+++ b/packages/ckeditor5/src/plugins/table_move/table_move_groups.spec.ts@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";import { modelTable } from "../../../test/table-kit.js";-import { adjustedHeadingCount, planGroupMove } from "./table_move_groups.js";+import { adjustedHeadingCount, planGroupMove, splitIntoGroups } from "./table_move_groups.js";describe("planGroupMove", () => {let editor: ClassicEditor;@@ -141,3 +141,50 @@ describe("adjustedHeadingCount", () => {expect(adjustedHeadingCount(1, up, false)).toBe(3);});});++describe("splitIntoGroups", () => {+ let editor: ClassicEditor;++ beforeEach(async () => {+ editor = await createTestEditor([Essentials, Paragraph, Table]);+ });++ function getTable(markup: string): ModelElement {+ setModelData(editor.model, markup);+ const table = editor.model.document.getRoot()?.getChild(0);+ if (!table?.is("element", "table")) {+ throw new Error("Fixture did not produce a table.");+ }+ return table;+ }++ it("puts every row of a table without merged cells in a group of its own", () => {+ const table = getTable(modelTable([["a"], ["b"], ["c"]]));+ expect(splitIntoGroups(table, "row", { first: 0, last: 2 }))+ .toEqual([{ first: 0, last: 0 }, { first: 1, last: 1 }, { first: 2, last: 2 }]);+ expect(splitIntoGroups(table, "row", { first: 1, last: 1 }))+ .toEqual([{ first: 1, last: 1 }]);+ });++ it("keeps the rows of a merged cell together and widens the range to them", () => {+ const table = getTable(modelTable([+ [{ contents: "a", rowspan: 2 }, "b"],+ ["c"],+ ["d", "e"]+ ]));+ const expected = [{ first: 0, last: 1 }, { first: 2, last: 2 }];+ expect(splitIntoGroups(table, "row", { first: 0, last: 2 })).toEqual(expected);+ expect(splitIntoGroups(table, "row", { first: 1, last: 2 })).toEqual(expected);+ expect(splitIntoGroups(table, "row", { first: 2, last: 2 }))+ .toEqual([{ first: 2, last: 2 }]);+ });++ it("groups columns the same way", () => {+ const table = getTable(modelTable([+ [{ contents: "a", colspan: 2 }, "b"],+ ["c", "d", "e"]+ ]));+ expect(splitIntoGroups(table, "column", { first: 0, last: 2 }))+ .toEqual([{ first: 0, last: 1 }, { first: 2, last: 2 }]);+ });+});diff --git a/packages/ckeditor5/src/plugins/table_move/table_move_groups.ts b/packages/ckeditor5/src/plugins/table_move/table_move_groups.tsindex 85438c96ab..0ef18a86c9 100644--- a/packages/ckeditor5/src/plugins/table_move/table_move_groups.ts+++ b/packages/ckeditor5/src/plugins/table_move/table_move_groups.ts@@ -43,6 +43,30 @@ export function planGroupMove(return { source, target: expandToGroup(previous, crossed, count) };}+/**+ * Splits `range`, widened so that no merged cell sticks out of it, into span groups: the smallest+ * blocks of rows or columns that no merged cell crosses.+ */+export function splitIntoGroups(+ table: ModelElement,+ axis: TableAxis,+ range: IndexRange+): IndexRange[] {+ const { crossed, count } = scanSpannedBoundaries(table, axis);+ const { first, last } = expandToGroup(range, crossed, count);++ const groups: IndexRange[] = [];+ let groupFirst = first;+ for (let index = first + 1; index <= last; index++) {+ if (!crossed[index]) {+ groups.push({ first: groupFirst, last: index - 1 });+ groupFirst = index;+ }+ }+ groups.push({ first: groupFirst, last });+ return groups;+}+/*** Returns the `headingRows`/`headingColumns` value after applying `plan`. The heading band is* positional: entries moved out of the leading band lose heading status and entries moved intodiff --git a/packages/ckeditor5/src/plugins/table_sort.spec.ts b/packages/ckeditor5/src/plugins/table_sort.spec.tsnew file mode 100644index 0000000000..c6d6bd8238--- /dev/null+++ b/packages/ckeditor5/src/plugins/table_sort.spec.ts@@ -0,0 +1,333 @@+import {+ _getModelData as getModelData,+ _setModelData as setModelData,+ Essentials,+ Notification,+ Paragraph,+ Table,+ TableCaption,+ TableSelection+} from "ckeditor5";+import type { ClassicEditor, ModelElement } from "ckeditor5";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { createTestEditor } from "../../test/editor-kit.js";+import { modelTable, selectCells } from "../../test/table-kit.js";+import TableSort from "./table_sort.js";++const ASCENDING = "triliumSortTableRowsAscending";+const DESCENDING = "triliumSortTableRowsDescending";+const TIED_MESSAGE = "Some rows were sorted together because merged cells tie them to each other";++describe("TableSort", () => {+ let editor: ClassicEditor;++ beforeEach(async () => {+ editor = await createTestEditor([Essentials, Paragraph, Table, TableCaption, TableSort],+ { language: { content: "en" } });+ });++ function tableData(target = editor): string {+ return getModelData(target.model, { withoutSelection: true });+ }++ function isEnabled(name = ASCENDING, target = editor): boolean {+ return target.commands.get(name)?.isEnabled === true;+ }++ describe("isEnabled", () => {+ it("is disabled outside a table", () => {+ setModelData(editor.model, "<paragraph>fo[]o</paragraph>");+ expect(isEnabled(ASCENDING)).toBe(false);+ expect(isEnabled(DESCENDING)).toBe(false);+ });++ it("is enabled in a column with at least two body rows", () => {+ setModelData(editor.model, modelTable([["b[]"], ["a"]]));+ expect(isEnabled(ASCENDING)).toBe(true);+ expect(isEnabled(DESCENDING)).toBe(true);+ });++ it("is disabled when fewer than two row groups can move", () => {+ setModelData(editor.model, modelTable([["a[]"]]));+ expect(isEnabled()).toBe(false);++ setModelData(editor.model, modelTable([["h[]"], ["a"]], 'headingRows="1"'));+ expect(isEnabled()).toBe(false);++ setModelData(editor.model, modelTable([+ [{ contents: "a[]", rowspan: 2 }, "b"],+ ["c"]+ ]));+ expect(isEnabled()).toBe(false);+ });++ it("is disabled when the selection spans more than one column", () => {+ setModelData(editor.model, modelTable([["a", "b"], ["c", "d"], ["e", "f"]]));+ selectCells(editor, [0, 0], [1, 1]);+ expect(isEnabled()).toBe(false);++ selectCells(editor, [0, 1], [2, 1]);+ expect(isEnabled()).toBe(true);+ });++ it("is disabled when the selected rows are header rows only", () => {+ setModelData(editor.model,+ modelTable([["h1"], ["h2"], ["a"], ["b"]], 'headingRows="2"'));+ selectCells(editor, [0, 0], [1, 0]);+ expect(isEnabled()).toBe(false);+ });++ it("is disabled in read-only mode", () => {+ setModelData(editor.model, modelTable([["b[]"], ["a"]]));+ editor.enableReadOnlyMode("spec");+ expect(isEnabled()).toBe(false);+ });+ });++ describe("sorting by the column of the caret", () => {+ it("sorts every body row by the caret column, in both directions", () => {+ setModelData(editor.model, modelTable([["b", "1"], ["c", "3[]"], ["a", "2"]]));++ editor.execute(ASCENDING);+ expect(tableData()).toBe(modelTable([["b", "1"], ["a", "2"], ["c", "3"]]));++ editor.execute(DESCENDING);+ expect(tableData()).toBe(modelTable([["c", "3"], ["a", "2"], ["b", "1"]]));+ });++ it("orders times, dates, numbers and text, with empty cells last", () => {+ const values = ["text", "", "10", "2026-09-30", "15:02", "9"];+ setModelData(editor.model, modelTable(values.map((value, index) =>+ index === 0 ? [`${value}[]`] : [value])));++ editor.execute(ASCENDING);+ expect(tableData()).toBe(modelTable(+ [["15:02"], ["2026-09-30"], ["9"], ["10"], ["text"], [""]]));++ editor.execute(DESCENDING);+ expect(tableData()).toBe(modelTable(+ [["text"], ["10"], ["9"], ["2026-09-30"], ["15:02"], [""]]));+ });++ it("keeps header and footer rows in place", async () => {+ const withFooters = await createTestEditor([Essentials, Paragraph, Table, TableSort],+ { table: { enableFooters: true } });+ setModelData(withFooters.model, modelTable(+ [["Name"], ["z[]"], ["x"], ["y"], ["Total"]], 'footerRows="1" headingRows="1"'));++ withFooters.execute(ASCENDING);+ expect(tableData(withFooters)).toBe(modelTable(+ [["Name"], ["x"], ["y"], ["z"], ["Total"]], 'footerRows="1" headingRows="1"'));+ });++ it("reads formatted and multi-paragraph cells as plain text", () => {+ setModelData(editor.model, modelTable([+ ["10[]"],+ ["2</paragraph><paragraph>0"],+ ["<softBreak></softBreak>1"]+ ]));++ editor.execute(ASCENDING);+ expect(tableData()).toBe(modelTable([+ ["<softBreak></softBreak>1"],+ ["2</paragraph><paragraph>0"],+ ["10"]+ ]));+ });++ it("keeps the selection in its cell and the caption in place", () => {+ setModelData(editor.model, "<table>"+ + "<tableRow><tableCell><paragraph>b[]</paragraph></tableCell></tableRow>"+ + "<tableRow><tableCell><paragraph>a</paragraph></tableCell></tableRow>"+ + "<caption>Caption</caption></table>");++ editor.execute(ASCENDING);+ expect(getModelData(editor.model)).toBe("<table>"+ + "<tableRow><tableCell><paragraph>a</paragraph></tableCell></tableRow>"+ + "<tableRow><tableCell><paragraph>b[]</paragraph></tableCell></tableRow>"+ + "<caption>Caption</caption></table>");+ });++ it("sorts in one undo step", () => {+ const original = modelTable([["c[]"], ["a"], ["b"]]);+ setModelData(editor.model, original);++ editor.execute(ASCENDING);+ expect(tableData()).toBe(modelTable([["a"], ["b"], ["c"]]));++ editor.execute("undo");+ expect(tableData()).toBe(modelTable([["c"], ["a"], ["b"]]));+ });++ it("applies no change to an already sorted table", () => {+ setModelData(editor.model, modelTable([["a[]"], ["b"]]));+ const version = editor.model.document.version;++ editor.execute(ASCENDING);+ expect(editor.model.document.version).toBe(version);+ });++ it("does nothing when executed without a plan", () => {+ setModelData(editor.model, "<paragraph>fo[]o</paragraph>");+ const command = editor.commands.get(ASCENDING);+ if (!command) {+ throw new Error("Command not registered.");+ }+ command.isEnabled = true;+ expect(() => command.execute()).not.toThrow();+ expect(tableData()).toBe("<paragraph>foo</paragraph>");+ });+ });++ describe("sorting a cell selection", () => {+ it("sorts only the selected rows and keeps them selected", () => {+ setModelData(editor.model, modelTable([["d"], ["c"], ["b"], ["a"]]));+ selectCells(editor, [1, 0], [2, 0]);++ editor.execute(ASCENDING);+ expect(tableData()).toBe(modelTable([["d"], ["b"], ["c"], ["a"]]));+ const selected = editor.plugins.get(TableSelection).getSelectedTableCells() ?? [];+ expect(selected.map((cell) => cell.parent?.index)).toEqual([1, 2]);+ expect(selected.map((cell) => cellTextOf(cell))).toEqual(["b", "c"]);+ });++ it("leaves header rows out of the selected range", () => {+ setModelData(editor.model, modelTable([["z"], ["c"], ["b"], ["a"]], 'headingRows="1"'));+ selectCells(editor, [0, 0], [2, 0]);++ editor.execute(ASCENDING);+ expect(tableData()).toBe(modelTable([["z"], ["b"], ["c"], ["a"]], 'headingRows="1"'));+ });++ it("widens the selection to the rows its merged cells tie together", () => {+ setModelData(editor.model, modelTable([+ ["z", "d"],+ [{ contents: "y", rowspan: 2 }, "c"],+ ["b"],+ ["x", "a"]+ ]));+ selectCells(editor, [0, 0], [1, 0]);++ editor.execute(ASCENDING);+ expect(tableData()).toBe(modelTable([+ [{ contents: "y", rowspan: 2 }, "c"],+ ["b"],+ ["z", "d"],+ ["x", "a"]+ ]));+ });+ });++ describe("merged cells", () => {+ it("moves the rows of a merged cell as one group", () => {+ setModelData(editor.model, modelTable([+ [{ contents: "a[]", rowspan: 2 }, "z"],+ ["y"],+ ["b", "x"]+ ]));++ editor.execute(DESCENDING);+ expect(tableData()).toBe(modelTable([+ ["b", "x"],+ [{ contents: "a", rowspan: 2 }, "z"],+ ["y"]+ ]));+ });++ it("sorts a group by the cell of its first row and reports the tie", () => {+ const showInfo = vi.spyOn(editor.plugins.get(Notification), "showInfo");+ setModelData(editor.model, modelTable([+ [{ contents: "a", rowspan: 2 }, "z[]"],+ ["y"],+ ["b", "x"]+ ]));++ editor.execute(ASCENDING);+ expect(tableData()).toBe(modelTable([+ ["b", "x"],+ [{ contents: "a", rowspan: 2 }, "z"],+ ["y"]+ ]));+ expect(showInfo).toHaveBeenCalledExactlyOnceWith(TIED_MESSAGE);+ });++ it("does not report a group whose sort column holds a single cell", () => {+ const showInfo = vi.spyOn(editor.plugins.get(Notification), "showInfo");+ setModelData(editor.model, modelTable([+ [{ contents: "b[]", rowspan: 2 }, "z"],+ ["y"],+ ["a", "x"]+ ]));++ editor.execute(ASCENDING);+ expect(tableData()).toBe(modelTable([+ ["a", "x"],+ [{ contents: "b", rowspan: 2 }, "z"],+ ["y"]+ ]));+ expect(showInfo).not.toHaveBeenCalled();+ });++ it("reads a cell that spans columns under each column it covers", () => {+ setModelData(editor.model, modelTable([+ [{ contents: "c", colspan: 2 }],+ ["y", "a[]"],+ ["x", "b"]+ ]));+ editor.execute(ASCENDING);+ expect(tableData()).toBe(modelTable([+ ["y", "a"],+ ["x", "b"],+ [{ contents: "c", colspan: 2 }]+ ]));+ });++ it("sorts by the first column of a caret cell that spans columns", () => {+ setModelData(editor.model, modelTable([+ [{ contents: "c[]", colspan: 2 }],+ ["y", "a"],+ ["x", "b"]+ ]));+ editor.execute(ASCENDING);+ expect(tableData()).toBe(modelTable([+ [{ contents: "c", colspan: 2 }],+ ["x", "b"],+ ["y", "a"]+ ]));+ });+ });++ describe("locale and formats", () => {+ it("reads numbers with the content language of the note", async () => {+ setModelData(editor.model, modelTable([["1.500[]"], ["2"]]));+ editor.execute(ASCENDING);+ expect(tableData()).toBe(modelTable([["1.500"], ["2"]]));++ const german = await createTestEditor([Essentials, Paragraph, Table, TableSort],+ { language: { content: "de" } });+ setModelData(german.model, modelTable([["1.500[]"], ["2"]]));+ german.execute(ASCENDING);+ expect(tableData(german)).toBe(modelTable([["2"], ["1.500"]]));+ });++ it("recognizes the configured date formats", async () => {+ const rows = [["01|10|2026[]"], ["30|09|2026"]];+ setModelData(editor.model, modelTable(rows));+ editor.execute(ASCENDING);+ expect(tableData()).toBe(modelTable([["01|10|2026"], ["30|09|2026"]]));++ const configured = await createTestEditor([Essentials, Paragraph, Table, TableSort],+ { autoSort: { dateFormats: ["DD|MM|YYYY"] } });+ setModelData(configured.model, modelTable(rows));+ configured.execute(ASCENDING);+ expect(tableData(configured)).toBe(modelTable([["30|09|2026"], ["01|10|2026"]]));+ });+ });+});++function cellTextOf(cell: ModelElement): string {+ const paragraph = cell.getChild(0);+ const text = paragraph?.is("element") ? paragraph.getChild(0) : null;+ return text?.is("$text") ? text.data : "";+}diff --git a/packages/ckeditor5/src/plugins/table_sort.ts b/packages/ckeditor5/src/plugins/table_sort.tsnew file mode 100644index 0000000000..d5c0bbcbc2--- /dev/null+++ b/packages/ckeditor5/src/plugins/table_sort.ts@@ -0,0 +1,199 @@+import { autoSort } from "@triliumnext/commons";+import {+ Command,+ Notification,+ Plugin,+ Table,+ TableUtils,+ TableWalker+} from "ckeditor5";+import type { Editor, Model, ModelElement, ModelPosition, ModelWriter } from "ckeditor5";++import { splitIntoGroups } from "./table_move/table_move_groups.js";+import type { IndexRange } from "./table_move/table_move_groups.js";++/**+ * Sorts the body rows of a table by the column of the selection, with `autoSort`. A caret sorts+ * every body row; a cell selection in one column sorts the selected rows. Header and footer rows+ * never move, and rows tied together by merged cells move as one group.+ */+export default class TableSort extends Plugin {++ static get requires() {+ return [Table, TableUtils, Notification] as const;+ }++ static get pluginName() {+ return "TableSort" as const;+ }++ init() {+ const editor = this.editor;+ editor.commands.add("triliumSortTableRowsAscending",+ new SortTableRowsCommand(editor, false));+ editor.commands.add("triliumSortTableRowsDescending",+ new SortTableRowsCommand(editor, true));+ }++}++interface SortPlan {+ table: ModelElement;+ column: number;+ groups: IndexRange[];+}++interface RowGroup {+ range: IndexRange;+ text: string;+ isTied: boolean;+}++export class SortTableRowsCommand extends Command {++ private readonly isDescending: boolean;++ constructor(editor: Editor, isDescending: boolean) {+ super(editor);+ this.isDescending = isDescending;+ }++ override refresh() {+ this.isEnabled = this.planSort() !== null;+ }++ override execute() {+ const plan = this.planSort();+ if (!plan) {+ return;+ }++ const editor = this.editor;+ const groups = readGroups(editor.model, plan);+ const sorted = autoSort(groups, (group) => group.text, {+ locale: editor.locale.contentLanguage,+ isDescending: this.isDescending,+ dateFormats: editor.config.get("autoSort")?.dateFormats+ });++ if (sorted.some((group, index) => group !== groups[index])) {+ this.applyOrder(plan.table, plan.groups[0].first, sorted.map((group) => group.range));+ }++ if (groups.some((group) => group.isTied)) {+ const t = editor.t;+ editor.plugins.get(Notification).showInfo(+ t("Some rows were sorted together because merged cells tie them to each other"));+ }+ }++ /** Moves the row groups into `order`, starting at row `firstIndex`, in one undo step. */+ private applyOrder(table: ModelElement, firstIndex: number, order: IndexRange[]) {+ const model = this.editor.model;+ const rows = [...table.getChildren()]+ .filter((child): child is ModelElement => child.is("element", "tableRow"));+ const firstRow = rows[firstIndex];++ // The selection ranges are live, so they follow the moved rows.+ model.change((writer) => {+ let previous: ModelElement | null = null;+ for (const range of order) {+ const insertAt = previous+ ? writer.createPositionAfter(previous)+ : writer.createPositionBefore(firstRow);+ moveRows(writer, rows[range.first], rows[range.last], insertAt);+ previous = rows[range.last];+ }+ });+ }++ private planSort(): SortPlan | null {+ const editor = this.editor;+ const tableUtils = editor.plugins.get(TableUtils);+ const selection = editor.model.document.selection;+ const cells = tableUtils.getSelectionAffectedTableCells(selection);+ const table = cells[0]?.findAncestor("table");+ if (!table) {+ return null;+ }++ const columns = tableUtils.getColumnIndexes(cells);+ if (columns.first !== columns.last) {+ return null;+ }++ const footerRows = Number(table.getAttribute("footerRows") ?? 0);+ const bodyFirst = Number(table.getAttribute("headingRows") ?? 0);+ const bodyLast = tableUtils.getRows(table) - footerRows - 1;+ const isCellSelection = tableUtils.getSelectedTableCells(selection).length > 1;+ const selected = isCellSelection ? tableUtils.getRowIndexes(cells) : null;+ const first = Math.max(selected?.first ?? bodyFirst, bodyFirst);+ const last = Math.min(selected?.last ?? bodyLast, bodyLast);+ if (first > last) {+ return null;+ }++ // The table post-fixer keeps merged cells inside the header, body or footer, so every+ // group lies inside the body.+ const groups = splitIntoGroups(table, "row", { first, last });+ return groups.length > 1 ? { table, column: columns.first, groups } : null;+ }++}++/**+ * Reads the text each group sorts by: the cell of its first row in the sort column. A group is tied+ * when the column has more than one cell in it.+ */+function readGroups(model: Model, { table, column, groups }: SortPlan): RowGroup[] {+ // The table post-fixer fills short rows, so every row has a slot in the column.+ const cellsByRow: ModelElement[] = [];+ const walker = new TableWalker(table, {+ startRow: groups[0].first,+ endRow: groups[groups.length - 1].last,+ includeAllSlots: true+ });+ for (const slot of walker) {+ if (slot.column === column) {+ cellsByRow[slot.row] = slot.cell;+ }+ }++ return groups.map((range) => ({+ range,+ text: cellText(model, cellsByRow[range.first]),+ isTied: new Set(cellsByRow.slice(range.first, range.last + 1)).size > 1+ }));+}++/** The plain text of a cell. Elements such as paragraphs and line breaks become spaces. */+function cellText(model: Model, cell: ModelElement): string {+ let text = "";+ for (const item of model.createRangeIn(cell).getItems()) {+ text += item.is("$textProxy") ? item.data : " ";+ }+ return text;+}++function moveRows(+ writer: ModelWriter,+ firstRow: ModelElement,+ lastRow: ModelElement,+ insertAt: ModelPosition+) {+ const start = writer.createPositionBefore(firstRow);+ if (!start.isEqual(insertAt)) {+ writer.move(writer.createRange(start, writer.createPositionAfter(lastRow)), insertAt);+ }+}++declare module "ckeditor5" {+ interface PluginsMap {+ [TableSort.pluginName]: TableSort;+ }++ interface CommandsMap {+ triliumSortTableRowsAscending: SortTableRowsCommand;+ triliumSortTableRowsDescending: SortTableRowsCommand;+ }+}diff --git a/packages/ckeditor5/src/plugins/table_toolbar_dropdowns.spec.ts b/packages/ckeditor5/src/plugins/table_toolbar_dropdowns.spec.tsindex 5725794e61..1dd91b9ee9 100644--- a/packages/ckeditor5/src/plugins/table_toolbar_dropdowns.spec.ts+++ b/packages/ckeditor5/src/plugins/table_toolbar_dropdowns.spec.ts@@ -1,4 +1,5 @@import {+ _getModelData as getModelData,_setModelData as setModelData,ButtonView,Essentials,@@ -154,6 +155,31 @@ describe("TableToolbarDropdowns", () => {dropdown.destroy();});});++ describe("the Sort dropdown", () => {+ it("sorts the rows with the clicked direction", async () => {+ const editor = await createTestEditor(+ [Essentials, Paragraph, Table, TableToolbarDropdowns], { toolbar: ["tableSort"] });+ const dropdown = editor.ui.view.toolbar.items.get(0) as DropdownView;+ const tableData = () => getModelData(editor.model, { withoutSelection: true });++ expect(dropdown.buttonView.label).toBe("Sort");+ expect(dropdown.buttonView.icon).toContain("<svg");+ expect(dropdown.isEnabled).toBe(false);++ setModelData(editor.model, modelTable([["b[]"], ["c"], ["a"]]));+ expect(dropdown.isEnabled).toBe(true);+ expect(getItems(dropdown)).toEqual([+ "triliumSortTableRowsAscending: Ascending",+ "triliumSortTableRowsDescending: Descending"+ ]);++ clickItem(dropdown, "Ascending");+ expect(tableData()).toBe(modelTable([["a"], ["b"], ["c"]]));+ clickItem(dropdown, "Descending");+ expect(tableData()).toBe(modelTable([["c"], ["b"], ["a"]]));+ });+ });});function getElement(view: { element: HTMLElement | null }): HTMLElement {diff --git a/packages/ckeditor5/src/plugins/table_toolbar_dropdowns.ts b/packages/ckeditor5/src/plugins/table_toolbar_dropdowns.tsindex 8f521f8c33..60c6f2eaaa 100644--- a/packages/ckeditor5/src/plugins/table_toolbar_dropdowns.ts+++ b/packages/ckeditor5/src/plugins/table_toolbar_dropdowns.ts@@ -1,3 +1,4 @@+import bxSort from "boxicons/svg/regular/bx-sort.svg?raw";import {addListToDropdown,Collection,@@ -19,11 +20,12 @@ import type {} from "ckeditor5";import TableContextMenu from "./table_context_menu.js";+import TableSort from "./table_sort.js";/*** Replaces the `tableColumn` and `mergeTableCells` dropdowns of `TableUI` with copies that add* commands of the table context menu: "Distribute columns evenly", "Merge selected cells" and- * "Unmerge cells".+ * "Unmerge cells". Adds the `tableSort` dropdown.** `TableUI` builds its item lists in private methods, so the dropdowns are rebuilt from public* helpers and command names instead of patched. The spec compares them with the upstream@@ -32,7 +34,7 @@ import TableContextMenu from "./table_context_menu.js";export default class TableToolbarDropdowns extends Plugin {static get requires() {- return [Table, TableContextMenu] as const;+ return [Table, TableContextMenu, TableSort] as const;}static get pluginName() {@@ -81,6 +83,15 @@ export default class TableToolbarDropdowns extends Plugin {buttonItem("triliumResetTableCellSpans", t("Unmerge cells"))]}));++ factory.add("tableSort", (locale) => this.createDropdown(locale, {+ label: t("Sort"),+ icon: bxSort,+ items: [+ buttonItem("triliumSortTableRowsAscending", t("Ascending")),+ buttonItem("triliumSortTableRowsDescending", t("Descending"))+ ]+ }));}/**diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex ad87483aed..d522f4500e 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -20,6 +20,7 @@ export * from "./lib/ws_api.js";export * from "./lib/attribute_names.js";export * from "./lib/search_syntax.js";export * from "./lib/sort_criteria.js";+export * from "./lib/auto_sort.js";export * from "./lib/note_type_ids.js";export * from "./lib/promoted_attribute_definition_parser.js";export { default as promotedAttributeDefinitionParser } from "./lib/promoted_attribute_definition_parser.js";diff --git a/packages/commons/src/lib/auto_sort.spec.ts b/packages/commons/src/lib/auto_sort.spec.tsnew file mode 100644index 0000000000..155ceda1f4--- /dev/null+++ b/packages/commons/src/lib/auto_sort.spec.ts@@ -0,0 +1,217 @@+import { describe, expect, it } from "vitest";++import { autoSort, type AutoSortOptions, classifyAutoSortValue } from "./auto_sort.js";++function sort(values: string[], options?: AutoSortOptions) {+ return autoSort(values, (value) => value, options);+}++function numberOf(text: string, locale = "en"): number | null {+ const value = classifyAutoSortValue(text, { locale });+ return value.kind === "number" ? value.key : null;+}++describe("classifyAutoSortValue", () => {+ it("detects each kind and its key", () => {+ expect(classifyAutoSortValue("15:02")).toEqual({ kind: "time", key: 54120, text: "15:02" });+ expect(classifyAutoSortValue("2026-09-30"))+ .toEqual({ kind: "date", key: Date.UTC(2026, 8, 30), text: "2026-09-30" });+ expect(classifyAutoSortValue("12 apples"))+ .toEqual({ kind: "number", key: 12, text: "12 apples" });+ expect(classifyAutoSortValue("Item 3")).toEqual({ kind: "text", key: 0, text: "Item 3" });+ expect(classifyAutoSortValue("")).toEqual({ kind: "empty", key: 0, text: "" });+ });++ it("trims the text and treats blank text as empty", () => {+ expect(classifyAutoSortValue(" \tabc \n")).toMatchObject({ kind: "text", text: "abc" });+ expect(classifyAutoSortValue(" 15:02 ")).toMatchObject({ kind: "time", text: "15:02" });+ for (const blank of [" ", "\t\t", " ", " \n "]) {+ expect(classifyAutoSortValue(blank).kind, JSON.stringify(blank)).toBe("empty");+ }+ });++ it("detects the documented date and time forms", () => {+ const dates = [+ "2026-09-30 15:02", "2026-09-30", "30 September 2026", "Wednesday, 30 September 2026",+ "2026-09-30T15:02:38+03:00"+ ];+ for (const text of dates) {+ expect(classifyAutoSortValue(text, { locale: "en" }).kind, text).toBe("date");+ }+ expect(classifyAutoSortValue("15:02").kind).toBe("time");+ expect(classifyAutoSortValue("3:02 PM").kind).toBe("time");+ });++ it("recognizes extra date formats", () => {+ expect(classifyAutoSortValue("30|09|2026").kind).toBe("number");+ expect(classifyAutoSortValue("30|09|2026", { dateFormats: ["DD|MM|YYYY"] }).kind)+ .toBe("date");+ });+});++describe("numbers", () => {+ it("reads the leading number and ignores what follows", () => {+ expect(numberOf("24.5m")).toBe(24.5);+ expect(numberOf("21 RON")).toBe(21);+ expect(numberOf("12%")).toBe(12);+ expect(numberOf("3 apples")).toBe(3);+ expect(numberOf("1e5")).toBe(1);+ expect(numberOf("1.5.")).toBe(1.5);+ expect(numberOf("007")).toBe(7);+ });++ it("skips a currency symbol before the number", () => {+ expect(numberOf("$ 12.04")).toBe(12.04);+ expect(numberOf("$12")).toBe(12);+ expect(numberOf("€12,50")).toBe(12.5);+ expect(numberOf("£ 1,234.56")).toBe(1234.56);+ expect(numberOf("¥1000")).toBe(1000);+ expect(numberOf("₹ 5")).toBe(5);+ expect(numberOf("-$12")).toBe(-12);+ expect(numberOf("$-12")).toBe(-12);+ expect(numberOf("$ -12")).toBe(-12);+ });++ it("reads the sign", () => {+ expect(numberOf("-5")).toBe(-5);+ expect(numberOf("−5")).toBe(-5);+ expect(numberOf("+5")).toBe(5);+ expect(numberOf("-0.5")).toBe(-0.5);+ });++ it("treats text that does not start with a number as text", () => {+ for (const text of ["RON 21", "US$ 5", "Item 3", ".5", "#5", "(5)", "- 5", "+-5", "-$-5"]) {+ expect(numberOf(text), text).toBeNull();+ }+ });++ it("reads grouping and decimal marks", () => {+ const cases: [string, number][] = [+ ["1,234.5", 1234.5],+ ["1,234,567", 1234567],+ ["1,234", 1234],+ ["1.234", 1.234],+ ["1,5", 1.5],+ ["12.04", 12.04],+ ["1.234,5", 1234.5],+ ["1.234.567,89", 1234567.89],+ ["1 234", 1234],+ ["1 234,5", 1234.5],+ ["5 000 000", 5000000],+ ["1 234", 1234],+ ["1 234,5", 1234.5],+ ["1'234.5", 1234.5],+ ["1’234", 1234]+ ];+ for (const [text, expected] of cases) {+ expect(numberOf(text), text).toBe(expected);+ }+ });++ it("reads a single mark before three digits as the locale does", () => {+ expect(numberOf("1.234", "de")).toBe(1234);+ expect(numberOf("1,234", "de")).toBe(1.234);+ expect(numberOf("1.5", "de")).toBe(1.5);+ expect(numberOf("1,5", "de")).toBe(1.5);+ expect(numberOf("1.234,5", "de")).toBe(1234.5);+ expect(numberOf("1,234.5", "de")).toBe(1234.5);+ expect(numberOf("1,234", "ro")).toBe(1.234);+ expect(numberOf("1,234", "fr")).toBe(1.234);+ });++ it("treats malformed digit runs as text", () => {+ const malformed = ["1.2.3", "192.168.1.1", "1,234.567.8", "1,2.5", "1,5 000", "1,23,456"];+ for (const text of malformed) {+ expect(classifyAutoSortValue(text, { locale: "en" }).kind, text).toBe("text");+ }+ });++ it("joins digits across a space only before exactly three digits", () => {+ expect(numberOf("10 20 30")).toBe(10);+ expect(numberOf("12 34")).toBe(12);+ expect(numberOf("2026 12345")).toBe(2026);+ });+});++describe("autoSort", () => {+ const mixed = ["b", "", "10", "2026-09-30", "15:02", "a", "9", "2025-01-01", "08:00", " "];++ it("orders times, dates, numbers, text, then empty values", () => {+ expect(sort(mixed, { locale: "en" })).toEqual(+ ["08:00", "15:02", "2025-01-01", "2026-09-30", "9", "10", "a", "b", "", " "]);+ });++ it("reverses all but the empty values when descending", () => {+ expect(sort(mixed, { locale: "en", isDescending: true })).toEqual(+ ["b", "a", "10", "9", "2026-09-30", "2025-01-01", "15:02", "08:00", "", " "]);+ });++ it("sorts dates written in different forms by their instant", () => {+ expect(sort([+ "30 September 2026",+ "2026-09-30 13:00",+ "2026-09-29",+ "2026-09-30T15:02:38+03:00",+ "Wednesday, 1 January 2025"+ ], { locale: "en" })).toEqual([+ "Wednesday, 1 January 2025",+ "2026-09-29",+ "30 September 2026",+ "2026-09-30T15:02:38+03:00",+ "2026-09-30 13:00"+ ]);+ });++ it("sorts 12-hour and 24-hour times together", () => {+ expect(sort(["3:02 PM", "14:00", "9:30 AM", "12:00 AM"], { locale: "en" }))+ .toEqual(["12:00 AM", "9:30 AM", "14:00", "3:02 PM"]);+ });++ it("sorts numbers by value and equal numbers by text", () => {+ expect(sort(["$ 12.04", "100", "-3", "24.5m", "21 RON", "2"], { locale: "en" }))+ .toEqual(["-3", "2", "$ 12.04", "21 RON", "24.5m", "100"]);+ expect(sort(["24.5km", "24.5 m", "24.5"], { locale: "en" }))+ .toEqual(["24.5", "24.5 m", "24.5km"]);+ });++ it("sorts text with numeric collation in the locale", () => {+ expect(sort(["Item 10", "Item 9", "item 1"], { locale: "en" }))+ .toEqual(["item 1", "Item 9", "Item 10"]);+ expect(sort(["Äpple", "Zebra"], { locale: "en" })).toEqual(["Äpple", "Zebra"]);+ expect(sort(["Äpple", "Zebra"], { locale: "sv" })).toEqual(["Zebra", "Äpple"]);+ });++ it("uses the decimal mark of the locale", () => {+ expect(sort(["1.500", "2"], { locale: "en" })).toEqual(["1.500", "2"]);+ expect(sort(["1.500", "2"], { locale: "de" })).toEqual(["2", "1.500"]);+ });++ it("keeps the order of equal values in both directions", () => {+ const items = [{ id: 1, text: "x" }, { id: 2, text: "x" }, { id: 3, text: "a" }];+ const ids = (options: AutoSortOptions) =>+ autoSort(items, (item) => item.text, options).map((item) => item.id);+ expect(ids({})).toEqual([3, 1, 2]);+ expect(ids({ isDescending: true })).toEqual([1, 2, 3]);+ });++ it("falls back to the text for keys beyond the number range", () => {+ const huge = `1${"0".repeat(400)}`;+ expect(sort([`${huge}b`, `${huge}a`, "5"])).toEqual(["5", `${huge}a`, `${huge}b`]);+ });++ it("accepts Trilium locale ids and survives invalid ones", () => {+ expect(classifyAutoSortValue("2026年9月30日", { locale: "cn" }).kind).toBe("date");+ expect(classifyAutoSortValue("30/09/2026", { locale: "pt_br" }).kind).toBe("date");+ expect(classifyAutoSortValue("9/30/2026", { locale: "en_rtl" }).kind).toBe("date");+ expect(classifyAutoSortValue("Item 3", { locale: "!!" }).kind).toBe("text");+ expect(classifyAutoSortValue("Item 3", { locale: "" }).kind).toBe("text");+ });++ it("returns a new array and leaves the input alone", () => {+ const values = ["b", "a"];+ const sorted = sort(values);+ expect(sorted).toEqual(["a", "b"]);+ expect(values).toEqual(["b", "a"]);+ expect(sort([])).toEqual([]);+ });+});diff --git a/packages/commons/src/lib/auto_sort.ts b/packages/commons/src/lib/auto_sort.tsnew file mode 100644index 0000000000..f99a0bf33b--- /dev/null+++ b/packages/commons/src/lib/auto_sort.ts@@ -0,0 +1,175 @@+import { createDateParser } from "./auto_sort_dates.js";+import { normalizeLocale } from "./i18n.js";++export type AutoSortKind = "time" | "date" | "number" | "text" | "empty";++export interface AutoSortOptions {+ /** A Trilium locale id or a BCP 47 tag. Defaults to the runtime's locale. */+ locale?: string;+ isDescending?: boolean;+ /** More date formats to recognize, in Day.js syntax. */+ dateFormats?: string[];+}++export interface AutoSortValue {+ kind: AutoSortKind;+ /** Seconds since midnight, milliseconds since the epoch, or the number; `0` otherwise. */+ key: number;+ /** The trimmed text. */+ text: string;+}++/**+ * Sorts strings whose type is not known in advance, such as table cells or lines. Each value is+ * detected as a time, a date, a number, text or empty. Ascending order is times, dates, numbers,+ * then text; descending order reverses it. Empty values are always last. Equal values keep their+ * order. Typed data, such as attributes, has its own comparators instead.+ */+export function autoSort<T>(+ items: readonly T[],+ textOf: (item: T) => string,+ options: AutoSortOptions = {}+): T[] {+ const locale = resolveLocale(options.locale);+ const classify = createClassifier(locale, options.dateFormats ?? []);+ const collator = new Intl.Collator(locale, { numeric: true });+ const direction = options.isDescending ? -1 : 1;++ return items+ .map((item) => ({ item, value: classify(textOf(item)) }))+ .sort((a, b) => compareValues(a.value, b.value, collator, direction))+ .map(({ item }) => item);+}++/** Detects the kind and the sort key of a single value. */+export function classifyAutoSortValue(text: string, options: AutoSortOptions = {}): AutoSortValue {+ return createClassifier(resolveLocale(options.locale), options.dateFormats ?? [])(text);+}++const KIND_RANKS: Record<AutoSortKind, number> = { time: 0, date: 1, number: 2, text: 3, empty: 4 };++// A sign and a currency symbol in either order, then digits with grouping and decimal marks. A+// space or an apostrophe is a separator only before exactly three digits.+const NUMBER_START =+ /^([-+−]?)(?:\p{Sc}\s*)?([-+−]?)(\d+(?:(?:[.,]|[\s'’](?=\d{3}(?!\d)))\d+)*)/u;++function resolveLocale(locale: string | undefined): string | undefined {+ if (!locale) {+ return undefined;+ }++ const tag = normalizeLocale(locale);+ for (const candidate of [tag, tag.split("-")[0]]) {+ try {+ return Intl.getCanonicalLocales(candidate)[0];+ } catch {+ // An invalid tag, such as `en-rtl`, falls back to its language.+ }+ }+ return undefined;+}++function createClassifier(locale: string | undefined, dateFormats: string[]) {+ const dates = createDateParser(locale, dateFormats);+ const decimalMark = getDecimalMark(locale);++ return (rawText: string): AutoSortValue => {+ const text = rawText.trim();+ if (!text) {+ return { kind: "empty", key: 0, text };+ }++ const time = dates.parseTime(text);+ if (time !== null) {+ return { kind: "time", key: time, text };+ }++ const date = dates.parseDate(text);+ if (date !== null) {+ return { kind: "date", key: date, text };+ }++ const number = parseNumber(text, decimalMark);+ if (number !== null) {+ return { kind: "number", key: number, text };+ }++ return { kind: "text", key: 0, text };+ };+}++function compareValues(+ a: AutoSortValue,+ b: AutoSortValue,+ collator: Intl.Collator,+ direction: number+) {+ const isEmptyA = a.kind === "empty";+ const isEmptyB = b.kind === "empty";+ if (isEmptyA || isEmptyB) {+ return Number(isEmptyA) - Number(isEmptyB);+ }++ // `||` also skips a `NaN` from two infinite keys.+ const order = KIND_RANKS[a.kind] - KIND_RANKS[b.kind]+ || a.key - b.key+ || collator.compare(a.text, b.text);+ return order * direction;+}++function getDecimalMark(locale: string | undefined): string {+ const parts = new Intl.NumberFormat(locale).formatToParts(1.5);+ return parts.some((part) => part.type === "decimal" && part.value === ",") ? "," : ".";+}++/** Reads the number `text` starts with, or returns `null` when it does not start with one. */+function parseNumber(text: string, decimalMark: string): number | null {+ const match = NUMBER_START.exec(text);+ if (!match) {+ return null;+ }++ const [, signBefore, signAfter, digits] = match;+ const value = parseDigits(digits, decimalMark);+ if (value === null || (signBefore && signAfter)) {+ return null;+ }++ const sign = signBefore || signAfter;+ return sign === "-" || sign === "−" ? -value : value;+}++/**+ * Reads digits with grouping and decimal marks. When both `.` and `,` appear, the last one is the+ * decimal mark. A single mark followed by other than three digits is a decimal mark. A single mark+ * followed by three digits follows the locale. Returns `null` for malformed runs such as `1.2.3`.+ */+function parseDigits(run: string, decimalMark: string): number | null {+ const groups = run.split(/\D/);+ const marks: string[] = run.match(/\D/g) ?? [];+ const last = marks.length - 1;+ const lastMark = marks[last];++ let decimalAt = -1;+ if (lastMark === "." || lastMark === ",") {+ const isUnique = marks.indexOf(lastMark) === last;+ const hasOtherMark = marks.includes(lastMark === "." ? "," : ".");+ if (hasOtherMark && !isUnique) {+ return null;+ }+ const isDecimalByDigits = groups[last + 1].length !== 3 || lastMark === decimalMark;+ if (hasOtherMark || (isUnique && isDecimalByDigits)) {+ decimalAt = last;+ }+ }++ for (const [index, group] of groups.slice(1).entries()) {+ if (index !== decimalAt && group.length !== 3) {+ return null;+ }+ }++ const integer = groups.slice(0, decimalAt === -1 ? undefined : decimalAt + 1).join("");+ const fraction = decimalAt === -1 ? "0" : groups[decimalAt + 1];+ return Number(`${integer}.${fraction}`);+}diff --git a/packages/commons/src/lib/auto_sort_dates.spec.ts b/packages/commons/src/lib/auto_sort_dates.spec.tsnew file mode 100644index 0000000000..113bbe77e5--- /dev/null+++ b/packages/commons/src/lib/auto_sort_dates.spec.ts@@ -0,0 +1,171 @@+import { describe, expect, it } from "vitest";++import { createDateParser } from "./auto_sort_dates.js";++const HOUR = 3600;+const MINUTE = 60;++describe("createDateParser", () => {+ describe("parseTime", () => {+ const { parseTime } = createDateParser("en", []);++ it("reads 24-hour times", () => {+ expect(parseTime("15:02")).toBe(15 * HOUR + 2 * MINUTE);+ expect(parseTime("9:05")).toBe(9 * HOUR + 5 * MINUTE);+ expect(parseTime("09:05")).toBe(9 * HOUR + 5 * MINUTE);+ expect(parseTime("15:02:38")).toBe(15 * HOUR + 2 * MINUTE + 38);+ expect(parseTime("15:02:38.250")).toBe(15 * HOUR + 2 * MINUTE + 38.25);+ expect(parseTime("0:00")).toBe(0);+ expect(parseTime("23:59:59")).toBe(24 * HOUR - 1);+ });++ it("reads 12-hour times with AM or PM", () => {+ expect(parseTime("3:02 PM")).toBe(15 * HOUR + 2 * MINUTE);+ expect(parseTime("3:02 pm")).toBe(15 * HOUR + 2 * MINUTE);+ expect(parseTime("3:02PM")).toBe(15 * HOUR + 2 * MINUTE);+ expect(parseTime("3:02 p.m.")).toBe(15 * HOUR + 2 * MINUTE);+ expect(parseTime("11:59 a. m.")).toBe(11 * HOUR + 59 * MINUTE);+ expect(parseTime("12:00 AM")).toBe(0);+ expect(parseTime("12:00 PM")).toBe(12 * HOUR);+ expect(parseTime("12:30:15 am")).toBe(30 * MINUTE + 15);+ });++ it("reads the AM and PM names of the locale", () => {+ expect(createDateParser("ko", []).parseTime("3:02 오후")).toBe(15 * HOUR + 2 * MINUTE);+ expect(createDateParser("ja", []).parseTime("3:02 午前")).toBe(3 * HOUR + 2 * MINUTE);+ expect(createDateParser("ro", []).parseTime("3:02 p.m.")).toBe(15 * HOUR + 2 * MINUTE);+ });++ it("rejects anything but a whole and valid time", () => {+ const invalid = [+ "", "24:00", "12:60", "12:30:60", "13:00 PM", "0:30 AM", "15:2", "1502", "15.02",+ "15:02 later", "at 15:02", "15:02+03:00", "15:02:38.5", "3:02 XM"+ ];+ for (const text of invalid) {+ expect(parseTime(text), text).toBeNull();+ }+ });+ });++ describe("parseDate", () => {+ const { parseDate } = createDateParser("en", []);++ it("reads ISO dates, with or without a time and an offset", () => {+ expect(parseDate("2026-09-30")).toBe(Date.UTC(2026, 8, 30));+ expect(parseDate("2026-9-3")).toBe(Date.UTC(2026, 8, 3));+ expect(parseDate("2026-09-30 15:02")).toBe(Date.UTC(2026, 8, 30, 15, 2));+ expect(parseDate("2026-09-30T15:02:38")).toBe(Date.UTC(2026, 8, 30, 15, 2, 38));+ expect(parseDate("2026-09-30T15:02:38.500Z")).toBe(Date.UTC(2026, 8, 30, 15, 2, 38, 500));+ expect(parseDate("2026-09-30t15:02:38z")).toBe(Date.UTC(2026, 8, 30, 15, 2, 38));+ expect(parseDate("2026-09-30T15:02:38+03:00")).toBe(Date.UTC(2026, 8, 30, 12, 2, 38));+ expect(parseDate("2026-09-30T15:02-0530")).toBe(Date.UTC(2026, 8, 30, 20, 32));+ expect(parseDate("2026-09-30 15:02 +03")).toBe(Date.UTC(2026, 8, 30, 12, 2));+ expect(parseDate("2026-09-30 3:02 PM")).toBe(Date.UTC(2026, 8, 30, 15, 2));+ });++ it("reads written dates with English names", () => {+ const expected = Date.UTC(2026, 8, 30);+ const texts = [+ "30 September 2026", "30 september 2026", "30 SEPTEMBER 2026", "30 Sep 2026",+ "30 Sep. 2026", "Wednesday, 30 September 2026", "Wed, 30 Sep 2026",+ "September 30, 2026", "Wednesday, September 30, 2026", "30 September 2026"+ ];+ for (const text of texts) {+ expect(parseDate(text), text).toBe(expected);+ }+ expect(parseDate("30 September 2026 15:02")).toBe(Date.UTC(2026, 8, 30, 15, 2));+ expect(parseDate("Wednesday, 30 September 2026, 3:02 PM"))+ .toBe(Date.UTC(2026, 8, 30, 15, 2));+ });++ it("reads the dates of the locale, as Intl writes them", () => {+ const expected = Date.UTC(2026, 8, 30);+ const cases: [string, string][] = [+ ["en", "9/30/2026"],+ ["en-GB", "30/09/2026"],+ ["en-GB", "30 Sept 2026"],+ ["de", "30.09.2026"],+ ["de", "30. September 2026"],+ ["de", "Mittwoch, 30. September 2026"],+ ["fr", "30 sept. 2026"],+ ["fr", "mercredi 30 septembre 2026"],+ ["ro", "miercuri, 30 septembrie 2026"],+ ["ru", "30 сентября 2026 г."],+ ["ru", "30 сентябрь 2026"],+ ["es", "30 de septiembre de 2026"],+ ["ja", "2026年9月30日"],+ ["ja", "2026/9/30"],+ ["ko", "2026. 9. 30."],+ ["ar", "30/9/2026"],+ ["th", "30/9/2026"]+ ];+ for (const [locale, text] of cases) {+ expect(createDateParser(locale, []).parseDate(text), `${locale}: ${text}`)+ .toBe(expected);+ }+ });++ it("matches English names in any locale", () => {+ expect(createDateParser("de", []).parseDate("30 Oct 2026")).toBe(Date.UTC(2026, 9, 30));+ expect(createDateParser("de", []).parseDate("30 Okt. 2026")).toBe(Date.UTC(2026, 9, 30));+ });++ it("reads the day-first dotted form in every locale", () => {+ expect(parseDate("30.09.2026")).toBe(Date.UTC(2026, 8, 30));+ expect(parseDate("1.2.2026")).toBe(Date.UTC(2026, 1, 1));+ });++ it("rejects anything but a whole and valid date", () => {+ const invalid = [+ "", "2026", "2026-09", "2026-02-30", "2026-13-01", "2026-00-10", "31 April 2026",+ "30 Foo 2026", "2026-09-30 at noon", "2026-09-30 25:00", "2026-09-30 15:02 later",+ "9/30/26", "30/09/2026", "Item 3", "15:02", "30 September", "September 2026"+ ];+ for (const text of invalid) {+ expect(parseDate(text), text).toBeNull();+ }+ });+ });++ describe("extra formats", () => {+ const { parseDate } = createDateParser("en", [+ "DD|MM|YYYY",+ "[Week] DD-MM-YY",+ "YYYY.MM.DD hh:mm",+ "YYYYMMDD Z",+ "Do MMMM YYYY",+ "",+ "HH:mm [h]",+ "[unclosed"+ ]);++ it("reads dates in Day.js formats", () => {+ expect(parseDate("30|09|2026")).toBe(Date.UTC(2026, 8, 30));+ expect(parseDate("30|09|2026 15:02")).toBe(Date.UTC(2026, 8, 30, 15, 2));+ expect(parseDate("Week 30-09-26")).toBe(Date.UTC(2026, 8, 30));+ expect(parseDate("Week 30-09-75")).toBe(Date.UTC(1975, 8, 30));+ expect(parseDate("20260930 +0100")).toBe(Date.UTC(2026, 8, 29, 23));+ });++ it("reads a 12-hour time without AM or PM as written", () => {+ expect(parseDate("2026.09.30 03:15")).toBe(Date.UTC(2026, 8, 30, 3, 15));+ expect(parseDate("2026.09.30 00:15")).toBeNull();+ });++ it("skips formats that are unsupported, empty or have no date", () => {+ expect(parseDate("30th September 2026")).toBeNull();+ expect(parseDate("15:02 h")).toBeNull();+ expect(parseDate("[unclosed")).toBeNull();+ });++ it("does not change the formats of other parsers", () => {+ expect(createDateParser("en", []).parseDate("30|09|2026")).toBeNull();+ });+ });++ it("reads the runtime locale when none is given", () => {+ const parser = createDateParser(undefined, []);+ expect(parser.parseDate("2026-09-30")).toBe(Date.UTC(2026, 8, 30));+ expect(parser.parseTime("15:02")).toBe(15 * HOUR + 2 * MINUTE);+ });+});diff --git a/packages/commons/src/lib/auto_sort_dates.ts b/packages/commons/src/lib/auto_sort_dates.tsnew file mode 100644index 0000000000..2b30717888--- /dev/null+++ b/packages/commons/src/lib/auto_sort_dates.ts@@ -0,0 +1,429 @@+/** Parses dates and times strictly, against Day.js-style formats and the locale's own patterns. */+export interface DateParser {+ /** Seconds since midnight, or `null` when `text` is not a time of day. */+ parseTime(text: string): number | null;+ /** Milliseconds since the epoch, or `null` when `text` is not a date. */+ parseDate(text: string): number | null;+}++/**+ * @param locale a BCP 47 tag for month, weekday and AM/PM names; English names always match.+ * @param extraFormats more date formats, in Day.js syntax. A format with unsupported tokens is+ * skipped.+ */+export function createDateParser(locale: string | undefined, extraFormats: string[]): DateParser {+ const data = getLocaleData(locale);+ const extraDateFormats = withTimes(tokenizeAll(extraFormats), data.timeTokens)+ .map((tokens) => compile(tokens, data));+ const dateFormats = [...data.dateFormats, ...extraDateFormats];++ return {+ parseTime: (text) => firstMatch(text, data.timeFormats, data, timeOfDay),+ parseDate: (text) => firstMatch(text, dateFormats, data, toEpoch)+ };+}++type NumericKind = "year" | "shortYear" | "month" | "day" | "hour" | "hour12" | "minute" | "second"+ | "millisecond";++type TokenKind = NumericKind | "monthName" | "weekday" | "meridiem" | "offset" | "optionalOffset"+ | "timeJoiner";++type Token = TokenKind | { literal: string };++interface FormatPart {+ kind?: TokenKind;+ regex: RegExp;+}++interface DateFields {+ year?: number;+ month?: number;+ day?: number;+ hour?: number;+ hour12?: number;+ isPm?: boolean;+ minute?: number;+ second?: number;+ millisecond?: number;+ offset?: number;+}++interface LocaleNames {+ months: Map<string, number>;+ monthPattern: string;+ weekdayPattern: string;+ meridiems: Map<string, boolean>;+ meridiemPattern: string;+}++interface LocaleData extends LocaleNames {+ timeTokens: Token[][];+ timeFormats: FormatPart[][];+ dateFormats: FormatPart[][];+}++const TIME_FORMATS = ["H:mm", "H:mm:ss", "H:mm:ss.SSS", "h:mm A", "h:mm:ss A", "h:mmA", "h:mm:ssA"];++const DATE_FORMATS = [+ "YYYY-MM-DD",+ "D.M.YYYY",+ "D MMMM YYYY",+ "dddd, D MMMM YYYY",+ "MMMM D, YYYY",+ "dddd, MMMM D, YYYY"+];++const INTL_DATE_OPTIONS: Intl.DateTimeFormatOptions[] = [+ { year: "numeric", month: "numeric", day: "numeric" },+ { dateStyle: "medium" },+ { dateStyle: "long" },+ { dateStyle: "full" }+];++const TOKEN_KINDS: Record<string, TokenKind> = {+ YYYY: "year",+ YY: "shortYear",+ MMMM: "monthName",+ MMM: "monthName",+ MM: "month",+ M: "month",+ DD: "day",+ D: "day",+ dddd: "weekday",+ ddd: "weekday",+ dd: "weekday",+ HH: "hour",+ H: "hour",+ hh: "hour12",+ h: "hour12",+ mm: "minute",+ m: "minute",+ ss: "second",+ s: "second",+ SSS: "millisecond",+ A: "meridiem",+ a: "meridiem",+ ZZ: "offset",+ Z: "offset"+};++// Alternatives are tried in order, so longer tokens are listed before their prefixes.+const TOKEN_REGEX = new RegExp(+ `\\[([^\\]]*)\\]|(${Object.keys(TOKEN_KINDS).join("|")})|([A-Za-z]+)|([^A-Za-z])`, "g");++const NUMBER_PATTERNS: Record<NumericKind, string> = {+ year: "\\d{4}",+ shortYear: "\\d{2}",+ month: "\\d{1,2}",+ day: "\\d{1,2}",+ hour: "\\d{1,2}",+ hour12: "\\d{1,2}",+ minute: "\\d{2}",+ second: "\\d{2}",+ millisecond: "\\d{3}"+};++const OFFSET_PATTERN = "\\s*(?:Z|[+-]\\d{2}(?::?\\d{2})?)";+const TIME_JOINER_PATTERN = "T|,?\\s+";+const SAMPLE_DATE = Date.UTC(2026, 8, 30);++const localeCache = new Map<string, LocaleData>();++function getLocaleData(locale: string | undefined): LocaleData {+ const cacheKey = locale ?? "";+ const cached = localeCache.get(cacheKey);+ if (cached) {+ return cached;+ }++ const names = buildNames(locale);+ const timeTokens = tokenizeAll(TIME_FORMATS);+ const dateTokens = [...tokenizeAll(DATE_FORMATS), ...intlDateTokens(locale)];+ const data: LocaleData = {+ ...names,+ timeTokens,+ timeFormats: timeTokens.map((tokens) => compile(tokens, names)),+ dateFormats: withTimes(dateTokens, timeTokens).map((tokens) => compile(tokens, names))+ };+ localeCache.set(cacheKey, data);+ return data;+}++function firstMatch(+ text: string,+ formats: FormatPart[][],+ names: LocaleNames,+ read: (fields: DateFields) => number | null+): number | null {+ for (const format of formats) {+ const fields = matchFormat(text, format, names);+ const value = fields ? read(fields) : null;+ if (value !== null) {+ return value;+ }+ }+ return null;+}++/** Each date format alone, then followed by each time format and an optional UTC offset. */+function withTimes(dateTokens: Token[][], timeTokens: Token[][]): Token[][] {+ const formats = [...dateTokens];+ for (const date of dateTokens) {+ for (const time of timeTokens) {+ formats.push([...date, "timeJoiner", ...time, "optionalOffset"]);+ }+ }+ return formats;+}++function tokenizeAll(formats: string[]): Token[][] {+ return formats.map(tokenize).filter((tokens) => tokens !== null);+}++/** Splits a Day.js format into tokens, or returns `null` when it uses an unsupported token. */+function tokenize(format: string): Token[] | null {+ const tokens: Token[] = [];+ for (const [, escaped, known, unsupported, character] of format.matchAll(TOKEN_REGEX)) {+ if (unsupported) {+ return null;+ }+ if (known) {+ tokens.push(TOKEN_KINDS[known]);+ continue;+ }++ const literal = escaped ?? character;+ const last = tokens.at(-1);+ if (typeof last === "object") {+ last.literal += literal;+ } else {+ tokens.push({ literal });+ }+ }+ return tokens.length > 0 ? tokens : null;+}++/** The locale's numeric and written date patterns, read from `Intl`. */+function intlDateTokens(locale: string | undefined): Token[][] {+ const formats: Token[][] = [];+ for (const options of INTL_DATE_OPTIONS) {+ const formatter = new Intl.DateTimeFormat(locale, {+ ...options,+ calendar: "gregory",+ numberingSystem: "latn",+ timeZone: "UTC"+ });+ const tokens = formatter.formatToParts(SAMPLE_DATE).map(intlPartToken);+ if (tokens.every((token) => token !== null)) {+ formats.push(tokens);+ }+ }+ return formats;+}++function intlPartToken({ type, value }: Intl.DateTimeFormatPart): Token | null {+ switch (type) {+ case "year": return "year";+ case "month": return /^\d+$/.test(value) ? "month" : "monthName";+ case "day": return "day";+ case "weekday": return "weekday";+ // Typed text has no right-to-left marks, which Arabic dates contain.+ case "literal": return { literal: value.replace(/[]/g, "") };+ default: return null;+ }+}++function compile(tokens: Token[], names: LocaleNames): FormatPart[] {+ return tokens.map((token) => typeof token === "string"+ ? { kind: token, regex: sticky(tokenPattern(token, names)) }+ : { regex: sticky(literalPattern(token.literal)) });+}++function tokenPattern(kind: TokenKind, names: LocaleNames): string {+ switch (kind) {+ case "monthName": return names.monthPattern;+ case "weekday": return names.weekdayPattern;+ case "meridiem": return names.meridiemPattern;+ case "offset": return OFFSET_PATTERN;+ case "optionalOffset": return `(?:${OFFSET_PATTERN})?`;+ case "timeJoiner": return TIME_JOINER_PATTERN;+ default: return NUMBER_PATTERNS[kind];+ }+}++function literalPattern(literal: string): string {+ return literal+ .split(/(\s+)/)+ .map((piece) => /^\s+$/.test(piece) ? "\\s+" : escapeRegExp(piece))+ .join("");+}++function sticky(pattern: string) {+ return new RegExp(`(?:${pattern})`, "iuy");+}++/** Reads the fields of `text` when the whole of it matches `format`. */+function matchFormat(text: string, format: FormatPart[], names: LocaleNames): DateFields | null {+ const fields: DateFields = {};+ let position = 0;+ for (const part of format) {+ part.regex.lastIndex = position;+ const match = part.regex.exec(text);+ if (!match) {+ return null;+ }+ if (part.kind) {+ readField(part.kind, match[0], fields, names);+ }+ position = part.regex.lastIndex;+ }+ return position === text.length ? fields : null;+}++function readField(kind: TokenKind, value: string, fields: DateFields, names: LocaleNames) {+ switch (kind) {+ case "shortYear": {+ const year = Number(value);+ fields.year = year > 68 ? 1900 + year : 2000 + year;+ break;+ }+ case "monthName":+ fields.month = names.months.get(nameKey(value));+ break;+ case "meridiem":+ fields.isPm = names.meridiems.get(nameKey(value));+ break;+ case "offset":+ case "optionalOffset":+ if (value) {+ fields.offset = parseOffset(value.trim());+ }+ break;+ case "weekday":+ case "timeJoiner":+ break;+ default:+ fields[kind] = Number(value);+ }+}++/** Minutes east of UTC, from `Z`, `+03`, `+0300` or `+03:00`. */+function parseOffset(value: string): number {+ if (value.toUpperCase() === "Z") {+ return 0;+ }+ const digits = value.slice(1).replace(":", "");+ const minutes = Number(digits.slice(0, 2)) * 60 + Number(digits.slice(2) || 0);+ return value.startsWith("-") ? -minutes : minutes;+}++function timeOfDay(fields: DateFields): number | null {+ let hour = fields.hour ?? 0;+ if (fields.hour12 !== undefined) {+ if (fields.hour12 < 1 || fields.hour12 > 12) {+ return null;+ }+ hour = fields.isPm === undefined+ ? fields.hour12+ : (fields.hour12 % 12) + (fields.isPm ? 12 : 0);+ }++ const minute = fields.minute ?? 0;+ const second = fields.second ?? 0;+ if (hour > 23 || minute > 59 || second > 59) {+ return null;+ }+ return hour * 3600 + minute * 60 + second + (fields.millisecond ?? 0) / 1000;+}++/** A date without an offset is read as UTC, so the result does not depend on the machine. */+function toEpoch(fields: DateFields): number | null {+ const { year, month, day } = fields;+ if (year === undefined || month === undefined || day === undefined) {+ return null;+ }++ const seconds = timeOfDay(fields);+ const date = new Date(Date.UTC(year, month - 1, day));+ if (seconds === null || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) {+ return null;+ }+ return date.getTime() + seconds * 1000 - (fields.offset ?? 0) * 60_000;+}++function buildNames(locale: string | undefined): LocaleNames {+ const months = new Map<string, number>();+ const weekdays = new Map<string, number>();+ const meridiems = new Map<string, boolean>([["am", false], ["pm", true]]);++ for (const current of [locale, "en"]) {+ for (const style of ["long", "short"] as const) {+ const standalone = new Intl.DateTimeFormat(current, { month: style, timeZone: "UTC" });+ // Some languages decline the month name inside a date ("30 сентября").+ const inDate = new Intl.DateTimeFormat(current,+ { day: "numeric", month: style, timeZone: "UTC" });+ for (let month = 0; month < 12; month++) {+ const date = Date.UTC(2000, month, 15);+ addName(months, standalone.format(date), month + 1);+ for (const name of partValues(inDate, date, "month")) {+ addName(months, name, month + 1);+ }+ }++ const weekday = new Intl.DateTimeFormat(current, { weekday: style, timeZone: "UTC" });+ for (let day = 0; day < 7; day++) {+ addName(weekdays, weekday.format(Date.UTC(2000, 0, 2 + day)), day);+ }+ }++ const hours = new Intl.DateTimeFormat(current,+ { hour: "numeric", hourCycle: "h12", timeZone: "UTC" });+ for (const [hour, isPm] of [[1, false], [13, true]] as const) {+ for (const name of partValues(hours, Date.UTC(2000, 0, 1, hour), "dayPeriod")) {+ addName(meridiems, name, isPm);+ }+ }+ }++ return {+ months,+ monthPattern: namesPattern(months),+ weekdayPattern: namesPattern(weekdays),+ meridiems,+ meridiemPattern: namesPattern(meridiems)+ };+}++function partValues(+ formatter: Intl.DateTimeFormat,+ date: number,+ type: Intl.DateTimeFormatPartTypes+) {+ return formatter.formatToParts(date)+ .filter((part) => part.type === type)+ .map((part) => part.value);+}++/** Names match ignoring case, spaces and dots: "Sept." matches "sept", "a. m." matches "AM". */+function nameKey(name: string) {+ return name.toLowerCase().replace(/[\s.]/g, "");+}++function addName<T>(names: Map<string, T>, name: string, value: T) {+ const key = nameKey(name);+ if (!names.has(key)) {+ names.set(key, value);+ }+}++function namesPattern(names: Map<string, unknown>): string {+ return [...names.keys()]+ .sort((a, b) => b.length - a.length)+ .map((key) => `${[...key].map(escapeRegExp).join("[\\s.]*")}\\.?`)+ .join("|");+}++function escapeRegExp(text: string) {+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}diff --git a/packages/commons/src/lib/i18n.spec.ts b/packages/commons/src/lib/i18n.spec.tsindex c7b8473f04..14f643b9cc 100644--- a/packages/commons/src/lib/i18n.spec.ts+++ b/packages/commons/src/lib/i18n.spec.ts@@ -1,6 +1,12 @@import { describe, expect, it } from "vitest";-import { getEnglishName, getTesseractCode, isDisplayableLocale, LOCALES } from "./i18n.js";+import {+ getEnglishName,+ getTesseractCode,+ isDisplayableLocale,+ LOCALES,+ normalizeLocale+} from "./i18n.js";describe("getTesseractCode", () => {it("returns the Tesseract code for a mapped locale", () => {@@ -95,3 +101,13 @@ describe("getEnglishName", () => {expect(getEnglishName("ro", silent)).toBe("Romanian");});});++describe("normalizeLocale", () => {+ it("turns Trilium locale ids into BCP 47 tags", () => {+ expect(normalizeLocale("zh_CN")).toBe("zh-CN");+ expect(normalizeLocale("cn")).toBe("zh-CN");+ expect(normalizeLocale("tw")).toBe("zh-TW");+ expect(normalizeLocale("pt_br")).toBe("pt-br");+ expect(normalizeLocale("en")).toBe("en");+ });+});diff --git a/packages/commons/src/lib/i18n.ts b/packages/commons/src/lib/i18n.tsindex 83b04d2845..941287e6f1 100644--- a/packages/commons/src/lib/i18n.ts+++ b/packages/commons/src/lib/i18n.ts@@ -143,11 +143,21 @@ export function getEnglishName(}}+/** Turns a Trilium locale id (`pt_br`, `cn`) into the BCP 47 tag `Intl` expects. */+export function normalizeLocale(locale: string) {+ locale = locale.replaceAll("_", "-");+ switch (locale) {+ case "cn": return "zh-CN";+ case "tw": return "zh-TW";+ default: return locale;+ }+}+/*** Locale ids that are not BCP-47 tags, mapped to one.** The Chinese pair deliberately resolves through the script subtags rather than the regions- * `normalizeLocale` (in the client's `utils/formatters`) maps them to: `zh-Hans` reads as+ * `normalizeLocale` maps them to: `zh-Hans` reads as* "Simplified Chinese", whereas `zh-CN` would say "Chinese (China)" — the wrong distinction for* entries differing by script.*/