"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FilePaste = void 0;
const prosemirror_model_1 = require("prosemirror-model");
const prosemirror_state_1 = require("prosemirror-state");
const prosemirror_transform_1 = require("prosemirror-transform");
const base_1 = require("../../base/index.js");
const utils_1 = require("../Clipboard/utils.js");
// Custom handler of pasted (or dropped) files to prevent insert a file preview in base64-format into editor's content (or open file in browser)
const FilePaste = (builder) => {
    builder.addPlugin(() => {
        return new prosemirror_state_1.Plugin({
            props: {
                handlePaste(view, event) {
                    const files = getFiles(event.clipboardData);
                    if (!files)
                        return false;
                    view.dispatch(view.state.tr
                        .replaceSelection(createFilesSlice(view.state.schema, files))
                        .scrollIntoView());
                    return true;
                },
                handleDrop(view, event) {
                    if (view.dragging)
                        return false;
                    const files = getFiles(event.dataTransfer);
                    if (!files)
                        return false;
                    const slice = createFilesSlice(view.state.schema, files);
                    const dropPos = view.posAtCoords({ left: event.clientX, top: event.clientY })?.pos ?? -1;
                    if (dropPos === -1)
                        return false;
                    const posToInsert = (0, prosemirror_transform_1.dropPoint)(view.state.doc, dropPos, slice);
                    if (posToInsert === null)
                        return false;
                    view.dispatch(view.state.tr.insert(posToInsert, slice.content));
                    return true;
                },
            },
        });
    }, builder.Priority.Lowest);
};
exports.FilePaste = FilePaste;
function getFiles(dataTransfer) {
    if (!dataTransfer || !(0, utils_1.isFilesOnly)(dataTransfer))
        return null;
    return Array.from(dataTransfer.files);
}
function createFilesSlice(schema, files) {
    const nodes = [];
    for (const file of files) {
        nodes.push((0, base_1.pType)(schema).create(null, schema.text(file.name)));
    }
    return new prosemirror_model_1.Slice(prosemirror_model_1.Fragment.from(nodes), 0, 0);
}
//# sourceMappingURL=index.js.map
