import { jsx as _jsx } from "react/jsx-runtime";
import { Portal } from '@gravity-ui/uikit';
import { getReactRendererFromState } from "../../../behavior/ReactRenderer/index.js";
import { generateEntityId, isInvalidEntityId } from "../../../../utils/entity-id.js";
import { MermaidConsts, defaultMermaidEntityId } from "../MermaidSpecs/const.js";
import { MermaidView, STOP_EVENT_CLASSNAME } from "./MermaidView.js";
let mermaidInstance;
export class WMermaidNodeView {
    dom;
    node;
    view;
    getPos;
    renderItem;
    loadRuntimeScript;
    constructor(node, view, getPos, opts) {
        const { loadRuntimeScript } = opts;
        this.node = node;
        this.dom = document.createElement('div');
        this.dom.classList.add('mermaid-container');
        this.dom.contentEditable = 'false';
        this.view = view;
        this.getPos = getPos;
        this.loadRuntimeScript = loadRuntimeScript;
        this.initializeMermaid();
        this.renderItem = getReactRendererFromState(view.state).createItem('mermaid-view', this.renderMermaid.bind(this));
        this.validateEntityId();
    }
    initializeMermaid() {
        // https://github.com/diplodoc-platform/mermaid-extension/tree/master#prepared-mermaid-runtime
        window.mermaidJsonp = window.mermaidJsonp || [];
        window.mermaidJsonp.push((mermaid) => {
            mermaidInstance = mermaid;
        });
        this.loadRuntimeScript();
    }
    update(node) {
        if (node.type !== this.node.type)
            return false;
        this.node = node;
        this.renderItem.rerender();
        return true;
    }
    destroy() {
        this.renderItem.remove();
    }
    ignoreMutation() {
        return true;
    }
    stopEvent(e) {
        const target = e.target;
        return target.classList.contains(STOP_EVENT_CLASSNAME);
    }
    validateEntityId() {
        if (isInvalidEntityId({
            node: this.node,
            doc: this.view.state.doc,
            defaultId: defaultMermaidEntityId,
        })) {
            const newId = generateEntityId(MermaidConsts.NodeName);
            this.view.dispatch(this.view.state.tr.setNodeAttribute(this.getPos(), MermaidConsts.NodeAttrs.EntityId, newId));
        }
    }
    onChange(attrs) {
        const pos = this.getPos();
        if (pos === undefined)
            return;
        const tr = this.view.state.tr.setNodeMarkup(pos, undefined, {
            ...this.node.attrs,
            ...attrs,
        }, []);
        this.view.dispatch(tr);
    }
    getMermaidInstance = () => mermaidInstance;
    renderMermaid() {
        return (_jsx(Portal, { container: this.dom, children: _jsx(MermaidView, { view: this.view, onChange: this.onChange.bind(this), node: this.node, getMermaidInstance: this.getMermaidInstance, getPos: this.getPos }) }));
    }
}
//# sourceMappingURL=NodeView.js.map
