]> BookStack Code Mirror - bookstack/blob - resources/js/services/drawio.js
Drawio: Started browser drawing backup store system
[bookstack] / resources / js / services / drawio.js
1 // Docs: https://www.diagrams.net/doc/faq/embed-mode
2 import * as store from './store';
3
4 let iFrame = null;
5 let lastApprovedOrigin;
6 let onInit;
7 let onSave;
8 const saveBackupKey = 'last-drawing-save';
9
10 function drawPostMessage(data) {
11     iFrame.contentWindow.postMessage(JSON.stringify(data), lastApprovedOrigin);
12 }
13
14 function drawEventExport(message) {
15     store.set(saveBackupKey, message.data);
16     if (onSave) {
17         onSave(message.data).then(() => {
18             store.del(saveBackupKey);
19         });
20     }
21 }
22
23 function drawEventSave(message) {
24     drawPostMessage({
25         action: 'export', format: 'xmlpng', xml: message.xml, spin: 'Updating drawing',
26     });
27 }
28
29 function drawEventInit() {
30     if (!onInit) return;
31     onInit().then(xml => {
32         drawPostMessage({action: 'load', autosave: 1, xml});
33     });
34 }
35
36 function drawEventConfigure() {
37     const config = {};
38     window.$events.emitPublic(iFrame, 'editor-drawio::configure', {config});
39     drawPostMessage({action: 'configure', config});
40 }
41
42 function drawEventClose() {
43     // eslint-disable-next-line no-use-before-define
44     window.removeEventListener('message', drawReceive);
45     if (iFrame) document.body.removeChild(iFrame);
46 }
47
48 /**
49  * Receive and handle a message event from the draw.io window.
50  * @param {MessageEvent} event
51  */
52 function drawReceive(event) {
53     if (!event.data || event.data.length < 1) return;
54     if (event.origin !== lastApprovedOrigin) return;
55
56     const message = JSON.parse(event.data);
57     if (message.event === 'init') {
58         drawEventInit();
59     } else if (message.event === 'exit') {
60         drawEventClose();
61     } else if (message.event === 'save') {
62         drawEventSave(message);
63     } else if (message.event === 'export') {
64         drawEventExport(message);
65     } else if (message.event === 'configure') {
66         drawEventConfigure();
67     }
68 }
69
70 /**
71  * Show the draw.io editor.
72  * onSaveCallback must return a promise that resolves on successful save and errors on failure.
73  * onInitCallback must return a promise with the xml to load for the editor.
74  * @param {String} drawioUrl
75  * @param {Function<Promise<String>>} onInitCallback
76  * @param {Function<Promise>} onSaveCallback - Is called with the drawing data on save.
77  */
78 export function show(drawioUrl, onInitCallback, onSaveCallback) {
79     onInit = onInitCallback;
80     onSave = onSaveCallback;
81
82     iFrame = document.createElement('iframe');
83     iFrame.setAttribute('frameborder', '0');
84     window.addEventListener('message', drawReceive);
85     iFrame.setAttribute('src', drawioUrl);
86     iFrame.setAttribute('class', 'fullscreen');
87     iFrame.style.backgroundColor = '#FFFFFF';
88     document.body.appendChild(iFrame);
89     lastApprovedOrigin = (new URL(drawioUrl)).origin;
90 }
91
92 export async function upload(imageData, pageUploadedToId) {
93     const data = {
94         image: imageData,
95         uploaded_to: pageUploadedToId,
96     };
97     const resp = await window.$http.post(window.baseUrl('/images/drawio'), data);
98     return resp.data;
99 }
100
101 export function close() {
102     drawEventClose();
103 }
104
105 /**
106  * Load an existing image, by fetching it as Base64 from the system.
107  * @param drawingId
108  * @returns {Promise<string>}
109  */
110 export async function load(drawingId) {
111     try {
112         const resp = await window.$http.get(window.baseUrl(`/images/drawio/base64/${drawingId}`));
113         return `data:image/png;base64,${resp.data.content}`;
114     } catch (error) {
115         if (error instanceof window.$http.HttpError) {
116             window.$events.showResponseError(error);
117         }
118         close();
119         throw error;
120     }
121 }