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