xref: /plugin/diagrams/script/DiagramsView.js (revision c949f2b3d2e6bcf98af329b2afe42b867baa2bf6)
1/**
2 * Prosemirror view for the diagrams node
3 */
4class DiagramsView extends AbstractNodeView {
5    /** {DiagramsForm} The form to edit the node attributes */
6    dForm = null;
7
8    constructor(node, view, getPos) {
9        super(node, view, getPos);
10        this.dForm = DiagramsForm.getInstance();
11    }
12
13    /**
14     * Render the node into this.dom
15     *
16     * We use the schema's spec.toDOM() method instead of directly using the passed attributes
17     * to render the node to avoid code duplication and to have a central way to map node
18     * attributes to dom attributes.
19     *
20     * @param {object} attrs
21     */
22    renderNode(attrs) {
23        const schemaSpec = this.node.type.spec.toDOM(this.node);
24        const elem = document.createElement(schemaSpec[0]);
25
26        // copy attributes to dom element
27        Object.entries(schemaSpec[1]).forEach(([key, value]) => {
28            if (value) {
29                elem.setAttribute(key, value);
30            }
31        });
32
33        this.dom = elem;
34    }
35
36    /**
37     * Handle node selection
38     *
39     * Update and show the form
40     */
41    selectNode() {
42        this.dom.classList.add('ProseMirror-selectednode');
43
44        this.dForm.updateFormFromView(this);
45        this.dForm.show();
46    }
47
48    /**
49     * Handle node deselection
50     *
51     * Closes the form
52     */
53    deselectNode() {
54        this.dom.classList.remove('ProseMirror-selectednode');
55        this.dForm.hide();
56        this.dForm.off('submit'); // FIXME is this needed/wanted?
57    }
58
59    /**
60     * Dispatches a node update to the editor
61     *
62     * @param {object} newAttrs
63     */
64    dispatchNodeUpdate(newAttrs) {
65        this.renderNode(newAttrs); // FIXME is this necessary?
66        const nodeStartPos = this.getPos();
67
68        this.outerView.dispatch(this.outerView.state.tr.setNodeMarkup(
69            nodeStartPos,
70            null,
71            newAttrs,
72            this.node.marks,
73        ));
74    }
75}
76