import { jsx as _jsx } from "react/jsx-runtime";
import { useMemo } from 'react';
import isNumber from 'is-number';
import { IMG_MAX_HEIGHT, getImageDimensions, insertImages } from "../../../markup/index.js";
import { ToolbarImagePopup } from "../custom/ToolbarImagePopup.js";
import { useMarkupToolbarContext } from "./context.js";
const noop = (err) => {
    console.error(err);
};
export const MToolbarImagePopup = ({ focus, onClick, hide, anchorElement, editor, className, }) => {
    const { uploadHandler, needToSetDimensionsForUploadedImages } = useMarkupToolbarContext();
    const selectedString = 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 (_jsx(ToolbarImagePopup, { imageTitle: selectedString, hide: hide, anchorElement: anchorElement, focus: focus, onClick: onClick, className: className, onSubmit: ({ url, name, alt, width, height }) => {
            insertImages([
                {
                    url,
                    alt,
                    title: name,
                    width: isNumber(width) ? String(width) : '',
                    height: isNumber(height) ? String(height) : '',
                },
            ])(editor.cm);
        }, uploadImages: uploadHandler, onSuccessUpload: async (res) => {
            const images = await toImageItems(res.success, Boolean(needToSetDimensionsForUploadedImages));
            insertImages(images)(editor.cm);
        } }));
};
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 getImageDimensions(file).then(({ height }) => {
                imgItem.height = String(Math.min(height, IMG_MAX_HEIGHT));
            }, noop);
        }
        return Promise.resolve();
    }));
    return imgItems;
}
//# sourceMappingURL=MToolbarImagePopup.js.map
