Skip to content

Build your personal knowledge base with Trilium Notes

15.0 KB
Raw Blame
import appContext from "../components/app_context.js";
import type FAttachment from "../entities/fattachment.js";
import type FNote from "../entities/fnote.js";
import attributeRenderer from "./attribute_renderer.js";
import { revealHighlightedBlocks } from "./block_reference.js";
import contentRenderer from "./content_renderer.js";
import froca from "./froca.js";
import { t } from "./i18n.js";
import linkService from "./link.js";
import { sanitizeNoteContentHtml } from "./sanitize_content.js";
import treeService from "./tree.js";
import utils from "./utils.js";

// Track all elements that open tooltips
let openTooltipElements: JQuery<HTMLElement>[] = [];
let dismissTimer: ReturnType<typeof setTimeout>;

function setupGlobalTooltip() {
    $(document).on("pointerenter", "a:not(.no-tooltip-preview)", mouseEnterHandler);
    $(document).on("pointerenter", "[data-href]:not(.no-tooltip-preview)", mouseEnterHandler);

    // close any note tooltip after click, this fixes the problem that sometimes tooltips remained on the screen.
    // Captured, as `goToLink()` stops the propagation of a click on a link.
    document.addEventListener("click", (e) => {
        if ($(e.target as Element).closest(".note-tooltip").length) {
            // click within the tooltip shouldn't close it
            return;
        }

        dismissAllTooltips();
    }, true);
}

function dismissAllTooltips() {
    clearTimeout(dismissTimer);
    openTooltipElements.forEach($el => {
        $el.tooltip("dispose");
        $el.removeAttr("aria-describedby");
    });
    openTooltipElements = [];
}

function setupElementTooltip($el: JQuery<HTMLElement>) {
    $el.on("pointerenter", mouseEnterHandler);
}

/**
 * A context menu is what the pointer is dealing with while it is up — the element underneath it is
 * only the menu's subject. `contextMenu.show()` dismisses the open tooltips, but the preview is
 * delayed and async, so one already in flight when the menu opened would still land on top of it.
 */
function isContextMenuShown() {
    return document.body.classList.contains("context-menu-shown");
}

/**
 * Whether the text editor shows the toolbar of a link: the link toolbar of CKEditor, or the widget
 * toolbar of a reference link. A preview opens below a link, which is where that toolbar sits.
 */
function isLinkToolbarShown() {
    return document.querySelector(
        ".ck-balloon-panel_visible .ck-link-toolbar, .ck-balloon-panel_visible.reference-link-toolbar"
    ) !== null;
}

export async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.TriggeredEvent<T, undefined, T, T>) {
    if (e.pointerType !== "mouse" || isContextMenuShown() || isLinkToolbarShown()) return;

    const $link = $(this);

    if ($link.hasClass("no-tooltip-preview") || $link.hasClass("disabled")) {
        return;
    } else if ($link.closest(".note-tooltip").length) {
        // don't show tooltip for links within tooltip
        return;
    }

    const url = $link.attr("href") || $link.attr("data-href");
    const { notePath, noteId, viewScope } = linkService.parseNavigationStateFromUrl(url);

    if (url?.startsWith("#fnref")) {
        // The "^" symbol from footnotes within text notes, doesn't require a tooltip.
        return;
    }

    const attachmentId = viewScope?.viewMode === "attachments" ? viewScope.attachmentId : undefined;
    if (!notePath || !noteId || (viewScope?.viewMode !== "default" && !attachmentId)) {
        return;
    }

    const linkId = $link.attr("data-link-id") || `link-${Math.floor(Math.random() * 1000000)}`;
    $link.attr("data-link-id", linkId);

    if ($(`.${linkId}`).is(":visible")) {
        // tooltip is already open for this link
        return;
    }

    // An optional line the trigger element contributes about the note it links to — a size in a
    // space-usage cell, say. Plain text: the element states a fact, it does not render markup.
    const detail = $link.attr("data-tooltip-detail");

    let renderPromise;
    let note: FNote | null = null;
    // In-page anchors and footnotes are always bare `#fragment` references; a `?` means this is a
    // note link carrying view params (e.g. the calendar's `#<noteId>?popup`), which must render a
    // note tooltip rather than being fed into a jQuery selector (the `?` is an invalid selector).
    if (url && url.startsWith("#") && !url.startsWith("#root/") && !url.includes("?")) {
        renderPromise = renderFootnoteOrAnchor($link, url);
    } else if (attachmentId) {
        const attachment = await froca.getAttachmentOfNote(noteId, attachmentId);
        renderPromise = renderTooltip(attachment, detail);
    } else if ($link.attr("data-note-deleted") != null) {
        // The element explicitly targets a soft-deleted note (e.g. an entry in the deleted-notes
        // dialog): read it via the deleted-content route. `DeletedFNote.load` returns null once the
        // note is erased, so the tooltip then shows the "note has been deleted" message.
        // Imported lazily to avoid a static import cycle (DeletedFNote extends FNote, which
        // transitively imports this module via the context menu).
        const { default: DeletedFNote } = await import("../entities/deleted_fnote.js");
        note = await DeletedFNote.load(noteId);
        renderPromise = renderTooltip(note, detail);
    } else {
        // Default route: a live note. A missing note (deleted/erased) renders the "note has been
        // deleted" placeholder — content previews of deleted notes are opt-in via `data-note-deleted`.
        note = await froca.getNote(noteId);
        renderPromise = renderTooltip(note, detail, viewScope?.block);
    }

    const [content] = await Promise.all([
        renderPromise,
        // to reduce flicker due to accidental mouseover, cursor must stay for a bit over the link for tooltip to appear
        new Promise((res) => setTimeout(res, 500))
    ]);

    if (!content || utils.isHtmlEmpty(content)) {
        return;
    }

    const sanitizedContent = sanitizeNoteContentHtml(content);
    const html = `<div class="note-tooltip-content">${sanitizedContent}</div>`;
    const tooltipClass = `tooltip-${Math.floor(Math.random() * 999_999_999)}${note ? ` ${note.getColorClass()}` : ""}`;

    // we need to check if we're still hovering over the element
    // since the operation to get tooltip content was async, it is possible that
    // we now create tooltip which won't close because it won't receive mouseleave event
    // — or that a context menu or a link toolbar opened in the meantime, which the preview must
    // not cover.
    //
    // The opt-out is re-read for the same reason: an element may take it on while its preview is
    // being fetched, which is how a surface that opens over the pointer says the preview is no
    // longer wanted — a calendar chip clicked gains it as the popover opens (see the class in
    // CalendarView's eventClassNames), and the pointer is still on the chip, so the hover test
    // alone would let the preview land on top of what the click just opened.
    if ($link.filter(":hover").length > 0 && !isContextMenuShown() && !isLinkToolbarShown()
        && !$link.hasClass("no-tooltip-preview")) {
        $link.tooltip({
            container: "body",
            // https://github.com/zadam/trilium/issues/2794 https://github.com/zadam/trilium/issues/2988
            // with bottom this flickering happens a bit less
            placement: "bottom",
            trigger: "manual",
            //TODO: boundary No longer applicable?
            //boundary: 'window',
            title: html,
            html: true,
            template: `<div class="tooltip note-tooltip ${tooltipClass}" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>`,
            // Content is pre-sanitized via DOMPurify so Bootstrap's built-in sanitizer
            // (which is too aggressive for our rich-text content) can be disabled.
            sanitize: false,
            customClass: linkId
        });

        dismissAllTooltips();
        $link.tooltip("show");

        openTooltipElements.push($link);

        const tooltipContent = $(`.${linkId} .note-tooltip-content`).get(0);
        if (viewScope?.block && tooltipContent) {
            revealHighlightedBlocks(tooltipContent);
        }

        // Dismiss the tooltip immediately if a link was clicked inside the tooltip.
        $(`.${tooltipClass} a`).on("click", (e) => {
            dismissAllTooltips();
        });

        // the purpose of the code below is to:
        // - allow user to go from hovering the link to hovering the tooltip to be able to scroll,
        //   click on links within tooltip etc. without tooltip disappearing
        // - once the user moves the cursor away from both link and the tooltip, hide the tooltip
        const checkTooltip = () => {

            if (isLinkToolbarShown()
                || (!$link.filter(":hover").length && !$(`.${linkId}:hover`).length)) {
                // a link toolbar opened under the tooltip, or the cursor is neither over the link nor
                // over the tooltip, user likely is not interested
                dismissAllTooltips();
            } else {
                dismissTimer = setTimeout(checkTooltip, 1000);
            }
        };

        dismissTimer = setTimeout(checkTooltip, 1000);
    }
}

/**
 * @param entity the note, or an attachment, which shows under the path of the note that owns it.
 * @param detail plain text the trigger element contributed about this note (see the `data-tooltip-detail`
 *               attribute), shown under the title. Absent on the vast majority of links, which say
 *               nothing beyond the note itself.
 * @param block the blocks of the note to highlight, a `block` link parameter.
 */
export async function renderTooltip(
    entity: FNote | FAttachment | null,
    detail?: string,
    block?: string
) {
    const attachment = entity && "attachmentId" in entity ? entity : null;
    const note = attachment ? attachment.getNote() : entity as FNote | null;
    if (!entity || !note) {
        return `<div>${t("note_tooltip.note-has-been-deleted")}</div>`;
    }

    // Lazy import to avoid a static import cycle (DeletedFNote extends FNote, which transitively
    // imports this module via the context menu).
    const { default: DeletedFNote } = await import("../entities/deleted_fnote.js");
    const isDeleted = note instanceof DeletedFNote;
    const hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId;
    const bestNotePath = note.getBestNotePathString(hoistedNoteId);

    // A soft-deleted note has no navigable path; still render it, just without the path-based title link.
    if (!bestNotePath && !isDeleted) {
        return;
    }

    const href = attachment
        ? `#${note.noteId}?viewMode=attachments&attachmentId=${attachment.attachmentId}`
        : `#${note.noteId}`;

    // An attachment has no attributes, and those of its note describe the note.
    const $renderedAttributes = attachment
        ? null
        : (await attributeRenderer.renderNormalAttributes(note)).$renderedAttributes;

    const { $renderedContent } = await contentRenderer.getRenderedContent(entity, {
        tooltip: true,
        trim: true,
        highlightBlock: block
    });
    const isContentEmpty = $renderedContent[0].innerHTML.length === 0;

    const titleClasses = ["note-tooltip-title"];
    if (isContentEmpty) {
        titleClasses.push("note-no-content");
    }

    let content = "";
    if (isDeleted) {
        // Plain, unlinked title — there is no live note to navigate to.
        content = `<h5 class="${titleClasses.join(" ")}">${utils.escapeHtml(note.title)}</h5>`;
    } else if (bestNotePath) {
        const noteTitleWithPathAsSuffix = await treeService.getNoteTitleWithPathAsSuffix(
            bestNotePath,
            attachment?.title
        );
        if (noteTitleWithPathAsSuffix) {
            const titleHtml = noteTitleWithPathAsSuffix.prop("outerHTML");
            content = `\
                <h5 class="${titleClasses.join(" ")}">
                    <a href="${href}" data-no-context-menu="true">${titleHtml}</a>
                </h5>`;
        }
    }

    const info = detail ?? (attachment
        ? t("note_tooltip.attachment-info", { size: utils.formatSize(attachment.contentLength) })
        : undefined);
    if (info) {
        content = `${content}<div class="note-tooltip-detail">${utils.escapeHtml(info)}</div>`;
    }

    if ($renderedAttributes) {
        const attributesHtml = $renderedAttributes[0].outerHTML;
        content = `${content}<div class="note-tooltip-attributes">${attributesHtml}</div>`;
    }
    if (!isContentEmpty) {
        content += $renderedContent[0].outerHTML;
    }

    // The quick-edit (popup) button opens the live editor, which doesn't apply to a deleted note.
    if (!isDeleted) {
        const popupHref = attachment ? `${href}&popup` : `${href}?popup`;
        const quickEdit = t("note_tooltip.quick-edit");
        content += `<a class="open-popup-button" title="${quickEdit}" href="${popupHref}">`
            + `<span class="bx bx-edit" /></a>`;
    }
    return content;
}

export function renderFootnoteOrAnchor($link: JQuery<HTMLElement>, url: string) {
    // A footnote text reference
    const footnoteRef = url.substring(3);
    let $targetContent: JQuery<HTMLElement>;

    if (url.startsWith("#fn")) {
        $targetContent = $link
            .closest(".ck-content") // find the parent CK content
            .find("> .footnote-section") // find the footnote section
            .find(`a[href="#fnref${footnoteRef}"]`) // find the footnote link
            .closest(".footnote-item") // find the parent container of the footnote
            .find(".footnote-content"); // find the actual text content of the footnote
    } else {
        $targetContent = $link
            .closest(".ck-content")
            .find(url)
            .closest("p");
    }

    if (!$targetContent.length) {
        // If the target content is not found, return an empty string
        return "";
    }

    const isEditable = $link.closest(".ck-content").hasClass("note-detail-editable-text-editor");
    if (isEditable) {
        /* Remove widget buttons for tables, formulas, and images in editable notes. */
        $targetContent.find('.ck-widget__selection-handle').remove();
        $targetContent.find('.ck-widget__type-around').remove();
        $targetContent.find('.ck-widget__resizer').remove();

        /* Handling in-line math formulas */
        $targetContent.find('.ck-math-tex.ck-math-tex-inline.ck-widget').each(function () {
            const $katex = $(this).find('.katex').first();
            if ($katex.length) {
                $(this).replaceWith($('<span class="math-tex"></span>').append($('<span></span>').append($katex.clone())));
            }
        });
    }

    let footnoteContent = $targetContent.html();
    footnoteContent = `<div class="ck-content">${footnoteContent}</div>`;
    /* v8 ignore next -- footnoteContent is always a non-empty wrapper div here, so the || "" fallback is unreachable */
    return footnoteContent || "";
}

export default {
    setupGlobalTooltip,
    setupElementTooltip,
    dismissAllTooltips
};