Skip to content

Build your personal knowledge base with Trilium Notes

feat(text): pick the inserted date/time format from a split button

Elian Dorana28f64fa4524
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 4baf753761..009e08f4e4 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -154,8 +154,8 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
setIconPickerRequest(request);
return () => setIconPickerRequest(null);
},
- formatDateTime(date: Date) {
- return utils.formatDateTime(date, options.get("customDateTimeFormat"));
+ formatDateTime(date: Date, format?: string) {
+ return utils.formatDateTime(date, format ?? options.get("customDateTimeFormat"));
},
// Keyboard shortcut
async insertDateTimeToTextCommand() {
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.html
index e28cf27695..786d663785 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
@@ -71,6 +71,23 @@ src="1_Insert buttons_image.png" width="502" height="95">
it and press <kbd>Ctrl</kbd>+<kbd>C</kbd>. Then use <kbd>Ctrl</kbd>+<kbd>V</kbd>,
to paste as many times as needed.</li>
</ul>
+<h2>Date and time</h2>
+<p>The <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.</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 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.</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> (for
+ example <code>DD.MM.YYYY HH:mm</code>).</p>
<h2>Icons</h2>
<p>Icons just like the ones for the <a href="#root/_help_p9kXRFAkwN4o">note icon</a> can
be inserted in text. For more information see&nbsp;<a class="reference-link"
diff --git a/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md b/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md
index 94d6f3badb..9a2d2a655d 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
@@ -60,6 +60,15 @@ Page breaks are marked in the editor with the words _Page break_, but they will
* To insert a page break, press the <span class="tn-icon cke cke-page-break"></span> in the formatting toolbar.
* To insert many page breaks at once, insert a page break first, click on it and press <kbd>Ctrl</kbd>+<kbd>C</kbd>. Then use <kbd>Ctrl</kbd>+<kbd>V</kbd>, to paste as many times as needed.
+## Date and time
+
+The <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 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 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`).
+
## Icons
Icons just like the ones for the [note icon](../../Basic%20Concepts%20and%20Features/Notes/Note%20Icons%20%26%20Colors.md) can be inserted in text. For more information see <a class="reference-link" href="Insert%20buttons/Icons.md">Icons</a>.
\ No newline at end of file
diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.ts
index 1df277d259..4ea2c1f5da 100644
--- a/packages/ckeditor5/src/augmentation.ts
+++ b/packages/ckeditor5/src/augmentation.ts
@@ -36,8 +36,11 @@ declare global {
* a balloon — leaves `container` alone and answers `null`.
*/
showIconPicker(request: IconPickerRequest): (() => void) | null;
- /** Formats `date` for insertion, in the user's `customDateTimeFormat`. */
- formatDateTime(date: Date): string;
+ /**
+ * Formats `date` for insertion in the Day.js `format`, or in the user's
+ * `customDateTimeFormat` when none is given.
+ */
+ formatDateTime(date: Date, format?: string): string;
loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string): Promise<void>;
createNoteForReferenceLink(title: string, intoInbox: boolean): Promise<string | undefined>;
loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>, boxSize?: string): void;
diff --git a/packages/ckeditor5/src/plugins/insert_date_time.spec.ts b/packages/ckeditor5/src/plugins/insert_date_time.spec.ts
index c3288c9bfc..5891ba54ca 100644
--- a/packages/ckeditor5/src/plugins/insert_date_time.spec.ts
+++ b/packages/ckeditor5/src/plugins/insert_date_time.spec.ts
@@ -1,16 +1,19 @@
-import { _getModelData, _setModelData, Bold, ButtonView, ClassicEditor, Essentials, HorizontalLine, Paragraph } from "ckeditor5";
+import {
+ _getModelData, _setModelData, Bold, ButtonView, ClassicEditor, DropdownView, Essentials, HorizontalLine, ListItemView,
+ Paragraph, SplitButtonView
+} from "ckeditor5";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
import { installGlobMock } from "../../test/globals-test-kit.js";
-import InsertDateTimePlugin, { COMMAND_NAME } from "./insert_date_time.js";
+import InsertDateTimePlugin, { COMMAND_NAME, DATE_TIME_PRESETS } from "./insert_date_time.js";
describe("InsertDateTimePlugin", () => {
let editor: ClassicEditor;
let formatDateTime: ReturnType<typeof vi.fn>;
beforeEach(async () => {
- formatDateTime = vi.fn(() => "2026-09-25 10:30");
+ formatDateTime = vi.fn((_date: Date, format?: string) => (format ? `<${format}>` : "2026-09-25 10:30"));
installGlobMock({
getComponentByEl: () => ({ formatDateTime })
});
@@ -22,18 +25,13 @@ describe("InsertDateTimePlugin", () => {
expect(editor.plugins.get(InsertDateTimePlugin)).toBeInstanceOf(InsertDateTimePlugin);
expect(editor.commands.get(COMMAND_NAME)).toBeDefined();
expect(editor.ui.componentFactory.has("dateTime")).toBe(true);
-
- // No dictionary is configured here, so `t()` renders the message id, which is the English
- // label.
- const view = editor.ui.componentFactory.create("dateTime") as { label?: string };
- expect(view.label).toBe("Insert date/time");
});
it("inserts the date formatted by the host at the caret", () => {
_setModelData(editor.model, "<paragraph>Due: []</paragraph>");
editor.execute(COMMAND_NAME);
- expect(formatDateTime).toHaveBeenCalledWith(expect.any(Date));
+ expect(formatDateTime).toHaveBeenCalledWith(expect.any(Date), undefined);
expect(_getModelData(editor.model)).toBe("<paragraph>Due: 2026-09-25 10:30[]</paragraph>");
});
@@ -61,15 +59,80 @@ describe("InsertDateTimePlugin", () => {
expect(_getModelData(editor.model)).toBe("<paragraph>[yesterday]</paragraph>");
});
- it("wires the button to the command (enablement and execution)", () => {
- const view = editor.ui.componentFactory.create("dateTime") as ButtonView;
- const command = editor.commands.get(COMMAND_NAME);
+ it("passes a chosen format to the host", () => {
+ _setModelData(editor.model, "<paragraph>[]</paragraph>");
+ editor.execute(COMMAND_NAME, { format: "HH:mm" });
+
+ expect(formatDateTime).toHaveBeenCalledWith(expect.any(Date), "HH:mm");
+ expect(_getModelData(editor.model)).toBe("<paragraph><HH:mm>[]</paragraph>");
+ });
+
+ describe("split button", () => {
+ let dropdown: DropdownView;
+
+ beforeEach(() => {
+ dropdown = editor.ui.componentFactory.create("dateTime") as DropdownView;
+ });
+
+ function openList() {
+ dropdown.isOpen = true;
+ const items = dropdown.listView?.items;
+ expect(items).toBeDefined();
+ return [ ...(items ?? []) ]
+ .filter((item): item is ListItemView => item instanceof ListItemView)
+ .map((item) => item.children.get(0) as ButtonView);
+ }
+
+ it("inserts the date in the default format from the main button", () => {
+ expect(dropdown.buttonView).toBeInstanceOf(SplitButtonView);
+ // No dictionary is configured here, so `t()` renders the message id, which is the
+ // English label.
+ expect(dropdown.buttonView.label).toBe("Insert date/time");
+
+ const spy = vi.spyOn(editor, "execute");
+ dropdown.buttonView.fire("execute");
+ expect(spy).toHaveBeenCalledWith(COMMAND_NAME);
+ });
+
+ 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}>`) ]);
+ });
+
+ it("leaves out a preset that renders the same as the default format", () => {
+ formatDateTime.mockImplementation((_date: Date, format?: string) => (format === "HH:mm" || !format ? "same" : `<${format}>`));
+
+ const labels = openList().map((button) => button.label);
+ expect(labels.filter((label) => label === "same")).toHaveLength(1);
+ expect(labels).toHaveLength(DATE_TIME_PRESETS.length);
+ });
+
+ it("renders the labels again every time it opens", () => {
+ openList();
+ dropdown.isOpen = false;
+ formatDateTime.mockImplementation(() => "later");
- expect(view.isEnabled).toBe(command?.isEnabled);
+ expect(openList().map((button) => button.label)).toContain("later");
+ });
- const spy = vi.spyOn(editor, "execute");
- view.fire("execute");
- expect(spy).toHaveBeenCalledWith(COMMAND_NAME);
+ it("inserts the date in the format picked from the list", () => {
+ const [ defaultItem, firstPreset ] = openList();
+ const spy = vi.spyOn(editor, "execute");
+
+ firstPreset.fire("execute");
+ expect(spy).toHaveBeenLastCalledWith(COMMAND_NAME, { format: DATE_TIME_PRESETS[0] });
+
+ defaultItem.fire("execute");
+ expect(spy).toHaveBeenLastCalledWith(COMMAND_NAME, { format: undefined });
+ });
+
+ it("follows the command's enabled state", () => {
+ expect(dropdown.isEnabled).toBe(true);
+ editor.enableReadOnlyMode("test");
+ expect(dropdown.isEnabled).toBe(false);
+ editor.disableReadOnlyMode("test");
+ });
});
it("is enabled only when the editor is editable", () => {
diff --git a/packages/ckeditor5/src/plugins/insert_date_time.ts b/packages/ckeditor5/src/plugins/insert_date_time.ts
index 54491dce63..0ed3e46505 100644
--- a/packages/ckeditor5/src/plugins/insert_date_time.ts
+++ b/packages/ckeditor5/src/plugins/insert_date_time.ts
@@ -1,8 +1,24 @@
-import { ButtonView, Command, Plugin } from 'ckeditor5';
+import {
+ addListToDropdown, Collection, Command, createDropdown, type Editor, type ListDropdownItemDefinition, Plugin,
+ SplitButtonView, ViewModel
+} from 'ckeditor5';
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;
+
+/**
+ * Introduces the `dateTime` split button: the button inserts the current date and time in the
+ * user's `customDateTimeFormat`, and the list offers the same date in each of `DATE_TIME_PRESETS`.
+ */
export default class InsertDateTimePlugin extends Plugin {
init() {
const editor = this.editor;
@@ -12,20 +28,37 @@ export default class InsertDateTimePlugin extends Plugin {
editor.commands.add(COMMAND_NAME, command);
editor.ui.componentFactory.add('dateTime', locale => {
- const view = new ButtonView( locale );
+ const dropdownView = createDropdown(locale, SplitButtonView);
+ const items = new Collection<ListDropdownItemDefinition>();
- view.set( {
+ addListToDropdown(dropdownView, items);
+
+ dropdownView.buttonView.set({
label: t('Insert date/time'),
icon: dateTimeIcon,
tooltip: true
- } );
+ });
+ dropdownView.bind('isEnabled').to(command, 'isEnabled');
- view.bind('isEnabled').to(command, 'isEnabled');
- view.on('execute', () => {
+ // The labels show the current time, so they are rendered each time the list opens.
+ dropdownView.on('change:isOpen', (_evt, _name, isOpen) => {
+ if (isOpen) {
+ items.clear();
+ items.addMany(createFormatItems(editor));
+ }
+ });
+
+ dropdownView.buttonView.on('execute', () => {
editor.execute(COMMAND_NAME);
editor.editing.view.focus();
});
- return view;
+ dropdownView.on('execute', evt => {
+ const { format } = evt.source as { format?: string };
+ editor.execute(COMMAND_NAME, { format });
+ editor.editing.view.focus();
+ });
+
+ return dropdownView;
});
}
}
@@ -36,11 +69,14 @@ export default class InsertDateTimePlugin extends Plugin {
*/
class InsertDateTimeCommand extends Command {
- execute() {
+ /**
+ * @param options.format a Day.js format string; without one, the host applies the user's
+ * `customDateTimeFormat`.
+ */
+ execute({ format }: { format?: string } = {}) {
const model = this.editor.model;
const selection = model.document.selection;
- const editorEl = this.editor.editing.view.getDomRoot();
- const text = glob.getComponentByEl<EditorComponent>(editorEl).formatDateTime(new Date());
+ const text = formatNow(this.editor, format);
model.change(writer => {
const attributes = selection.getAttributes();
@@ -49,3 +85,33 @@ class InsertDateTimeCommand extends Command {
}
}
+
+/**
+ * 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.
+ */
+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;
+ }
+
+ seenLabels.add(label);
+ definitions.push({
+ type: 'button',
+ model: new ViewModel({ format, label, withText: true })
+ });
+ }
+
+ return definitions;
+}
+
+function formatNow(editor: Editor, format?: string) {
+ const editorEl = editor.editing.view.getDomRoot();
+ return glob.getComponentByEl<EditorComponent>(editorEl).formatDateTime(new Date(), format);
+}