1/**
2 * Integrate diagrams editing into the editor
3 *
4 * This requires some global code that's executed early (not in document.ready)
5 */
6if (typeof window.toolbar !== 'undefined') {
7    /**
8     * Select the diagram at the current cursor position
9     *
10     * @param area
11     * @returns {selection_class}
12     */
13    function selectDiagram(area) {
14        const selection = DWgetSelection(area);
15        const open = '<diagram';
16        const close = '</diagram>';
17        const min = 0;
18        const max = area.value.length;
19
20        // we ignore any selection and only use cursor position
21        selection.end = selection.start;
22
23        // potential boundaries
24        const start = area.value.lastIndexOf(open, selection.start);
25        const end = area.value.indexOf(close, selection.end);
26
27        // boundaries of the previous and next elements of the same type
28        const prev = area.value.lastIndexOf(close, selection.start - close.length);
29        const next = area.value.indexOf(open, selection.start + open.length);
30
31        // out of bounds?
32        if (start < min) return selection;
33        if (prev > -1 && prev > min && start < prev) return selection;
34        if (end > max) return selection;
35        if (next > -1 && next < end && end > next) return selection;
36
37        // still here? we are inside a boundary, new selection
38        selection.start = area.value.indexOf('>', start) + 1;
39        selection.end = end;
40        DWsetSelection(selection);
41        return selection;
42    }
43
44    function addBtnActionDiagramsPlugin($btn, props, edid) {
45        $btn.on('click', function (e) {
46            e.preventDefault();
47            const diagramsEditor = new DiagramsEditor();
48
49            const area = document.getElementById(edid);
50            const selection = selectDiagram(area);
51
52            const origSvg = area.value.substring(selection.start, selection.end);
53
54            diagramsEditor.editMemory(origSvg, svg => {
55                if (!origSvg) {
56                    // if this is a new diagram, wrap it in a <diagram> tag
57                    svg = '<diagram>' + svg + '</diagram>';
58                }
59                area.value = area.value.substring(0, selection.start) +
60                    svg +
61                    area.value.substring(selection.end, area.value.length);
62                return true;
63            });
64
65
66        });
67    }
68
69    toolbar[toolbar.length] = {
70        type: "DiagramsPlugin",
71        title: LANG.plugins.diagrams.toolbarButton,
72        icon: "../../plugins/diagrams/img/diagramsnet.png",
73    };
74}
75