Skip to content

Build your personal knowledge base with Trilium Notes

21.3 KB
Raw Blame
import type { CKTextEditor, ContentEmbedState, PositionValue } from "@triliumnext/ckeditor5";
import { EXTENDED_CODE_BLOCK_CLASS } from "@triliumnext/commons";

import type { GeoMouseEvent } from "../widgets/collections/geomap/map.js";

import appContext, { type CommandNames } from "../components/app_context.js";
import type FAttachment from "../entities/fattachment.js";
import type FNote from "../entities/fnote.js";
import froca from "../services/froca.js";
import { t } from "../services/i18n.js";
import type { ViewScope } from "../services/link.js";
import { openUrlExternally } from "../services/open.js";
import utils, { escapeHtml, isMobile, isShare } from "../services/utils.js";
import { DISPLAY_MODE_OPTIONS } from "../widgets/type_widgets/helpers/split_editor_mode.js";
import { getContentEmbedTools } from "../widgets/type_widgets/text/content_embed_tools.js";
import { getClosestNtxId } from "../widgets/widget_utils.js";
import contextMenu, { type MenuItem } from "./context_menu.js";
import { submenuItem } from "./context_menu_utils.js";
import { getTextEditorContaining, keepEditorFocused } from "./text_editor_context_menu.js";

/**
 * Where a link menu opens, and the element it is opened from. A mouse event is one; a control
 * acting on something shown elsewhere passes that thing as `target`.
 */
export type LinkMenuOrigin = Pick<MouseEvent, "pageX" | "pageY" | "target">;

/** The event that a note is opened from, whose target picks the split a new split goes next to. */
type EventOrigin = Pick<Event, "target"> | GeoMouseEvent;

/** The embed a menu is opened on, in a text note open for editing. */
interface MenuEmbed {
    editor: CKTextEditor;
    element: Element;
    state: ContentEmbedState;
}

const CHECK_ICON = "bx bx-check";

/** The positions of an embed under one heading of its menu. */
interface PositionGroup {
    titleKey: string;
    positions: { value: PositionValue; titleKey: string }[];
}

/** The positions of an embed, under how the text runs around it, as its toolbar lists them. */
const POSITION_GROUPS: PositionGroup[] = [
    {
        titleKey: "link_context_menu.break_text",
        positions: [
            { value: "left", titleKey: "link_context_menu.align_left" },
            { value: "center", titleKey: "link_context_menu.align_center" },
            { value: "right", titleKey: "link_context_menu.align_right" }
        ]
    },
    {
        titleKey: "link_context_menu.wrap_text",
        positions: [
            { value: "wrap-left", titleKey: "link_context_menu.align_left" },
            { value: "wrap-right", titleKey: "link_context_menu.align_right" }
        ]
    }
];

/** The icons of the positions, from the editor's icon font. */
const POSITION_ICONS: Record<PositionValue, string> = {
    left: "cke cke-object-left",
    center: "cke cke-object-center",
    right: "cke cke-object-right",
    "wrap-left": "cke cke-object-inline-left",
    "wrap-right": "cke cke-object-inline-right"
};

let lastMenuRequest = 0;

async function openContextMenu(
    notePath: string,
    e: LinkMenuOrigin,
    viewScope: ViewScope = {},
    hoistedNoteId: string | null = null
) {
    const request = ++lastMenuRequest;
    const noteId = notePath.split("/").at(-1) ?? notePath;
    const editor = await getEditingTextEditor(getTarget(e));
    const embed = editor && getMenuEmbed(e, editor);
    const ownItems = viewScope.viewMode === "attachments" && viewScope.attachmentId
        ? await getAttachmentItems(noteId, viewScope.attachmentId, e, editor, embed)
        : await getNoteItems(noteId, e, editor, embed, !!viewScope.block);
    // A later right-click opened its own menu while this one waited for the editor or the
    // attachment.
    if (request !== lastMenuRequest) {
        return;
    }

    contextMenu.show({
        x: e.pageX,
        y: e.pageY,
        items: [ ...getItems(e), ...ownItems ],
        selectMenuItemHandler: ({ command }) => handleLinkContextMenuItem(command, e, notePath, viewScope, hoistedNoteId),
        ...(editor ? keepEditorFocused(editor) : {})
    });
}

/**
 * Opens the menu of the embed at `e` with its own commands only, for an embed that shows no note or
 * attachment, such as one that keeps its source in the note or one that plays a video.
 */
async function openEmbedContextMenu(e: LinkMenuOrigin) {
    const request = ++lastMenuRequest;
    const editor = await getEditingTextEditor(getTarget(e));
    const embed = editor && getMenuEmbed(e, editor);
    if (!editor || !embed || request !== lastMenuRequest) {
        return;
    }

    const { url } = embed.state;
    contextMenu.show({
        x: e.pageX,
        y: e.pageY,
        items: url ? getVideoItems(embed, url) : getSourceItems(embed),
        selectMenuItemHandler: () => {},
        ...keepEditorFocused(editor)
    });
}

/**
 * The menu of an embed that plays the video at `url`: opening the video outside Trilium, the
 * commands of the embed, and deleting it, each in a group of its own.
 */
function getVideoItems(embed: MenuEmbed, url: string): MenuItem<CommandNames>[] {
    return [
        {
            title: t("link_context_menu.open_externally"),
            uiIcon: "bx bx-link-external",
            handler: () => openUrlExternally(url)
        },
        { kind: "separator" },
        ...getEmbedItems(embed),
        ...getDeleteEmbedGroup(embed)
    ];
}

/**
 * The menu of an embed that keeps its source in the note: the commands of the embed, and for an
 * extended code block, deleting it in a group of its own.
 */
function getSourceItems(embed: MenuEmbed): MenuItem<CommandNames>[] {
    if (!embed.element.classList.contains(EXTENDED_CODE_BLOCK_CLASS)) {
        return getEmbedItems(embed);
    }

    return [ ...getEmbedItems(embed), ...getDeleteEmbedGroup(embed) ];
}

/** "Delete", which removes the embed from the note, in a group of its own. */
function getDeleteEmbedGroup(embed: MenuEmbed): MenuItem<CommandNames>[] {
    return [
        { kind: "separator" },
        {
            title: t("link_context_menu.delete"),
            uiIcon: "bx bx-trash destructive-action-icon",
            handler: () => runEmbedCommand(embed, "deleteContentEmbed")
        }
    ];
}

/** The origin of a menu that opens below `anchor` and acts from `target`. */
function getOriginBelow(anchor: Element, target: Element = anchor): LinkMenuOrigin {
    const { left, bottom } = anchor.getBoundingClientRect();
    return { pageX: left + window.scrollX, pageY: bottom + window.scrollY, target };
}

/**
 * The ways of opening a link. A shared page has no splits and no popup, so it offers only a new tab
 * and a new window, which open the note's shared page in the browser.
 */
function getItems(e: LinkMenuOrigin | GeoMouseEvent): MenuItem<CommandNames>[] {
    if (isShare) {
        return getOpenItems(e).filter((item) => "command" in item && item.command !== "openNoteInNewSplit");
    }

    return [ ...getOpenItems(e), getQuickEditItem() ];
}

/** On a shared page, the URL of a note's shared page, or `null` for a note that has none. */
let resolveShareLink: ((noteId: string) => string | null) | undefined;

/** Sets how a shared page finds the shared page of a note it opens, which only its host knows. */
function setShareLinkResolver(resolver: ((noteId: string) => string | null) | undefined) {
    resolveShareLink = resolver;
}

/** The places the note can be opened in, without the quick edit popup. */
function getOpenItems(e: LinkMenuOrigin | GeoMouseEvent): MenuItem<CommandNames>[] {
    const ntxId = getNtxId(e);
    const isMobileSplitOpen = isMobile() && appContext.tabManager.getNoteContextById(ntxId).getMainContext().getSubContexts().length > 1;

    return [
        { title: t("link_context_menu.open_note_in_new_tab"), command: "openNoteInNewTab", uiIcon: "bx bx-link-external" },
        { title: !isMobileSplitOpen ? t("link_context_menu.open_note_in_new_split") : t("link_context_menu.open_note_in_other_split"), command: "openNoteInNewSplit", uiIcon: "bx bx-dock-right" },
        { title: t("link_context_menu.open_note_in_new_window"), command: "openNoteInNewWindow", uiIcon: "bx bx-window-open" }
    ];
}

/** Opens the note in a popup over the current one. */
function getQuickEditItem(): MenuItem<CommandNames> {
    return { title: t("link_context_menu.open_note_in_popup"), command: "openNoteInPopup", uiIcon: "bx bx-edit" };
}

/**
 * The same places, folded into one submenu, for a menu that lists entries of its own beside them.
 *
 * The items keep their commands, so `handleLinkContextMenuItem` handles them from a submenu as it
 * does from the top level. The entry carries the first of those commands itself, so that picking it
 * opens a new tab without going into the submenu for the place it is opened in most often.
 */
function getOpenNoteItem(e: LinkMenuOrigin | GeoMouseEvent): MenuItem<CommandNames> {
    return {
        title: t("link_context_menu.open_note"),
        uiIcon: "bx bx-link-external",
        command: "openNoteInNewTab",
        items: getOpenItems(e)
    };
}

function handleLinkContextMenuItem(command: string | undefined, e: EventOrigin, notePath: string, viewScope = {}, hoistedNoteId: string | null = null) {
    if (isShare) {
        return openSharedPage(command, notePath);
    }

    if (!hoistedNoteId) {
        hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId ?? null;
    }

    if (command === "openNoteInNewTab") {
        appContext.tabManager.openContextWithNote(notePath, {
            hoistedNoteId, viewScope, placement: "afterCurrent"
        });
        return true;
    } else if (command === "openNoteInNewSplit") {
        const ntxId = getNtxId(e);
        if (!ntxId) return false;
        appContext.triggerCommand("openNewNoteSplit", { ntxId, notePath, hoistedNoteId, viewScope });
        return true;
    } else if (command === "openNoteInNewWindow") {
        appContext.triggerCommand("openInWindow", { notePath, hoistedNoteId, viewScope });
        return true;
    } else if (command === "openNoteInPopup") {
        appContext.triggerCommand("openInPopup", { noteIdOrPath: notePath, viewScope });
        return true;
    }

    return false;
}

/** Opens the shared page of the note at `notePath` in a new browser tab or window. */
function openSharedPage(command: string | undefined, notePath: string) {
    const link = resolveShareLink?.(notePath.split("/").at(-1) ?? notePath);
    if (!link || (command !== "openNoteInNewTab" && command !== "openNoteInNewWindow")) {
        return false;
    }

    window.open(link, "_blank", command === "openNoteInNewWindow" ? "noopener,popup" : "noopener");
    return true;
}

/**
 * The actions on the attachment a link points to, each group after a separator. A menu opened on
 * an embed of it has the commands of the embed after the first group, and deleting the embed last.
 * A menu opened in a note shown read-only has only the actions that leave the attachment unchanged.
 */
async function getAttachmentItems(
    noteId: string,
    attachmentId: string,
    e: LinkMenuOrigin,
    editor: CKTextEditor | null,
    embed: MenuEmbed | null
): Promise<MenuItem<CommandNames>[]> {
    // Imported on demand: `attachment_actions` imports `link`, which imports this module.
    const [ attachment, { getAttachmentActionGroups }, isReadOnly ] = await Promise.all([
        froca.getAttachmentOfNote(noteId, attachmentId),
        import("../services/attachment_actions.js"),
        isInReadOnlyNote(getTarget(e))
    ]);
    if (!attachment) {
        return [];
    }

    const actionGroups = getAttachmentActionGroups(attachment, { isReadOnly });
    const [ firstGroup = [], ...otherGroups ] = actionGroups
        .map((group) => group.map((action): MenuItem<CommandNames> => ({
            title: action.title,
            uiIcon: action.icon,
            enabled: !action.disabledReason,
            handler: () => void action.run()
        })));
    const groups = [ firstGroup, embed ? getEmbedItems(embed) : [], ...otherGroups ];
    const actionItems = groups
        .filter((group) => group.length > 0)
        .flatMap((group): MenuItem<CommandNames>[] => [ { kind: "separator" }, ...group ]);

    const embedItem = await getConvertToEmbedItem(
        e, editor, t("link_context_menu.convert_link_to_embed"), async () => attachment
    );
    const conversionItems = [ embedItem, embed && getConvertToLinkItem(embed) ]
        .filter((item) => !!item);
    return [ ...actionItems, ...conversionItems, ...(embed ? getDeleteEmbedGroup(embed) : []) ];
}

/**
 * The commands of an embedded note that the menu is opened on, in a group of their own, converting
 * it in another, and deleting it last. A menu opened on a link to the note offers converting the
 * link, to an excerpt for a link to blocks of the note.
 */
async function getNoteItems(
    noteId: string,
    e: LinkMenuOrigin,
    editor: CKTextEditor | null,
    embed: MenuEmbed | null,
    isBlockReference: boolean
): Promise<MenuItem<CommandNames>[]> {
    if (!embed) {
        const embedItem = await getConvertToEmbedItem(
            e, editor, isBlockReference
                ? t("link_context_menu.convert_link_to_note_excerpt")
                : t("link_context_menu.convert_link_to_included_note"),
            () => froca.getNote(noteId),
            isBlockReference
        );
        return embedItem ? [ { kind: "separator" }, embedItem ] : [];
    }

    const linkItem = getConvertToLinkItem(embed);
    return [
        { kind: "separator" },
        ...getEmbedItems(embed),
        ...(linkItem ? [ { kind: "separator" } as const, linkItem ] : []),
        ...getDeleteEmbedGroup(embed)
    ];
}

/**
 * The embed that a menu is opened on: from its title row, or from a control acting on the whole
 * embed, such as its toolbar. A link inside the embedded content opens the menu of that link.
 */
function getMenuEmbed(e: LinkMenuOrigin, editor: CKTextEditor): MenuEmbed | null {
    const target = getTarget(e);
    const element = target?.matches(".include-note")
        ? target
        : target?.closest(".include-note-title-row")?.closest(".include-note");
    if (!element || !editor.plugins.has("ContentEmbed")) {
        return null;
    }

    const state = editor.plugins.get("ContentEmbed").getEmbedStateAt(element);
    return state ? { editor, element, state } : null;
}

/**
 * The commands that the toolbar of an embed offers, with what each shows checked, and the items
 * that its content adds after Editable. Editable is offered only for content that has an editable
 * mode.
 */
function getEmbedItems(embed: MenuEmbed): MenuItem<CommandNames>[] {
    const { editor, state } = embed;
    const sizeItems = editor.plugins.get("ContentEmbed").getBoxSizes(embed.element)
        .map(({ value, label }): MenuItem<CommandNames> => ({
            title: escapeHtml(label),
            trailingIcon: value === state.boxSize ? CHECK_ICON : undefined,
            handler: () => runEmbedCommand(embed, "contentEmbedBoxSize", { value })
        }));
    const editableItems: MenuItem<CommandNames>[] = state.isEditableToggleable ? [ {
        title: t("link_context_menu.editable"),
        uiIcon: "bx bx-edit-alt",
        checked: state.isEditable,
        handler: () => runEmbedCommand(embed, "toggleContentEmbedEditable")
    } ] : [];
    const contentItems = getContentEmbedTools(embed.element)?.getMenuItems?.() ?? [];
    const displayModeItems = state.displayMode
        ? DISPLAY_MODE_OPTIONS.map(({ value, icon, titleKey }): MenuItem<CommandNames> => ({
            title: t(titleKey),
            uiIcon: icon,
            checked: value === state.displayMode,
            handler: () => runEmbedCommand(embed, "contentEmbedDisplayMode", { value })
        }))
        : [];

    return [
        ...editableItems,
        ...contentItems,
        ...(contentItems.length ? [ { kind: "separator" } as const ] : []),
        ...displayModeItems,
        ...(displayModeItems.length ? [ { kind: "separator" } as const ] : []),
        submenuItem({
            title: t("link_context_menu.include_size"),
            uiIcon: "bx bx-expand-vertical"
        }, sizeItems),
        ...getPositionItems(embed),
        ...(state.isTitleSupported ? [ {
            title: t("link_context_menu.show_title"),
            uiIcon: "bx bx-window-alt",
            enabled: state.isTitleToggleable,
            checked: state.isTitleShown,
            handler: () => runEmbedCommand(embed, "toggleContentEmbedTitle")
        } ] : []),
        ...(state.isCaptionSupported ? [ {
            title: t("link_context_menu.show_caption"),
            uiIcon: "bx bx-captions",
            enabled: state.isCaptionToggleable,
            checked: state.hasCaption,
            handler: () => runEmbedCommand(embed, "toggleContentEmbedCaption", {
                focusCaptionOnShow: true
            })
        } ] : [])
    ];
}

/**
 * The submenu that sets where the embed is placed in the text, with the icon of its position, for
 * content that has positions.
 */
function getPositionItems(embed: MenuEmbed): MenuItem<CommandNames>[] {
    const position = embed.state.position;
    if (!position) {
        return [];
    }

    const items = POSITION_GROUPS.flatMap((group): MenuItem<CommandNames>[] => [
        { kind: "header", title: t(group.titleKey) },
        ...group.positions.map(({ value, titleKey }): MenuItem<CommandNames> => ({
            title: t(titleKey),
            uiIcon: POSITION_ICONS[value],
            checked: value === position,
            handler: () => runEmbedCommand(embed, "contentEmbedPosition", { value })
        }))
    ]);
    return [ submenuItem({
        title: t("link_context_menu.include_position"),
        uiIcon: POSITION_ICONS[position]
    }, items) ];
}

/** Runs `command` on the embed, which the commands act on once it is selected. */
function runEmbedCommand(
    { editor, element }: MenuEmbed,
    command: string,
    options?: Record<string, unknown>
) {
    if (editor.plugins.get("ContentEmbed").selectEmbedAt(element)) {
        editor.execute(command, options);
        editor.editing.view.focus();
    }
}

/**
 * The item titled `title` that converts a link to a note or an attachment into an embed, in a
 * text note open for editing, for a link that the editor can convert. `isExcerpt` is set for a
 * link to blocks of a note.
 */
async function getConvertToEmbedItem(
    e: LinkMenuOrigin,
    editor: CKTextEditor | null,
    title: string,
    getLinkedEntity: () => Promise<FNote | FAttachment | null>,
    isExcerpt = false
): Promise<MenuItem<CommandNames> | null> {
    const link = getTarget(e)?.closest<HTMLElement>("a.reference-link");
    if (!link || !editor?.commands.get("convertLinkToEmbed")?.isEnabled
            || !editor.plugins.get("ContentEmbed").canConvertLinkToEmbed(link)) {
        return null;
    }

    // Imported on demand: `content_renderer` imports `link`, which imports this module.
    const [ entity, { EXCERPT_BOX_SIZE, getEmbedBoxSize } ] = await Promise.all([
        getLinkedEntity(),
        import("../services/content_renderer.js")
    ]);
    if (!entity) {
        return null;
    }

    return {
        title,
        uiIcon: "bx bx-window-alt",
        handler: () => editor.execute("convertLinkToEmbed", {
            domElement: link,
            boxSize: isExcerpt ? EXCERPT_BOX_SIZE : getEmbedBoxSize(entity)
        })
    };
}

/** "Convert to link", for an embed that names a note or an attachment. */
function getConvertToLinkItem(embed: MenuEmbed): MenuItem<CommandNames> | null {
    if (!embed.state.isConvertibleToLink) {
        return null;
    }

    return {
        title: t("link_context_menu.convert_embed_to_link"),
        uiIcon: "bx bx-link",
        handler: () => runEmbedCommand(embed, "convertEmbedToLink")
    };
}

function getTarget(e: LinkMenuOrigin) {
    return e.target instanceof Element ? e.target : null;
}

/**
 * Whether `element` is in a split pane whose note is shown read-only, by its `#readOnly` label or
 * by its size.
 */
async function isInReadOnlyNote(element: Element | null) {
    const ntxId = element instanceof HTMLElement ? getClosestNtxId(element) : null;
    const noteContext = ntxId
        ? appContext.tabManager.getNoteContexts().find((context) => context.ntxId === ntxId)
        : null;

    return (await noteContext?.isReadOnly()) ?? false;
}

/** The text editor containing `element`, or `null` when there is none or it is read-only. */
async function getEditingTextEditor(element: Element | null) {
    // An editor in read-only mode renders its editable with `contenteditable="false"`.
    if (!element?.closest(".ck-editor__editable[contenteditable='true']")) {
        return null;
    }

    return getTextEditorContaining(element);
}

function getNtxId(e: EventOrigin) {
    if (utils.isDesktop()) {
        const subContexts = appContext.tabManager.getActiveContext()?.getSubContexts();
        if (!subContexts) return null;
        return subContexts[subContexts.length - 1].ntxId;
    } else {
        const target = "originalEvent" in e ? e.originalEvent?.target : e.target;
        if (target instanceof HTMLElement) {
            const closest = getClosestNtxId(target);
            if (closest) return closest;
        }
    }
    // Fallback: when the event originates outside any note-context DOM
    // (e.g. mobile sidebar), target the currently active context so downstream
    // lookups don't fail with a null ntxId.
    return appContext.tabManager.activeNtxId ?? null;
}

export default {
    getItems,
    getOriginBelow,
    getQuickEditItem,
    getOpenNoteItem,
    handleLinkContextMenuItem,
    openContextMenu,
    openEmbedContextMenu,
    setShareLinkResolver
};