import { toggleMark } from 'prosemirror-commands';
import { TextSelection } from 'prosemirror-state';
import { isMarkActive } from "../../../../utils/marks.js";
import { LinkAttr } from "../LinkSpecs/index.js";
import { removeLink } from "../commands.js";
import { normalizeUrlFactory } from "../utils.js";
export function linkCommand(markType, deps) {
    const normalizeUrl = normalizeUrlFactory(deps);
    return {
        isActive(state) {
            return Boolean(isMarkActive(state, markType));
        },
        isEnable(state) {
            return toggleMark(markType)(state);
        },
        run(state, dispatch, view, attrs) {
            if (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({
                            [LinkAttr.Href]: normalizeResult.url,
                            [LinkAttr.Title]: title,
                        }),
                    ]), false));
                    return;
                }
                toggleMark(markType, {
                    [LinkAttr.Href]: normalizeResult.url,
                    [LinkAttr.Title]: title,
                })(state, dispatch);
            }
        },
        meta(state) {
            const { selection } = state;
            return {
                hasSelection: !selection.empty && selection instanceof TextSelection,
                text() {
                    const fragment = selection.content().content;
                    return fragment.textBetween(0, fragment.size);
                },
            };
        },
    };
}
//# sourceMappingURL=linkActions.js.map
