"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WMermaidNodeView = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const uikit_1 = require("@gravity-ui/uikit");
const behavior_1 = require("../../../behavior/index.js");
const MermaidView_1 = require("./MermaidView.js");
let mermaidInstance;
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 = (0, behavior_1.getReactRendererFromState)(view.state).createItem('mermaid-view', this.renderMermaid.bind(this));
    }
    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(MermaidView_1.STOP_EVENT_CLASSNAME);
    }
    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 ((0, jsx_runtime_1.jsx)(uikit_1.Portal, { container: this.dom, children: (0, jsx_runtime_1.jsx)(MermaidView_1.MermaidView, { view: this.view, onChange: this.onChange.bind(this), node: this.node, getMermaidInstance: this.getMermaidInstance, getPos: this.getPos }) }));
    }
}
exports.WMermaidNodeView = WMermaidNodeView;
//# sourceMappingURL=NodeView.js.map
