xref: /plugin/diagrams/script/DiagramsMenuItemDispatcher.js (revision ab4202fa8a6983f7bc07d26fd7b4cb517c5eca80)
1class DiagramsMenuItemDispatcher extends AbstractMenuItemDispatcher {
2    static isAvailable(schema) {
3        return !!schema.nodes.diagrams;
4    }
5
6    static getMenuItem(schema) {
7        if (!this.isAvailable(schema)) {
8            throw new Error('Diagrams is missing in provided Schema!');
9        }
10
11        return new MenuItem({
12            command: (state, dispatch) => {
13                const { $from } = state.selection;
14                const index = $from.index();
15                if (!$from.parent.canReplaceWith(index, index, schema.nodes.diagrams)) {
16                    return false;
17                }
18                if (dispatch) {
19                    let textContent = '';
20                    state.selection.content().content.descendants((node) => {
21                        textContent += node.textContent;
22                        return false;
23                    });
24
25                    const dForm = DiagramsForm.getInstance();
26                    if (textContent) {
27                        dForm.setSource(textContent);
28                    }
29
30                    dForm.show();
31
32                    dForm.on('submit', DiagramsForm.resolveSubmittedLinkData(
33                        {},
34                        dForm,
35                        (newAttrs) => {
36                            dispatch(state.tr.replaceSelectionWith(schema.nodes.diagrams.create(newAttrs)));
37                            dForm.off('submit');
38                            dForm.hide();
39                            dForm.resetForm();
40                        },
41                    ));
42                }
43                return true;
44            },
45            icon: document.createElement('span'), // FIXME
46            label: LANG.plugins.diagrams['PMMenuItem'],
47        });
48    }
49}
50