import React, { useRef, useEffect, useMemo } from 'react';
import { Editor as Editor$1, getProcessor } from 'bytemd';

const Editor = ({ children, onChange, ...props }) => {
    const ed = useRef();
    const el = useRef(null);
    useEffect(() => {
        if (!el.current)
            return;
        const editor = new Editor$1({
            target: el.current,
            props,
        });
        editor.$on('change', (e) => {
            onChange === null || onChange === void 0 ? void 0 : onChange(e.detail.value);
        });
        ed.current = editor;
        return () => {
            editor.$destroy();
        };
    }, []);
    useEffect(() => {
        var _a;
        // TODO: performance
        (_a = ed.current) === null || _a === void 0 ? void 0 : _a.$set(props);
    }, [props]);
    return React.createElement("div", { ref: el });
};

const Viewer = ({ value, sanitize, plugins }) => {
    var _a;
    const elRef = useRef(null);
    const result = useMemo(() => {
        try {
            return getProcessor({ sanitize, plugins }).processSync(value);
        }
        catch (err) {
            console.error(err);
        }
    }, [value, sanitize, plugins]);
    useEffect(() => {
        const $el = elRef.current;
        if (!$el || !result)
            return;
        const cbs = plugins === null || plugins === void 0 ? void 0 : plugins.map(({ viewerEffect }) => viewerEffect && viewerEffect({ $el, result }));
        return () => {
            cbs === null || cbs === void 0 ? void 0 : cbs.forEach((cb) => cb && cb());
        };
    }, [result, plugins]);
    return (React.createElement("div", { onClick: (e) => {
            var _a, _b;
            const $ = e.target;
            if ($.tagName !== 'A')
                return;
            const href = $.getAttribute('href');
            if (!(href === null || href === void 0 ? void 0 : href.startsWith('#')))
                return;
            (_b = (_a = elRef.current) === null || _a === void 0 ? void 0 : _a.querySelector('#user-content-' + href.slice(1))) === null || _b === void 0 ? void 0 : _b.scrollIntoView();
        }, ref: elRef, className: "markdown-body", dangerouslySetInnerHTML: { __html: (_a = result === null || result === void 0 ? void 0 : result.toString()) !== null && _a !== void 0 ? _a : '' } }));
};

export { Editor, Viewer };
//# sourceMappingURL=index.esm.js.map
