-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
844 lines (704 loc) · 23.5 KB
/
app.js
File metadata and controls
844 lines (704 loc) · 23.5 KB
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
// register service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./service-worker.js', { scope: '/markdown-viewer/' })
.then(reg => console.log('service worker registered', reg))
.catch(err => console.log('service worker registration failed', err));
}
// theme handling - persist preference
let isDarkMode = localStorage.getItem('theme') !== 'light';
// track active panzoom instances for cleanup
let activePanzoomInstances = [];
// track open files
const APP_TITLE = 'Markdown Viewer';
let openDocuments = [];
let activeDocumentId = null;
let nextDocumentId = 0;
// apply saved theme on load
if (!isDarkMode) {
document.body.classList.add('light-theme');
const hlStyle = document.querySelector('link[href*="highlight.js"]');
if (hlStyle) {
hlStyle.href = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css';
}
}
// configure marked with syntax highlighting via marked-highlight extension
const { markedHighlight: markedHighlightFn } = globalThis.markedHighlight;
marked.use(
markedHighlightFn({
langPrefix: 'hljs language-',
highlight: function(code, lang) {
// skip mermaid blocks - they will be rendered as diagrams
// must escape HTML since highlight return values are treated as raw HTML
if (lang === 'mermaid') {
return code.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(code, { language: lang }).value;
} catch (err) {
console.error('highlight error:', err);
}
}
return hljs.highlightAuto(code).value;
}
})
);
marked.setOptions({
breaks: true,
gfm: true
});
// initialize mermaid
mermaid.initialize({
startOnLoad: false,
theme: isDarkMode ? 'dark' : 'default',
});
// destroy all active panzoom instances
function disposePanzoomInstances() {
activePanzoomInstances.forEach(pz => pz.dispose());
activePanzoomInstances = [];
}
// dom elements
const dropZone = document.getElementById('dropZone');
const tabBar = document.getElementById('tabBar');
const tabList = document.getElementById('tabList');
const content = document.getElementById('content');
const fileInfo = document.getElementById('fileInfo');
const fileName = document.getElementById('fileName');
const fileSize = document.getElementById('fileSize');
const wordCount = document.getElementById('wordCount');
const readTime = document.getElementById('readTime');
const fileInput = document.getElementById('fileInput');
const openFileBtn = document.getElementById('openFile');
const toggleThemeBtn = document.getElementById('toggleTheme');
const scrollTopBtn = document.getElementById('scrollTop');
const helpBtn = document.getElementById('helpBtn');
const shortcutsModal = document.getElementById('shortcutsModal');
const closeModal = document.getElementById('closeModal');
// fullscreen diagram modal
const diagramFullscreen = document.getElementById('diagramFullscreen');
const fullscreenContainer = document.getElementById('fullscreenContainer');
const closeFullscreenBtn = document.getElementById('closeFullscreen');
let fullscreenPanzoom = null;
function createDocumentId() {
nextDocumentId += 1;
return `doc-${nextDocumentId}`;
}
function getFileSignature(file) {
return `${file.name}:${file.size}:${file.lastModified}`;
}
function isMarkdownFile(file) {
const normalizedName = file.name.toLowerCase();
return normalizedName.endsWith('.md') || normalizedName.endsWith('.markdown');
}
function hasDraggedFiles(event) {
return Array.from(event.dataTransfer?.types || []).includes('Files');
}
function getDocumentById(documentId) {
return openDocuments.find(documentEntry => documentEntry.id === documentId) || null;
}
function getActiveDocument() {
return getDocumentById(activeDocumentId);
}
function getActiveDocumentIndex() {
return openDocuments.findIndex(documentEntry => documentEntry.id === activeDocumentId);
}
function getTabElement(documentId) {
return tabList.querySelector(`[data-tab-id="${documentId}"]`);
}
function isOverlayOpen() {
return shortcutsModal.style.display !== 'none' || diagramFullscreen.style.display !== 'none';
}
async function activateAdjacentDocument(direction, { focusTab = false } = {}) {
if (openDocuments.length < 2 || !activeDocumentId) {
return;
}
const activeIndex = getActiveDocumentIndex();
if (activeIndex === -1) {
return;
}
const nextIndex = (activeIndex + direction + openDocuments.length) % openDocuments.length;
const nextDocument = openDocuments[nextIndex];
await activateDocument(nextDocument.id, { preserveScroll: true });
if (focusTab) {
getTabElement(nextDocument.id)?.focus();
}
}
function showDropZoneError(message) {
if (dropZone.style.display === 'none') {
console.warn(message);
return;
}
const dropContent = dropZone.querySelector('.drop-zone-content');
const errorMessage = document.createElement('p');
errorMessage.className = 'error-message';
errorMessage.textContent = message;
dropContent.appendChild(errorMessage);
setTimeout(() => {
if (errorMessage.isConnected) {
errorMessage.remove();
}
}, 3000);
}
function updateTabs() {
tabList.innerHTML = '';
tabBar.style.display = openDocuments.length ? 'block' : 'none';
openDocuments.forEach(documentEntry => {
const tab = document.createElement('div');
tab.className = 'tab';
tab.dataset.tabId = documentEntry.id;
tab.setAttribute('role', 'tab');
tab.setAttribute('aria-controls', 'content');
tab.setAttribute('aria-selected', documentEntry.id === activeDocumentId ? 'true' : 'false');
tab.tabIndex = documentEntry.id === activeDocumentId ? 0 : -1;
if (documentEntry.id === activeDocumentId) {
tab.classList.add('active');
}
const label = document.createElement('span');
label.className = 'tab-label';
label.textContent = documentEntry.name;
const closeButton = document.createElement('button');
closeButton.type = 'button';
closeButton.className = 'tab-close';
closeButton.dataset.tabClose = 'true';
closeButton.setAttribute('aria-label', `Close ${documentEntry.name}`);
closeButton.title = `Close ${documentEntry.name}`;
closeButton.textContent = 'x';
tab.appendChild(label);
tab.appendChild(closeButton);
tabList.appendChild(tab);
});
const activeTab = tabList.querySelector('.tab.active');
if (activeTab) {
requestAnimationFrame(() => {
activeTab.scrollIntoView({ block: 'nearest', inline: 'nearest' });
});
}
}
function showViewerError(message) {
closeDiagramFullscreen();
disposePanzoomInstances();
dropZone.style.display = openDocuments.length ? 'none' : 'block';
fileInfo.style.display = 'none';
content.innerHTML = '';
content.style.display = 'block';
const errorEl = document.createElement('p');
errorEl.style.color = '#f85149';
errorEl.textContent = message;
content.appendChild(errorEl);
document.title = APP_TITLE;
}
function resetViewer() {
closeDiagramFullscreen();
disposePanzoomInstances();
activeDocumentId = null;
updateTabs();
dropZone.style.display = 'block';
fileInfo.style.display = 'none';
content.style.display = 'none';
content.innerHTML = '';
document.title = APP_TITLE;
scrollTopBtn.style.display = 'none';
window.scrollTo(0, 0);
}
async function createDocumentFromFile(file) {
const text = await file.text();
return {
id: createDocumentId(),
signature: getFileSignature(file),
name: file.name,
size: file.size,
html: marked.parse(text),
stats: getTextStats(text),
scrollTop: 0
};
}
async function openMarkdownFiles(files) {
const fileList = Array.from(files || []);
if (!fileList.length) {
return;
}
const markdownFiles = fileList.filter(isMarkdownFile);
const invalidFiles = fileList.length - markdownFiles.length;
if (!markdownFiles.length) {
showDropZoneError('Please open only .md or .markdown files.');
return;
}
if (invalidFiles > 0) {
showDropZoneError('Some files were skipped because they are not markdown.');
}
let nextActiveId = activeDocumentId;
let addedNewDocument = false;
let nextActiveShouldRestoreScroll = true;
for (const file of markdownFiles) {
try {
const signature = getFileSignature(file);
const existingDocument = openDocuments.find(documentEntry => documentEntry.signature === signature);
if (existingDocument) {
nextActiveId = existingDocument.id;
nextActiveShouldRestoreScroll = true;
continue;
}
const documentEntry = await createDocumentFromFile(file);
openDocuments.push(documentEntry);
nextActiveId = documentEntry.id;
addedNewDocument = true;
nextActiveShouldRestoreScroll = false;
} catch (err) {
console.error(`error loading ${file.name}:`, err);
if (!openDocuments.length) {
showViewerError(`Error loading ${file.name}: ${err.message}`);
}
}
}
if (!openDocuments.length) {
return;
}
updateTabs();
if (nextActiveId && (addedNewDocument || nextActiveId !== activeDocumentId || content.style.display === 'none')) {
await activateDocument(nextActiveId, { preserveScroll: nextActiveShouldRestoreScroll });
}
}
async function activateDocument(documentId, { preserveScroll = true } = {}) {
const nextDocument = getDocumentById(documentId);
if (!nextDocument) {
return;
}
const currentDocument = getActiveDocument();
if (currentDocument) {
currentDocument.scrollTop = window.scrollY;
}
activeDocumentId = nextDocument.id;
updateTabs();
await renderActiveDocument({ preserveScroll });
}
async function closeDocument(documentId) {
const documentIndex = openDocuments.findIndex(documentEntry => documentEntry.id === documentId);
if (documentIndex === -1) {
return;
}
if (documentId === activeDocumentId) {
const currentDocument = getActiveDocument();
if (currentDocument) {
currentDocument.scrollTop = window.scrollY;
}
}
openDocuments.splice(documentIndex, 1);
if (!openDocuments.length) {
resetViewer();
return;
}
if (documentId === activeDocumentId) {
const nextDocument = openDocuments[Math.max(0, documentIndex - 1)] || openDocuments[0];
await activateDocument(nextDocument.id, { preserveScroll: true });
} else {
updateTabs();
}
}
async function renderActiveDocument({ preserveScroll = true } = {}) {
const documentEntry = getActiveDocument();
if (!documentEntry) {
resetViewer();
return;
}
try {
closeDiagramFullscreen();
disposePanzoomInstances();
content.innerHTML = documentEntry.html;
content.style.display = 'block';
await renderMermaidDiagrams();
dropZone.style.display = 'none';
fileInfo.style.display = 'flex';
fileName.textContent = documentEntry.name;
fileSize.textContent = formatFileSize(documentEntry.size);
wordCount.textContent = `${documentEntry.stats.words.toLocaleString()} words`;
readTime.textContent = `${documentEntry.stats.minutes} min read`;
document.title = `${documentEntry.name} - ${APP_TITLE}`;
window.scrollTo(0, preserveScroll ? documentEntry.scrollTop : 0);
} catch (err) {
console.error('error rendering markdown:', err);
showViewerError('Error loading file: ' + err.message);
}
}
// theme toggle
toggleThemeBtn.addEventListener('click', async () => {
isDarkMode = !isDarkMode;
localStorage.setItem('theme', isDarkMode ? 'dark' : 'light');
document.body.classList.toggle('light-theme', !isDarkMode);
// update highlight.js theme
const hlStyle = document.querySelector('link[href*="highlight.js"]');
if (hlStyle) {
hlStyle.href = isDarkMode
? 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css'
: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css';
}
// update mermaid theme and re-render diagrams
mermaid.initialize({
startOnLoad: false,
theme: isDarkMode ? 'dark' : 'default',
});
if (activeDocumentId) {
await renderActiveDocument({ preserveScroll: true });
}
});
// file handling api - handle files opened from os
if ('launchQueue' in window) {
console.log('file handling api supported');
window.launchQueue.setConsumer(async launchParams => {
if (!launchParams.files.length) {
return;
}
const files = [];
for (const fileHandle of launchParams.files) {
files.push(await fileHandle.getFile());
}
await openMarkdownFiles(files);
});
}
// manual file selection
openFileBtn.addEventListener('click', () => {
fileInput.click();
});
fileInput.addEventListener('change', async event => {
const files = Array.from(event.target.files || []);
if (files.length) {
await openMarkdownFiles(files);
}
event.target.value = '';
});
// tabs
tabList.addEventListener('click', async event => {
const tab = event.target.closest('.tab');
if (!tab) {
return;
}
const { tabId } = tab.dataset;
if (event.target.closest('[data-tab-close]')) {
event.stopPropagation();
await closeDocument(tabId);
return;
}
if (tabId !== activeDocumentId) {
await activateDocument(tabId, { preserveScroll: true });
}
});
tabList.addEventListener('auxclick', async event => {
if (event.button !== 1) {
return;
}
const tab = event.target.closest('.tab');
if (!tab) {
return;
}
event.preventDefault();
await closeDocument(tab.dataset.tabId);
});
tabList.addEventListener('keydown', async event => {
const tab = event.target.closest('.tab');
if (!tab) {
return;
}
if (event.key === 'ArrowLeft') {
event.preventDefault();
await activateAdjacentDocument(-1, { focusTab: true });
return;
}
if (event.key === 'ArrowRight') {
event.preventDefault();
await activateAdjacentDocument(1, { focusTab: true });
return;
}
if ((event.key === 'Enter' || event.key === ' ') && tab.dataset.tabId !== activeDocumentId) {
event.preventDefault();
await activateDocument(tab.dataset.tabId, { preserveScroll: true });
}
});
// drag and drop support
dropZone.addEventListener('dragover', event => {
event.preventDefault();
dropZone.classList.add('drag-over');
});
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('drag-over');
});
dropZone.addEventListener('drop', async event => {
event.preventDefault();
dropZone.classList.remove('drag-over');
await openMarkdownFiles(event.dataTransfer.files);
});
window.addEventListener('dragover', event => {
if (!openDocuments.length || !hasDraggedFiles(event)) {
return;
}
event.preventDefault();
});
window.addEventListener('drop', async event => {
if (!openDocuments.length || !hasDraggedFiles(event)) {
return;
}
event.preventDefault();
await openMarkdownFiles(event.dataTransfer.files);
});
// render mermaid diagrams after markdown is parsed
async function renderMermaidDiagrams() {
disposePanzoomInstances();
const codeBlocks = content.querySelectorAll('code.language-mermaid');
if (codeBlocks.length === 0) {
return;
}
codeBlocks.forEach((codeBlock, index) => {
const pre = codeBlock.parentElement;
// create wrapper structure
const wrapper = document.createElement('div');
wrapper.classList.add('diagram-wrapper');
wrapper.setAttribute('data-diagram-id', index);
// zoom controls (appear on hover via CSS)
wrapper.innerHTML = `
<div class="zoom-controls">
<button data-zoom="in" aria-label="Zoom in" title="Zoom in">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="12" y1="5" x2="12" y2="19"></line>
<line x1="5" y1="12" x2="19" y2="12"></line>
</svg>
</button>
<button data-zoom="out" aria-label="Zoom out" title="Zoom out">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="5" y1="12" x2="19" y2="12"></line>
</svg>
</button>
<button data-zoom="reset" aria-label="Reset zoom" title="Reset zoom">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="1 4 1 10 7 10"></polyline>
<path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path>
</svg>
</button>
<button data-zoom="fullscreen" aria-label="Fullscreen" title="Fullscreen">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="15 3 21 3 21 9"></polyline>
<polyline points="9 21 3 21 3 15"></polyline>
<line x1="21" y1="3" x2="14" y2="10"></line>
<line x1="3" y1="21" x2="10" y2="14"></line>
</svg>
</button>
<span class="zoom-hint">Ctrl+scroll to zoom</span>
</div>
`;
// diagram container
const container = document.createElement('div');
container.classList.add('diagram-container');
const mermaidDiv = document.createElement('div');
mermaidDiv.classList.add('mermaid');
mermaidDiv.textContent = codeBlock.textContent;
mermaidDiv.setAttribute('data-mermaid-source', codeBlock.textContent);
container.appendChild(mermaidDiv);
wrapper.appendChild(container);
pre.replaceWith(wrapper);
});
try {
await mermaid.run({ querySelector: '#content .mermaid', suppressErrors: true });
} catch (err) {
console.error('mermaid rendering error:', err);
}
initializePanzoom();
}
// initialize panzoom on all rendered mermaid SVGs
function initializePanzoom() {
const wrappers = content.querySelectorAll('.diagram-wrapper');
wrappers.forEach(wrapper => {
const container = wrapper.querySelector('.diagram-container');
const svg = container.querySelector('.mermaid svg');
if (!svg) {
return;
}
// remove mermaid's inline max-width so panzoom can scale freely
svg.style.maxWidth = 'none';
const pz = panzoom(svg, {
maxZoom: 10,
minZoom: 0.1,
smoothScroll: false,
zoomDoubleClickSpeed: 1,
bounds: false,
boundsPadding: 0.1,
beforeWheel: function(event) {
// only zoom when Ctrl is held, otherwise let page scroll
return !event.ctrlKey;
}
});
activePanzoomInstances.push(pz);
// wire up zoom control buttons
const controls = wrapper.querySelector('.zoom-controls');
controls.addEventListener('click', event => {
const button = event.target.closest('button');
if (!button) {
return;
}
const action = button.getAttribute('data-zoom');
const rect = container.getBoundingClientRect();
const cx = rect.width / 2;
const cy = rect.height / 2;
if (action === 'in') {
pz.smoothZoom(cx, cy, 1.5);
} else if (action === 'out') {
pz.smoothZoom(cx, cy, 0.67);
} else if (action === 'reset') {
pz.moveTo(0, 0);
pz.zoomAbs(0, 0, 1);
} else if (action === 'fullscreen') {
openDiagramFullscreen(wrapper);
}
});
});
}
function openDiagramFullscreen(wrapper) {
const svg = wrapper.querySelector('.mermaid svg');
if (!svg) {
return;
}
// clone the SVG so the inline one stays untouched
const clonedSvg = svg.cloneNode(true);
// remap IDs to avoid collisions with the original SVG
clonedSvg.querySelectorAll('[id]').forEach(el => {
const oldId = el.id;
const newId = 'fs-' + oldId;
el.id = newId;
clonedSvg.querySelectorAll(`[href="#${oldId}"]`).forEach(ref => {
ref.setAttribute('href', '#' + newId);
});
clonedSvg.querySelectorAll('*').forEach(node => {
for (const attr of node.attributes) {
if (attr.value.includes(`url(#${oldId})`)) {
node.setAttribute(attr.name, attr.value.replace(`url(#${oldId})`, `url(#${newId})`));
}
}
});
});
fullscreenContainer.innerHTML = '';
fullscreenContainer.appendChild(clonedSvg);
diagramFullscreen.style.display = 'flex';
// initialize panzoom on the cloned SVG (no beforeWheel guard in fullscreen)
fullscreenPanzoom = panzoom(clonedSvg, {
maxZoom: 20,
minZoom: 0.05,
smoothScroll: false,
bounds: false
});
}
function closeDiagramFullscreen() {
if (fullscreenPanzoom) {
fullscreenPanzoom.dispose();
fullscreenPanzoom = null;
}
fullscreenContainer.innerHTML = '';
diagramFullscreen.style.display = 'none';
}
closeFullscreenBtn.addEventListener('click', closeDiagramFullscreen);
diagramFullscreen.addEventListener('click', event => {
if (event.target === diagramFullscreen) {
closeDiagramFullscreen();
}
});
// wire up fullscreen zoom controls
document.querySelector('.fullscreen-controls').addEventListener('click', event => {
const button = event.target.closest('button');
if (!button || !fullscreenPanzoom) {
return;
}
const action = button.getAttribute('data-zoom');
const rect = fullscreenContainer.getBoundingClientRect();
const cx = rect.width / 2;
const cy = rect.height / 2;
if (action === 'in') {
fullscreenPanzoom.smoothZoom(cx, cy, 1.5);
} else if (action === 'out') {
fullscreenPanzoom.smoothZoom(cx, cy, 0.67);
} else if (action === 'reset') {
fullscreenPanzoom.moveTo(0, 0);
fullscreenPanzoom.zoomAbs(0, 0, 1);
}
});
// format file size
function formatFileSize(bytes) {
if (bytes < 1024) {
return bytes + ' B';
}
if (bytes < 1024 * 1024) {
return (bytes / 1024).toFixed(1) + ' KB';
}
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}
// text stats for word count and reading time
function getTextStats(text) {
const words = text.trim().split(/\s+/).filter(word => word.length > 0).length;
const minutes = Math.max(1, Math.ceil(words / 200));
return { words, minutes };
}
// scroll to top button
window.addEventListener('scroll', () => {
scrollTopBtn.style.display = window.scrollY > 300 ? 'flex' : 'none';
const activeDocument = getActiveDocument();
if (activeDocument) {
activeDocument.scrollTop = window.scrollY;
}
});
scrollTopBtn.addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
// keyboard shortcuts help modal
helpBtn.addEventListener('click', () => {
shortcutsModal.style.display = 'flex';
});
closeModal.addEventListener('click', () => {
shortcutsModal.style.display = 'none';
});
shortcutsModal.addEventListener('click', event => {
if (event.target === shortcutsModal) {
shortcutsModal.style.display = 'none';
}
});
// keyboard shortcuts
document.addEventListener('keydown', event => {
if (event.defaultPrevented) {
return;
}
// ctrl/cmd + o to open file(s)
if ((event.ctrlKey || event.metaKey) && event.key === 'o') {
event.preventDefault();
fileInput.click();
}
// ctrl/cmd + d to toggle theme
if ((event.ctrlKey || event.metaKey) && event.key === 'd') {
event.preventDefault();
toggleThemeBtn.click();
}
if (
!event.ctrlKey &&
!event.metaKey &&
!event.altKey &&
!event.shiftKey &&
!isOverlayOpen() &&
openDocuments.length > 1
) {
if (event.key === 'ArrowLeft') {
event.preventDefault();
activateAdjacentDocument(-1);
return;
}
if (event.key === 'ArrowRight') {
event.preventDefault();
activateAdjacentDocument(1);
return;
}
}
// ? to show shortcuts help
if (event.key === '?' && !event.ctrlKey && !event.metaKey) {
shortcutsModal.style.display = shortcutsModal.style.display === 'none' ? 'flex' : 'none';
}
// escape to close fullscreen or modal
if (event.key === 'Escape') {
if (diagramFullscreen.style.display !== 'none') {
closeDiagramFullscreen();
} else {
shortcutsModal.style.display = 'none';
}
}
});
console.log('markdown viewer initialized');