Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(collections/table): add note date columns (closes #11728)
Elian Doran8b922b4881d8
diff --git a/apps/client/src/services/note_dates.spec.ts b/apps/client/src/services/note_dates.spec.tsindex 0c82a60910..662556fe49 100644--- a/apps/client/src/services/note_dates.spec.ts+++ b/apps/client/src/services/note_dates.spec.ts@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { getCreationDate, loadCreationDates } from "./note_dates";+import { getCreationDate, loadCreationDates, loadNoteDates } from "./note_dates";import server from "./server";/** Names notes uniquely per test: the cache is module-level and is never emptied. */@@ -85,3 +85,49 @@ describe("loadCreationDates", () => {expect(sizes).toEqual([ 1000, 1000, 500 ]);});});++describe("loadNoteDates", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ });++ it("asks every time, since a modification date changes with each edit", async () => {+ const [ edited, missing ] = noteIds(2);+ const post = vi.spyOn(server, "post").mockResolvedValue({+ [edited]: {+ utcDateCreated: "2026-01-05 09:30:00.000Z",+ utcDateModified: "2026-03-01 12:00:00.000Z"+ }+ });++ const dates = await loadNoteDates([ edited, missing ]);+ expect(dates.get(edited)).toEqual({+ created: Date.parse("2026-01-05 09:30:00.000Z"),+ modified: Date.parse("2026-03-01 12:00:00.000Z")+ });+ expect(dates.get(missing)).toBeUndefined();++ await loadNoteDates([ edited ]);+ expect(post).toHaveBeenCalledTimes(2);+ });++ it("keeps the creation dates it reads for getCreationDate()", async () => {+ const [ note ] = noteIds(1);+ vi.spyOn(server, "post").mockResolvedValue({+ [note]: { utcDateCreated: "2026-01-05 09:30:00.000Z" }+ });++ await loadNoteDates([ note ]);++ expect(getCreationDate(note)).toBe(Date.parse("2026-01-05 09:30:00.000Z"));+ expect(await loadCreationDates([ note ])).toBe(false);+ });++ it("splits a large set into batches", async () => {+ respondWith({});++ await loadNoteDates(noteIds(1500));++ expect(server.post).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/client/src/services/note_dates.ts b/apps/client/src/services/note_dates.tsindex bcc2105d60..ab69f7d2f9 100644--- a/apps/client/src/services/note_dates.ts+++ b/apps/client/src/services/note_dates.ts@@ -55,6 +55,36 @@ export function getCreationDate(noteId: string) {return creationDates.get(noteId);}+/** The creation and modification times of a note, in milliseconds. */+export interface NoteDates {+ created: number | undefined;+ modified: number | undefined;+}++/**+ * Loads the creation and modification dates of the given notes. Unlike `loadCreationDates()`, it+ * always asks the server, because `utcDateModified` changes with every edit. The creation dates it+ * reads are kept for `getCreationDate()`.+ *+ * @returns the dates by note ID, without the notes the server does not know.+ */+export async function loadNoteDates(noteIds: string[]) {+ const batches: Promise<Record<string, MetadataResponse>>[] = [];+ for (let at = 0; at < noteIds.length; at += BATCH_SIZE) {+ batches.push(fetchMetadata(noteIds.slice(at, at + BATCH_SIZE)));+ }++ const dates = new Map<string, NoteDates>();+ for (const metadata of await Promise.all(batches)) {+ for (const [ noteId, { utcDateCreated, utcDateModified } ] of Object.entries(metadata)) {+ const created = parseDate(utcDateCreated);+ creationDates.set(noteId, created);+ dates.set(noteId, { created, modified: parseDate(utcDateModified) });+ }+ }+ return dates;+}+function load(noteIds: string[]) {const request = fetchDates(noteIds).finally(() => {for (const noteId of noteIds) {@@ -70,11 +100,18 @@ function load(noteIds: string[]) {}async function fetchDates(noteIds: string[]) {- const metadata = await server.post<Record<string, MetadataResponse>>(- "notes/metadata", { noteIds });+ const metadata = await fetchMetadata(noteIds);for (const noteId of noteIds) {- const created = Date.parse(metadata?.[noteId]?.utcDateCreated ?? "");- creationDates.set(noteId, Number.isNaN(created) ? undefined : created);+ creationDates.set(noteId, parseDate(metadata[noteId]?.utcDateCreated));}}++async function fetchMetadata(noteIds: string[]) {+ return await server.post<Record<string, MetadataResponse>>("notes/metadata", { noteIds }) ?? {};+}++function parseDate(value: string | undefined) {+ const time = Date.parse(value ?? "");+ return Number.isNaN(time) ? undefined : time;+}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 4028a4d629..665ea5e906 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3609,7 +3609,11 @@"new-column-label": "Label...","new-column-relation": "Relation...","properties": "Table properties...",- "properties-title": "Table properties"+ "properties-title": "Table properties",+ "column-note-id": "Note ID",+ "column-title": "Title",+ "column-date-created": "Created",+ "column-date-modified": "Modified"},"book_properties_config": {"board-inbox-column": "Show inbox column",diff --git a/apps/client/src/widgets/collections/table/columns.spec.ts b/apps/client/src/widgets/collections/table/columns.spec.tsindex d257a38806..5220ed494d 100644--- a/apps/client/src/widgets/collections/table/columns.spec.ts+++ b/apps/client/src/widgets/collections/table/columns.spec.ts@@ -227,6 +227,30 @@ describe("buildColumnDefinitions — typed columns", () => {});});+describe("buildColumnDefinitions — note dates", () => {+ it("offers the creation and modification dates as hidden, read-only date & time columns", () => {+ const columns = buildColumnDefinitions({+ info: [],+ movableRows: false,+ existingColumnData: undefined,+ rowNumberHint: 1+ });++ for (const field of [ "dateCreated", "dateModified" ]) {+ const column = columns.find((candidate) => candidate.field === field);+ if (!column) throw new Error(`expected a ${field} column`);+ expect(column).toMatchObject({ visible: false, sorter: "string" });+ expect(column.editor).toBeUndefined();++ const formatter = column.formatter;+ if (typeof formatter !== "function") throw new Error("expected a formatter of its own");+ const value = "2026-01-05T09:30:00.000Z";+ expect(formatter({ getValue: () => value } as CellComponent, {}, () => {}))+ .toBe(formatLabelDate(value, true));+ }+ });+});+describe("buildColumnDefinitions — relation columns", () => {function relationColumn(isMulti: boolean) {return buildColumnDefinitions({diff --git a/apps/client/src/widgets/collections/table/columns.tsx b/apps/client/src/widgets/collections/table/columns.tsxindex aae394ec88..6245edb0b1 100644--- a/apps/client/src/widgets/collections/table/columns.tsx+++ b/apps/client/src/widgets/collections/table/columns.tsx@@ -7,6 +7,7 @@ import { useEffect, useRef, useState } from "preact/hooks";import type { CellComponent, ColumnComponent, ColumnDefinition, EmptyCallback, FormatterParams, RowComponent, ValueBooleanCallback, ValueVoidCallback } from "tabulator-tables";import froca from "../../../services/froca.js";+import { t } from "../../../services/i18n.js";import { safeUrlHref } from "../../../utils/url.js";import { applyLinkScheme, asLabelValues, formatLabelDate, LabelValueChips } from "../../attribute_widgets/label_value_display.jsx";import LabelValueInput from "../../attribute_widgets/label_value_input.jsx";@@ -120,6 +121,16 @@ function relationTitle(row: RowComponent, column: ColumnComponent): string {return relationTitles?.[name] ?? "";}+/**+ * A column showing one of the note's own dates. The rows hold the dates as ISO strings, so the+ * string sorter orders them by time.+ */+const noteDateColumn: Partial<ColumnDefinition> = {+ formatter: (cell) => formatLabelDate(cell.getValue(), true),+ sorter: "string",+ visible: false+};+interface BuildColumnArgs {info: AttributeDefinitionInformation[];movableRows: boolean;@@ -153,13 +164,13 @@ export function buildColumnDefinitions({ info, movableRows, existingColumnData,},{field: "noteId",- title: "Note ID",+ title: t("table_view.column-note-id"),formatter: wrapFormatter(({ cell }) => <code>{cell.getValue()}</code>),visible: false},{field: "title",- title: "Title",+ title: t("table_view.column-title"),editor: "input",formatter: wrapFormatter(({ cell }) => {const { noteId, iconClass, colorClass } = cell.getRow().getData();@@ -168,6 +179,16 @@ export function buildColumnDefinitions({ info, movableRows, existingColumnData,</span>;}),width: 400+ },+ {+ field: "dateCreated",+ title: t("table_view.column-date-created"),+ ...noteDateColumn+ },+ {+ field: "dateModified",+ title: t("table_view.column-date-modified"),+ ...noteDateColumn}];diff --git a/apps/client/src/widgets/collections/table/rows.spec.ts b/apps/client/src/widgets/collections/table/rows.spec.tsindex 997e9ab111..388d84d90f 100644--- a/apps/client/src/widgets/collections/table/rows.spec.ts+++ b/apps/client/src/widgets/collections/table/rows.spec.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import FAttribute from "../../../entities/fattribute";import type FNote from "../../../entities/fnote";@@ -161,6 +161,49 @@ describe("buildRowDefinitions", () => {relationTitles: { assignee: "" }});});++ it("carries each note's creation and modification dates as ISO strings, nested rows included", async () => {+ const parent = buildNote({+ title: "Collection",+ children: [+ { title: "Task", children: [ { title: "Subtask" } ] },+ { title: "Unknown to the server" }+ ]+ });+ const [ task, unknown ] = await Promise.all(parent.getChildBranches().map((branch) => branch.getNote()));+ const subtask = await task?.getChildBranches()[0]?.getNote();+ if (!task || !subtask || !unknown) throw new Error("expected the child notes to be built");++ const post = vi.spyOn(server, "post").mockResolvedValue({+ [task.noteId]: {+ utcDateCreated: "2026-01-05 09:30:00.000Z",+ utcDateModified: "2026-03-01 12:00:00.000Z"+ },+ [subtask.noteId]: {+ utcDateCreated: "2026-02-10 08:00:00.000Z",+ utcDateModified: "2026-02-11 08:00:00.000Z"+ }+ });++ const { definitions } = await buildRowDefinitions(parent, [], false);++ // The whole tree in one request rather than one per level.+ expect(post.mock.calls.filter(([ url ]) => url === "notes/metadata")).toHaveLength(1);+ expect(definitions).toMatchObject([+ {+ title: "Task",+ dateCreated: "2026-01-05T09:30:00.000Z",+ dateModified: "2026-03-01T12:00:00.000Z",+ _children: [ {+ title: "Subtask",+ dateCreated: "2026-02-10T08:00:00.000Z",+ dateModified: "2026-02-11T08:00:00.000Z"+ } ]+ },+ { title: "Unknown to the server", dateCreated: undefined, dateModified: undefined }+ ]);+ post.mockRestore();+ });});/** Gives the note another relation under a name it already carries, which one literal cannot. */diff --git a/apps/client/src/widgets/collections/table/rows.ts b/apps/client/src/widgets/collections/table/rows.tsindex 4f406b6553..8bd180956a 100644--- a/apps/client/src/widgets/collections/table/rows.ts+++ b/apps/client/src/widgets/collections/table/rows.ts@@ -2,6 +2,7 @@ import { extractAttributeDefinitionTypeAndName, LabelType } from "@triliumnext/cimport FNote from "../../../entities/fnote.js";import froca from "../../../services/froca.js";+import { loadNoteDates } from "../../../services/note_dates.js";import type { AttributeDefinitionInformation } from "./columns.js";export type TableData = {@@ -17,6 +18,10 @@ export type TableData = {* carries their titles joined, which is also the order the sort should read the set in.*/relationTitles: Record<string, string>;+ /** When the note was created, as an ISO string so that the string sorter orders it by time. */+ dateCreated: string | undefined;+ /** When the note was last modified, as an ISO string. */+ dateModified: string | undefined;branchId: string;colorClass: string | undefined;isArchived: boolean;@@ -63,6 +68,8 @@ export async function buildRowDefinitions(parentNote: FNote, infos: AttributeDeflabels,relations,relationTitles: {},+ dateCreated: undefined,+ dateModified: undefined,isArchived: note.isArchived,branchId: branch.branchId,colorClass: note.getColorClass()@@ -78,10 +85,10 @@ export async function buildRowDefinitions(parentNote: FNote, infos: AttributeDefdefinitions.push(def);}- // Filled over the whole tree at once, from the outermost call, so the targets are fetched as- // one batch rather than a request per row.+ // Filled over the whole tree at once, from the outermost call, so the targets and dates are+ // fetched as one batch rather than a request per row.if (currentDepth === 0) {- await fillRelationTitles(definitions);+ await Promise.all([ fillRelationTitles(definitions), fillNoteDates(definitions) ]);}return {@@ -119,6 +126,26 @@ async function fillRelationTitles(definitions: TableData[]) {});}+/** Fills each row's `dateCreated` and `dateModified`, loading the dates of the whole tree at once. */+async function fillNoteDates(definitions: TableData[]) {+ const noteIds: string[] = [];+ visitRows(definitions, ({ noteId }) => noteIds.push(noteId));+ if (noteIds.length === 0) {+ return;+ }++ const dates = await loadNoteDates(noteIds);+ visitRows(definitions, (def) => {+ const { created, modified } = dates.get(def.noteId) ?? {};+ def.dateCreated = toIsoString(created);+ def.dateModified = toIsoString(modified);+ });+}++function toIsoString(time: number | undefined) {+ return time === undefined ? undefined : new Date(time).toISOString();+}+/** A relation cell's targets: the one it holds, the several a set holds, or none at all. */function asTargetIds(value: TableData["relations"][string]): string[] {if (Array.isArray(value)) return value.filter(Boolean);diff --git a/docs/User Guide/User Guide/Collections/Table.md b/docs/User Guide/User Guide/Collections/Table.mdindex bf570829ad..5dbac3997d 100644--- a/docs/User Guide/User Guide/Collections/Table.md+++ b/docs/User Guide/User Guide/Collections/Table.md@@ -21,6 +21,7 @@ There are also a few predefined columns:* This simply counts the note and is affected by sorting.* <a class="reference-link" href="../Advanced%20Usage/Note%20ID.md">Note ID</a>, representing the unique ID used internally by Trilium* The title of the note.+* _Created_ and _Modified_, the date and time the note was created and last modified. These columns are hidden by default and can't be edited; show them from the column context menu and click their header to sort by them.## Interaction@@ -135,7 +136,7 @@ Limitations:## Limitations-* There is no support to filter the rows by a certain criteria. Consider using the table view in search for that use case.+* There is no support to filter the rows by a certain criteria. Consider using the table view in search for that use case; for example, `note.dateCreated >= TODAY-7` lists the notes created in the last week.## Use in search