dragdrop.js 4.1 KB
Newer Older
A
AUTOMATIC 已提交
1 2
// allows drag-dropping files into gradio image elements, and also pasting images from clipboard

3
function isValidImageList(files) {
4 5 6
    return files && files?.length === 1 && ['image/png', 'image/gif', 'image/jpeg'].includes(files[0].type);
}

7 8
function dropReplaceImage(imgWrap, files) {
    if (!isValidImageList(files)) {
9 10
        return;
    }
11

M
MMaker 已提交
12 13
    const tmpFile = files[0];

14
    imgWrap.querySelector('.modify-upload button + button, .touch-none + div button + button')?.click();
15
    const callback = () => {
16
        const fileInput = imgWrap.querySelector('input[type="file"]');
17 18
        if (fileInput) {
            if (files.length === 0) {
M
MMaker 已提交
19 20 21 22 23 24
                files = new DataTransfer();
                files.items.add(tmpFile);
                fileInput.files = files.files;
            } else {
                fileInput.files = files;
            }
25
            fileInput.dispatchEvent(new Event('change'));
26
        }
27
    };
28 29

    if (imgWrap.closest('#pnginfo_image')) {
30 31
        // special treatment for PNG Info tab, wait for fetch request to finish
        const oldFetch = window.fetch;
32
        window.fetch = async(input, options) => {
33
            const response = await oldFetch(input, options);
34
            if ('api/predict/' === input) {
35 36
                const content = await response.text();
                window.fetch = oldFetch;
37
                window.requestAnimationFrame(() => callback());
38 39 40 41
                return new Response(content, {
                    status: response.status,
                    statusText: response.statusText,
                    headers: response.headers
42
                });
43 44
            }
            return response;
45
        };
46
    } else {
47
        window.requestAnimationFrame(() => callback());
48
    }
49 50
}

51 52 53 54 55 56 57 58 59
function eventHasFiles(e) {
    if (!e.dataTransfer || !e.dataTransfer.files) return false;
    if (e.dataTransfer.files.length > 0) return true;
    if (e.dataTransfer.items.length > 0 && e.dataTransfer.items[0].kind == "file") return true;

    return false;
}

function dragDropTargetIsPrompt(target) {
A
AUTOMATIC 已提交
60 61
    if (target?.placeholder && target?.placeholder.indexOf("Prompt") >= 0) return true;
    if (target?.parentNode?.parentNode?.className?.indexOf("prompt") > 0) return true;
62 63 64
    return false;
}

65 66
window.document.addEventListener('dragover', e => {
    const target = e.composedPath()[0];
67 68 69 70 71
    if (!eventHasFiles(e)) return;

    var targetImage = target.closest('[data-testid="image"]');
    if (!dragDropTargetIsPrompt(target) && !targetImage) return;

72 73
    e.stopPropagation();
    e.preventDefault();
74
    e.dataTransfer.dropEffect = 'copy';
75 76 77 78
});

window.document.addEventListener('drop', e => {
    const target = e.composedPath()[0];
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    if (!eventHasFiles(e)) return;

    if (dragDropTargetIsPrompt(target)) {
        e.stopPropagation();
        e.preventDefault();

        let prompt_target = get_tab_index('tabs') == 1 ? "img2img_prompt_image" : "txt2img_prompt_image";

        const imgParent = gradioApp().getElementById(prompt_target);
        const files = e.dataTransfer.files;
        const fileInput = imgParent.querySelector('input[type="file"]');
        if (fileInput) {
            fileInput.files = files;
            fileInput.dispatchEvent(new Event('change'));
        }
D
d8ahazard 已提交
94
    }
95 96 97 98 99 100 101

    var targetImage = target.closest('[data-testid="image"]');
    if (targetImage) {
        e.stopPropagation();
        e.preventDefault();
        const files = e.dataTransfer.files;
        dropReplaceImage(targetImage, files);
102 103 104 105 106 107
        return;
    }
});

window.addEventListener('paste', e => {
    const files = e.clipboardData.files;
108
    if (!isValidImageList(files)) {
109 110
        return;
    }
111 112

    const visibleImageFields = [...gradioApp().querySelectorAll('[data-testid="image"]')]
113
        .filter(el => uiElementIsVisible(el))
A
AUTOMATIC 已提交
114
        .sort((a, b) => uiElementInSight(b) - uiElementInSight(a));
115 116


117
    if (!visibleImageFields.length) {
118 119
        return;
    }
120

121
    const firstFreeImageField = visibleImageFields
E
ezt19 已提交
122
        .filter(el => !el.querySelector('img'))?.[0];
123 124 125

    dropReplaceImage(
        firstFreeImageField ?
126 127 128 129
            firstFreeImageField :
            visibleImageFields[visibleImageFields.length - 1]
        , files
    );
130
});