Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

33.9 KB
Raw Blame
import {isTableLikeView} from "./viewType";
import {Menu} from "../../../plugin/Menu";
import {transaction} from "../../wysiwyg/transaction";
import {updateAttrViewCellAnimation} from "./action";
import {isMobile} from "../../../util/functions";
import {Constants} from "../../../constants";
import {uploadFiles, uploadLocalFiles} from "../../upload";
import {pathPosix} from "../../../util/pathName";
import {openMenu} from "../../../menus/commonMenuItem";
import {MenuItem} from "../../../menus/Menu";
import {copyPNGByLink, exportAsset, writeAssetToClipboard} from "../../../menus/util";
import {setPosition} from "../../../util/setPosition";
import {getAVBatchEditMode, getAVBatchSourceValue} from "./batchValue";
import {previewAttrViewImages} from "../../preview/image";
import {showMessage} from "../../../dialog/message";
import {hasClosestBlock, hasClosestByClassName} from "../../util/hasClosest";
import {
    genCellValueByElement,
    getTypeByCellElement,
    updateAttrViewCellInOtherElements,
    updateCellsValue
} from "./cell";
import {writeText} from "../../util/compatibility";
import {escapeAriaLabel, escapeAttr, escapeHtml} from "../../../util/escape";
import {renameAsset} from "../../../editor/rename";
import dayjs from "dayjs";
import {getColId} from "./col";
import {getFieldIdByCellElement} from "./row";
import {getCompressURL, removeCompressURL} from "../../../util/image";
import {base64ToURL, showBase64ImageSizeLimit} from "../../upload/base64";
import {isBrowserRenderableImagePath} from "../../../util/imageURL";
import {genNetworkImageAssetValue} from "./assetValue";
import {getAssetUploadSuccesses} from "../../upload/uploadResult";
import {getAVSelectedCells, resolveAVSelectedCell, type IAVSelectedCell, type IAVCellPoint} from "./selectionState";
import {getAVData, getAVSelectedTableCells} from "./virtualScroll";
import {getAVAssetUploadTargets} from "./assetUploadTarget";
import {captureUploadDocument} from "../../upload/insertPosition";

export const bindAssetEvent = (options: {
    protyle: IProtyle,
    menuElement: HTMLElement,
    cellElements: HTMLElement[],
    blockElement: Element
}) => {
    options.menuElement.querySelector("input").addEventListener("change", (event: InputEvent & {
        target: HTMLInputElement
    }) => {
        if (event.target.files.length === 0) {
            return;
        }
        const upload = captureAssetCellUpload(options.protyle, options.blockElement,
            options.cellElements, options.menuElement);
        uploadFiles(options.protyle, event.target.files, event.target, (_res, result) => {
            upload.apply(result);
        }, undefined, {source: "file-picker", target: "av-cell", document: upload.document});
    });
};

const getVisibleAssetValues = (cellElements: HTMLElement[]) => {
    const batchMode = getAVBatchEditMode(cellElements[0]);
    if (batchMode === "add") {
        return [];
    }
    if (batchMode === "remove") {
        const assets = new Map<string, IAVCellAssetValue>();
        cellElements.forEach(item => {
            const renderedValue = genCellValueByElement("mAsset", item);
            getAVBatchSourceValue(item, renderedValue).mAsset?.forEach(asset => {
                assets.set(`${asset.type}:${asset.content}:${asset.name}`, asset);
            });
        });
        return Array.from(assets.values());
    }
    return genCellValueByElement("mAsset", cellElements[0]).mAsset || [];
};

export const getAssetHTML = (cellElements: HTMLElement[]) => {
    let html = "";
    const batchMode = getAVBatchEditMode(cellElements[0]);
    getVisibleAssetValues(cellElements).forEach((item, index) => {
        let contentHTML;
        if (item.type === "image" && isBrowserRenderableImagePath(item.content)) {
            contentHTML = `<span data-type="openAssetItem" class="fn__flex-1 ariaLabel" aria-label="${escapeAriaLabel(item.content)}">
    <img style="max-height: 180px;max-width: 360px;border-radius: var(--b3-border-radius);margin: 4px 0;" src="${getCompressURL(encodeURI(item.content))}"/>
</span>`;
        } else {
            contentHTML = `<span data-type="openAssetItem" class="fn__ellipsis b3-menu__label ariaLabel" aria-label="${escapeAriaLabel(item.content)}" style="max-width: 360px">${escapeHtml(item.name || item.content)}</span>`;
        }

        html += `<button class="b3-menu__item" draggable="true" data-index="${index}" data-name="${escapeAttr(item.name)}" data-type="${item.type}" data-content="${escapeAttr(item.content)}">
<svg class="b3-menu__icon fn__grab"><use xlink:href="#iconDrag"></use></svg>
${contentHTML}
${batchMode === "replace" ? '<svg class="b3-menu__action" data-type="editAssetItem"><use xlink:href="#iconEdit"></use></svg>' : ""}
</button>`;
    });
    const ids: string[] = [];
    cellElements.forEach(item => {
        ids.push(item.dataset.id);
    });
    return `<div class="b3-menu__items" data-ids="${ids}">
    ${html}
    <button data-type="addAssetExist" class="b3-menu__item b3-menu__item--current">
        <svg class="b3-menu__icon"><use xlink:href="#iconImage"></use></svg>
        <span class="b3-menu__label">${window.siyuan.languages.assets}</span>
    </button>
    <button class="b3-menu__item">
        <svg class="b3-menu__icon"><use xlink:href="#iconUpload"></use></svg>
        <span class="b3-menu__label">${window.siyuan.languages.insertAsset}</span> 
        <input multiple class="b3-form__upload" type="file">
    </button>
    <button data-type="addAssetLink" data-asset-type="image" class="b3-menu__item">
        <svg class="b3-menu__icon"><use xlink:href="#iconImage"></use></svg>
        <span class="b3-menu__label">${window.siyuan.languages.insertImgURL}</span>
    </button>
    <button data-type="addAssetLink" data-asset-type="file" class="b3-menu__item">
        <svg class="b3-menu__icon"><use xlink:href="#iconLink"></use></svg>
        <span class="b3-menu__label">${window.siyuan.languages.link}</span>
    </button>
</div>`;
};

export const updateAssetCell = (options: {
    protyle: IProtyle,
    cellElements: HTMLElement[],
    replaceValue?: IAVCellAssetValue[],
    targets?: IAVCellPoint[],
    addValue?: IAVCellAssetValue[],
    updateValue?: { index: number, value: IAVCellAssetValue }
    removeIndex?: number,
    blockElement: Element,
    menuElement?: HTMLElement | null,
}) => {
    if (options.protyle.disabled) {
        return;
    }
    const viewType = options.blockElement.getAttribute("data-av-type") as TAVView;
    const colId = options.targets?.[0]?.colID || getColId(options.cellElements[0], viewType);
    const cellDoOperations: IOperation[] = [];
    const cellUndoOperations: IOperation[] = [];
    let mAssetValue: IAVCellAssetValue[];
    const batchMode = getAVBatchEditMode(options.cellElements[0]);
    const batchTarget = typeof options.removeIndex === "number" ?
        getVisibleAssetValues(options.cellElements)[options.removeIndex] : undefined;
    options.cellElements.forEach((item, elementIndex) => {
        const target = options.targets?.[elementIndex];
        const rowID = target?.rowID || getFieldIdByCellElement(item, viewType);
        const data = target && getAVData(options.blockElement as HTMLElement);
        const selectedCell = data && resolveAVSelectedCell(data, target);
        if (target && data && selectedCell?.column.type !== "mAsset") {
            return;
        }
        item = resolveAssetCellElement(options.blockElement, item, target || {
            rowID, colID: getColId(item, viewType), groupID: "",
        }, viewType);
        if (!item && !selectedCell) {
            return;
        }
        if (item) {
            options.cellElements[elementIndex] = item;
        }
        const renderedValue: IAVCellValue = selectedCell ? JSON.parse(JSON.stringify(selectedCell.cell.value)) :
            genCellValueByElement(getTypeByCellElement(item) || item.dataset.type as TAVCol, item);
        const cellValue = selectedCell || batchMode === "replace" ? renderedValue : getAVBatchSourceValue(item, renderedValue);
        const oldValue = JSON.parse(JSON.stringify(cellValue));
        if (batchMode === "add" && options.addValue?.length > 0) {
            const existing = new Set((cellValue.mAsset || []).map(asset =>
                `${asset.type}:${asset.content}:${asset.name}`));
            cellValue.mAsset = (cellValue.mAsset || []).concat(options.addValue.filter(asset =>
                !existing.has(`${asset.type}:${asset.content}:${asset.name}`)));
        } else if (batchMode === "remove" && batchTarget) {
            cellValue.mAsset = (cellValue.mAsset || []).filter(asset =>
                asset.type !== batchTarget.type || asset.content !== batchTarget.content ||
                asset.name !== batchTarget.name);
        } else if (options.targets && options.addValue?.length > 0) {
            cellValue.mAsset = (cellValue.mAsset || []).concat(options.addValue);
        } else if (elementIndex === 0) {
            if (typeof options.removeIndex === "number") {
                cellValue.mAsset.splice(options.removeIndex, 1);
            } else if (options.addValue?.length > 0) {
                cellValue.mAsset = cellValue.mAsset.concat(options.addValue);
            } else if (options.updateValue) {
                cellValue.mAsset.find((assetItem, index) => {
                    if (index === options.updateValue.index) {
                        assetItem.content = options.updateValue.value.content;
                        assetItem.type = options.updateValue.value.type;
                        assetItem.name = options.updateValue.value.name;
                        return true;
                    }
                });
            } else if (options.replaceValue?.length > 0) {
                cellValue.mAsset = options.replaceValue;
            }
            mAssetValue = cellValue.mAsset;
        } else {
            cellValue.mAsset = mAssetValue;
        }
        const avID = options.blockElement.getAttribute("data-av-id");
        cellDoOperations.push({
            action: "updateAttrViewCell",
            id: cellValue.id,
            keyID: colId,
            rowID,
            avID,
            data: cellValue
        });
        cellUndoOperations.push({
            action: "updateAttrViewCell",
            id: cellValue.id,
            keyID: colId,
            rowID,
            avID,
            data: oldValue
        });
        if (item && !item.classList.contains("custom-attr__avvalue")) {
            updateAttrViewCellAnimation(item, cellValue);
        }
        updateAttrViewCellInOtherElements(options.protyle, avID, rowID, colId, cellValue, item);
    });
    if (cellDoOperations.length === 0) {
        showMessage(window.siyuan.languages.uploadInsertTargetUnavailable);
        return;
    }
    cellDoOperations.push({
        action: "doUpdateUpdated",
        id: options.blockElement.getAttribute("data-node-id"),
        data: dayjs().format("YYYYMMDDHHmmss"),
    });
    transaction(options.protyle, cellDoOperations, cellUndoOperations);
    const menuElement = typeof options.menuElement === "undefined" ?
        document.querySelector<HTMLElement>(".av__panel > .b3-menu") :
        options.menuElement?.isConnected ? options.menuElement : null;
    if (menuElement && options.cellElements.every(item => options.blockElement.contains(item))) {
        menuElement.innerHTML = getAssetHTML(options.cellElements);
        bindAssetEvent({
            protyle: options.protyle,
            menuElement,
            cellElements: options.cellElements,
            blockElement: options.blockElement
        });
        const cellRect = (options.cellElements[0].classList.contains("custom-attr__avvalue") ? options.cellElements[0] : options.protyle.wysiwyg.element.querySelector(`.av__cell[data-id="${options.cellElements[0].dataset.id}"]`)).getBoundingClientRect();
        setTimeout(() => {
            setPosition(menuElement, cellRect.left, cellRect.bottom, cellRect.height, 0, true);
        }, Constants.TIMEOUT_LOAD);  // 等待图片加载
    }
};

export const editAssetItem = (options: {
    protyle: IProtyle,
    cellElements: HTMLElement[],
    blockElement: Element,
    content: string,
    type: "image" | "file",
    name: string,
    index: number,
    rect: DOMRect,
    keepMenuOpen?: boolean,
}) => {
    if (options.protyle.disabled) {
        return;
    }
    const linkAddress = removeCompressURL(options.content);
    const type = options.type as "image" | "file";
    const menu = new Menu(Constants.MENU_AV_ASSET_EDIT, async () => {
        if (options.protyle.disabled) {
            return;
        }
        let currentLink = textElements[0].value;
        if ((!textElements[1] && currentLink === decodeURI(linkAddress)) ||
            (textElements[1] && currentLink === decodeURI(linkAddress) && textElements[1].value === options.name)) {
            return;
        }
        if (type === "image" && currentLink.startsWith("data:image/")) {
            let base64Src: Array<string | undefined>;
            try {
                base64Src = await base64ToURL([currentLink], options.protyle, {
                    source: "programmatic",
                    target: "av-cell",
                });
            } catch (error) {
                if (showBase64ImageSizeLimit(error)) {
                    return;
                }
                throw error;
            }
            currentLink = base64Src[0] || currentLink;
        }

        updateAssetCell({
            protyle: options.protyle,
            cellElements: options.cellElements,
            blockElement: options.blockElement,
            updateValue: {
                index: options.index,
                value: {
                    content: currentLink,
                    name: textElements[1] ? textElements[1].value : "",
                    type
                }
            }
        });
    }, options.keepMenuOpen);
    if (menu.isOpen) {
        return;
    }
    if (type === "file") {
        menu.addItem({
            id: "linkAndTitle",
            iconHTML: "",
            type: "readonly",
            label: `<div class="fn__flex">
    <span class="fn__flex-center">${window.siyuan.languages.link}</span>
    <span class="fn__space"></span>
    <span data-action="copy" class="block__icon block__icon--show b3-tooltips b3-tooltips__e fn__flex-center" aria-label="${window.siyuan.languages.copy}">
        <svg><use xlink:href="#iconCopy"></use></svg>
    </span>   
</div><textarea rows="1" style="margin:4px 0;width: ${isMobile() ? "100%" : "360px"};resize: vertical;" class="b3-text-field"></textarea><div class="fn__hr"></div><div class="fn__flex">
    <span class="fn__flex-center">${window.siyuan.languages.title}</span>
    <span class="fn__space"></span>
    <span data-action="copy" class="block__icon block__icon--show b3-tooltips b3-tooltips__e fn__flex-center" aria-label="${window.siyuan.languages.copy}">
        <svg><use xlink:href="#iconCopy"></use></svg>
    </span>   
</div><textarea style="width: ${isMobile() ? "100%" : "360px"};margin: 4px 0;resize: vertical;" rows="1" class="b3-text-field"></textarea>`,
            bind(element) {
                element.addEventListener("click", (event) => {
                    let target = event.target as HTMLElement;
                    while (target) {
                        if (target.dataset.action === "copy") {
                            writeText((target.parentElement.nextElementSibling as HTMLTextAreaElement).value);
                            showMessage(window.siyuan.languages.copied);
                            break;
                        }
                        target = target.parentElement;
                    }
                });
            }
        });
        menu.addSeparator({id: "separator_1"});
        menu.addItem({
            id: "copy",
            label: window.siyuan.languages.copy,
            icon: "iconCopy",
            click() {
                writeText(`[${textElements[1].value || textElements[0].value}](${textElements[0].value})`);
            }
        });
    } else {
        menu.addItem({
            id: "link",
            iconHTML: "",
            type: "readonly",
            label: `<div class="fn__flex">
    <span class="fn__flex-center">${window.siyuan.languages.link}</span>
    <span class="fn__space"></span>
    <span data-action="copy" class="block__icon block__icon--show b3-tooltips b3-tooltips__e fn__flex-center" aria-label="${window.siyuan.languages.copy}">
        <svg><use xlink:href="#iconCopy"></use></svg>
    </span>   
</div><textarea rows="1" style="margin:4px 0;width: ${isMobile() ? "100%" : "360px"};resize: vertical;" class="b3-text-field"></textarea>`,
            bind(element) {
                element.addEventListener("click", (event) => {
                    let target = event.target as HTMLElement;
                    while (target) {
                        if (target.dataset.action === "copy") {
                            writeText((target.parentElement.nextElementSibling as HTMLTextAreaElement).value);
                            showMessage(window.siyuan.languages.copied);
                            break;
                        }
                        target = target.parentElement;
                    }
                });
            }
        });
        menu.addSeparator({id: "separator_1"});
        menu.addItem({
            id: "copy",
            label: window.siyuan.languages.copy,
            icon: "iconCopy",
            click() {
                writeText(`![](${textElements[0].value})`);
            }
        });
        menu.addItem({
            id: "copyAsPNG",
            label: window.siyuan.languages.copyAsPNG,
            icon: "iconImage",
            click() {
                copyPNGByLink(textElements[0].value);
            }
        });
    }
    menu.addItem({
        id: "delete",
        icon: "iconTrashcan",
        label: window.siyuan.languages.delete,
        click() {
            updateAssetCell({
                protyle: options.protyle,
                cellElements: options.cellElements,
                blockElement: options.blockElement,
                removeIndex: options.index
            });
        }
    });
    if (linkAddress?.startsWith("assets/")) {
        menu.addItem({
            id: "rename",
            label: window.siyuan.languages.rename,
            icon: "iconEdit",
            click() {
                renameAsset(decodeURI(linkAddress));
                document.querySelector(".av__panel")?.remove();
            }
        });
    }
    const openSubMenu = openMenu(options.protyle ? options.protyle.app : window.siyuan.ws.app, decodeURI(linkAddress), true, false);
    if (type !== "file" || openSubMenu.length > 0) {
        menu.addSeparator({id: "separator_2"});
    }
    if (type !== "file" && isBrowserRenderableImagePath(linkAddress)) {
        menu.addItem({
            id: "cardPreview",
            icon: "iconPreview",
            label: window.siyuan.languages.cardPreview,
            click() {
                previewAttrViewImages(
                    linkAddress,
                    options.blockElement.getAttribute("data-av-id"),
                    options.blockElement.getAttribute("data-node-id"),
                    options.blockElement.getAttribute(Constants.CUSTOM_SY_AV_VIEW),
                    options.blockElement.querySelector('[data-type="av-search"]')?.textContent.trim() || "",
                    options.cellElements[0]?.closest<HTMLElement>(".av__body")?.dataset.groupId
                );
            }
        });
    }
    if (openSubMenu.length > 0) {
        window.siyuan.menus.menu.append(new MenuItem({
            id: "openBy",
            label: window.siyuan.languages.openBy,
            icon: "iconOpen",
            submenu: openSubMenu
        }).element);
    }
    if (linkAddress?.startsWith("assets/")) {
        window.siyuan.menus.menu.append(new MenuItem(exportAsset(decodeURI(linkAddress))).element);
        window.siyuan.menus.menu.append(new MenuItem(writeAssetToClipboard(decodeURI(linkAddress))).element);
    }
    const rect = options.rect;
    /// #if MOBILE
    menu.fullscreen();
    /// #else
    menu.open({
        x: rect.right,
        y: rect.bottom,
        w: rect.width,
        h: rect.height,
    });
    /// #endif
    const textElements = menu.element.querySelectorAll("textarea");
    textElements[0].value = decodeURI(linkAddress);
    textElements[0].focus();
    textElements[0].select();
    if (textElements.length > 1) {
        textElements[1].value = options.name;
    }
};

export const addAssetLink = (protyle: IProtyle, cellElements: HTMLElement[], target: HTMLElement, blockElement: Element,
                             assetType: "image" | "file", keepMenuOpen = false) => {
    const menu = new Menu(Constants.MENU_AV_ASSET_EDIT, () => {
        const textElements = menu.element.querySelectorAll("textarea");
        if (assetType === "image") {
            const value = genNetworkImageAssetValue(textElements[0].value);
            if (!value) {
                if (textElements[0].value) {
                    showMessage(window.siyuan.languages.invalid);
                }
                return;
            }
            updateAssetCell({
                protyle,
                cellElements,
                blockElement,
                addValue: [value]
            });
            return;
        }
        if (!textElements[0].value && !textElements[1].value) {
            return;
        }
        updateAssetCell({
            protyle,
            cellElements,
            blockElement,
            addValue: [{
                type: "file",
                name: textElements[1].value,
                content: textElements[0].value,
            }]
        });
    }, keepMenuOpen);
    if (menu.isOpen) {
        return;
    }
    menu.addItem({
        iconHTML: "",
        type: "readonly",
        label: assetType === "image" ? `${window.siyuan.languages.insertImgURL}
<textarea rows="1" style="margin:4px 0;width: ${isMobile() ? "100%" : "360px"};resize: vertical;" class="b3-text-field"></textarea>` : `${window.siyuan.languages.link}
<textarea rows="1" style="margin:4px 0;width: ${isMobile() ? "100%" : "360px"};resize: vertical;" class="b3-text-field"></textarea>
<div class="fn__hr"></div>
${window.siyuan.languages.title}
<textarea style="width: ${isMobile() ? "100%" : "360px"};margin: 4px 0;resize: vertical;" rows="1" class="b3-text-field"></textarea>`,
    });
    /// #if MOBILE
    menu.fullscreen();
    /// #else
    const rect = target.getBoundingClientRect();
    menu.open({
        x: rect.right,
        y: rect.bottom,
        w: target.parentElement.clientWidth + 8,
        h: rect.height,
    });
    /// #endif
    menu.element.querySelector("textarea").focus();
};

const getUploadedAssetValues = (result: Omit<IAssetUploadResult, "requestId" | "input">,
                                formatName: (name: string) => string = name => name,
                                sort = false) => {
    const values: IAVCellAssetValue[] = [];
    const successes = Array.from(getAssetUploadSuccesses(result));
    if (sort) {
        successes.sort((a, b) => a.name.localeCompare(b.name, undefined, {numeric: true}) || a.index - b.index);
    }
    successes.forEach(success => {
        const type = pathPosix().extname(success.name).toLowerCase();
        const filename = formatName(success.name);
        values.push({
            type: Constants.SIYUAN_ASSETS_IMAGE.includes(type) ? "image" : "file",
            name: filename,
            content: success.path,
        });
    });
    return values;
};

const getAssetCellMenu = (cellElement: HTMLElement) => {
    const menuElement = document.querySelector<HTMLElement>(".av__panel > .b3-menu");
    const ids = menuElement?.querySelector(".b3-menu__items")?.getAttribute("data-ids")?.split(",") || [];
    return ids.includes(cellElement.dataset.id) ? menuElement : null;
};

const resolveAssetCellElement = (blockElement: Element, cellElement: HTMLElement,
                                 target: IAVCellPoint, viewType: TAVView) => {
    let item = cellElement;
    if (!blockElement.contains(item) || getColId(item, viewType) !== target.colID ||
        getFieldIdByCellElement(item, viewType) !== target.rowID) {
        item = (cellElement.classList.contains("custom-attr__avvalue") ?
            blockElement.querySelector(`.custom-attr__avvalue[data-row-id="${target.rowID}"][data-col-id="${target.colID}"]`) :
            isTableLikeView(viewType) ?
                blockElement.querySelector(`.av__row[data-id="${target.rowID}"] .av__cell[data-col-id="${target.colID}"]`) :
            blockElement.querySelector(`.av__gallery-item[data-id="${target.rowID}"] .av__cell[data-field-id="${target.colID}"]`)) as HTMLElement;
    }
    return item && (getTypeByCellElement(item) || item.dataset.type) === "mAsset" ? item : null;
};

const captureAssetCellUpload = (protyle: IProtyle, blockElement: Element, cells: HTMLElement[],
                                menuElement: HTMLElement | null) => {
    const cellElements = Array.from(cells);
    const viewType = blockElement.getAttribute("data-av-type") as TAVView;
    const avID = blockElement.getAttribute("data-av-id");
    const blockID = blockElement.getAttribute("data-node-id");
    const attributeID = blockElement.getAttribute("data-attribute-id");
    const ownerElement = blockElement.closest(".protyle-db-row");
    const targets = cellElements.map(item => ({
        rowID: getFieldIdByCellElement(item, viewType),
        colID: getColId(item, viewType),
        groupID: item.closest<HTMLElement>(".av__body")?.dataset.groupId || "",
    }));
    // 独立条目的上下文编辑器不挂载 DOM,使用可见面板并按原条目重新解析刷新后的字段。
    const resolveBlock = () => ownerElement ? ownerElement.querySelector<HTMLElement>(
        `[data-av-id="${avID}"][data-node-id="${blockID}"][data-attribute-id="${attributeID}"]`) : blockElement;
    const isAvailable = () => {
        const currentBlock = resolveBlock();
        if (protyle.disabled || !currentBlock || !document.body.contains(currentBlock) ||
            currentBlock.getAttribute("data-av-id") !== avID ||
            currentBlock.getAttribute("data-node-id") !== blockID) {
            return false;
        }
        const data = getAVData(currentBlock as HTMLElement);
        return targets.some((target, index) => data ? resolveAVSelectedCell(data, target)?.column.type === "mAsset" :
            Boolean(resolveAssetCellElement(currentBlock, cellElements[index], target, viewType)));
    };
    return {
        document: captureUploadDocument(protyle, {element: ownerElement || protyle.element, isAvailable}),
        apply: (result: Omit<IAssetUploadResult, "requestId" | "input">) => {
            if (!isAvailable()) {
                return;
            }
            const addValue = getUploadedAssetValues(result);
            if (addValue.length === 0) {
                return;
            }
            updateAssetCell({protyle, blockElement: resolveBlock(), cellElements, targets, addValue, menuElement});
        },
    };
};

export const captureAVAssetUploadHandler = (protyle: IProtyle, blockElement: HTMLElement) => {
    const panelElement = document.querySelector<HTMLElement>(".av__panel");
    const usePanelTarget = Boolean(panelElement?.querySelector(".b3-form__upload"));
    const cellElements: HTMLElement[] = [];
    let stableCells: IAVSelectedCell[] = [];

    if (usePanelTarget) {
        blockElement.querySelectorAll<HTMLElement>(".av__cell--active").forEach(item => {
            if (getTypeByCellElement(item) === "mAsset") {
                cellElements.push(item);
            }
        });
        if (cellElements.length === 0) {
            panelElement.querySelector(".b3-menu__items")?.getAttribute("data-ids")?.split(",").forEach(id => {
                const item = blockElement.querySelector<HTMLElement>(
                    `.av__gallery-fields [data-dtype="mAsset"][data-id="${id}"]`);
                if (item) {
                    cellElements.push(item);
                }
            });
        }
    } else {
        const selectedCells = getAVSelectedCells(blockElement);
        const stableCellCandidates = (selectedCells.length > 0 ? selectedCells :
            getAVSelectedTableCells(blockElement)).filter(item => item.column.type === "mAsset");
        blockElement.querySelectorAll(".av__row--select:not(.av__row--header)").forEach(item => {
            item.querySelectorAll<HTMLElement>(".av__cell").forEach(cellItem => {
                if (getTypeByCellElement(cellItem) === "mAsset") {
                    cellElements.push(cellItem);
                }
            });
        });
        if (cellElements.length === 0) {
            blockElement.querySelectorAll<HTMLElement>(".av__cell--active").forEach(item => {
                if (getTypeByCellElement(item) === "mAsset") {
                    cellElements.push(item);
                }
            });
        }
        stableCells = stableCellCandidates;
    }

    const targetCellElements = Array.from(cellElements);
    if (!usePanelTarget && stableCells.length === 0 && cellElements.length > 1) {
        const colId = cellElements[0].dataset.colId;
        let currentRowElement = hasClosestByClassName(cellElements[cellElements.length - 1], "av__row") as HTMLElement;
        while (currentRowElement?.nextElementSibling?.classList.contains("av__row")) {
            currentRowElement = currentRowElement.nextElementSibling as HTMLElement;
            const cellElement = currentRowElement.querySelector<HTMLElement>(`.av__cell[data-col-id="${colId}"]`);
            if (cellElement) {
                targetCellElements.push(cellElement);
            }
        }
    }
    const targets = getAVAssetUploadTargets(stableCells, targetCellElements);
    const applyPanelUpload = usePanelTarget && cellElements.length > 0 ?
        captureAssetCellUpload(protyle, blockElement, cellElements, panelElement?.querySelector(".b3-menu")) : undefined;

    return async (result: Omit<IAssetUploadResult, "requestId" | "input">) => {
        if (!document.body.contains(blockElement)) {
            return;
        }
        const values = getUploadedAssetValues(result, protyle.options.upload.filename, true);
        if (values.length === 0) {
            return;
        }
        if (usePanelTarget) {
            if (applyPanelUpload) {
                applyPanelUpload.apply(result);
                if (panelElement.isConnected) {
                    panelElement.remove();
                }
            }
            return;
        }
        if (targets.length === 0) {
            return;
        }
        const data = targets[0].stableCell ? getAVData(blockElement) : undefined;
        if (targets.length === 1) {
            const target = targets[0];
            const selectedCell = data && target.stableCell ? resolveAVSelectedCell(data, target.stableCell) : undefined;
            if (selectedCell?.column.type === "mAsset") {
                await updateCellsValue(protyle, blockElement, values, undefined, undefined, undefined,
                    false, false, false, [selectedCell]);
            } else if (target.cellElement) {
                await updateCellsValue(protyle, blockElement, values, [target.cellElement]);
            }
            return;
        }
        const doOperations: IOperation[] = [];
        const undoOperations: IOperation[] = [];
        for (let i = 0; i < values.length; i++) {
            const target = targets[i];
            if (!target) {
                break;
            }
            let selectedCell: IAVSelectedCell | undefined;
            if (target.stableCell) {
                selectedCell = data ? resolveAVSelectedCell(data, target.stableCell) : undefined;
                if (selectedCell?.column.type !== "mAsset") {
                    continue;
                }
            }
            const operations = await updateCellsValue(protyle, blockElement, [values[i]],
                target.cellElement ? [target.cellElement] : undefined, undefined, undefined,
                true, false, false, selectedCell ? [selectedCell] : undefined);
            doOperations.push(...operations.doOperations);
            undoOperations.push(...operations.undoOperations);
        }
        if (doOperations.length > 0 && document.body.contains(blockElement)) {
            const id = blockElement.dataset.nodeId;
            doOperations.push({
                action: "doUpdateUpdated",
                id,
                data: dayjs().format("YYYYMMDDHHmmss"),
            });
            undoOperations.push({
                action: "doUpdateUpdated",
                id,
                data: blockElement.getAttribute("updated"),
            });
            transaction(protyle, doOperations, undoOperations);
        }
    };
};

export const dragUpload = (files: ILocalFiles[], protyle: IProtyle, cellElement: HTMLElement,
                           position?: IAssetUploadPosition) => {
    const blockElement = hasClosestBlock(cellElement);
    if (!blockElement) {
        return;
    }
    const menuElement = getAssetCellMenu(cellElement);
    const upload = captureAssetCellUpload(protyle, blockElement, [cellElement], menuElement);
    uploadLocalFiles(files, protyle, true, {source: "drop", target: "av-cell", position, document: upload.document}, (_response, result) => {
        upload.apply(result);
    });
};

export const uploadFilesToAssetCell = (files: FileList | File[], protyle: IProtyle, cellElement: HTMLElement,
                                       options: { source: TAssetUploadSource, position?: IAssetUploadPosition }) => {
    const blockElement = hasClosestBlock(cellElement);
    if (!blockElement) {
        return;
    }
    const menuElement = getAssetCellMenu(cellElement);
    const upload = captureAssetCellUpload(protyle, blockElement, [cellElement], menuElement);
    uploadFiles(protyle, files, undefined, (_response, result) => {
        upload.apply(result);
    }, undefined, {source: options.source, target: "av-cell", position: options.position, document: upload.document});
};

export const dragUploadFiles = (files: FileList | File[], protyle: IProtyle, cellElement: HTMLElement,
                                position?: IAssetUploadPosition) => {
    uploadFilesToAssetCell(files, protyle, cellElement, {source: "drop", position});
};