]> BookStack Code Mirror - bookstack/blob - resources/assets/js/libs/drawio.js
a44c12c4459d36ebaf41e2fcad4efada7b43aa55
[bookstack] / resources / assets / js / libs / 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 export 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 }
23
24 export 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: ''});
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 }