"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LinkWidgetDescriptor = exports.addPlaceholder = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const WidgetDecoration_1 = require("../../../behavior/WidgetDecoration/index.js");
const ReactWidgetDescriptor_1 = require("../../../behavior/WidgetDecoration/ReactWidgetDescriptor.js");
const LinkSpecs_1 = require("../LinkSpecs/index.js");
const utils_1 = require("../utils.js");
const widget_1 = require("./widget.js");
const addPlaceholder = (tr, deps) => {
    return new LinkWidgetDescriptor(tr.selection.from, deps).applyTo(tr);
};
exports.addPlaceholder = addPlaceholder;
class LinkWidgetDescriptor extends ReactWidgetDescriptor_1.ReactWidgetDescriptor {
    #domElem;
    #view;
    #getPos;
    normalizeUrl;
    constructor(initPos, deps) {
        super(initPos, 'link-empty');
        this.#domElem = document.createElement('span');
        this.normalizeUrl = (0, utils_1.normalizeUrlFactory)(deps);
    }
    getDomElem() {
        return this.#domElem;
    }
    renderReactElement(view, getPos) {
        this.#view = view;
        this.#getPos = getPos;
        return (0, jsx_runtime_1.jsx)(widget_1.LinkPlaceholderWidget, { onCancel: this.onCancel, onSubmit: this.onSubmit });
    }
    onCancel = () => {
        if (!this.#view)
            return;
        this.#view.dispatch((0, WidgetDecoration_1.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, (0, LinkSpecs_1.linkType)(this.#view.state.schema).create({ [LinkSpecs_1.LinkAttr.Href]: url }));
        tr = (0, WidgetDecoration_1.removeDecoration)(tr, this.id);
        this.#view.dispatch(tr);
        this.#view.focus();
    };
}
exports.LinkWidgetDescriptor = LinkWidgetDescriptor;
//# sourceMappingURL=descriptor.js.map
