]> BookStack Code Mirror - bookstack/blob - resources/js/services/drawio.js
move zip export into exportservice
[bookstack] / resources / js / services / drawio.js
1 let iFrame = null;
2
3 let onInit, onSave;
4
5 /**
6  * Show the draw.io editor.
7  * @param {String} drawioUrl
8  * @param {Function} onInitCallback - Must return a promise with the xml to load for the editor.
9  * @param {Function} onSaveCallback - Is called with the drawing data on save.
10  */
11 function show(drawioUrl, onInitCallback, onSaveCallback) {
12     onInit = onInitCallback;
13     onSave = onSaveCallback;
14
15     iFrame = document.createElement('iframe');
16     iFrame.setAttribute('frameborder', '0');
17     window.addEventListener('message', drawReceive);
18     iFrame.setAttribute('src', drawioUrl);
19     iFrame.setAttribute('class', 'fullscreen');
20     iFrame.style.backgroundColor = '#FFFFFF';
21     document.body.appendChild(iFrame);
22 }
23
24 function close() {
25     drawEventClose();
26 }
27
28 function drawReceive(event) {
29     if (!event.data || event.data.length < 1) return;
30     let message = JSON.parse(event.data);
31     if (message.event === 'init') {
32         drawEventInit();
33     } else if (message.event === 'exit') {
34         drawEventClose();
35     } else if (message.event === 'save') {
36         drawEventSave(message);
37     } else if (message.event === 'export') {
38         drawEventExport(message);
39     }
40 }
41
42 function drawEventExport(message) {
43     if (onSave) {
44         onSave(message.data);
45     }
46 }
47
48 function drawEventSave(message) {
49     drawPostMessage({action: 'export', format: 'xmlpng', xml: message.xml, spin: 'Updating drawing'});
50 }
51
52 function drawEventInit() {
53     if (!onInit) return;
54     onInit().then(xml => {
55         drawPostMessage({action: 'load', autosave: 1, xml: xml});
56     });
57 }
58
59 function drawEventClose() {
60     window.removeEventListener('message', drawReceive);
61     if (iFrame) document.body.removeChild(iFrame);
62 }
63
64 function drawPostMessage(data) {
65     iFrame.contentWindow.postMessage(JSON.stringify(data), '*');
66 }
67
68 async function upload(imageData, pageUploadedToId) {
69     let data = {
70         image: imageData,
71         uploaded_to: pageUploadedToId,
72     };
73     const resp = await window.$http.post(window.baseUrl(`/images/drawio`), data);
74     return resp.data;
75 }
76
77 /**
78  * Load an existing image, by fetching it as Base64 from the system.
79  * @param drawingId
80  * @returns {Promise<string>}
81  */
82 async function load(drawingId) {
83     const resp = await window.$http.get(window.baseUrl(`/images/drawio/base64/${drawingId}`));
84     return `data:image/png;base64,${resp.data.content}`;
85 }
86
87 export default {show, close, upload, load};