-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
367 lines (335 loc) · 15.7 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
<!DOCTYPE html>
<html>
<head>
<title>Simple, Auditable and Offline Mermaid.js Editor</title>
<style>
.editor {
width: 35%;
height: 100vh;
float: left;
}
.output {
width: 64%;
height: 100vh;
float: left;
overflow: auto;
margin: 0.5%;
}
.mermaidError {
color: maroon;
padding-left: 1em;
padding-top: 1em;
}
#controls ul {
padding: 0;
margin: 0;
}
#controls li {
display: inline-block;
}
#controls li:not(:last-child):after {
content: ' | ';
}
#controls a:visited, #controls a:link {
color: blue;
}
</style>
</head>
<body>
<div class="editor">
<div id="controls">
<span id="filePicker">Load Data...<input type="file" id="loadData"></span>
<button id="saveData">Save Data...</button>
<button id="saveSvg">Save SVG</button>
<button id="savePng">Save PNG</button>
<button id="saveHtml">Save HTML</button>
<button id="redraw">Redraw</button>
<button id="fullscreen">Fullscreen Diagram</button>
<br>
<ul>
<li><a href="https://mermaid.js.org/syntax/flowchart.html" target="_blank">Syntax</a></li>
<li><a href="https://mermaid.live/edit/" target="_blank"> Live Editor</a></li>
<li><a href="https://github.com/sosnik/mermaid-offline-editor"> About</a></li>
</ul>
</div>
<textarea id="editor" autofocus spellcheck="false" style="width: 100%; height: 100%;"></textarea>
</div>
<div class="output"></div>
<script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
<script src="lib/svg-pan-zoom.min.js"></script>
<script>
let editor = document.getElementById('editor');
let output = document.querySelector('.output');
let saveData = document.getElementById('saveData');
let loadData = document.getElementById('loadData');
let saveSvg = document.getElementById('saveSvg');
let savePng = document.getElementById('savePng');
let saveHtml = document.getElementById('saveHtml');
let redraw = document.getElementById('redraw');
let fullscreen = document.getElementById('fullscreen');
let filePicker = document.getElementById('filePicker');
////// I/O //////
if ('showOpenFilePicker' in window) {
loadData.remove();
let btn = document.createElement('button');
btn.innerText = 'Choose File';
let loadedFile = document.createElement('span')
loadedFile.id = 'loadedFile';
loadedFile.innerText = 'No file chosen';
btn.addEventListener('click', async function() {
// Prompt before overwriting
if (editor.value.trim() !== '') {
if (!confirm('Are you sure you want to overwrite the current text?')) {
loadData.value = null; // Reset the file input. The event only triggers on a change so will prevent the user from selecting the same file again after cancelling an overwrite.
return;
}
}
try {
const [fileHandle] = await window.showOpenFilePicker();
const file = await fileHandle.getFile();
const text = await file.text();
editor.value = text;
drawDiagram();
loadedFile.innerText = file.name;
//setIndexedDBItem(`${file.name.split('.').pop()}FileHandle`, fileHandle);
setIndexedDBItem(`dataFileHandle`, fileHandle);
} catch (err) {
console.error(err);
}
});
filePicker.append(btn, loadedFile);
} else {
loadData.addEventListener('change', async function(e) {
// Prompt before overwriting
if (editor.value.trim() !== '') {
if (!confirm('Are you sure you want to overwrite the current text?')) {
loadData.value = null; // Reset the file input. The event only triggers on a change so will prevent the user from selecting the same file again after cancelling an overwrite.
return;
}
}
const file = e.target.files[0];
const text = await file.text();
editor.value = text;
drawDiagram();
});
}
saveData.addEventListener('click', function(e) {
const data = editor.value;
const blob = new Blob([data], { type: 'text/plain' });
saveFile(blob, guessFilename(), 'data', e.shiftKey);
});
saveSvg.addEventListener('click', function(e) {
const svg = output.querySelector('svg');
const svgString = new XMLSerializer().serializeToString(svg);
const blob = new Blob([svgString], { type: 'image/svg+xml' });
saveFile(blob, guessFilename(), 'svg', e.shiftKey);
});
savePng.addEventListener('click', function(e) {
const svg = output.querySelector('svg');
svg["font-size"] = "24px";
const svgString = new XMLSerializer().serializeToString(svg);
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = function() {
const minSize = 300; // Minimum size for small diagrams
// the scale here is arbitrary, the goal is to force the output to be legible. Easier to downscale, amirite?
canvas.width = Math.max(img.width, minSize) * 3;
canvas.height = Math.max(img.height, minSize) * 3;
ctx.drawImage(img, 0, 0);
canvas.toBlob(function(blob) {
saveFile(blob, guessFilename(), 'png', e.shiftKey);
});
};
img.src = 'data:image/svg+xml;base64,' + btoa(svgString);
});
saveHtml.addEventListener('click', function(e) {
const svg = output.querySelector('svg');
const svgString = new XMLSerializer().serializeToString(svg);
const blob = new Blob([`<html><head><title>${guessFilename() || 'diagram'}</title></head><body><h1>${guessFilename() || 'diagram'}</h1>${svgString}</body></html>`], { type: 'text/html' });
saveFile(blob, guessFilename(), 'html', e.shiftKey);
});
async function saveFile(blob, filename, extension, saveAs = false) {
if ('showSaveFilePicker' in window) {
try {
let handle;
const existingHandle = await getIndexedDBItem(`${extension}FileHandle`);
if (existingHandle && !saveAs) {
handle = existingHandle;
} else {
// for image files (pretend HTML is an image in this case) ...
if (['svg', 'png', 'html'].includes(extension)) {
handle = await window.showSaveFilePicker({
id: 'imgOutput',
suggestedName: `${filename?.substring(0, filename.lastIndexOf('.')) || 'diagram'}.${extension}`,
types: [{
description: 'Diagrams',
accept: {
'image/svg+xml': ['.svg'],
'image/png': ['.png'],
'image/html': ['.html']
}
}]
});
} else {
handle = await window.showSaveFilePicker({
id: 'dataOutput',
suggestedName: filename || 'data.txt',
types: [{
description: 'Text Files',
accept: {
'text/plain': ['.txt', '.dat', '.data', '.mermaid']
}
}]
});
}
await setIndexedDBItem(`${extension}FileHandle`, handle);
}
const writable = await handle.createWritable();
await writable.write(blob);
await writable.close();
} catch (err) {
console.error(err);
}
} else {
saveFileLegacy(blob, null, extension);
}
}
function saveFileLegacy(blob, filename = null, extension = null) {
// Try to reuse the filename if a previous datafile was loaded; otherwise prompt the user for a name
// Note: we cannot simply leave the `download` attribute empty and let the browser handle the filename, as it will default to the blob/object URL and won't show the file save dialog
if (!filename) {
filename = loadData.files[0] ? loadData.files[0].name : prompt('Enter filename');
}
let link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
// Cleanup
URL.revokeObjectURL(link.href);
}
////// Mermaid rendering //////
mermaid.initialize({ startOnLoad: false });
const drawDiagram = async function () {
const graphDefinition = editor.value;
try {
const { svg } = await mermaid.render('output', graphDefinition);
output.innerHTML = svg;
// enable pan and zoom via a library. Ideally I'd like to replace this with a local implementation
// quirks: the lib sets some stupid, stupid defaults that need to be eradicated with a cyber-axe
// this is why I prefer writing my own code and not using people's libraries: this also breaks `Fullscreen Diagram` functionality
let viewport = document.querySelector('.output svg')
svgPanZoom(viewport);
viewport.style.height = '100%';
viewport.style.maxWidth = null;
} catch (err) {
output.innerHTML = `<pre class="mermaidError">${err}</pre>`;
}
};
editor.addEventListener('input', drawDiagram);
// Additional controls
redraw.addEventListener('click', drawDiagram);
fullscreen.addEventListener('click', function() {
const svg = output.querySelector('svg');
const svgString = new XMLSerializer().serializeToString(svg);
const blob = new Blob([svgString], { type: 'image/svg+xml' });
const url = URL.createObjectURL(blob);
const win = window.open(url, '_blank');
win.document.write('<img src="' + url + '">');
// Cleanup
win.addEventListener('beforeunload', function(e) {
URL.revokeObjectURL(url);
});
});
////// QOL //////
// Keybinds
window.addEventListener('keydown', function(e) {
if (e.ctrlKey && e.key === 'o') {
e.preventDefault(); // Prevent the default Open behavior
loadData.click();
} else if (e.ctrlKey && e.key === 's') {
e.preventDefault(); // Prevent the default save behavior
saveData.click();
}
});
// end keybinds
// Prevent accidental page close; also do cleanup
window.addEventListener('beforeunload', function(e) {
e.preventDefault();
e.returnValue = '';
// cleanup IndexedDB
window.indexedDB.deleteDatabase('moeDB');
});
// Capture tab key inside textarea and convert to indentation
editor.addEventListener('keydown', function(e) {
if (e.key === 'Tab') {
e.preventDefault();
const start = editor.selectionStart;
const end = editor.selectionEnd;
const value = editor.value;
editor.value = value.substring(0, start) + ' ' + value.substring(end);
editor.selectionStart = editor.selectionEnd = start + 4;
}
});
////// util //////
async function getIndexedDBItem(key) {
return new Promise((resolve, reject) => {
const request = window.indexedDB.open('moeDB');
request.onupgradeneeded = function(event) {
const db = event.target.result;
db.createObjectStore('moeStore');
};
request.onsuccess = function(event) {
const db = event.target.result;
const transaction = db.transaction('moeStore', 'readonly');
const store = transaction.objectStore('moeStore');
const getRequest = store.get(key);
getRequest.onsuccess = function(event) {
const item = event.target.result;
resolve(item);
};
getRequest.onerror = function(event) {
reject(event.target.error);
};
};
request.onerror = function(event) {
reject(event.target.error);
};
});
}
async function setIndexedDBItem(key, value) {
return new Promise((resolve, reject) => {
const request = window.indexedDB.open('moeDB');
request.onupgradeneeded = function(event) {
const db = event.target.result;
db.createObjectStore('moeStore');
};
request.onsuccess = function(event) {
const db = event.target.result;
const transaction = db.transaction('moeStore', 'readwrite');
const store = transaction.objectStore('moeStore');
const putRequest = store.put(value, key);
putRequest.onsuccess = function(event) {
resolve();
};
putRequest.onerror = function(event) {
reject(event.target.error);
};
};
request.onerror = function(event) {
reject(event.target.error);
};
});
}
function guessFilename() {
if (loadData.files[0]) {
return loadData.files[0].name
} else if (document.getElementById('loadedFile').innerText !== 'No file chosen') {
return document.getElementById('loadedFile').innerText
} else {
return null;
}
}
</script>
</body>
</html>