"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.linkCommand = linkCommand;
const prosemirror_commands_1 = require("prosemirror-commands");
const prosemirror_state_1 = require("prosemirror-state");
const marks_1 = require("../../../../utils/marks.js");
const LinkSpecs_1 = require("../LinkSpecs/index.js");
const commands_1 = require("../commands.js");
const utils_1 = require("../utils.js");
function linkCommand(markType, deps) {
    const normalizeUrl = (0, utils_1.normalizeUrlFactory)(deps);
    return {
        isActive(state) {
            return Boolean((0, marks_1.isMarkActive)(state, markType));
        },
        isEnable(state) {
            return (0, prosemirror_commands_1.toggleMark)(markType)(state);
        },
        run(state, dispatch, view, attrs) {
            if ((0, commands_1.removeLink)(state, dispatch, view))
                return;
            if (!attrs)
                return;
            const { text, title } = attrs;
            const normalizeResult = normalizeUrl(attrs.href);
            if (normalizeResult) {
                if (text && state.selection.empty) {
                    dispatch(state.tr.replaceSelectionWith(state.schema.text(text, [
                        markType.create({
                            [LinkSpecs_1.LinkAttr.Href]: normalizeResult.url,
                            [LinkSpecs_1.LinkAttr.Title]: title,
                        }),
                    ]), false));
                    return;
                }
                (0, prosemirror_commands_1.toggleMark)(markType, {
                    [LinkSpecs_1.LinkAttr.Href]: normalizeResult.url,
                    [LinkSpecs_1.LinkAttr.Title]: title,
                })(state, dispatch);
            }
        },
        meta(state) {
            const { selection } = state;
            return {
                hasSelection: !selection.empty && selection instanceof prosemirror_state_1.TextSelection,
                text() {
                    const fragment = selection.content().content;
                    return fragment.textBetween(0, fragment.size);
                },
            };
        },
    };
}
//# sourceMappingURL=linkActions.js.map
