Skip to content

Build your personal knowledge base with Trilium Notes

4.7 KB
Raw Blame
import { t } from "./i18n.js";
import link from "./link.js";
import toast from "./toast.js";
import utils from "./utils.js";

export function copyText(text: string) {
    if (!text) {
        return;
    }
    try {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text);
            return true;
        } 
        // Fallback method: https://stackoverflow.com/a/72239825
        const textArea = document.createElement("textarea");
        textArea.value = text;
        textArea.style.position = "fixed";
        textArea.style.opacity = "0";
        // An open Bootstrap modal traps focus, so the textarea goes inside it to keep its selection.
        const previouslyFocused = document.activeElement;
        const container = previouslyFocused?.closest(".modal.show") ?? document.body;
        try {
            container.appendChild(textArea);
            textArea.focus();
            textArea.select();
            return document.execCommand('copy');
        } finally {
            textArea.remove();
            if (previouslyFocused instanceof HTMLElement) {
                previouslyFocused.focus();
            }
        }
        
    } catch (e) {
        console.warn(e);
        return false;
    }
}

export function copyTextWithToast(text: string) {
    if (copyText(text)) {
        toast.showMessage(t("clipboard.copy_success"));
    } else {
        toast.showError(t("clipboard.copy_failed"));
    }
}

/**
 * Copies rich HTML — so it pastes with formatting into a note or another rich editor — with
 * `plainText` as the plain-text alternative. Returns whether the clipboard was written.
 *
 * `navigator.clipboard.write()` is the richer path but browsers expose it only in secure contexts,
 * and Trilium is routinely served over plain HTTP on a LAN, where the API is simply undefined
 * (#10723). The copy event is the fallback there, and also when the write is denied.
 */
export async function copyHtml(html: string, plainText: string = html) {
    if (navigator.clipboard?.write && typeof ClipboardItem !== "undefined") {
        try {
            await navigator.clipboard.write([
                new ClipboardItem({
                    "text/html": new Blob([html], { type: "text/html" }),
                    "text/plain": new Blob([plainText], { type: "text/plain" })
                })
            ]);

            return true;
        } catch (e) {
            // A denied permission or an unfocused document still leaves the copy event to try.
            console.warn(e);
        }
    }

    try {
        return utils.copyHtmlToClipboard(html, plainText);
    } catch (e) {
        console.warn(e);
        return false;
    }
}

/**
 * Copies rich HTML as {@link copyHtml} does and reports the outcome as a toast.
 */
export async function copyHtmlWithToast(html: string, plainText: string = html) {
    if (await copyHtml(html, plainText)) {
        toast.showMessage(t("clipboard.copy_success"));
    } else {
        toast.showError(t("clipboard.copy_failed"));
    }
}

/**
 * Copies `href` as an `<a class="reference-link">`, which a text note renders as the title, icon
 * and colour of the note it points at. Reports the outcome as a toast.
 *
 * The plain-text flavour is `href` itself, for a Markdown or code note. `ReferenceLink` upcasts
 * only the `href` and resolves the rest through `link.loadReferenceLinkTitle()`, so the markup
 * written here reaches non-Trilium targets alone.
 */
export async function copyReferenceWithToast(href: string) {
    const $link = $("<a>").addClass("reference-link").attr("href", href);
    await link.loadReferenceLinkTitle($link, href);

    await copyHtmlWithToast($link[0].outerHTML, href);
}

/**
 * Whether {@link readClipboardText} can work here: always on desktop, and in a browser that has
 * `navigator.clipboard.readText()` (a secure context) unless the `clipboard-read` permission is
 * denied.
 */
export async function canReadClipboardText() {
    if (window.electronApi) return true;
    if (!navigator.clipboard?.readText) return false;

    try {
        // The DOM typings do not list `clipboard-read`, which only Chromium knows.
        const name = "clipboard-read" as unknown as PermissionName;
        const { state } = await navigator.permissions.query({ name });
        return state !== "denied";
    } catch {
        // Firefox and Safari have no `clipboard-read` permission and ask on each read.
        return true;
    }
}

/**
 * Reads the text on the clipboard, through the main process on desktop. Rejects when the read is
 * not allowed.
 */
export async function readClipboardText() {
    if (window.electronApi) {
        return window.electronApi.clipboard.readText();
    }

    return navigator.clipboard.readText();
}