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 appContext, { type ContextMenuCommandData, type FilteredCommandNames } from "../components/app_context.js";
import type Component from "../components/component.js";
import type NoteContext from "../components/note_context.js";
import type { SelectMenuItemEventListener } from "../components/events.js";
import type FAttachment from "../entities/fattachment.js";
import type FBranch from "../entities/fbranch.js";
import type FNote from "../entities/fnote.js";
import attributes from "../services/attributes.js";
import { executeBulkActions } from "../services/bulk_action.js";
import clipboard from "../services/clipboard.js";
import { copyTextWithToast } from "../services/clipboard_ext.js";
import dialogService from "../services/dialog.js";
import froca from "../services/froca.js";
import { t } from "../services/i18n.js";
import noteCreateService from "../services/note_create.js";
import { notePresetOptions } from "../services/note_presets.js";
import noteTypesService from "../services/note_types.js";
import server from "../services/server.js";
import toastService from "../services/toast.js";
import treeService from "../services/tree.js";
import utils from "../services/utils.js";
import { showImageCompressionDialog } from "../widgets/dialogs/image_compression/image_compression_dialog.jsx";
import type NoteTreeWidget from "../widgets/note_tree.js";
import contextMenu, { type MenuCommandItem, type MenuItem } from "./context_menu.js";
import NoteColorPicker from "./custom-items/NoteColorPicker.jsx";
// TODO: Deduplicate once client/server is well split.
interface ConvertToAttachmentResponse {
attachment?: FAttachment;
}
let lastTargetNode: HTMLElement | null = null;
// This will include all commands that implement ContextMenuCommandData, but it will not work if it additional options are added via the `|` operator,
// so they need to be added manually.
export type TreeCommandNames = FilteredCommandNames<ContextMenuCommandData> | "openBulkActionsDialog" | "searchInSubtree";
/**
* Tree-agnostic context passed to the shared context-menu builder/handler.
* Fancytree's `TreeContextMenu` adapter and the mobile drill-down navigator both
* construct one of these from their native representations.
*/
export interface TreeContextMenuContext {
/** The note the menu is for. */
note: FNote;
/** The branch used to reach `note` in the current view (parent-to-child relation). */
branch: FBranch;
/** The note path to the target note in the current view. */
notePath: string;
/**
* Component responsible for dispatching tree commands (e.g. moveNotesTo,
* deleteNotes). Fancytree passes the tree widget itself; mobile passes its
* own parent component.
*/
component: Component;
/**
* Note context to activate newly created notes in. Trees hosted in popup dialogs (e.g. the
* task states tree popup) pass their own context, which lives outside the tab manager —
* without it, creation would activate the note in the background tab.
*/
noteContext?: NoteContext;
/** Branches to operate on in bulk-capable commands (defaults to [branch.branchId]). */
selectedOrActiveBranchIds?: string[];
/** Notes to operate on in bulk-capable commands (defaults to [note.noteId]). */
selectedOrActiveNoteIds?: string[];
/** Notes to use for archived / conversion-eligibility checks (defaults to [note]). */
selectedNotes?: FNote[];
/** Whether the note is currently spotlighted (Fancytree only). */
isSpotlighted?: boolean;
/**
* Which surface is showing the menu. Used to suppress items that don't make
* sense on a given surface (e.g. `expandSubtree` / `collapseSubtree` have no
* meaning in the mobile drill-down navigator). Defaults to `"desktop"`.
*/
target?: "desktop" | "mobile";
/**
* Invoked right before a command in `COMMANDS_THAT_SHOW_A_NOTE` runs. On mobile, callers
* switch to the detail screen here so that the note the command opens is visible.
*/
onRevealNote?: () => void;
/**
* Fancytree node for the target, when available. A handful of tree
* commands (cut/paste/export/expand/collapse/sort) read `node.data` or call
* tree-service helpers that expect a Fancytree node, so we forward it
* through the command payload for Fancytree callers. Omitted by mobile.
*/
node?: Fancytree.FancytreeNode;
}
/**
* Normalize a caller-supplied context into its defaulted form.
*/
function resolveContext(ctx: TreeContextMenuContext) {
return {
...ctx,
selectedOrActiveBranchIds: ctx.selectedOrActiveBranchIds ?? [ctx.branch.branchId],
selectedOrActiveNoteIds: ctx.selectedOrActiveNoteIds ?? [ctx.note.noteId],
selectedNotes: ctx.selectedNotes ?? [ctx.note],
isSpotlighted: ctx.isSpotlighted ?? false,
target: ctx.target ?? "desktop"
};
}
/**
* Build the list of context menu items for `ctx`. Callers render via
* `contextMenu.show({ items })` and dispatch selections with
* `handleTreeContextMenuSelect`.
*/
export async function buildTreeContextMenuItems(ctx: TreeContextMenuContext): Promise<MenuItem<TreeCommandNames>[]> {
const resolved = resolveContext(ctx);
const { note, branch, selectedNotes, isSpotlighted, target } = resolved;
const isMobileTarget = target === "mobile";
const isNotRoot = note.noteId !== "root";
const isHoisted = note.noteId === appContext.tabManager.getActiveContext()?.hoistedNoteId;
const parentNote = isNotRoot ? await froca.getNote(branch.parentNoteId) : null;
const isArchived = selectedNotes.every((n) => n.isArchived);
const canToggleArchived = !selectedNotes.some((n) => n.isArchived !== isArchived);
// Multi-select-aware actions are disabled when multiple distinct notes are selected,
// the exception being when the only selection is the target itself.
const noSelectedNotes = resolved.selectedOrActiveNoteIds.length <= 1
|| (resolved.selectedOrActiveNoteIds.length === 1 && resolved.selectedOrActiveNoteIds[0] === note.noteId);
const notSearch = note.type !== "search";
const hasSubtreeHidden = note.isLabelTruthy("subtreeHidden") ?? false;
const notOptions = !note.noteId.startsWith("_options");
// Help pages are virtual notes, which the server never clones, moves or gives children.
const notHelp = !note.noteId.startsWith("_help");
const notOptionsOrHelp = notOptions && notHelp;
const parentNotSearch = !parentNote || parentNote.type !== "search";
const insertNoteAfterEnabled = isNotRoot && !isHoisted && parentNotSearch;
const clipboardContents = clipboard.getContents();
// Pasting copied notes clones them; pasting cut notes moves them.
const pasteTooltip = (key: string) => clipboardContents?.mode === "copy"
? t(key, { count: clipboardContents.noteIds.length })
: undefined;
// Both submenus are built from the same templates, so they are fetched once and shared.
const noteTypeData = insertNoteAfterEnabled || notSearch
? await noteTypesService.loadNoteTypeData()
: null;
const insertNoteAfterItems = noteTypeData && insertNoteAfterEnabled
? noteTypesService.buildNoteTypeItems(noteTypeData, "insertNoteAfter")
: null;
const insertChildNoteItems = noteTypeData && notSearch
? noteTypesService.buildNoteTypeItems(noteTypeData, "insertChildNote")
: null;
const protectItem: MenuCommandItem<TreeCommandNames> = { title: t("tree-context-menu.protect-subtree"), command: "protectSubtree", uiIcon: "bx bx-check-shield", enabled: noSelectedNotes };
const unprotectItem: MenuCommandItem<TreeCommandNames> = { title: t("tree-context-menu.unprotect-subtree"), command: "unprotectSubtree", uiIcon: "bx bx-shield", enabled: noSelectedNotes };
const items: (MenuItem<TreeCommandNames> | null)[] = [
{
kind: "actions",
items: [
{
title: t("tree-context-menu.cut"),
command: "cutNotesToClipboard",
keyboardShortcut: "cutNotesToClipboard",
uiIcon: "bx bx-cut",
enabled: isNotRoot && !isHoisted && parentNotSearch && notHelp
},
{ title: t("tree-context-menu.clone"), tooltip: t("tree-context-menu.clone-tooltip"), command: "copyNotesToClipboard", keyboardShortcut: "copyNotesToClipboard", uiIcon: "bx bx-copy", enabled: isNotRoot && !isHoisted && notHelp },
// Shown only while something is cut or copied, which is when they are looked for.
...(!clipboardContents ? [] : [
{
title: t("tree-context-menu.paste-into"),
tooltip: pasteTooltip("tree-context-menu.paste-into-tooltip"),
command: "pasteNotesFromClipboard",
keyboardShortcut: "pasteNotesFromClipboard",
uiIcon: "bx bx-clipboard",
uiIconBadge: "bx bx-subdirectory-right",
enabled: notSearch && noSelectedNotes && notHelp
},
{
title: t("tree-context-menu.paste-after"),
tooltip: pasteTooltip("tree-context-menu.paste-after-tooltip"),
command: "pasteNotesAfterFromClipboard",
uiIcon: "bx bx-clipboard",
uiIconBadge: "bx bx-down-arrow-alt",
enabled: isNotRoot && !isHoisted && parentNotSearch && noSelectedNotes && notHelp
}
] satisfies MenuCommandItem<TreeCommandNames>[]),
{
title: t("tree-context-menu.delete-short"),
command: "deleteNotes",
keyboardShortcut: "deleteNotes",
uiIcon: "bx bx-trash destructive-action-icon",
enabled: isNotRoot && !isHoisted && parentNotSearch && notOptionsOrHelp
}
]
},
{ kind: "separator" },
// As the link context menu has it: the row opens a new tab, its arrow the other places. A
// mobile menu runs no action of a submenu's row, so there the places are rows of their own.
...(isMobileTarget ? [
{ title: t("tree-context-menu.open"), command: "openNote", uiIcon: "bx bx-file", enabled: noSelectedNotes },
{ title: t("tree-context-menu.open-in-a-new-tab"), command: "openInTab", uiIcon: "bx bx-link-external", enabled: noSelectedNotes },
{ title: t("tree-context-menu.open-in-a-new-split"), command: "openNoteInSplit", uiIcon: "bx bx-dock-right", enabled: noSelectedNotes }
] satisfies MenuItem<TreeCommandNames>[] : [ {
title: t("link_context_menu.open_note"),
command: "openInTab",
uiIcon: "bx bx-link-external",
enabled: noSelectedNotes,
items: [
{ title: t("tree-context-menu.open-in-a-new-tab"), command: "openInTab", shortcut: "Ctrl+Click", uiIcon: "bx bx-link-external" },
{ title: t("tree-context-menu.open-in-a-new-split"), command: "openNoteInSplit", uiIcon: "bx bx-dock-right" },
{ title: t("tree-context-menu.open-in-a-new-window"), command: "openNoteInWindow", uiIcon: "bx bx-window-open" }
]
} satisfies MenuItem<TreeCommandNames> ]),
{ title: t("tree-context-menu.open-in-popup"), command: "openNoteInPopup", uiIcon: "bx bx-edit", enabled: noSelectedNotes },
isHoisted
? null
: {
title: `${t("tree-context-menu.hoist-note")}`,
command: "toggleNoteHoisting",
keyboardShortcut: "toggleNoteHoisting",
uiIcon: "bx bxs-chevrons-up",
enabled: noSelectedNotes && notSearch
},
!isHoisted || !isNotRoot
? null
: { title: t("tree-context-menu.unhoist-note"), command: "toggleNoteHoisting", keyboardShortcut: "toggleNoteHoisting", uiIcon: "bx bx-door-open" },
{ kind: "separator" },
{
title: t("tree-context-menu.insert-note-after"),
command: "insertNoteAfter",
keyboardShortcut: "createNoteAfter",
uiIcon: "bx bx-plus",
items: insertNoteAfterItems,
filterable: true,
enabled: insertNoteAfterEnabled && noSelectedNotes && notOptionsOrHelp
},
{
title: t("tree-context-menu.insert-child-note"),
command: "insertChildNote",
keyboardShortcut: "createNoteInto",
uiIcon: "bx bx-subdirectory-right",
items: insertChildNoteItems,
filterable: true,
enabled: notSearch && noSelectedNotes && notOptionsOrHelp && !hasSubtreeHidden && !isSpotlighted
},
{ kind: "separator" },
{
title: t("tree-context-menu.move-to"),
command: "moveNotesTo",
keyboardShortcut: "moveNotesTo",
uiIcon: "bx bx-transfer",
enabled: isNotRoot && !isHoisted && parentNotSearch && notHelp
},
{ title: t("tree-context-menu.clone-to"), command: "cloneNotesTo", keyboardShortcut: "cloneNotesTo", uiIcon: "bx bx-duplicate", enabled: isNotRoot && !isHoisted && notHelp },
{
title: t("tree-context-menu.duplicate"),
command: "duplicateSubtree",
keyboardShortcut: "duplicateSubtree",
uiIcon: "bx bx-outline",
enabled: parentNotSearch && isNotRoot && !isHoisted && notOptionsOrHelp,
items: getDuplicateItems(selectedNotes)
},
{
title: !isArchived ? t("tree-context-menu.archive") : t("tree-context-menu.unarchive"),
uiIcon: !isArchived ? "bx bx-archive" : "bx bx-archive-out",
enabled: canToggleArchived,
handler: () => {
if (!selectedNotes.length) return;
if (selectedNotes.length == 1) {
const n = selectedNotes[0];
if (!isArchived) {
attributes.addLabel(n.noteId, "archived");
} else {
attributes.removeOwnedLabelByName(n, "archived");
}
} else {
const noteIds = selectedNotes.map((n) => n.noteId);
if (!isArchived) {
executeBulkActions(noteIds, [{
name: "addLabel", labelName: "archived"
}]);
} else {
executeBulkActions(noteIds, [{
name: "deleteLabel", labelName: "archived"
}]);
}
}
}
},
// Runs what the note's own state calls for; the submenu keeps both, for a subtree that is
// protected only in part.
{
...(note.isProtected ? unprotectItem : protectItem),
items: [ protectItem, unprotectItem ]
},
{ kind: "separator" },
(notOptionsOrHelp && selectedNotes.length === 1) ? {
kind: "custom",
componentFn: () => NoteColorPicker({ note })
} : null,
{ kind: "separator" },
{ title: t("tree-context-menu.import-into-note"), command: "importIntoNote", uiIcon: "bx bx-import", enabled: notSearch && noSelectedNotes && notOptionsOrHelp },
{ title: t("tree-context-menu.export"), command: "exportNote", uiIcon: "bx bx-export", enabled: notSearch && noSelectedNotes && notOptions },
{ kind: "separator" },
{
title: t("tree-context-menu.search-in-subtree"),
command: "searchInSubtree",
keyboardShortcut: "searchInSubtree",
uiIcon: "bx bx-search",
enabled: notSearch && noSelectedNotes
},
{
title: t("tree-context-menu.advanced"),
uiIcon: "bx bxs-wrench",
enabled: true,
items: [
{ title: t("tree-context-menu.apply-bulk-actions"), command: "openBulkActionsDialog", uiIcon: "bx bx-list-plus", enabled: true },
{
// One note at a time: the dialog is configured against what that note holds and
// reports on what it changed there, neither of which a multi-selection has.
title: t("compress-images-menu"),
uiIcon: "bx bx-collapse-alt",
enabled: noSelectedNotes && notOptionsOrHelp,
handler: () => void showImageCompressionDialog({ type: "note", noteId: note.noteId })
},
{ kind: "separator" },
{
title: t("tree-context-menu.edit-branch-prefix"),
command: "editBranchPrefix",
keyboardShortcut: "editBranchPrefix",
uiIcon: "bx bx-rename",
enabled: isNotRoot && parentNotSearch && notOptionsOrHelp
},
{
title: t("tree-context-menu.convert-to-attachment"),
command: "convertNoteToAttachment",
uiIcon: "bx bx-paperclip",
enabled: isNotRoot && !isHoisted && notOptionsOrHelp && selectedNotes.some((n) => n.isEligibleForConversionToAttachment())
},
{ kind: "separator" },
!hasSubtreeHidden && !isMobileTarget && { title: t("tree-context-menu.expand-subtree"), command: "expandSubtree", keyboardShortcut: "expandSubtree", uiIcon: "bx bx-expand", enabled: noSelectedNotes },
!hasSubtreeHidden && !isMobileTarget && { title: t("tree-context-menu.collapse-subtree"), command: "collapseSubtree", keyboardShortcut: "collapseSubtree", uiIcon: "bx bx-collapse", enabled: noSelectedNotes },
{
title: hasSubtreeHidden ? t("tree-context-menu.show-subtree") : t("tree-context-menu.hide-subtree"),
uiIcon: "bx bx-show",
enabled: isNotRoot,
handler: async () => {
attributes.setBooleanWithInheritance(note, "subtreeHidden", !hasSubtreeHidden);
}
},
{
title: t("tree-context-menu.sort-by"),
command: "sortChildNotes",
keyboardShortcut: "sortChildNotes",
uiIcon: "bx bx-sort-down",
enabled: noSelectedNotes && notSearch
},
{ kind: "separator" },
{ title: t("tree-context-menu.copy-note-path-to-clipboard"), command: "copyNotePathToClipboard", uiIcon: "bx bx-directions", enabled: true },
{ title: t("tree-context-menu.recent-changes-in-subtree"), command: "recentChangesInSubtree", uiIcon: "bx bx-history", enabled: noSelectedNotes && notOptionsOrHelp }
].filter(Boolean) as MenuItem<TreeCommandNames>[]
}
];
return items.filter((row) => row !== null) as MenuItem<TreeCommandNames>[];
}
/**
* Dispatch a selection from a tree context menu. Most commands are forwarded via
* `ctx.component.triggerCommand`; a handful are handled locally because they
* need app-level services or tree-agnostic state.
*/
export async function handleTreeContextMenuSelect(
item: MenuCommandItem<TreeCommandNames>,
ctx: TreeContextMenuContext
) {
const { command, type, mime, templateNoteId, notePreset } = item;
const resolved = resolveContext(ctx);
const { note, branch, notePath, component, selectedOrActiveBranchIds, selectedOrActiveNoteIds } = resolved;
if (command && COMMANDS_THAT_SHOW_A_NOTE.has(command)) {
resolved.onRevealNote?.();
}
if (command === "openNote") {
await (resolved.noteContext ?? appContext.tabManager.getActiveContext())?.setNote(notePath);
} else if (command === "openInTab") {
appContext.tabManager.openTabWithNoteWithHoisting(notePath, { placement: "afterCurrent" });
} else if (command === "insertNoteAfter") {
const parentNotePath = parentNotePathOf(notePath);
const parentNote = await froca.getNote(branch.parentNoteId);
noteCreateService.createNote(parentNotePath, {
target: "after",
targetBranchId: branch.branchId,
type,
mime,
isProtected: parentNote?.isProtected ?? false,
templateNoteId,
...notePresetOptions(notePreset),
noteContext: resolved.noteContext
});
} else if (command === "insertChildNote") {
noteCreateService.createNote(notePath, {
type,
mime,
isProtected: note.isProtected,
templateNoteId,
...notePresetOptions(notePreset),
noteContext: resolved.noteContext
});
} else if (command === "openNoteInSplit") {
const subContexts = appContext.tabManager.getActiveContext()?.getSubContexts();
const { ntxId } = subContexts?.[subContexts.length - 1] ?? {};
component.triggerCommand("openNewNoteSplit", { ntxId, notePath });
} else if (command === "openNoteInWindow") {
appContext.triggerCommand("openInWindow", {
notePath,
hoistedNoteId: appContext.tabManager.getActiveContext()?.hoistedNoteId
});
} else if (command === "openNoteInPopup") {
appContext.triggerCommand("openInPopup", { noteIdOrPath: notePath });
} else if (command === "convertNoteToAttachment") {
if (!(await dialogService.confirm(t("tree-context-menu.convert-to-attachment-confirm")))) {
return;
}
let converted = 0;
for (const noteId of selectedOrActiveNoteIds) {
const candidate = await froca.getNote(noteId);
if (candidate?.isEligibleForConversionToAttachment()) {
const { attachment } = await server.post<ConvertToAttachmentResponse>(`notes/${candidate.noteId}/convert-to-attachment`);
if (attachment) {
converted++;
}
}
}
toastService.showMessage(t("tree-context-menu.converted-to-attachments", { count: converted }));
} else if (command === "copyNotePathToClipboard") {
// Not `navigator.clipboard`: it is undefined outside secure contexts, and Trilium is
// routinely served over plain HTTP on a LAN. Matches the breadcrumb's copy of this command.
copyTextWithToast(`#${notePath}`);
} else if (command) {
component.triggerCommand<TreeCommandNames>(command, {
node: resolved.node,
notePath,
noteId: note.noteId,
branchId: branch.branchId,
selectedOrActiveBranchIds,
selectedOrActiveNoteIds
});
}
}
/**
* The commands whose result is a note on the detail screen: a new note, a duplicate, a split or a
* search. Every other command acts on the tree, the clipboard or a dialog, so the tree stays shown.
*/
const COMMANDS_THAT_SHOW_A_NOTE = new Set<TreeCommandNames>([
"insertNoteAfter",
"insertChildNote",
"duplicateNote",
"duplicateSubtree",
"openNoteInSplit",
"searchInSubtree"
]);
/**
* The choice between copying the children or not, offered only when a note to copy has children.
*/
export function getDuplicateItems(notes: FNote[]): MenuItem<TreeCommandNames>[] | null {
if (!notes.some((n) => n.hasChildren())) {
return null;
}
return [
{ title: t("tree-context-menu.duplicate-with-children"), command: "duplicateSubtree", keyboardShortcut: "duplicateSubtree", uiIcon: "bx bx-sitemap" },
{ title: t("tree-context-menu.duplicate-note-only"), command: "duplicateNote", keyboardShortcut: "duplicateNote", uiIcon: "bx bx-file" }
];
}
function parentNotePathOf(notePath: string): string {
const idx = notePath.lastIndexOf("/");
return idx >= 0 ? notePath.slice(0, idx) : "";
}
export default class TreeContextMenu implements SelectMenuItemEventListener<TreeCommandNames> {
private treeWidget: NoteTreeWidget;
private node: Fancytree.FancytreeNode;
constructor(treeWidget: NoteTreeWidget, node: Fancytree.FancytreeNode) {
this.treeWidget = treeWidget;
this.node = node;
}
async show(e: PointerEvent | JQuery.TouchStartEvent | JQuery.ContextMenuEvent) {
const ctx = await this.#buildContext();
if (!ctx) return;
await contextMenu.show({
x: e.pageX ?? 0,
y: e.pageY ?? 0,
items: await buildTreeContextMenuItems(ctx),
selectMenuItemHandler: (item) => handleTreeContextMenuSelect(item, ctx),
onHide: () => {
lastTargetNode?.classList.remove("fancytree-menu-target");
}
});
// It's placed after show to ensure the old target is cleared before showing the context menu again on repeated right-clicks.
lastTargetNode?.classList.remove("fancytree-menu-target");
lastTargetNode = this.node.span;
lastTargetNode.classList.add("fancytree-menu-target");
}
// Kept so callers using `selectMenuItemHandler` on this instance still work
// (e.g. via `SelectMenuItemEventListener`).
async selectMenuItemHandler(item: MenuCommandItem<TreeCommandNames>) {
const ctx = await this.#buildContext();
if (!ctx) return;
await handleTreeContextMenuSelect(item, ctx);
}
async #buildContext(): Promise<TreeContextMenuContext | null> {
const note = this.node.data.noteId ? await froca.getNote(this.node.data.noteId) : null;
const branch = froca.getBranch(this.node.data.branchId);
if (!note || !branch) return null;
const selNodes = this.treeWidget.getSelectedNodes();
const selectedNotes = await froca.getNotes(selNodes.map((n) => n.data.noteId));
if (!selectedNotes.includes(note)) selectedNotes.push(note);
return {
note,
branch,
notePath: treeService.getNotePath(this.node),
component: this.treeWidget,
noteContext: this.treeWidget.noteContext,
selectedOrActiveBranchIds: this.treeWidget.getSelectedOrActiveBranchIds(this.node),
selectedOrActiveNoteIds: this.treeWidget.getSelectedOrActiveNoteIds(this.node),
selectedNotes,
isSpotlighted: this.node.extraClasses.includes("spotlighted-node"),
node: this.node,
onRevealNote: () => {
if (utils.isMobile()) {
this.treeWidget.triggerCommand("setActiveScreen", { screen: "detail" });
}
}
};
}
}