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
import type { CKTextEditor } from "@triliumnext/ckeditor5";
import appContext, { type CommandNames } from "../components/app_context.js";
import { buildBlockReferenceMenuItems } from "../services/block_reference.js";
import { copyHtml, copyTextWithToast } from "../services/clipboard_ext.js";
import { t } from "../services/i18n.js";
import { getSearchEngine } from "../services/search_engine.js";
import server from "../services/server.js";
import utils from "../services/utils.js";
import { buildCodeEditorContextMenuItems } from "./code_editor_context_menu.js";
import contextMenu, { type MenuItem } from "./context_menu.js";
import { splitMenuItem } from "./context_menu_utils.js";
import { buildTableContextMenuSections, hasTableCellSelection } from "./table_context_menu.js";
import {
buildAiActionsMenuItem, buildSortSelectionMenuItem, getTextEditorAtSelection,
getTextEditorContaining
} from "./text_editor_context_menu.js";
/** What the pointer was over when the menu was summoned. */
export interface ContextMenuTarget {
/** URL of the link under the pointer, or an empty string. */
linkURL: string;
/** Visible text of that link, or an empty string. */
linkText: string;
/** Whether the pointer is over an image, video or audio element. */
isMedia: boolean;
/** Whether the element under the pointer accepts typing. */
isEditable: boolean;
/** The selected text, or an empty string. */
selectionText: string;
/** The element under the pointer, when the host can resolve one. */
element?: Element | null;
}
/**
* What the surrounding application can run on the menu's behalf. An optional member the host leaves
* out drops the rows that depend on it: a page never reaches the spell checker's state, and reads
* the clipboard only in a secure context, so the browser host leaves out what it cannot serve.
*/
export interface ContextMenuHost {
spelling?: {
misspelledWord: string;
suggestions: string[];
addToDictionary(word: string): void;
};
paste?: {
enabled: boolean;
run(): void;
runAsPlainText(): void;
/** Reads the clipboard, for the rows that paste through an editor command. */
read(): Promise<{ html: string; text: string }>;
};
canCut: boolean;
cut(): void | Promise<void>;
canCopy: boolean;
copy(): void | Promise<void>;
/** Opens a URL outside the note, in whatever the host uses for external links. */
openExternal(url: string): void;
}
/**
* Puts Trilium's menu over the browser's own wherever the pointer sits on a selection. A click at a
* bare caret keeps the native menu, the only way to spelling corrections and the browser's paste.
* Electron replaces the menu everywhere; see `electron_context_menu.ts`.
*/
export function setupContextMenu() {
document.addEventListener("contextmenu", (event) => {
// A widget that answers the click itself — the note tree, an internal link — has already
// put its own menu up.
if (event.defaultPrevented) {
return;
}
// Shift+right-click is Firefox's own way back to the browser's menu; honoring it gives
// Chrome and Safari, which have no bypass of their own, the same one.
if (event.shiftKey) {
return;
}
const element = event.target instanceof HTMLElement ? event.target : null;
const isEditable = acceptsTyping(element);
// `window.getSelection()` does not report a selection inside an `<input>` or `<textarea>`,
// so those keep the browser's menu, which is the better one for a plain text field.
// The clipboard and search rows act on the selection, so the pointer has to be on it: a
// right-click on the surrounding UI, which takes no selection of its own, leaves an
// earlier one standing.
const selection = window.getSelection();
const selectionText = selection?.toString() ?? "";
const isOnSelection = !!selection && (isOnSelectedCodeLine(selection, element, isEditable)
|| (!!selectionText.trim()
&& isPointInSelection(selection, event.clientX, event.clientY)));
// A table cell in the text editor is claimed even at a bare caret, for the table section.
const isOnEditableTableCell = isEditable && !!element?.closest("td, th");
if (!isOnSelection && !isOnEditableTableCell) {
return;
}
// Claimed before the items are built: after an await the default action has already run.
event.preventDefault();
const link = element?.closest("a[href]");
void showBrowserContextMenu(event.pageX, event.pageY, {
linkURL: link instanceof HTMLAnchorElement ? link.href : "",
linkText: link?.textContent ?? "",
isMedia: !!element?.closest("img, video, audio"),
isEditable,
// Claimed off the selection (a bare caret in a table cell), those rows get none.
selectionText: isOnSelection ? selectionText : "",
element
});
});
}
/**
* The rows the menu shows for `target`, in order, leaving out whatever `host` cannot serve.
*
* Callers own the positioning and the `selectMenuItemHandler`, because the spelling suggestions
* carry a `replaceMisspelling` command rather than a handler — only the host that produced them
* can commit one.
*/
export async function buildNoteContextMenuItems(
target: ContextMenuTarget,
host: ContextMenuHost
): Promise<MenuItem<CommandNames>[]> {
const platformModifier = utils.isMac() ? "Meta" : "Ctrl";
const items: MenuItem<CommandNames>[] = [];
// Resolved before the menu is built rather than lazily in a handler: the rows it produces
// depend on how the editor answers, and `isEditable` keeps the lookup off every click that
// lands somewhere a completion could not be committed anyway (a read-only note, the tree).
const aiActions = target.isEditable ? await buildAiActionsMenuItem() : null;
const tableSections = target.isEditable
? await buildTableContextMenuSections(target.element, host.paste)
: null;
// Read after the table sections are built, which moves the selection into the clicked cell.
// A cell selection supersedes `selectionText`: over one, Electron reports the hidden
// fake-selection label as the selected text, which no row should act on.
const hasCellSelection = tableSections !== null && await hasTableCellSelection(target.element);
const blockReferenceItems = target.isEditable
? await buildBlockReferenceMenuItems(target.element, host.paste)
: null;
const codeEditorItems = target.isEditable
? await buildCodeEditorContextMenuItems(target.element)
: null;
// The table section sorts the rows.
const sortItem = target.isEditable
? buildSortSelectionMenuItem(await getTextEditorContaining(target.element),
{ isRowsExcluded: tableSections !== null })
: null;
const hasText = !hasCellSelection && target.selectionText.trim().length > 0;
const hasClipboardContent = hasText || hasCellSelection;
if (host.spelling?.misspelledWord) {
const { misspelledWord, suggestions, addToDictionary } = host.spelling;
for (const suggestion of suggestions) {
items.push({
title: suggestion,
command: "replaceMisspelling",
spellingSuggestion: suggestion,
uiIcon: "bx bx-empty"
});
}
items.push({
title: t("electron_context_menu.add-term-to-dictionary", { term: utils.escapeHtml(misspelledWord) }),
uiIcon: "bx bx-plus",
handler: () => addToDictionary(misspelledWord)
});
items.push({ kind: "separator" });
}
if (aiActions) {
items.push(aiActions, { kind: "separator" });
}
if (tableSections) {
items.push(...tableSections.main, { kind: "separator" });
}
if (target.isEditable) {
items.push({
enabled: host.canCut && hasClipboardContent,
title: t("electron_context_menu.cut"),
shortcut: `${platformModifier}+X`,
uiIcon: "bx bx-cut",
handler: () => host.cut()
});
}
if (target.isEditable || hasText) {
const copyVariants: MenuItem<CommandNames>[] = [
{
enabled: hasClipboardContent,
title: t("electron_context_menu.copy-as-markdown"),
uiIcon: "bx bx-copy-alt",
handler: copySelectionAsMarkdown
}
];
const referenceItems = [ blockReferenceItems?.copy, blockReferenceItems?.copyTab ]
.filter((item): item is MenuItem<CommandNames> => !!item);
if (referenceItems.length) {
copyVariants.push({ kind: "separator" }, ...referenceItems);
}
items.push(splitMenuItem({
enabled: host.canCopy && hasClipboardContent,
title: t("electron_context_menu.copy"),
shortcut: `${platformModifier}+C`,
uiIcon: "bx bx-copy",
handler: () => host.copy()
}, copyVariants));
}
const unlinkable = [ "", "javascript:", "about:blank#blocked" ];
if (!unlinkable.includes(target.linkURL) && !target.isMedia) {
items.push({
title: t("electron_context_menu.copy-link"),
uiIcon: "bx bx-copy",
handler: () => {
const text = utils.escapeHtml(target.linkText || target.linkURL);
const html = `<a href="${utils.escapeHtml(target.linkURL)}">${text}</a>`;
void copyHtml(html, target.linkURL);
}
});
}
if (host.paste && target.isEditable) {
const { enabled, run, runAsPlainText } = host.paste;
const pasteVariants: MenuItem<CommandNames>[] = [
{
enabled,
title: t("electron_context_menu.paste-as-plain-text"),
shortcut: `${platformModifier}+Shift+V`,
uiIcon: "bx bx-paste",
handler: runAsPlainText
}
];
if (blockReferenceItems?.paste.length) {
pasteVariants.push({ kind: "separator" }, ...blockReferenceItems.paste);
}
if (tableSections?.pasteRows.length) {
pasteVariants.push({ kind: "separator" }, ...tableSections.pasteRows);
}
items.push(splitMenuItem({
enabled,
title: t("electron_context_menu.paste"),
shortcut: `${platformModifier}+V`,
uiIcon: "bx bx-paste",
handler: run
}, pasteVariants));
}
if (tableSections) {
const sortItems = sortItem ? [ tableSections.sort, sortItem ] : [ tableSections.sort ];
items.push({ kind: "separator" }, ...sortItems, { kind: "separator" },
...tableSections.delete, { kind: "separator" }, tableSections.select);
} else if (sortItem) {
items.push({ kind: "separator" }, sortItem);
}
if (codeEditorItems) {
items.push({ kind: "separator" }, ...codeEditorItems);
}
if (hasText) {
const { selectionText } = target;
const shortenedSelection = selectionText.length > 15
? `${selectionText.slice(0, 13)}…`
: selectionText;
items.push({ kind: "separator" });
const searchEngine = getSearchEngine();
if (searchEngine) {
const searchUrl = searchEngine.url.replace("{keyword}", encodeURIComponent(selectionText));
items.push({
title: t("electron_context_menu.search_online", {
term: utils.escapeHtml(shortenedSelection),
searchEngine: utils.escapeHtml(searchEngine.name)
}),
uiIcon: searchEngine.icon,
handler: () => host.openExternal(searchUrl)
});
}
items.push({
title: t("electron_context_menu.search_in_trilium", { term: utils.escapeHtml(shortenedSelection) }),
uiIcon: "bx bx-search",
handler: async () => {
await appContext.triggerCommand("searchNotes", { searchString: selectionText });
}
});
}
return items;
}
/**
* Returns the HTML to feed to the Markdown converter for the "Copy as Markdown" action.
*
* When the selection lives inside the active text note's CKEditor, we take the editor's
* data-pipeline HTML (`getSelectedHtml()`) — clean stored markup without the editing-view
* artifacts (`data-list-item-id`, collapsible handle/arrow spans, bogus-paragraph wrappers)
* that cloning the live DOM range drags along. For any other selection (read-only notes,
* dialogs, plain inputs) we fall back to cloning the DOM range.
*/
export async function getSelectedHtmlForMarkdown(): Promise<string> {
const editor = await getTextEditorAtSelection();
const selectedHtml = editor?.getSelectedHtml();
if (selectedHtml) return selectedHtml;
const selection = window.getSelection();
if (!selection || !selection.rangeCount) return "";
const range = selection.getRangeAt(0);
const div = document.createElement("div");
div.appendChild(range.cloneContents());
return div.innerHTML;
}
async function showBrowserContextMenu(x: number, y: number, target: ContextMenuTarget) {
const editor = await getTextEditorAtSelection();
const items = await buildNoteContextMenuItems(target, browserHost(editor, target.element));
if (!items.length) return;
contextMenu.show({ x, y, items, selectMenuItemHandler: () => {} });
}
/**
* Whether `element` is on a line of an editable code editor that `selection` touches. The whole
* line counts, so that the text tools are reachable for a selection of blank lines or spaces.
*/
function isOnSelectedCodeLine(
selection: Selection,
element: HTMLElement | null,
isEditable: boolean
) {
const line = isEditable ? element?.closest(".cm-line") : null;
return !!line && !selection.isCollapsed && selection.containsNode(line, true);
}
/** Whether the point (`x`, `y`), in viewport coordinates, lands on what `selection` highlights. */
function isPointInSelection(selection: Selection, x: number, y: number) {
for (let i = 0; i < selection.rangeCount; i++) {
for (const rect of Array.from(selection.getRangeAt(i).getClientRects())) {
if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {
return true;
}
}
}
return false;
}
/**
* Whether `element` takes typing, which is what decides the rows that write to a note.
*
* `isContentEditable` alone does not answer it inside a code note. CodeMirror drives
* `contenteditable` off its `editable` facet, which Trilium never lowers, and marks a read-only
* note with `aria-readonly` on the same element instead — so the attribute is what tells the two
* apart.
*/
function acceptsTyping(element: HTMLElement | null) {
return !!element?.isContentEditable && !element.closest("[aria-readonly='true']");
}
/**
* The host for a page, which has web APIs and nothing more.
*
* `editor` is what the selection sits in, when it sits in a text note at all — `null` in a code
* note, which has a CodeMirror instead, and in a plain field.
*/
function browserHost(
editor: CKTextEditor | null,
element: Element | null | undefined
): ContextMenuHost {
const paste = browserPaste(editor, element);
return {
...(paste && { paste }),
canCut: !editor?.isReadOnly,
cut() {
// A text note's editor is asked directly, so that the clipboard gets the clean
// data-pipeline HTML `copySelection` reads rather than the editing view's markup.
// Everywhere else the browser cuts, and CodeMirror takes that as it would any edit.
if (!editor) {
document.execCommand("cut");
return;
}
return copySelection().then(() => editor.execute("delete"));
},
canCopy: true,
copy: copySelection,
openExternal: (url) => window.open(url, "_blank", "noopener")
};
}
/**
* The paste rows for a page, supplied when `navigator.clipboard.read()` exists, which requires a
* secure context.
*/
function browserPaste(
editor: CKTextEditor | null,
element: Element | null | undefined
): ContextMenuHost["paste"] {
if (!navigator.clipboard?.read) {
return undefined;
}
return {
// Whether the clipboard holds anything is unknowable without reading it, which prompts
// for permission, so the rows stay enabled and an empty clipboard pastes nothing.
enabled: true,
run: () => void pasteFromClipboard(editor, element, false),
runAsPlainText: () => void pasteFromClipboard(editor, element, true),
read: readClipboard
};
}
async function pasteFromClipboard(
editor: CKTextEditor | null,
element: Element | null | undefined,
asPlainText: boolean
) {
// Pinned before the read, which can wait on a permission prompt, so the paste lands where the
// menu was opened.
const pasteTarget = editor?.capturePasteTarget();
try {
const { html, text } = await readClipboard();
// The editor's clipboard pipeline, so a paste lands the way a native one does — a table
// pasted into a multi-cell selection merges into it.
if (pasteTarget) {
pasteTarget.paste(asPlainText ? "" : html, text);
return;
}
// A non-CKEditor editable (a code note's CodeMirror, a plain field) takes the text
// flavor as a typed insertion.
const editable = element?.closest<HTMLElement>("[contenteditable]");
if (editable && text) {
editable.focus();
document.execCommand("insertText", false, text);
}
} catch (error) {
console.warn("Failed to paste from the clipboard:", error);
} finally {
pasteTarget?.release();
}
}
/** The first `text/html` and `text/plain` flavors on the clipboard, empty when absent. */
async function readClipboard(): Promise<{ html: string; text: string }> {
let html = "";
let text = "";
for (const item of await navigator.clipboard.read()) {
if (!html && item.types.includes("text/html")) {
html = await (await item.getType("text/html")).text();
}
if (!text && item.types.includes("text/plain")) {
text = await (await item.getType("text/plain")).text();
}
}
return { html, text };
}
/** Copies the selection as rich text, so that it pastes back into a note with its formatting. */
async function copySelection() {
const html = await getSelectedHtmlForMarkdown();
// The editor's own plain-text flavor first: over a multi-cell table selection the DOM
// selection reads as the hidden fake-selection label, not as cell text.
const editor = await getTextEditorAtSelection();
const plainText = (editor?.getSelectedPlainText() || window.getSelection()?.toString()) ?? "";
if (!html && !plainText) return;
await copyHtml(html || utils.escapeHtml(plainText), plainText);
}
async function copySelectionAsMarkdown() {
const htmlContent = await getSelectedHtmlForMarkdown();
if (!htmlContent) return;
try {
const { markdownContent } = await server.post<{ markdownContent: string }>(
"other/to-markdown",
// The clipboard never reimports, so a headerless table (a copied subset of body
// cells) becomes a markdown table under a blank header instead of raw HTML.
{ htmlContent, headerlessTables: "emptyHeader" }
);
copyTextWithToast(markdownContent);
} catch (error) {
console.error("Failed to copy as markdown:", error);
}
}