"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.linkActionSpec2 = exports.addLinkCmd2 = exports.addEmptyLink = void 0;
const prosemirror_commands_1 = require("prosemirror-commands");
const prosemirror_state_1 = require("prosemirror-state");
const utils_1 = require("../../../../utils/index.js");
const marks_1 = require("../../../../utils/marks.js");
const const_1 = require("../../../yfm/ImgSize/const.js");
const ImageSpecs_1 = require("../../Image/ImageSpecs/index.js");
const LinkSpecs_1 = require("../LinkSpecs/index.js");
const commands_1 = require("../PlaceholderWidget/commands.js");
const commands_2 = require("../commands.js");
const addEmptyLink = (state, dispatch) => {
    const linkMarkType = (0, LinkSpecs_1.linkType)(state.schema);
    const { selection } = state;
    const { nodeAfter } = selection.$from;
    if (selection.empty ||
        ((0, utils_1.isNodeSelection)(selection) && selection.node.type !== (0, ImageSpecs_1.imageType)(state.schema)) ||
        (!(nodeAfter?.isInline && nodeAfter?.isAtom) && !nodeAfter?.isText))
        return false;
    const { $from, $to } = selection;
    // text selection inside one text node
    if ($from.parent !== $to.parent)
        return false;
    let tr = state.tr;
    const toggleResult = (0, prosemirror_commands_1.toggleMark)(linkMarkType, {
        [LinkSpecs_1.LinkAttr.Href]: '',
        [LinkSpecs_1.LinkAttr.IsPlaceholder]: true,
    })(state, (_tr) => {
        tr = _tr;
    });
    if (!toggleResult)
        return false;
    tr.scrollIntoView();
    if (selection instanceof prosemirror_state_1.NodeSelection) {
        tr.setSelection(prosemirror_state_1.NodeSelection.create(tr.doc, $to.pos - 1));
        if (selection.node.type === (0, ImageSpecs_1.imageType)(state.schema)) {
            const meta = { linkAdded: true };
            tr.setMeta(const_1.imageRendererKey, meta);
        }
    }
    else {
        const selectedText = state.doc.textBetween($from.pos, $to.pos);
        const countOfWhitespacesAtEnd = selectedText.length - selectedText.trimEnd().length;
        tr.setSelection(prosemirror_state_1.TextSelection.create(tr.doc, $to.pos - countOfWhitespacesAtEnd - 1));
    }
    dispatch?.(tr);
    return true;
};
exports.addEmptyLink = addEmptyLink;
const addLinkCmd2 = (deps) => (0, prosemirror_commands_1.chainCommands)(commands_2.removeLink, exports.addEmptyLink, (0, commands_1.addLinkPlaceholder)(deps));
exports.addLinkCmd2 = addLinkCmd2;
const linkActionSpec2 = (deps) => ({
    isActive: (state) => Boolean((0, marks_1.isMarkActive)(state, (0, LinkSpecs_1.linkType)(state.schema))),
    isEnable: (0, exports.addLinkCmd2)(deps),
    run: (0, exports.addLinkCmd2)(deps),
});
exports.linkActionSpec2 = linkActionSpec2;
//# sourceMappingURL=linkEnhanceActions.js.map
