import { jsx as _jsx } from "react/jsx-runtime";
import { removeDecoration } from "../../../behavior/WidgetDecoration/index.js";
import { ReactWidgetDescriptor } from "../../../behavior/WidgetDecoration/ReactWidgetDescriptor.js";
import { LinkAttr, linkType } from "../LinkSpecs/index.js";
import { normalizeUrlFactory } from "../utils.js";
import { LinkPlaceholderWidget } from "./widget.js";
export const addPlaceholder = (tr, deps) => {
    return new LinkWidgetDescriptor(tr.selection.from, deps).applyTo(tr);
};
export class LinkWidgetDescriptor extends ReactWidgetDescriptor {
    #domElem;
    #view;
    #getPos;
    normalizeUrl;
    constructor(initPos, deps) {
        super(initPos, 'link-empty');
        this.#domElem = document.createElement('span');
        this.normalizeUrl = normalizeUrlFactory(deps);
    }
    getDomElem() {
        return this.#domElem;
    }
    renderReactElement(view, getPos) {
        this.#view = view;
        this.#getPos = getPos;
        return _jsx(LinkPlaceholderWidget, { onCancel: this.onCancel, onSubmit: this.onSubmit });
    }
    onCancel = () => {
        if (!this.#view)
            return;
        this.#view.dispatch(removeDecoration(this.#view.state.tr, this.id));
        this.#view.focus();
    };
    onSubmit = (params) => {
        const normalizeResult = this.normalizeUrl(params.url);
        if (!normalizeResult || !this.#view || !this.#getPos)
            return;
        const { url } = normalizeResult;
        const text = params.text.trim() || normalizeResult.text;
        const from = this.#getPos();
        const to = from + text.length;
        let tr = this.#view.state.tr;
        tr = tr.insertText(text, from);
        tr = tr.addMark(from, to, linkType(this.#view.state.schema).create({ [LinkAttr.Href]: url }));
        tr = removeDecoration(tr, this.id);
        this.#view.dispatch(tr);
        this.#view.focus();
    };
}
//# sourceMappingURL=descriptor.js.map
