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(mobile/nav): integrate full context menu for mobile
Elian Doranac7ccbc11a02
diff --git a/apps/client/src/menus/tree_context_menu.ts b/apps/client/src/menus/tree_context_menu.tsindex 7fc1a8b008..7547f2e16c 100644--- a/apps/client/src/menus/tree_context_menu.ts+++ b/apps/client/src/menus/tree_context_menu.ts@@ -1,6 +1,9 @@import appContext, { type ContextMenuCommandData, type FilteredCommandNames } from "../components/app_context.js";+import type Component from "../components/component.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";@@ -28,338 +31,437 @@ let lastTargetNode: HTMLElement | null = null;// so they need to be added manually.export type TreeCommandNames = FilteredCommandNames<ContextMenuCommandData> | "openBulkActionsDialog" | "searchInSubtree";-export default class TreeContextMenu implements SelectMenuItemEventListener<TreeCommandNames> {- private treeWidget: NoteTreeWidget;- private node: Fancytree.FancytreeNode;+/**+ * 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;+ /** 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;+ /**+ * Invoked right before any command's handler runs. Fancytree uses this to+ * switch to the detail screen on mobile so dialogs/navigations are visible.+ */+ onBeforeCommand?: () => 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;+}- constructor(treeWidget: NoteTreeWidget, node: Fancytree.FancytreeNode) {- this.treeWidget = treeWidget;- this.node = node;- }+/**+ * 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+ };+}- async show(e: PointerEvent | JQuery.TouchStartEvent | JQuery.ContextMenuEvent) {- await contextMenu.show({- x: e.pageX ?? 0,- y: e.pageY ?? 0,- items: await this.getMenuItems(),- selectMenuItemHandler: (item, e) => this.selectMenuItemHandler(item),- 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');- }+/**+ * 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 } = resolved;++ 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 notOptionsOrHelp = !note.noteId.startsWith("_options") && !note.noteId.startsWith("_help");+ const parentNotSearch = !parentNote || parentNote.type !== "search";+ const insertNoteAfterEnabled = isNotRoot && !isHoisted && parentNotSearch;++ const items: (MenuItem<TreeCommandNames> | null)[] = [+ { title: t("tree-context-menu.open-in-a-new-tab"), command: "openInTab", shortcut: "Ctrl+Click", 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 },+ { title: t("tree-context-menu.open-in-a-new-window"), command: "openNoteInWindow", uiIcon: "bx bx-window-open", enabled: noSelectedNotes },+ { 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: insertNoteAfterEnabled ? await noteTypesService.getNoteTypeItems("insertNoteAfter") : null,+ enabled: insertNoteAfterEnabled && noSelectedNotes && notOptionsOrHelp,+ columns: 2+ },++ {+ title: t("tree-context-menu.insert-child-note"),+ command: "insertChildNote",+ keyboardShortcut: "createNoteInto",+ uiIcon: "bx bx-plus",+ items: notSearch ? await noteTypesService.getNoteTypeItems("insertChildNote") : null,+ enabled: notSearch && noSelectedNotes && notOptionsOrHelp && !hasSubtreeHidden && !isSpotlighted,+ columns: 2+ },++ { kind: "separator" },++ { title: t("tree-context-menu.protect-subtree"), command: "protectSubtree", uiIcon: "bx bx-check-shield", enabled: noSelectedNotes },++ { title: t("tree-context-menu.unprotect-subtree"), command: "unprotectSubtree", uiIcon: "bx bx-shield", enabled: noSelectedNotes },++ { kind: "separator" },++ {+ 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 },++ { 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())+ },- async getMenuItems(): Promise<MenuItem<TreeCommandNames>[]> {- const note = this.node.data.noteId ? await froca.getNote(this.node.data.noteId) : null;- const branch = froca.getBranch(this.node.data.branchId);- const isNotRoot = note?.noteId !== "root";- const isHoisted = note?.noteId === appContext.tabManager.getActiveContext()?.hoistedNoteId;- const parentNote = isNotRoot && branch ? await froca.getNote(branch.parentNoteId) : null;+ { kind: "separator" },- // some actions don't support multi-note, so they are disabled when notes are selected,- // the only exception is when the only selected note is the one that was right-clicked, then- // it's clear what the user meant to do.- const selNodes = this.treeWidget.getSelectedNodes();- const selectedNotes = await froca.getNotes(selNodes.map(node => node.data.noteId));- if (note && !selectedNotes.includes(note)) selectedNotes.push(note);- const isArchived = selectedNotes.every(note => note.isArchived);- const canToggleArchived = !selectedNotes.some(note => note.isArchived !== isArchived);-- const noSelectedNotes = selNodes.length === 0 || (selNodes.length === 1 && selNodes[0] === this.node);-- const notSearch = note?.type !== "search";- const hasSubtreeHidden = note?.isLabelTruthy("subtreeHidden") ?? false;- const isSpotlighted = this.node.extraClasses.includes("spotlighted-node");- const notOptionsOrHelp = !note?.noteId.startsWith("_options") && !note?.noteId.startsWith("_help");- const parentNotSearch = !parentNote || parentNote.type !== "search";- const insertNoteAfterEnabled = isNotRoot && !isHoisted && parentNotSearch;-- const items: (MenuItem<TreeCommandNames> | null)[] = [- { title: t("tree-context-menu.open-in-a-new-tab"), command: "openInTab", shortcut: "Ctrl+Click", 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 },- { title: t("tree-context-menu.open-in-a-new-window"), command: "openNoteInWindow", uiIcon: "bx bx-window-open", enabled: noSelectedNotes },- { 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",+ !hasSubtreeHidden && { title: t("tree-context-menu.expand-subtree"), command: "expandSubtree", keyboardShortcut: "expandSubtree", uiIcon: "bx bx-expand", enabled: noSelectedNotes },+ !hasSubtreeHidden && { 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",+ 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},- !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: insertNoteAfterEnabled ? await noteTypesService.getNoteTypeItems("insertNoteAfter") : null,- enabled: insertNoteAfterEnabled && noSelectedNotes && notOptionsOrHelp,- columns: 2- },- {- title: t("tree-context-menu.insert-child-note"),- command: "insertChildNote",- keyboardShortcut: "createNoteInto",- uiIcon: "bx bx-plus",- items: notSearch ? await noteTypesService.getNoteTypeItems("insertChildNote") : null,- enabled: notSearch && noSelectedNotes && notOptionsOrHelp && !hasSubtreeHidden && !isSpotlighted,- columns: 2- },+ { 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>[]+ },++ { kind: "separator" },++ {+ title: t("tree-context-menu.cut"),+ command: "cutNotesToClipboard",+ keyboardShortcut: "cutNotesToClipboard",+ uiIcon: "bx bx-cut",+ enabled: isNotRoot && !isHoisted && parentNotSearch+ },++ { title: t("tree-context-menu.copy-clone"), command: "copyNotesToClipboard", keyboardShortcut: "copyNotesToClipboard", uiIcon: "bx bx-copy", enabled: isNotRoot && !isHoisted },++ {+ title: t("tree-context-menu.paste-into"),+ command: "pasteNotesFromClipboard",+ keyboardShortcut: "pasteNotesFromClipboard",+ uiIcon: "bx bx-paste",+ enabled: !clipboard.isClipboardEmpty() && notSearch && noSelectedNotes+ },++ {+ title: t("tree-context-menu.paste-after"),+ command: "pasteNotesAfterFromClipboard",+ uiIcon: "bx bx-paste",+ enabled: !clipboard.isClipboardEmpty() && isNotRoot && !isHoisted && parentNotSearch && noSelectedNotes+ },++ {+ title: t("tree-context-menu.move-to"),+ command: "moveNotesTo",+ keyboardShortcut: "moveNotesTo",+ uiIcon: "bx bx-transfer",+ enabled: isNotRoot && !isHoisted && parentNotSearch+ },++ { title: t("tree-context-menu.clone-to"), command: "cloneNotesTo", keyboardShortcut: "cloneNotesTo", uiIcon: "bx bx-duplicate", enabled: isNotRoot && !isHoisted },++ {+ title: t("tree-context-menu.duplicate"),+ command: "duplicateSubtree",+ keyboardShortcut: "duplicateSubtree",+ uiIcon: "bx bx-outline",+ enabled: parentNotSearch && isNotRoot && !isHoisted && notOptionsOrHelp+ },++ {+ 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"+ }]);+ }+ }+ }+ },+ {+ title: t("tree-context-menu.delete"),+ command: "deleteNotes",+ keyboardShortcut: "deleteNotes",+ uiIcon: "bx bx-trash destructive-action-icon",+ enabled: isNotRoot && !isHoisted && parentNotSearch && notOptionsOrHelp+ },- { kind: "separator" },-- { title: t("tree-context-menu.protect-subtree"), command: "protectSubtree", uiIcon: "bx bx-check-shield", enabled: noSelectedNotes },-- { title: t("tree-context-menu.unprotect-subtree"), command: "unprotectSubtree", uiIcon: "bx bx-shield", enabled: noSelectedNotes },-- { kind: "separator" },-- {- 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 },-- { 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(note => note.isEligibleForConversionToAttachment())- },-- { kind: "separator" },-- !hasSubtreeHidden && { title: t("tree-context-menu.expand-subtree"), command: "expandSubtree", keyboardShortcut: "expandSubtree", uiIcon: "bx bx-expand", enabled: noSelectedNotes },- !hasSubtreeHidden && { 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",- handler: async () => {- const note = await froca.getNote(this.node.data.noteId);- if (!note) return;- 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>[]- },+ { kind: "separator" },- { kind: "separator" },+ (notOptionsOrHelp && selectedNotes.length === 1) ? {+ kind: "custom",+ componentFn: () => NoteColorPicker({ note })+ } : null,- {- title: t("tree-context-menu.cut"),- command: "cutNotesToClipboard",- keyboardShortcut: "cutNotesToClipboard",- uiIcon: "bx bx-cut",- enabled: isNotRoot && !isHoisted && parentNotSearch- },+ { kind: "separator" },- { title: t("tree-context-menu.copy-clone"), command: "copyNotesToClipboard", keyboardShortcut: "copyNotesToClipboard", uiIcon: "bx bx-copy", enabled: isNotRoot && !isHoisted },+ { title: t("tree-context-menu.import-into-note"), command: "importIntoNote", uiIcon: "bx bx-import", enabled: notSearch && noSelectedNotes && notOptionsOrHelp },- {- title: t("tree-context-menu.paste-into"),- command: "pasteNotesFromClipboard",- keyboardShortcut: "pasteNotesFromClipboard",- uiIcon: "bx bx-paste",- enabled: !clipboard.isClipboardEmpty() && notSearch && noSelectedNotes- },+ { title: t("tree-context-menu.export"), command: "exportNote", uiIcon: "bx bx-export", enabled: notSearch && noSelectedNotes && notOptionsOrHelp },- {- title: t("tree-context-menu.paste-after"),- command: "pasteNotesAfterFromClipboard",- uiIcon: "bx bx-paste",- enabled: !clipboard.isClipboardEmpty() && isNotRoot && !isHoisted && parentNotSearch && noSelectedNotes- },+ { kind: "separator" },- {- title: t("tree-context-menu.move-to"),- command: "moveNotesTo",- keyboardShortcut: "moveNotesTo",- uiIcon: "bx bx-transfer",- enabled: isNotRoot && !isHoisted && parentNotSearch- },+ {+ title: t("tree-context-menu.search-in-subtree"),+ command: "searchInSubtree",+ keyboardShortcut: "searchInSubtree",+ uiIcon: "bx bx-search",+ enabled: notSearch && noSelectedNotes+ }+ ];- { title: t("tree-context-menu.clone-to"), command: "cloneNotesTo", keyboardShortcut: "cloneNotesTo", uiIcon: "bx bx-duplicate", enabled: isNotRoot && !isHoisted },+ return items.filter((row) => row !== null) as MenuItem<TreeCommandNames>[];+}- {- title: t("tree-context-menu.duplicate"),- command: "duplicateSubtree",- keyboardShortcut: "duplicateSubtree",- uiIcon: "bx bx-outline",- enabled: parentNotSearch && isNotRoot && !isHoisted && notOptionsOrHelp- },+/**+ * 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 } = item;+ const resolved = resolveContext(ctx);+ const { note, branch, notePath, component, selectedOrActiveBranchIds, selectedOrActiveNoteIds } = resolved;++ resolved.onBeforeCommand?.();++ if (command === "openInTab") {+ appContext.tabManager.openTabWithNoteWithHoisting(notePath);+ } 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+ });+ } else if (command === "insertChildNote") {+ noteCreateService.createNote(notePath, {+ type,+ mime,+ isProtected: note.isProtected,+ templateNoteId+ });+ } 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;+ }- {- 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 note = selectedNotes[0];- if (!isArchived) {- attributes.addLabel(note.noteId, "archived");- } else {- attributes.removeOwnedLabelByName(note, "archived");- }- } else {- const noteIds = selectedNotes.map(note => note.noteId);- if (!isArchived) {- executeBulkActions(noteIds, [{- name: "addLabel", labelName: "archived"- }]);- } else {- executeBulkActions(noteIds, [{- name: "deleteLabel", labelName: "archived"- }]);- }- }- }- },- {- title: t("tree-context-menu.delete"),- command: "deleteNotes",- keyboardShortcut: "deleteNotes",- uiIcon: "bx bx-trash destructive-action-icon",- enabled: isNotRoot && !isHoisted && parentNotSearch && notOptionsOrHelp- },+ let converted = 0;- { kind: "separator"},+ for (const noteId of selectedOrActiveNoteIds) {+ const candidate = await froca.getNote(noteId);- (notOptionsOrHelp && selectedNotes.length === 1) ? {- kind: "custom",- componentFn: () => {- return NoteColorPicker({note});- }- } : null,+ if (candidate?.isEligibleForConversionToAttachment()) {+ const { attachment } = await server.post<ConvertToAttachmentResponse>(`notes/${candidate.noteId}/convert-to-attachment`);- { kind: "separator" },+ if (attachment) {+ converted++;+ }+ }+ }- { title: t("tree-context-menu.import-into-note"), command: "importIntoNote", uiIcon: "bx bx-import", enabled: notSearch && noSelectedNotes && notOptionsOrHelp },+ toastService.showMessage(t("tree-context-menu.converted-to-attachments", { count: converted }));+ } else if (command === "copyNotePathToClipboard") {+ navigator.clipboard.writeText(`#${notePath}`);+ } else if (command) {+ component.triggerCommand<TreeCommandNames>(command, {+ node: resolved.node,+ notePath,+ noteId: note.noteId,+ selectedOrActiveBranchIds,+ selectedOrActiveNoteIds+ });+ }+}- { title: t("tree-context-menu.export"), command: "exportNote", uiIcon: "bx bx-export", enabled: notSearch && noSelectedNotes && notOptionsOrHelp },+function parentNotePathOf(notePath: string): string {+ const idx = notePath.lastIndexOf("/");+ return idx >= 0 ? notePath.slice(0, idx) : "";+}- { kind: "separator" },+export default class TreeContextMenu implements SelectMenuItemEventListener<TreeCommandNames> {+ private treeWidget: NoteTreeWidget;+ private node: Fancytree.FancytreeNode;- {- title: t("tree-context-menu.search-in-subtree"),- command: "searchInSubtree",- keyboardShortcut: "searchInSubtree",- uiIcon: "bx bx-search",- enabled: notSearch && noSelectedNotes- }- ];- return items.filter((row) => row !== null) as MenuItem<TreeCommandNames>[];+ constructor(treeWidget: NoteTreeWidget, node: Fancytree.FancytreeNode) {+ this.treeWidget = treeWidget;+ this.node = node;}- async selectMenuItemHandler({ command, type, mime, templateNoteId }: MenuCommandItem<TreeCommandNames>) {- const notePath = treeService.getNotePath(this.node);-- if (utils.isMobile()) {- this.treeWidget.triggerCommand("setActiveScreen", { screen: "detail" });- }+ async show(e: PointerEvent | JQuery.TouchStartEvent | JQuery.ContextMenuEvent) {+ const ctx = await this.#buildContext();+ if (!ctx) return;- if (command === "openInTab") {- appContext.tabManager.openTabWithNoteWithHoisting(notePath);- } else if (command === "insertNoteAfter") {- const parentNotePath = treeService.getNotePath(this.node.getParent());- const isProtected = treeService.getParentProtectedStatus(this.node);-- noteCreateService.createNote(parentNotePath, {- target: "after",- targetBranchId: this.node.data.branchId,- type,- mime,- isProtected,- templateNoteId- });- } else if (command === "insertChildNote") {- const parentNotePath = treeService.getNotePath(this.node);-- noteCreateService.createNote(parentNotePath, {- type,- mime,- isProtected: this.node.data.isProtected,- templateNoteId- });- } else if (command === "openNoteInSplit") {- const subContexts = appContext.tabManager.getActiveContext()?.getSubContexts();- const { ntxId } = subContexts?.[subContexts.length - 1] ?? {};-- this.treeWidget.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;+ 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");+ }- let converted = 0;-- for (const noteId of this.treeWidget.getSelectedOrActiveNoteIds(this.node)) {- const note = await froca.getNote(noteId);+ // 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);+ }- if (note?.isEligibleForConversionToAttachment()) {- const { attachment } = await server.post<ConvertToAttachmentResponse>(`notes/${note.noteId}/convert-to-attachment`);+ 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;- if (attachment) {- converted++;- }+ 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,+ selectedOrActiveBranchIds: this.treeWidget.getSelectedOrActiveBranchIds(this.node),+ selectedOrActiveNoteIds: this.treeWidget.getSelectedOrActiveNoteIds(this.node),+ selectedNotes,+ isSpotlighted: this.node.extraClasses.includes("spotlighted-node"),+ node: this.node,+ onBeforeCommand: () => {+ if (utils.isMobile()) {+ this.treeWidget.triggerCommand("setActiveScreen", { screen: "detail" });}}-- toastService.showMessage(t("tree-context-menu.converted-to-attachments", { count: converted }));- } else if (command === "copyNotePathToClipboard") {- navigator.clipboard.writeText(`#${ notePath}`);- } else if (command) {- this.treeWidget.triggerCommand<TreeCommandNames>(command, {- node: this.node,- notePath,- noteId: this.node.data.noteId,- selectedOrActiveBranchIds: this.treeWidget.getSelectedOrActiveBranchIds(this.node),- selectedOrActiveNoteIds: this.treeWidget.getSelectedOrActiveNoteIds(this.node)- });- }+ };}}diff --git a/apps/client/src/widgets/mobile_widgets/MobileNoteNavigator.tsx b/apps/client/src/widgets/mobile_widgets/MobileNoteNavigator.tsxindex aa73976814..6ccdeb93dd 100644--- a/apps/client/src/widgets/mobile_widgets/MobileNoteNavigator.tsx+++ b/apps/client/src/widgets/mobile_widgets/MobileNoteNavigator.tsx@@ -3,19 +3,13 @@ import "./MobileNoteNavigator.css";import clsx from "clsx";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";-import appContext from "../../components/app_context";import type Component from "../../components/component";import type FNote from "../../entities/fnote";-import contextMenu, { MenuItem } from "../../menus/context_menu";-import NoteColorPicker from "../../menus/custom-items/NoteColorPicker";-import link_context_menu from "../../menus/link_context_menu";-import { TreeCommandNames } from "../../menus/tree_context_menu";-import attributes from "../../services/attributes";-import branches from "../../services/branches";+import contextMenu from "../../menus/context_menu";+import { buildTreeContextMenuItems, handleTreeContextMenuSelect } from "../../menus/tree_context_menu";import froca from "../../services/froca";import { t } from "../../services/i18n";-import note_create from "../../services/note_create";-import tree from "../../services/tree";+import utils from "../../services/utils";import { NoteContent } from "../collections/legacy/ListOrGridView";import {useActiveNoteContext,@@ -414,15 +408,22 @@ function buildStackForActiveNote(activeNotePath: string | null | undefined, hois}/**- * Mirrors the tree / breadcrumb right-click menu: open-in-* actions plus- * hoist / move / clone / duplicate / archive / delete / color / recent / search.+ * Builds the same rich tree context menu as Fancytree's `TreeContextMenu`, but+ * sourced from a note path so it can be used from the mobile navigator. The+ * heavy lifting (item construction, command dispatch) lives in+ * `tree_context_menu.ts`; this function just resolves `notePath` into the shared+ * `TreeContextMenuContext` and wires up the `contextMenu.show(...)` boilerplate.*/function buildNoteContextMenu(notePath: string, parentComponent: Component | null) {return async (e: MouseEvent) => {e.preventDefault();- const { noteId, parentNoteId } = tree.getNoteIdAndParentIdFromUrl(notePath);- if (!parentNoteId || !noteId) return;+ if (!parentComponent) return;++ const segments = notePath.split("/");+ const noteId = segments[segments.length - 1];+ const parentNoteId = segments.length >= 2 ? segments[segments.length - 2] : undefined;+ if (!noteId || !parentNoteId) return;const branchId = await froca.getBranchId(parentNoteId, noteId);if (!branchId) return;@@ -432,97 +433,23 @@ function buildNoteContextMenu(notePath: string, parentComponent: Component | nulconst note = await branch.getNote();if (!note) return;- const notSearch = note.type !== "search";- const notOptionsOrHelp = !note.noteId.startsWith("_options") && !note.noteId.startsWith("_help");- const isArchived = note.isArchived;- const isNotRoot = note.noteId !== "root";- const isHoisted = note.noteId === appContext.tabManager.getActiveContext()?.hoistedNoteId;- const parentNote = isNotRoot && branch ? await froca.getNote(branch.parentNoteId) : null;- const parentNotSearch = !parentNote || parentNote.type !== "search";-- const items = [- ...link_context_menu.getItems(e),- {- title: t("tree-context-menu.hoist-note"),- command: "toggleNoteHoisting",- uiIcon: "bx bxs-chevrons-up",- enabled: notSearch- },- { kind: "separator" },- {- title: t("tree-context-menu.move-to"),- command: "moveNotesTo",- uiIcon: "bx bx-transfer",- enabled: isNotRoot && !isHoisted && parentNotSearch- },- {- title: t("tree-context-menu.clone-to"),- command: "cloneNotesTo",- uiIcon: "bx bx-duplicate",- enabled: isNotRoot && !isHoisted- },- { kind: "separator" },- {- title: t("tree-context-menu.duplicate"),- command: "duplicateSubtree",- uiIcon: "bx bx-outline",- enabled: parentNotSearch && isNotRoot && !isHoisted && notOptionsOrHelp && note.isContentAvailable(),- handler: () => note_create.duplicateSubtree(noteId, branch.parentNoteId)- },- {- title: !isArchived ? t("tree-context-menu.archive") : t("tree-context-menu.unarchive"),- uiIcon: !isArchived ? "bx bx-archive" : "bx bx-archive-out",- handler: () => {- if (!isArchived) {- attributes.addLabel(note.noteId, "archived");- } else {- attributes.removeOwnedLabelByName(note, "archived");- }- }- },- {- title: t("tree-context-menu.delete"),- command: "deleteNotes",- uiIcon: "bx bx-trash destructive-action-icon",- enabled: isNotRoot && !isHoisted && parentNotSearch && notOptionsOrHelp,- handler: () => branches.deleteNotes([branchId])- },- { kind: "separator" },- notOptionsOrHelp- ? {- kind: "custom",- componentFn: () => NoteColorPicker({ note })+ const ctx = {+ note,+ branch,+ notePath,+ component: parentComponent,+ onBeforeCommand: () => {+ if (utils.isMobile()) {+ parentComponent.triggerCommand("setActiveScreen", { screen: "detail" });}- : null,- { kind: "separator" },- {- title: t("tree-context-menu.recent-changes-in-subtree"),- uiIcon: "bx bx-history",- enabled: notOptionsOrHelp,- handler: () => parentComponent?.triggerCommand("showRecentChanges", { ancestorNoteId: noteId })- },- {- title: t("tree-context-menu.search-in-subtree"),- command: "searchInSubtree",- uiIcon: "bx bx-search",- enabled: notSearch}- ];+ };- contextMenu.show({- items: items.filter(Boolean) as MenuItem<TreeCommandNames>[],+ await contextMenu.show({x: e.pageX,y: e.pageY,- selectMenuItemHandler: ({ command }) => {- if (link_context_menu.handleLinkContextMenuItem(command, e, notePath)) return;- if (!command) return;- parentComponent?.triggerCommand(command, {- noteId,- notePath,- selectedOrActiveBranchIds: [branchId],- selectedOrActiveNoteIds: [noteId]- });- }+ items: await buildTreeContextMenuItems(ctx),+ selectMenuItemHandler: (item) => handleTreeContextMenuSelect(item, ctx)});};}