1/**
2 * Attach editing button to media file diagrams in pages
3 */
4document.addEventListener('DOMContentLoaded', async () => {
5
6    // get all diagrams images and their IDs
7    const diagrams = document.querySelectorAll('object.diagrams-svg[data-id]');
8    const diagramIDs = Array.from(diagrams).map(image => image.getAttribute('data-id'));
9
10    // check which of the found diagrams are editable
11    const body = new FormData();
12    body.set('diagrams', JSON.stringify(diagramIDs));
13    const result = await fetch(DOKU_BASE + 'lib/exe/ajax.php?call=plugin_diagrams_mediafile_editcheck', {
14        method: 'POST',
15        cache: 'no-cache',
16        body: body,
17    });
18    const editableDiagrams = await result.json();
19
20    // add edit button to editable diagrams
21    diagrams.forEach(image => {
22        if (editableDiagrams.includes(image.getAttribute('data-id'))) {
23            const button = document.createElement('button');
24            button.className = 'diagrams-btn';
25            button.innerText = LANG.plugins.diagrams.editButtonShort;
26            button.title = LANG.plugins.diagrams.editButton;
27
28            const icon = ButtonFunctions.getButtonIcon('edit');
29            button.prepend(icon);
30
31            button.addEventListener('click', event => {
32                event.preventDefault();
33                const diagramsEditor = new DiagramsEditor(() => {
34                    // replace instead of reload to avoid accidentally re-submitting forms
35                    window.location.replace(window.location.href);
36                });
37                diagramsEditor.editMediaFile(image.getAttribute('data-id'));
38            });
39            image.parentNode.querySelector('.diagrams-buttons').appendChild(button);
40        }
41    });
42});
43