"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MToolbarImagePopup = void 0;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const is_number_1 = tslib_1.__importDefault(require("is-number"));
const markup_1 = require("../../../markup/index.js");
const ToolbarImagePopup_1 = require("../custom/ToolbarImagePopup.js");
const context_1 = require("./context.js");
const noop = (err) => {
    console.error(err);
};
const MToolbarImagePopup = ({ focus, onClick, hide, anchorElement, editor, className, }) => {
    const { uploadHandler, needToSetDimensionsForUploadedImages } = (0, context_1.useMarkupToolbarContext)();
    const selectedString = (0, react_1.useMemo)(() => {
        const { from, to } = editor.cm.state.selection.main;
        return editor.cm.state.doc.sliceString(from, to);
        // we need to calculate the selection only once
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    return ((0, jsx_runtime_1.jsx)(ToolbarImagePopup_1.ToolbarImagePopup, { imageTitle: selectedString, hide: hide, anchorElement: anchorElement, focus: focus, onClick: onClick, className: className, onSubmit: ({ url, name, alt, width, height }) => {
            (0, markup_1.insertImages)([
                {
                    url,
                    alt,
                    title: name,
                    width: (0, is_number_1.default)(width) ? String(width) : '',
                    height: (0, is_number_1.default)(height) ? String(height) : '',
                },
            ])(editor.cm);
        }, uploadImages: uploadHandler, onSuccessUpload: async (res) => {
            const images = await toImageItems(res.success, Boolean(needToSetDimensionsForUploadedImages));
            (0, markup_1.insertImages)(images)(editor.cm);
        } }));
};
exports.MToolbarImagePopup = MToolbarImagePopup;
async function toImageItems(items, withDimensions) {
    const imgItems = [];
    await Promise.all(items.map(({ result, file }) => {
        const imgItem = { url: result.url, alt: result.name ?? file.name };
        imgItems.push(imgItem);
        if (withDimensions) {
            return (0, markup_1.getImageDimensions)(file).then(({ height }) => {
                imgItem.height = String(Math.min(height, markup_1.IMG_MAX_HEIGHT));
            }, noop);
        }
        return Promise.resolve();
    }));
    return imgItems;
}
//# sourceMappingURL=MToolbarImagePopup.js.map
