|
1 | 1 | // Docs: https://www.diagrams.net/doc/faq/embed-mode |
| 2 | +import * as store from './store'; |
2 | 3 |
|
3 | 4 | let iFrame = null; |
4 | 5 | let lastApprovedOrigin; |
5 | | -let onInit; let |
6 | | - onSave; |
| 6 | +let onInit; |
| 7 | +let onSave; |
| 8 | +const saveBackupKey = 'last-drawing-save'; |
7 | 9 |
|
8 | 10 | function drawPostMessage(data) { |
9 | 11 | iFrame.contentWindow.postMessage(JSON.stringify(data), lastApprovedOrigin); |
10 | 12 | } |
11 | 13 |
|
12 | 14 | function drawEventExport(message) { |
| 15 | + store.set(saveBackupKey, message.data); |
13 | 16 | if (onSave) { |
14 | | - onSave(message.data); |
| 17 | + onSave(message.data).then(() => { |
| 18 | + store.del(saveBackupKey); |
| 19 | + }); |
15 | 20 | } |
16 | 21 | } |
17 | 22 |
|
@@ -62,16 +67,43 @@ function drawReceive(event) { |
62 | 67 | } |
63 | 68 | } |
64 | 69 |
|
| 70 | +/** |
| 71 | + * Attempt to prompt and restore unsaved drawing content if existing. |
| 72 | + * @returns {Promise<void>} |
| 73 | + */ |
| 74 | +async function attemptRestoreIfExists() { |
| 75 | + const backupVal = await store.get(saveBackupKey); |
| 76 | + const dialogEl = document.getElementById('unsaved-drawing-dialog'); |
| 77 | + |
| 78 | + if (!dialogEl) { |
| 79 | + console.error('Missing expected unsaved-drawing dialog'); |
| 80 | + } |
| 81 | + |
| 82 | + if (backupVal) { |
| 83 | + /** @var {ConfirmDialog} */ |
| 84 | + const dialog = window.$components.firstOnElement(dialogEl, 'confirm-dialog'); |
| 85 | + const restore = await dialog.show(); |
| 86 | + if (restore) { |
| 87 | + onInit = async () => backupVal; |
| 88 | + } |
| 89 | + } |
| 90 | +} |
| 91 | + |
65 | 92 | /** |
66 | 93 | * Show the draw.io editor. |
| 94 | + * onSaveCallback must return a promise that resolves on successful save and errors on failure. |
| 95 | + * onInitCallback must return a promise with the xml to load for the editor. |
| 96 | + * Will attempt to provide an option to restore unsaved changes if found to exist. |
67 | 97 | * @param {String} drawioUrl |
68 | | - * @param {Function} onInitCallback - Must return a promise with the xml to load for the editor. |
69 | | - * @param {Function} onSaveCallback - Is called with the drawing data on save. |
| 98 | + * @param {Function<Promise<String>>} onInitCallback |
| 99 | + * @param {Function<Promise>} onSaveCallback - Is called with the drawing data on save. |
70 | 100 | */ |
71 | | -export function show(drawioUrl, onInitCallback, onSaveCallback) { |
| 101 | +export async function show(drawioUrl, onInitCallback, onSaveCallback) { |
72 | 102 | onInit = onInitCallback; |
73 | 103 | onSave = onSaveCallback; |
74 | 104 |
|
| 105 | + await attemptRestoreIfExists(); |
| 106 | + |
75 | 107 | iFrame = document.createElement('iframe'); |
76 | 108 | iFrame.setAttribute('frameborder', '0'); |
77 | 109 | window.addEventListener('message', drawReceive); |
|
0 commit comments