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(text): offer every date/time format in the slash commands
Elian Doran24185f5f24e8
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex d4498eea1d..a8cb9be6d4 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4217,6 +4217,7 @@"insert-an-empty-mermaid-diagram": "Insert an empty Mermaid diagram","insert-below": "Insert below","insert-date-time": "Insert date/time",+ "insert-date-time-0": "Insert date/time: %0","insert-footnote-0": "Insert footnote %0","insert-math": "Insert math","insert-mermaid-diagram": "Insert Mermaid diagram",@@ -4224,7 +4225,7 @@"insert-paragraph-after-code-block": "Insert paragraph after code block","insert-paragraph-before-code-block": "Insert paragraph before code block","insert-text-snippet": "Insert text snippet",- "insert-the-current-date-and-time": "Insert the current date and time",+ "insert-time-0": "Insert time: %0","internal-link": "Internal link","justify-text-alignment": "Justify text alignment","keyboard-shortcut": "Keyboard shortcut",diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Insert buttons.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Insert buttons.htmlindex 786d663785..4ec6ddae29 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Insert buttons.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Insert buttons.html@@ -77,13 +77,15 @@ src="1_Insert buttons_image.png" width="502" height="95">there is any. The inserted text takes the formatting of the text aroundit, so a date inserted inside bold text is bold too.</p><ul>- <li>To insert the date in the default format, press the button itself, press <kbd>Alt</kbd>+<kbd>T</kbd>,- or use the <em>Insert date/time</em> entry of the <a class="reference-link"- href="#root/_help_ZlN4nump6EbW">Slash Commands</a>.</li>+ <li>To insert the date in the default format, press the button itself or press <kbd>Alt</kbd>+<kbd>T</kbd>.</li><li>To insert it in another format, press the arrow next to the button andpick a format from the list. Each entry shows the current date and timein that format: the default one, the date or the time alone, the date writtenout, and ISO 8601.</li>+ <li>The same formats are offered by the <a class="reference-link" href="#root/_help_ZlN4nump6EbW">Slash Commands</a>:+ type <code>/date</code>, <code>/time</code>, <code>/now</code> or <code>/today</code>.+ The <em>Insert date/time</em> entry uses the default format, and shows what+ it inserts underneath; the other entries show their output in the title.</li></ul><p>The default format can be changed in <a class="reference-link" href="#root/_help_4TIF1oA4VQRO">Options</a> → <em>Text Notes</em> → <em>Editor</em> → <em>Date/time format</em>,using <a href="https://day.js.org/docs/en/display/format">Day.js format tokens</a> (fordiff --git a/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md b/docs/User Guide/User Guide/Note Types/Text/Insert buttons.mdindex 9a2d2a655d..037d375af2 100644--- a/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md+++ b/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md@@ -64,8 +64,9 @@ Page breaks are marked in the editor with the words _Page break_, but they willThe <span class="tn-icon cke cke-trilium-date-time"></span> button inserts the current date and time at the cursor, replacing the selected text if there is any. The inserted text takes the formatting of the text around it, so a date inserted inside bold text is bold too.-* To insert the date in the default format, press the button itself, press <kbd>Alt</kbd>+<kbd>T</kbd>, or use the _Insert date/time_ entry of the <a class="reference-link" href="Slash%20Commands.md">Slash Commands</a>.+* To insert the date in the default format, press the button itself or press <kbd>Alt</kbd>+<kbd>T</kbd>.* To insert it in another format, press the arrow next to the button and pick a format from the list. Each entry shows the current date and time in that format: the default one, the date or the time alone, the date written out, and ISO 8601.+* The same formats are offered by the <a class="reference-link" href="Slash%20Commands.md">Slash Commands</a>: type `/date`, `/time`, `/now` or `/today`. The _Insert date/time_ entry uses the default format, and shows what it inserts underneath; the other entries show their output in the title.The default format can be changed in <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Text Notes_ → _Editor_ → _Date/time format_, using [Day.js format tokens](https://day.js.org/docs/en/display/format) (for example `DD.MM.YYYY HH:mm`).diff --git a/packages/ckeditor5/src/plugins/insert_date_time.spec.ts b/packages/ckeditor5/src/plugins/insert_date_time.spec.tsindex 5891ba54ca..bbb8e30e14 100644--- a/packages/ckeditor5/src/plugins/insert_date_time.spec.ts+++ b/packages/ckeditor5/src/plugins/insert_date_time.spec.ts@@ -97,7 +97,7 @@ describe("InsertDateTimePlugin", () => {it("lists the default format and every preset, labeled with the current date in it", () => {const labels = openList().map((button) => button.label);- expect(labels).toEqual([ "2026-09-25 10:30", ...DATE_TIME_PRESETS.map((format) => `<${format}>`) ]);+ expect(labels).toEqual([ "2026-09-25 10:30", ...DATE_TIME_PRESETS.map(({ format }) => `<${format}>`) ]);});it("leaves out a preset that renders the same as the default format", () => {@@ -121,7 +121,7 @@ describe("InsertDateTimePlugin", () => {const spy = vi.spyOn(editor, "execute");firstPreset.fire("execute");- expect(spy).toHaveBeenLastCalledWith(COMMAND_NAME, { format: DATE_TIME_PRESETS[0] });+ expect(spy).toHaveBeenLastCalledWith(COMMAND_NAME, { format: DATE_TIME_PRESETS[0].format });defaultItem.fire("execute");expect(spy).toHaveBeenLastCalledWith(COMMAND_NAME, { format: undefined });diff --git a/packages/ckeditor5/src/plugins/insert_date_time.ts b/packages/ckeditor5/src/plugins/insert_date_time.tsindex 0ed3e46505..d600526e8e 100644--- a/packages/ckeditor5/src/plugins/insert_date_time.ts+++ b/packages/ckeditor5/src/plugins/insert_date_time.ts@@ -6,14 +6,17 @@ import dateTimeIcon from '../icons/date-time.svg?raw';export const COMMAND_NAME = 'insertDateTimeToText';-/** The Day.js formats the split button offers besides the user's own `customDateTimeFormat`. */-export const DATE_TIME_PRESETS = [- 'YYYY-MM-DD',- 'HH:mm',- 'D MMMM YYYY',- 'dddd, D MMMM YYYY',- 'YYYY-MM-DDTHH:mm:ssZ'-] as const;+/**+ * The Day.js formats offered besides the user's own `customDateTimeFormat`. `kind` is `time` for a+ * format that shows only the time, so the `/` palette can title it "Insert time".+ */+export const DATE_TIME_PRESETS: readonly DateTimePreset[] = [+ { format: 'YYYY-MM-DD', kind: 'dateTime' },+ { format: 'HH:mm', kind: 'time' },+ { format: 'D MMMM YYYY', kind: 'dateTime' },+ { format: 'dddd, D MMMM YYYY', kind: 'dateTime' },+ { format: 'YYYY-MM-DDTHH:mm:ssZ', kind: 'dateTime' }+];/*** Introduces the `dateTime` split button: the button inserts the current date and time in the@@ -86,29 +89,45 @@ class InsertDateTimeCommand extends Command {}+export interface DateTimePreset {+ format: string;+ kind: 'dateTime' | 'time';+}++/** A format the user can insert the date in, with the current date and time rendered in it. */+export interface DateTimeFormatOption {+ /** A Day.js format string, or `undefined` for the user's `customDateTimeFormat`. */+ format?: string;+ kind: DateTimePreset['kind'];+ preview: string;+}+/**- * One list item per format, labeled with the current date in it. A preset that renders the same- * as the user's default is left out.+ * The user's default format followed by each of `DATE_TIME_PRESETS`, as the split button and the+ * `/` palette offer them. A preset whose preview matches an earlier one is left out.*/-function createFormatItems(editor: Editor) {- const formats = [ undefined, ...DATE_TIME_PRESETS ];- const seenLabels = new Set<string>();- const definitions: ListDropdownItemDefinition[] = [];-- for (const format of formats) {- const label = formatNow(editor, format);- if (seenLabels.has(label)) {- continue;- }+export function getDateTimeFormatOptions(editor: Editor): DateTimeFormatOption[] {+ const seenPreviews = new Set<string>();+ const options: DateTimeFormatOption[] = [];- seenLabels.add(label);- definitions.push({- type: 'button',- model: new ViewModel({ format, label, withText: true })- });+ const formats: Omit<DateTimeFormatOption, 'preview'>[] = [ { kind: 'dateTime' }, ...DATE_TIME_PRESETS ];++ for (const { format, kind } of formats) {+ const preview = formatNow(editor, format);+ if (!seenPreviews.has(preview)) {+ seenPreviews.add(preview);+ options.push({ format, kind, preview });+ }}- return definitions;+ return options;+}++function createFormatItems(editor: Editor): ListDropdownItemDefinition[] {+ return getDateTimeFormatOptions(editor).map(({ format, preview }) => ({+ type: 'button',+ model: new ViewModel({ format, label: preview, withText: true })+ }));}function formatNow(editor: Editor, format?: string) {diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.tsindex cf622ce185..98e8b2e887 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts@@ -18,10 +18,11 @@ import {import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";+import { installGlobMock } from "../../../test/globals-test-kit.js";import { COMMAND_NAME as INCLUDE_NOTE_COMMAND } from "../includenote.js";import { INSERT_ICON_COMMAND } from "../inline_icon/inline_icon_editing.js";import InlineIconUI from "../inline_icon/inline_icon_ui.js";-import { COMMAND_NAME as INSERT_DATE_TIME_COMMAND } from "../insert_date_time.js";+import InsertDateTimePlugin, { COMMAND_NAME as INSERT_DATE_TIME_COMMAND, DATE_TIME_PRESETS } from "../insert_date_time.js";import { COMMAND_NAME as INTERNAL_LINK_COMMAND } from "../internallink.js";import { COMMAND_NAME as MARKDOWN_IMPORT_COMMAND } from "../markdownimport.js";import MathUI from "../math/math_ui.js";@@ -630,7 +631,6 @@ describe("buildTriliumSlashCommands", () => {it.each([[ "collapsible", "Collapsible block", "collapsible" ],[ "footnote", "Footnote", "InsertFootnote" ],- [ "datetime", "Insert date/time", INSERT_DATE_TIME_COMMAND ],[ "internal-link", "Internal link", INTERNAL_LINK_COMMAND ],[ "include-note", "Include note", INCLUDE_NOTE_COMMAND ],[ "page-break", "Page break", "pageBreak" ],@@ -662,6 +662,62 @@ describe("buildTriliumSlashCommands", () => {expect(executeSpy).toHaveBeenCalledWith("alignment", { value });});+ it("offers no date/time entries without the date/time plugin", () => {+ expect(buildTriliumSlashCommands(editor).some((entry) => entry.id.startsWith("datetime"))).toBe(false);+ });++ describe("date/time entries", () => {+ let formatDateTime: ReturnType<typeof vi.fn>;++ beforeEach(async () => {+ formatDateTime = vi.fn((_date: Date, format?: string) => format ?? "2026-09-25 10:30");+ installGlobMock({ getComponentByEl: () => ({ formatDateTime }) });+ editor = await createTestEditor([ Essentials, Paragraph, InsertDateTimePlugin ]);+ });++ function dateTimeEntries() {+ return buildTriliumSlashCommands(editor).filter((entry) => entry.id.startsWith("datetime"));+ }++ it("shows the default format's output under the plain entry", () => {+ const entry = definition("datetime");++ expect(entry.title).toBe("Insert date/time");+ expect(entry.description).toBe("2026-09-25 10:30");+ expect(entry.commandName).toBe(INSERT_DATE_TIME_COMMAND);+ expect(entry.icon).toContain("<svg");+ });++ it("offers each preset titled with its output, inserting in that format", () => {+ const { fake, executeSpy } = makeFakeEditor();+ const presets = dateTimeEntries().slice(1);++ expect(presets.map((entry) => entry.title))+ .toEqual(DATE_TIME_PRESETS.map(({ format, kind }) => (kind === "time" ? `Insert time: ${format}` : `Insert date/time: ${format}`)));+ expect(presets.map((entry) => entry.title)).toContain("Insert time: HH:mm");++ for (const [ index, entry ] of presets.entries()) {+ expect(entry.commandName).toBe(INSERT_DATE_TIME_COMMAND);+ entry.execute?.(fake);+ expect(executeSpy).toHaveBeenLastCalledWith(INSERT_DATE_TIME_COMMAND, { format: DATE_TIME_PRESETS[index].format });+ }+ });++ it("leaves out a preset whose output matches the default format", () => {+ formatDateTime.mockImplementation((_date: Date, format?: string) => (format === "HH:mm" ? "2026-09-25 10:30" : format ?? "2026-09-25 10:30"));++ expect(dateTimeEntries()).toHaveLength(DATE_TIME_PRESETS.length);+ });++ it("finds every date/time entry by the words people type for it", () => {+ const entries = dateTimeEntries();++ for (const query of [ "date", "time", "now", "today", "timestamp" ]) {+ expect(matchSlashCommands(entries, query)).toHaveLength(entries.length);+ }+ });+ });+it("finds the to-do list under the names other editors give it", () => {const definitions = buildTriliumSlashCommands(editor);diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.tsindex beab1097a5..a1ab08f475 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts@@ -47,7 +47,7 @@ import aiIcon from "../ai_assistant/theme/icons/ai.svg?raw";import { COMMAND_NAME as INCLUDE_NOTE_COMMAND } from "../includenote.js";import { INSERT_ICON_COMMAND } from "../inline_icon/inline_icon_editing.js";import InlineIconUI from "../inline_icon/inline_icon_ui.js";-import { COMMAND_NAME as INSERT_DATE_TIME_COMMAND } from "../insert_date_time.js";+import InsertDateTimePlugin, { COMMAND_NAME as INSERT_DATE_TIME_COMMAND, getDateTimeFormatOptions } from "../insert_date_time.js";import { COMMAND_NAME as INTERNAL_LINK_COMMAND } from "../internallink.js";import { COMMAND_NAME as MARKDOWN_IMPORT_COMMAND } from "../markdownimport.js";import MathUI from "../math/math_ui.js";@@ -352,13 +352,7 @@ export function buildTriliumSlashCommands(editor: Editor): SlashCommandDefinitioicon: insertFootnoteIcon,commandName: "InsertFootnote"},- {- id: "datetime",- title: t("Insert date/time"),- description: t("Insert the current date and time"),- icon: dateTimeIcon,- commandName: INSERT_DATE_TIME_COMMAND- },+ ...buildDateTimeSlashCommands(editor),{id: "internal-link",title: t("Internal link"),@@ -530,6 +524,42 @@ function buildMermaidSlashCommands(editor: Editor): SlashCommandDefinition[] {return [ blank, ...templates ];}+/**+ * One entry per format `getDateTimeFormatOptions()` offers. The entry for the user's default format+ * shows its output as the description; each preset carries it in the title, so the rows differ at a+ * glance. `_catalog()` runs on every query, so the previews show the current time.+ */+function buildDateTimeSlashCommands(editor: Editor): SlashCommandDefinition[] {+ if (!editor.plugins.has(InsertDateTimePlugin)) {+ return [];+ }++ const t = editor.locale.t;+ const [ defaultOption, ...presets ] = getDateTimeFormatOptions(editor);+ const aliases = [ "date", "time", "now", "today", "timestamp" ];++ const defaultEntry: SlashCommandDefinition = {+ id: "datetime",+ title: t("Insert date/time"),+ description: defaultOption.preview,+ aliases,+ icon: dateTimeIcon,+ commandName: INSERT_DATE_TIME_COMMAND+ };++ const presetEntries = presets.map(({ format, kind, preview }) => ({+ id: `datetime-${format}`,+ title: kind === "time" ? t("Insert time: %0", preview) : t("Insert date/time: %0", preview),+ aliases,+ icon: dateTimeIcon,+ // `commandName` supplies the enabled state; `execute` passes the format along.+ commandName: INSERT_DATE_TIME_COMMAND,+ execute: (target: Editor) => target.execute(INSERT_DATE_TIME_COMMAND, { format })+ }));++ return [ defaultEntry, ...presetEntries ];+}+function buildAlignmentSlashCommands(editor: Editor): SlashCommandDefinition[] {const t = editor.locale.t;