import dd from 'ts-dedent';
import { getLoggerFromState } from "../../../core/index.js";
import { DataTransferType, isJetBrains, isVSCode, tryParseVSCodeData } from "../../../utils/clipboard.js";
import { codeBlockType } from "./const.js";
export const handlePaste = (view, e) => {
    const data = e.clipboardData;
    if (!data)
        return false;
    const code = getCodeData(data);
    if (!code)
        return false;
    const { state } = view;
    const { tr, schema, selection } = state;
    const $from = selection.$from;
    const inCodeBlock = Boolean($from.parent.type.spec.code);
    getLoggerFromState(state).event({
        domEvent: 'paste',
        event: 'paste-from-code-editor',
        editor: code.editor,
        editorMode: code.mode,
        empty: !code.value,
        inline: code.inline,
        dataTypes: Array.from(data.types),
    });
    if (!code.value) {
        return false;
    }
    insertCode({
        tr,
        schema,
        code,
        from: selection.from,
        to: selection.to,
        inCodeBlock,
    });
    view.dispatch(tr.scrollIntoView());
    e.preventDefault();
    return true;
};
export function insertCode({ tr, schema, code, from, to, inCodeBlock }) {
    if (inCodeBlock) {
        tr.insertText(code.value, from, to);
    }
    else if (code.inline) {
        insertInlineCode(tr, schema, code.value);
    }
    else {
        insertCodeBlock(tr, schema, code.value);
    }
}
function insertInlineCode(tr, schema, value) {
    const codeMarkType = schema.marks.code;
    const marks = codeMarkType ? [codeMarkType.create()] : undefined;
    const textNode = schema.text(value, marks);
    tr.replaceSelectionWith(textNode, false);
}
function insertCodeBlock(tr, schema, value) {
    const nodeType = codeBlockType(schema);
    const textNode = schema.text(value);
    const codeBlockNode = nodeType.create(null, textNode);
    tr.replaceSelectionWith(codeBlockNode);
}
export function getCodeData(data) {
    const text = data.getData(DataTransferType.Text);
    if (!text)
        return null;
    if (isVSCode(data)) {
        return processVSCodePaste(data, text);
    }
    if (isJetBrains(data)) {
        return processJetBrainsPaste(text);
    }
    return null;
}
function processVSCodePaste(data, text) {
    const vsCodeData = tryParseVSCodeData(data);
    return {
        editor: 'vscode',
        value: dd(text),
        inline: isInlineCode(text),
        mode: vsCodeData?.mode,
    };
}
function processJetBrainsPaste(text) {
    return {
        editor: 'jetbrains',
        value: dd(text),
        inline: isInlineCode(text),
    };
}
export function isInlineCode(text) {
    return !text.includes('\n');
}
//# sourceMappingURL=handle-paste.js.map
