Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
7004 lines (6050 loc) · 256 KB
/
Copy pathscript.js
File metadata and controls
7004 lines (6050 loc) · 256 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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==================== DOM Elements ====================
const markdownInput = document.getElementById('markdown-input');
const previewContent = document.getElementById('preview-content');
const btnDownload = document.getElementById('btn-download');
const btnClear = document.getElementById('btn-clear');
const btnUpload = document.getElementById('btn-upload');
const btnExamples = document.getElementById('btn-examples');
const btnAbout = document.getElementById('btn-about');
const btnFullscreen = document.getElementById('btn-fullscreen');
const btnZoomIn = document.getElementById('btn-zoom-in');
const btnZoomOut = document.getElementById('btn-zoom-out');
const btnEditorZoomIn = document.getElementById('btn-editor-zoom-in');
const btnEditorZoomOut = document.getElementById('btn-editor-zoom-out');
const btnNewDoc = document.getElementById('btn-new-doc');
const btnSaveMd = document.getElementById('btn-save-md');
const btnSaveMdFs = document.getElementById('btn-save-md-fs');
const btnDownloadFs = document.getElementById('btn-download-fs');
const fileInput = document.getElementById('file-input');
const pageNumbers = document.getElementById('page-numbers');
const pagelessMode = document.getElementById('pageless-mode');
const startingPage = document.getElementById('starting-page');
const startingNumber = document.getElementById('starting-number');
const startingPageContainer = document.getElementById('starting-page-container');
const startingNumberContainer = document.getElementById('starting-number-container');
const pageNumberStyle = document.getElementById('page-number-style');
const pageNumberStyleContainer = document.getElementById('page-number-style-container');
const pageNumberSize = document.getElementById('page-number-size');
const pageNumberSizeValue = document.getElementById('page-number-size-value');
const pageNumberSizeContainer = document.getElementById('page-number-size-container');
const pageNumberVertical = document.getElementById('page-number-vertical');
const pageNumberHorizontal = document.getElementById('page-number-horizontal');
const pageNumberPositionContainer = document.getElementById('page-number-position-container');
const pageNumberOptions = document.getElementById('page-number-options');
const btnCopyFormatting = document.getElementById('btn-copy-formatting');
const formattingCodeBlock = document.getElementById('formatting-code-block');
const loadingOverlay = document.getElementById('loading-overlay');
const loadingText = document.querySelector('.loading-text');
const loadingSubtext = document.querySelector('.loading-subtext');
const loadingProgressFill = document.getElementById('loading-progress-fill');
const toast = document.getElementById('toast');
const editorProjectStatus = document.getElementById('editor-project-status');
const cssInput = document.getElementById('css-input');
const tabMarkdown = document.getElementById('tab-markdown');
const tabCss = document.getElementById('tab-css');
const editorContainer = document.querySelector('.editor-container');
const editorDivider = document.getElementById('editor-divider');
const editorWrapper = document.querySelector('.editor-wrapper');
const STORAGE_KEYS = {
markdown: 'md2pdf_content',
pageNumbers: 'md2pdf_page_numbers',
startingPage: 'md2pdf_starting_page',
startingNumber: 'md2pdf_starting_number',
pageNumberStyle: 'md2pdf_page_number_style',
pageNumberSize: 'md2pdf_page_number_size',
pageNumberVertical: 'md2pdf_page_number_vertical',
pageNumberHorizontal: 'md2pdf_page_number_horizontal',
pagelessMode: 'md2pdf_pageless_mode',
customCss: 'md2pdf_custom_css',
savedDefaultCssHash: 'md2pdf_saved_default_css_hash',
previewZoom: 'md2pdf_preview_zoom',
editorZoom: 'md2pdf_editor_zoom',
editorSplit: 'md2pdf_editor_split',
// MarkDownForge project persistence (refresh continuity)
mdfprojDisplayName: 'md2pdf_mdfproj_display_name',
mdfprojLastSavedHash: 'md2pdf_mdfproj_last_saved_hash',
mdfprojCss: 'md2pdf_mdfproj_css'
};
let defaultMarkdownCssText = '';
let currentDocBaseName = 'document';
let markdownEditor = null;
let cssEditor = null;
let previewSourceBlocks = [];
let activePreviewSourceBlockId = null;
let editorHoverFrame = null;
let lastEditorHoverLine = null;
let previewRenderVersion = 0;
let previewHoverFrame = null;
let activeEditorSourceBlockId = null;
let activeEditorSourceLineHandles = [];
let selectedPreviewImage = null;
let imageResizeOverlay = null;
let imageResizeHandle = null;
let imageAlignToolbar = null;
let imageResizeState = null;
let imageCropBox = null;
let imageCropState = null;
let imageCropActive = false;
let imageCropRect = null;
let tableResizeState = null;
let previewTableWidthMarkers = new Map();
let previewTableHandleId = 0;
// ==================== MarkDownForge Project (.mdfproj) ====================
// A .mdfproj is a ZIP with:
// - document.md (Markdown + optional embedded CSS comment block)
// - images/ (images referenced by markdown)
// - meta.json
let mdfprojFileHandle = null;
let mdfprojDisplayName = '';
let mdfprojIsModified = false;
let mdfprojIsBusy = false;
let suppressMdfprojModifiedTracking = false;
// When working with a non-project import (.md/.zip), keep the original filename
// visible in the editor header so the user always knows what they're editing.
let nonProjectFileLabel = '';
function isMdfprojActive() {
return !!(mdfprojFileHandle || (mdfprojDisplayName && String(mdfprojDisplayName).trim()));
}
function isPagelessMode() {
return !!(pagelessMode && pagelessMode.checked);
}
function getDocumentLayoutState() {
return {
pageless: isPagelessMode(),
pageNumbers: {
enabled: pageNumbers ? pageNumbers.checked : false,
startingPage: startingPage ? parseInt(startingPage.value, 10) || 1 : 1,
startingNumber: startingNumber ? parseInt(startingNumber.value, 10) || 1 : 1,
style: pageNumberStyle ? pageNumberStyle.value : 'page',
size: pageNumberSize ? parseInt(pageNumberSize.value, 10) || 10 : 10,
vertical: pageNumberVertical ? pageNumberVertical.value : 'bottom',
horizontal: pageNumberHorizontal ? pageNumberHorizontal.value : 'right'
}
};
}
function computeMdfprojContentHash() {
const content = embedCustomCssIntoMarkdown(getMarkdownValue(), getCustomCss());
return hashText(`${content}\n${JSON.stringify(getDocumentLayoutState())}`);
}
function persistMdfprojStateSnapshot() {
// Persist name + CSS so refresh doesn't lose project identity/styling.
if (!isMdfprojActive()) return;
try {
const name = String(mdfprojDisplayName || '').trim();
if (name) localStorage.setItem(STORAGE_KEYS.mdfprojDisplayName, name);
localStorage.setItem(STORAGE_KEYS.mdfprojCss, String(getCustomCss() || ''));
} catch { /* ignore */ }
}
function makeFreshDocumentBaseName(prefix = 'document') {
const d = new Date();
const pad2 = (n) => String(n).padStart(2, '0');
const y = d.getFullYear();
const m = pad2(d.getMonth() + 1);
const day = pad2(d.getDate());
const hh = pad2(d.getHours());
const mm = pad2(d.getMinutes());
const ss = pad2(d.getSeconds());
return `${prefix}-${y}${m}${day}-${hh}${mm}${ss}`;
}
async function createNewDocument(options = {}) {
const silent = !!options.silent;
const skipPrompt = !!options.skipPrompt;
// In-app new document flow.
// If there are unsaved changes, prompt the user to save (OK) or discard (Cancel).
if (!skipPrompt && shouldWarnBeforeClosingTab()) {
const saveFirst = confirm('You have unsaved changes. Save before creating a new document?');
if (saveFirst) {
try {
await overwriteMdfproj();
} catch (e) {
// User canceled Save As or save failed => keep current document.
console.warn('New document aborted due to save error/cancel:', e);
showToast('⚠️ New document canceled');
return;
}
}
// If user chose not to save: continue and discard.
}
try {
await resetSessionWorkspace();
} catch { /* ignore */ }
runWithoutMdfprojModifiedTracking(() => {
setMarkdownValue('');
userEditedCss = false;
setCustomCssProgrammatic(defaultMarkdownCssText);
if (pagelessMode) pagelessMode.checked = false;
applyPageNumberVisibility();
});
// New doc should not look/behave like the previous imported file.
nonProjectFileLabel = '';
setMdfprojHandle(null);
mdfprojDisplayName = '';
setMdfprojModified(false);
clearMdfprojPersistedState();
// Use a unique default filename so Save As won't suggest overwriting the previous doc.
currentDocBaseName = makeFreshDocumentBaseName('document');
resetTextareaView(markdownEditor || markdownInput);
resetTextareaView(cssEditor || cssInput);
updatePreview();
autoSave();
if (!silent) {
showToast('📄 New document');
}
}
function persistMdfprojAsLastSaved() {
try {
persistMdfprojStateSnapshot();
localStorage.setItem(STORAGE_KEYS.mdfprojLastSavedHash, computeMdfprojContentHash());
} catch { /* ignore */ }
}
function clearMdfprojPersistedState() {
try {
localStorage.removeItem(STORAGE_KEYS.mdfprojDisplayName);
localStorage.removeItem(STORAGE_KEYS.mdfprojLastSavedHash);
localStorage.removeItem(STORAGE_KEYS.mdfprojCss);
} catch { /* ignore */ }
}
function supportsFileSystemAccessApi() {
// Requires secure context (https or localhost) in Chromium-based browsers.
return !!(window && window.isSecureContext && window.showSaveFilePicker && window.showOpenFilePicker);
}
function stripMdfprojExtension(filename) {
const raw = String(filename || '').trim();
if (!raw) return '';
const justName = raw.split(/[\\/]/).pop() || raw;
return justName.toLowerCase().endsWith('.mdfproj') ? justName.slice(0, -'.mdfproj'.length) : guessBaseNameFromFilename(justName);
}
function setMdfprojHandle(handle) {
mdfprojFileHandle = handle || null;
if (mdfprojFileHandle && mdfprojFileHandle.name) {
mdfprojDisplayName = stripMdfprojExtension(mdfprojFileHandle.name) || mdfprojDisplayName;
}
persistMdfprojStateSnapshot();
updateMdfprojStatusUi();
}
function setMdfprojDisplayNameFromFilename(filename) {
const base = stripMdfprojExtension(filename);
if (base) mdfprojDisplayName = base;
persistMdfprojStateSnapshot();
updateMdfprojStatusUi();
}
function setMdfprojModified(isModified) {
mdfprojIsModified = !!isModified;
updateMdfprojStatusUi();
}
function markMdfprojModified() {
if (suppressMdfprojModifiedTracking) return;
if (mdfprojIsBusy) return;
// Smart check: compare current content hash with last saved hash
// If they match, don't mark as modified (handles undo back to saved state)
try {
const savedHash = localStorage.getItem(STORAGE_KEYS.mdfprojLastSavedHash);
if (savedHash) {
const currentHash = computeMdfprojContentHash();
const isActuallyModified = currentHash !== savedHash;
if (mdfprojIsModified !== isActuallyModified) {
mdfprojIsModified = isActuallyModified;
updateMdfprojStatusUi();
}
return;
}
} catch (e) {
// Fallback to simple marking if hash check fails
console.warn('Hash check failed:', e);
}
// Fallback: mark as modified (for new unsaved files)
if (!mdfprojIsModified) {
mdfprojIsModified = true;
updateMdfprojStatusUi();
}
}
function updateMdfprojStatusUi() {
if (!editorProjectStatus) return;
const isProject = !!(mdfprojFileHandle || (mdfprojDisplayName && String(mdfprojDisplayName).trim()));
if (isProject) {
const nameWithExt = mdfprojFileHandle
? String(mdfprojFileHandle.name || '').trim()
: `${String(mdfprojDisplayName || 'Document').trim() || 'Document'}.mdfproj`;
const displayName = mdfprojIsModified ? `${nameWithExt}*` : nameWithExt;
editorProjectStatus.textContent = displayName;
editorProjectStatus.title = displayName;
return;
}
if (nonProjectFileLabel) {
const label = String(nonProjectFileLabel).trim();
const displayName = mdfprojIsModified ? `${label}*` : label;
editorProjectStatus.textContent = displayName;
editorProjectStatus.title = displayName;
return;
}
editorProjectStatus.textContent = 'Unsaved File';
editorProjectStatus.title = 'Unsaved File';
}
function shouldWarnBeforeClosingTab() {
// If a save/import is in progress, avoid trapping the user.
if (mdfprojIsBusy) return false;
// Primary signal: modified tracking.
if (mdfprojIsModified) return true;
// If the user has already saved/imported a project (name known) and there are no
// unsaved modifications, do not warn.
if (!mdfprojFileHandle && mdfprojDisplayName && !mdfprojIsModified) return false;
// Secondary signal: an unsaved doc that has content (new or imported without a file handle).
// This covers cases where the file handle is unavailable (non-secure context, non-Chromium, etc.).
if (!mdfprojFileHandle) {
const markdownText = String(getMarkdownValue() || '').trim();
if (markdownText) return true;
// If user customized CSS (vs. default), consider that meaningful work too.
const cssText = normalizeCss(getCustomCss());
const defaultCss = normalizeCss(defaultMarkdownCssText);
if (cssText && cssText !== defaultCss) return true;
}
return false;
}
function bindBeforeUnloadPrompt() {
// Browser limitation: you cannot show a custom "Save / Don't Save" dialog.
// This triggers the built-in "Leave site?" confirmation when there are unsaved changes.
window.addEventListener('beforeunload', (event) => {
if (!shouldWarnBeforeClosingTab()) return;
event.preventDefault();
// Chrome/Edge require returnValue to be set to trigger the prompt.
event.returnValue = '';
});
}
function runWithoutMdfprojModifiedTracking(fn) {
suppressMdfprojModifiedTracking = true;
try {
return fn();
} finally {
suppressMdfprojModifiedTracking = false;
}
}
function extractFirstHeadingTitle(markdownText) {
const src = String(markdownText || '').replace(/\r\n/g, '\n');
const lines = src.split('\n');
for (const line of lines) {
const m = line.match(/^\s*#\s+(.+?)\s*$/);
if (m && m[1]) return m[1].trim();
}
return '';
}
function extractImageRelPathsFromMarkdown(markdownText) {
const src = String(markdownText || '');
const found = new Set();
// Markdown image syntax: 
for (const m of src.matchAll(/!\[[^\]]*\]\(([^\)\s]+)(?:\s+"[^"]*")?\)/g)) {
const path = String(m[1] || '').trim();
if (path.toLowerCase().startsWith('images/')) found.add(path);
}
// HTML: <img src="...">
for (const m of src.matchAll(/<img\b[^>]*?\ssrc=("|')([^"']+)(\1)[^>]*>/gi)) {
const path = String(m[2] || '').trim();
if (path.toLowerCase().startsWith('images/')) found.add(path);
}
return Array.from(found);
}
async function fetchSessionImageBlob(relativePath) {
const rel = String(relativePath || '').replace(/\\/g, '/');
if (!rel) throw new Error('Missing image path');
const sid = currentSessionId || await ensureSession();
const url = `${getServerOrigin()}/s/${sid}/${rel}`;
const res = await fetch(url);
if (!res.ok) throw new Error(`Could not fetch image: ${rel}`);
return await res.blob();
}
async function buildMdfprojZipBlob() {
if (typeof JSZip === 'undefined') {
throw new Error('JSZip is not available');
}
const zip = new JSZip();
const markdownWithCss = embedCustomCssIntoMarkdown(getMarkdownValue(), getCustomCss());
zip.file('document.md', markdownWithCss);
const title = extractFirstHeadingTitle(markdownWithCss) || mdfprojDisplayName || currentDocBaseName || 'My Markdown Document';
const layoutState = getDocumentLayoutState();
const meta = {
title,
lastSaved: new Date().toISOString(),
version: '1.0',
author: 'MarkDownForge User',
layout: {
pageless: layoutState.pageless
},
pageNumbers: layoutState.pageNumbers
};
zip.file('meta.json', JSON.stringify(meta, null, 2));
const imageRelPaths = extractImageRelPathsFromMarkdown(markdownWithCss);
if (imageRelPaths.length) {
// Ensure session exists; images are stored server-side in the current app.
await ensureSession();
for (const rel of imageRelPaths) {
const blob = await fetchSessionImageBlob(rel);
zip.file(rel, blob);
}
}
return await zip.generateAsync({ type: 'blob' });
}
async function writeBlobToFileHandle(fileHandle, blob) {
const writable = await fileHandle.createWritable();
try {
await writable.write(blob);
} finally {
await writable.close();
}
}
async function saveMdfprojAs() {
// First-time save: show Save As.
if (!supportsFileSystemAccessApi()) {
// Fallback: download, but we can't keep a writable handle for overwrite.
const blob = await buildMdfprojZipBlob();
const base = (mdfprojDisplayName || currentDocBaseName || 'project').trim() || 'project';
downloadBlobAsFile(blob, `${base}.mdfproj`);
setMdfprojDisplayNameFromFilename(`${base}.mdfproj`);
setMdfprojModified(false);
persistMdfprojAsLastSaved();
showToast('💾 Project downloaded (.mdfproj). Use Chrome/Edge for overwrite saves.');
return;
}
const base = (mdfprojDisplayName || currentDocBaseName || 'project').trim() || 'project';
const handle = await window.showSaveFilePicker({
suggestedName: `${base}.mdfproj`,
types: [
{
description: 'MarkDownForge Project',
accept: { 'application/zip': ['.mdfproj'] }
}
]
});
setMdfprojHandle(handle);
setMdfprojDisplayNameFromFilename(handle.name);
await overwriteMdfproj();
}
async function overwriteMdfproj() {
if (!mdfprojFileHandle) {
return saveMdfprojAs();
}
if (mdfprojIsBusy) return;
mdfprojIsBusy = true;
try {
const blob = await buildMdfprojZipBlob();
await writeBlobToFileHandle(mdfprojFileHandle, blob);
setMdfprojModified(false);
persistMdfprojAsLastSaved();
showToast('💾 Project saved');
} finally {
mdfprojIsBusy = false;
}
}
function downloadBlobAsFile(blob, filename) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}
async function importMdfprojFromFile(file, fileHandle) {
if (typeof JSZip === 'undefined') {
showToast('❌ Could not import .mdfproj (JSZip missing)');
return;
}
const buf = await file.arrayBuffer();
const zip = await JSZip.loadAsync(buf);
const docFile = zip.file('document.md');
if (!docFile) throw new Error('Missing document.md in .mdfproj');
const markdownWithCss = await docFile.async('string');
const extracted = extractCustomCssFromMarkdown(markdownWithCss);
// Read metadata if available
let projectMeta = null;
const metaFile = zip.file('meta.json');
if (metaFile) {
try {
const metaJson = await metaFile.async('string');
projectMeta = JSON.parse(metaJson);
} catch (e) {
console.warn('Could not parse meta.json:', e);
}
}
// Reset server workspace so imported images don't collide with previous sessions.
await resetSessionWorkspace();
// Upload images to the current session and rewrite markdown to the new relative paths.
// (Server assigns filenames; we remap references.)
let rewrittenMarkdown = extracted.markdown;
const imageFiles = Object.values(zip.files).filter((f) => f && !f.dir && String(f.name || '').toLowerCase().startsWith('images/'));
const guessMimeFromImagePath = (path) => {
const p = String(path || '').toLowerCase();
if (p.endsWith('.png')) return 'image/png';
if (p.endsWith('.jpg') || p.endsWith('.jpeg')) return 'image/jpeg';
if (p.endsWith('.gif')) return 'image/gif';
if (p.endsWith('.webp')) return 'image/webp';
if (p.endsWith('.svg')) return 'image/svg+xml';
return 'image/png';
};
if (imageFiles.length) {
showToast('📦 Importing project images...');
for (const entry of imageFiles) {
const oldRel = String(entry.name || '').replace(/\\/g, '/');
const buf = await entry.async('arraybuffer');
const blob = new Blob([buf], { type: guessMimeFromImagePath(oldRel) });
const newRel = await uploadPastedImageBlob(blob);
// Replace all occurrences of the old relative path.
rewrittenMarkdown = rewrittenMarkdown.split(oldRel).join(newRel);
}
}
runWithoutMdfprojModifiedTracking(() => {
setMarkdownValue(rewrittenMarkdown);
userEditedCss = !!(extracted.css && normalizeCss(extracted.css) && normalizeCss(extracted.css) !== normalizeCss(defaultMarkdownCssText));
setCustomCssProgrammatic(extracted.css || defaultMarkdownCssText);
});
resetTextareaView(markdownEditor || markdownInput);
resetTextareaView(cssEditor || cssInput);
// Restore page layout + page number settings from metadata
if (pagelessMode) {
pagelessMode.checked = !!(projectMeta && projectMeta.layout && projectMeta.layout.pageless);
}
if (projectMeta && projectMeta.pageNumbers) {
if (pageNumbers) {
pageNumbers.checked = projectMeta.pageNumbers.enabled || false;
}
if (startingPage && projectMeta.pageNumbers.startingPage) {
startingPage.value = projectMeta.pageNumbers.startingPage;
}
if (startingNumber && projectMeta.pageNumbers.startingNumber) {
startingNumber.value = projectMeta.pageNumbers.startingNumber;
}
if (pageNumberStyle && projectMeta.pageNumbers.style) {
pageNumberStyle.value = projectMeta.pageNumbers.style;
}
if (pageNumberSize && projectMeta.pageNumbers.size) pageNumberSize.value = projectMeta.pageNumbers.size;
if (pageNumberVertical && projectMeta.pageNumbers.vertical) pageNumberVertical.value = projectMeta.pageNumbers.vertical;
if (pageNumberHorizontal && projectMeta.pageNumbers.horizontal) pageNumberHorizontal.value = projectMeta.pageNumbers.horizontal;
syncPageNumberSizeOutput();
}
// Update UI visibility for page number controls after pageless restoration.
applyPageNumberVisibility();
updatePreview();
autoSave();
setMdfprojHandle(fileHandle || null);
setMdfprojDisplayNameFromFilename(file.name);
setMdfprojModified(false);
persistMdfprojAsLastSaved();
currentDocBaseName = stripMdfprojExtension(file.name) || currentDocBaseName;
showToast('✅ Project imported (.mdfproj)');
}
// CSS tab persistence:
// Only persist CSS when the user actually edits the CSS tab.
// This prevents an old bundled default from getting stuck in localStorage and
// overriding edits made to markdown-styles.css on disk.
let userEditedCss = false;
let suppressCssTracking = false;
function looksLikeBundledDefaultCss(cssText) {
const t = String(cssText || '').toLowerCase();
return t.includes('markdown content styles') && t.includes('these styles are applied to the preview and pdf output');
}
function setCustomCssProgrammatic(value) {
suppressCssTracking = true;
try {
setCustomCss(value || '');
} finally {
suppressCssTracking = false;
}
}
function hashText(text) {
// Non-crypto hash (fast) used only for cache invalidation.
const s = String(text || '');
let h = 2166136261;
for (let i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return String(h >>> 0);
}
// ==================== Session Workspace (server-side) ====================
// We keep a per-tab session workspace on the FastAPI server.
// Markdown stores images as relative paths (images/<name>), but preview/PDF need
// absolute URLs to fetch from the server securely.
const SESSION_STORAGE_KEY = 'md2pdf_session_id';
let currentSessionId = null;
function bestEffortDeleteSession(sessionId) {
const sid = sessionId || currentSessionId;
if (!sid) return;
const url = getApiUrl(`/api/session/${sid}/delete`);
try {
if (navigator && typeof navigator.sendBeacon === 'function') {
// sendBeacon is designed for page unload and doesn't block.
const blob = new Blob([], { type: 'text/plain' });
navigator.sendBeacon(url, blob);
return;
}
} catch { /* ignore */ }
try {
// keepalive allows the request to outlive the page during unload.
fetch(url, { method: 'POST', keepalive: true }).catch(() => { /* ignore */ });
} catch { /* ignore */ }
}
function bestEffortPruneOtherSessions(keepSessionId) {
const sid = keepSessionId || currentSessionId;
if (!sid) return;
const url = getApiUrl('/api/sessions/prune');
try {
fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ keep_session_id: sid })
}).catch(() => { /* ignore */ });
} catch { /* ignore */ }
}
function getServerOrigin() {
const protocol = window.location && window.location.protocol;
if (protocol === 'http:' || protocol === 'https:') return window.location.origin;
// When opened from disk (file://), use the default dev server.
return 'http://127.0.0.1:8010';
}
function getApiUrl(path) {
const base = getServerOrigin();
if (path.startsWith('http://') || path.startsWith('https://')) return path;
if (!path.startsWith('/')) path = '/' + path;
return base + path;
}
async function ensureSession() {
const candidates = [];
const fromSession = sessionStorage.getItem(SESSION_STORAGE_KEY);
if (fromSession) candidates.push(fromSession);
// Always treat a new tab/window as a new document session.
// If older builds persisted a session id in localStorage, clear it best-effort.
try { localStorage.removeItem('md2pdf_persist_session_id'); } catch { /* ignore */ }
for (const existing of candidates) {
try {
const res = await fetch(getApiUrl(`/api/session/${existing}/touch`), { method: 'POST' });
if (res.ok) {
currentSessionId = existing;
sessionStorage.setItem(SESSION_STORAGE_KEY, existing);
bestEffortPruneOtherSessions(existing);
return existing;
}
} catch { /* ignore */ }
// If the session exists in storage but cannot be touched, it's likely stale.
// Best-effort delete so we don't accumulate abandoned workspaces.
bestEffortDeleteSession(existing);
}
const res = await fetch(getApiUrl('/api/session/new'), { method: 'POST' });
if (!res.ok) throw new Error('Could not create session');
const json = await res.json();
currentSessionId = json.session_id;
sessionStorage.setItem(SESSION_STORAGE_KEY, currentSessionId);
bestEffortPruneOtherSessions(currentSessionId);
return currentSessionId;
}
async function resetSessionWorkspace() {
const sid = currentSessionId || sessionStorage.getItem(SESSION_STORAGE_KEY);
if (!sid) return ensureSession();
try {
const res = await fetch(getApiUrl(`/api/session/${sid}/reset`), { method: 'POST' });
if (!res.ok) throw new Error('Reset failed');
const json = await res.json();
currentSessionId = json.session_id;
sessionStorage.setItem(SESSION_STORAGE_KEY, currentSessionId);
return currentSessionId;
} catch {
// Fall back to a new session.
sessionStorage.removeItem(SESSION_STORAGE_KEY);
currentSessionId = null;
return ensureSession();
}
}
function rewriteSessionImageUrlsInHtml(html, sessionId) {
const sid = sessionId || currentSessionId;
if (!sid) return html;
const origin = getServerOrigin();
// Convert src="images/foo.png" or src='images/foo.png' into an absolute URL.
return String(html || '').replace(
/(<img\b[^>]*?\ssrc=)(["'])(images\/[^"']+)(\2)/gi,
`$1$2${origin}/s/${sid}/$3$4`
);
}
function isCodeMirrorInstance(target) {
return !!(target && typeof target.getDoc === 'function');
}
function getMarkdownValue() {
return markdownEditor ? markdownEditor.getValue() : markdownInput.value;
}
function setMarkdownValue(value) {
const nextValue = value || '';
if (markdownEditor) {
markdownEditor.setValue(nextValue);
} else {
markdownInput.value = nextValue;
}
}
function getCssValue() {
if (cssEditor) return cssEditor.getValue();
return (cssInput && typeof cssInput.value === 'string') ? cssInput.value : '';
}
function setCssValue(value) {
const nextValue = value || '';
if (cssEditor) {
cssEditor.setValue(nextValue);
// Refresh CodeMirror to ensure display is updated
setTimeout(() => {
if (cssEditor) cssEditor.refresh();
}, 0);
} else if (cssInput) {
cssInput.value = nextValue;
}
}
function normalizeCss(css) {
return String(css || '').replace(/\r\n/g, '\n').trim();
}
async function initDefaultMarkdownCss() {
// Prefer fetching the raw file when served over http(s) so formatting/comments are preserved.
// When opened via file://, fetch(file://...) is blocked; we fall back to cssRules (which is normalized).
let css = '';
if (window.location && (window.location.protocol === 'http:' || window.location.protocol === 'https:')) {
// Cache-bust so edits to markdown-styles.css are reflected immediately.
css = await loadCSS('markdown-styles.css', true);
}
if (!css) {
css = getLoadedStylesheetText('markdown-styles.css');
}
defaultMarkdownCssText = css || '';
}
function guessBaseNameFromFilename(filename) {
const raw = String(filename || '').trim();
if (!raw) return 'document';
const justName = raw.split(/[\\/]/).pop() || raw;
const dotIndex = justName.lastIndexOf('.');
const base = dotIndex > 0 ? justName.slice(0, dotIndex) : justName;
return base.trim() || 'document';
}
const EMBED_MARKER_START = '<!-- MD2PDF_CUSTOM_CSS\n';
const EMBED_MARKER_END = '\nMD2PDF_CUSTOM_CSS -->';
function getCustomCss() {
return getCssValue();
}
function setCustomCss(value) {
setCssValue(value || '');
applyCustomCssToPreview();
}
function ensureCustomCssStyleEl() {
let el = document.getElementById('custom-css-style');
if (!el) {
el = document.createElement('style');
el.id = 'custom-css-style';
document.head.appendChild(el);
}
return el;
}
function applyCustomCssToPreview() {
const el = ensureCustomCssStyleEl();
const css = getCustomCss();
el.textContent = scopeDocumentCss(css || '');
}
function splitCssSelectorList(selectorText) {
const selectors = [];
let start = 0;
let depth = 0;
let quote = '';
const text = String(selectorText || '');
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (quote) {
if (char === quote && text[i - 1] !== '\\') quote = '';
continue;
}
if (char === '"' || char === "'") {
quote = char;
continue;
}
if (char === '(' || char === '[') depth++;
if (char === ')' || char === ']') depth = Math.max(0, depth - 1);
if (char === ',' && depth === 0) {
selectors.push(text.slice(start, i).trim());
start = i + 1;
}
}
selectors.push(text.slice(start).trim());
return selectors.filter(Boolean);
}
function scopeDocumentSelector(selector) {
const scope = ':is(#preview-content, #preview-measure-root)';
let value = String(selector || '').trim();
if (!value) return '';
if (/^(?:html|body|:root)(?=$|[\s>+~.#[:])/i.test(value)) {
value = value.replace(/^(?:html|body|:root)/i, scope);
return value;
}
if (/^(?:#preview-content|\.preview-content)(?=$|[\s>+~.#[:])/i.test(value)) {
value = value.replace(/^(?:#preview-content|\.preview-content)/i, scope);
return value;
}
return `${scope} ${value}`;
}
function scopeDocumentCss(cssText) {
const source = String(cssText || '');
if (!source.trim()) return '';
const parser = document.createElement('style');
parser.media = 'not all';
parser.textContent = source;
document.head.appendChild(parser);
const serializeRule = (rule, insideKeyframes = false) => {
if (!rule) return '';
if (!insideKeyframes && rule.type === CSSRule.STYLE_RULE && rule.selectorText) {
const selectors = splitCssSelectorList(rule.selectorText)
.map(scopeDocumentSelector)
.filter(Boolean)
.join(', ');
return selectors ? `${selectors} { ${rule.style.cssText} }` : '';
}
const isKeyframes = typeof CSSRule.KEYFRAMES_RULE === 'number' && rule.type === CSSRule.KEYFRAMES_RULE;
if (rule.cssRules && !isKeyframes) {
const cssText = String(rule.cssText || '');
const header = cssText.slice(0, cssText.indexOf('{')).trim();
const children = Array.from(rule.cssRules).map((child) => serializeRule(child, false)).join('\n');
return `${header} {\n${children}\n}`;
}
return rule.cssText || '';
};
let scoped = '';
try {
scoped = Array.from(parser.sheet?.cssRules || []).map((rule) => serializeRule(rule)).join('\n');
} catch (error) {
console.warn('Could not scope document CSS:', error);
}
parser.remove();
return scoped;
}
function resetTextareaView(textarea) {
if (!textarea) return;
if (isCodeMirrorInstance(textarea)) {
const doc = textarea.getDoc();
doc.setCursor({ line: 0, ch: 0 });
textarea.scrollTo(0, 0);
return;
}
try {
textarea.selectionStart = 0;
textarea.selectionEnd = 0;
textarea.scrollTop = 0;
textarea.scrollLeft = 0;
} catch { /* ignore */ }
}
function applyPageNumberVisibility() {
if (!previewContent) return;
const pageless = isPagelessMode();
const isChecked = !!(pageNumbers && pageNumbers.checked && !pageless);
previewContent.classList.toggle('show-page-numbers', isChecked);
previewContent.classList.toggle('is-pageless-mode', pageless);
previewContent.dataset.layoutMode = pageless ? 'pageless' : 'paged';
if (pageNumberOptions) pageNumberOptions.hidden = !isChecked;
const pageNumberPanel = pageNumbers ? pageNumbers.closest('.page-number-panel') : null;
if (pageNumberPanel) {
pageNumberPanel.classList.toggle('is-disabled', pageless);
pageNumberPanel.setAttribute('aria-disabled', pageless ? 'true' : 'false');
}
if (pageNumbers) pageNumbers.disabled = pageless;
[
startingPage,
startingNumber,
pageNumberStyle,
pageNumberSize,
pageNumberVertical,
pageNumberHorizontal
].forEach((control) => {
if (control) control.disabled = pageless;
});
}
function syncPageNumberSizeOutput() {
if (pageNumberSizeValue && pageNumberSize) pageNumberSizeValue.textContent = `${pageNumberSize.value}px`;
}
function getStartingPage() {
if (!startingPage) return 1;
const val = parseInt(startingPage.value, 10);
return (Number.isFinite(val) && val >= 1) ? val : 1;
}
function getStartingNumber() {
if (!startingNumber) return 1;
const val = parseInt(startingNumber.value, 10);
return (Number.isFinite(val) && val >= 1) ? val : 1;
}
// ==================== Editor Context Menu ====================