Repository navigation
Expand file tree
/
Copy pathrender.js
More file actions
983 lines (830 loc) · 38.5 KB
/
Copy pathrender.js
File metadata and controls
983 lines (830 loc) · 38.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
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
/**
* Markdown Renderer Configuration
*/
// Configure Marked for code blocks & Mermaid
marked.use({
renderer: {
code(token) {
const lang = (token.lang || '').trim().toLowerCase();
if (lang === 'mermaid') {
return `<pre class="mermaid">${token.text}</pre>`;
}
return false;
}
}
});
// Configure Marked to use Highlight.js
marked.setOptions({
highlight: function (code, lang) {
const language = hljs.getLanguage(lang) ? lang : 'plaintext';
return hljs.highlight(code, { language }).value;
},
langPrefix: 'hljs language-',
gfm: true,
breaks: true
});
// Initialize Mermaid if available
function initMermaid() {
if (typeof mermaid !== 'undefined') {
const currentTheme = localStorage.getItem('theme') || (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
mermaid.initialize({
startOnLoad: false,
theme: currentTheme === 'light' ? 'default' : 'dark',
securityLevel: 'loose'
});
}
}
initMermaid();
const contentEl = document.getElementById('content');
const loaderEl = document.getElementById('loader');
const fileNameEl = document.getElementById('display-filename');
const filePathEl = document.getElementById('display-path');
let currentMarkdownContent = '';
let currentMarkdownFilename = '';
// Search feature state
let docSentences = [];
let isSearchOpen = false;
let isPaginationMode = false;
let searchQuery = '';
let searchResults = [];
let currentMatchIndex = -1;
let currentDocumentTags = [];
/**
* Converts standard GitHub URL to raw.githubusercontent.com URL
*/
function convertGitHubUrl(url) {
try {
const u = new URL(url);
if (u.hostname === 'github.com') {
const parts = u.pathname.split('/').filter(Boolean);
if (parts.length >= 4 && (parts[2] === 'blob' || parts[2] === 'raw')) {
const user = parts[0];
const repo = parts[1];
const branch = parts[3];
const rest = parts.slice(4).join('/');
return `https://raw.githubusercontent.com/${user}/${repo}/${branch}/${rest}`;
}
}
} catch (e) {
// Not a valid URL or other parsing error, return original
}
return url;
}
/**
* Fetches and renders the markdown file
*/
async function loadMarkdown(filePath) {
resetSearch();
if (!filePath) {
showError("No markdown file specified.", "Specify a file using ?file=path/to/file.md");
return;
}
// Update UI
loaderEl.style.display = 'flex';
contentEl.style.display = 'none';
document.getElementById('download-btn').style.display = 'none';
let filename = '';
let rawMarkdown = '';
if (filePath === 'session') {
// Read local file from sessionStorage
rawMarkdown = sessionStorage.getItem('custom_markdown_content') || '';
filename = sessionStorage.getItem('custom_markdown_filename') || 'local.md';
if (!rawMarkdown) {
showError("No local markdown content found.", "Please upload/drag-and-drop a file first.");
return;
}
fileNameEl.textContent = filename.replace('.md', '').replaceAll('_', ' ').replaceAll('-', ' ');
filePathEl.textContent = 'Local File';
document.title = `${fileNameEl.textContent} | Reader`;
} else {
let fetchUrl = filePath;
if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
fetchUrl = convertGitHubUrl(filePath);
}
filename = fetchUrl.split('/').pop().split('#')[0].split('?')[0];
fileNameEl.textContent = filename.replace('.md', '').replaceAll('_', ' ').replaceAll('-', ' ');
filePathEl.textContent = filePath;
document.title = `${fileNameEl.textContent} | Reader`;
try {
const response = await fetch(fetchUrl);
if (!response.ok) throw new Error(`Failed to load file: ${response.statusText}`);
rawMarkdown = await response.text();
} catch (error) {
console.error(error);
showError("Could not load the file.", error.message);
return;
}
}
try {
// Replace <<pagebreak>> with a div
let processedMarkdown = rawMarkdown.replace(/(`+)(?:[\s\S]*?)\1|<<pagebreak>>/g, (match, ticks) => ticks ? match : '\n\n<div class="page-break"></div>\n\n');
const htmlContent = marked.parse(processedMarkdown);
const cleanHtml = DOMPurify.sanitize(htmlContent, {
DATA_URI_TAGS: ['img']
});
contentEl.innerHTML = cleanHtml;
// Handle links for nested navigation
handleLinks(filePath);
// Resolve relative image paths
handleImages(filePath);
// Render Math
renderMath(contentEl);
// Render Mermaid Diagrams
if (typeof mermaid !== 'undefined') {
const mermaidNodes = contentEl.querySelectorAll('.mermaid');
if (mermaidNodes.length > 0) {
try {
await mermaid.run({ nodes: mermaidNodes });
} catch (err) {
console.error("Mermaid rendering error:", err);
}
}
}
// Save current markdown content & filename for download
currentMarkdownContent = rawMarkdown;
currentMarkdownFilename = filename;
document.getElementById('download-btn').style.display = 'flex';
// Reveal content
loaderEl.style.display = 'none';
contentEl.style.display = 'block';
// Generate Table of Contents
generateToC();
// Index document and show search button
indexDocument();
currentDocumentTags = parseTags(rawMarkdown);
const searchToggle = document.getElementById('floating-search-toggle');
if (searchToggle) searchToggle.style.display = 'flex';
window.scrollTo(0, 0);
} catch (error) {
console.error(error);
showError("Could not render the file.", error.message);
}
}
/**
* Renders LaTeX using KaTeX
*/
function renderMath(element) {
renderMathInElement(element, {
delimiters: [
{ left: '$$', right: '$$', display: true },
{ left: '$', right: '$', display: false },
{ left: '\\(', right: '\\)', display: false },
{ left: '\\[', right: '\\]', display: true }
],
throwOnError: false
});
}
/**
* Intercepts links to local markdown files
*/
function handleLinks(currentPath) {
const links = contentEl.querySelectorAll('a');
links.forEach(link => {
const href = link.getAttribute('href');
// If it's a relative link to an MD file and not already routed through render.html
if (href && (href.endsWith('.md') || href.includes('.md#')) && !href.startsWith('http') && !href.includes('render.html')) {
if (currentPath === 'session') {
// Prevent navigation for local session files
link.addEventListener('click', (e) => {
e.preventDefault();
alert("Relative markdown links cannot be resolved for locally uploaded files.");
});
return;
}
link.addEventListener('click', (e) => {
e.preventDefault();
// Construct the new path relative to the current file's directory
let finalPath;
if (currentPath.startsWith('http://') || currentPath.startsWith('https://')) {
let resolver = new URL(href, currentPath);
finalPath = resolver.href;
} else {
let fileDir = currentPath.substring(0, currentPath.lastIndexOf('/') + 1);
let resolver = new URL(href, "http://dummy/" + fileDir);
finalPath = resolver.pathname.substring(1); // remove leading /
}
// Update URL and reload
const newUrl = new URL(window.location.href);
newUrl.searchParams.set('file', finalPath);
window.history.pushState({ path: finalPath }, '', newUrl);
loadMarkdown(finalPath);
});
}
});
}
/**
* Resolves relative image paths to be relative to the markdown file's directory
*/
function handleImages(currentPath) {
const images = contentEl.querySelectorAll('img');
images.forEach(img => {
const src = img.getAttribute('src');
// If it's a relative image link (not absolute, not data URI)
if (src && !src.startsWith('http') && !src.startsWith('data:')) {
if (currentPath === 'session') {
return; // Local uploaded files don't have relative paths resolved
}
// Construct the new path relative to the current file's directory
let finalPath;
if (currentPath.startsWith('http://') || currentPath.startsWith('https://')) {
let resolver = new URL(src, currentPath);
finalPath = resolver.href;
} else {
let fileDir = currentPath.substring(0, currentPath.lastIndexOf('/') + 1);
let resolver = new URL(src, "http://dummy/" + fileDir);
finalPath = resolver.pathname.substring(1); // remove leading /
}
img.setAttribute('src', finalPath);
}
});
}
function showError(title, message) {
loaderEl.style.display = 'none';
contentEl.innerHTML = `
<div class="error-container">
<i class="fa-solid fa-circle-exclamation error-icon"></i>
<h2>${title}</h2>
<p>${message}</p>
<br>
<a href="javascript:history.back()" style="color: var(--accent-color); text-decoration: none; font-weight: 600;">
<i class="fa-solid fa-arrow-left"></i> Go Back
</a>
</div>
`;
contentEl.style.display = 'block';
fileNameEl.textContent = "Error";
// Hide ToC toggle on error
document.getElementById('toc-toggle').style.display = 'none';
// Hide search button and close search on error
const searchToggle = document.getElementById('floating-search-toggle');
if (searchToggle) searchToggle.style.display = 'none';
closeSearch();
}
/**
* Sidebar & Table of Contents Logic
*/
const navPane = document.getElementById('nav-pane');
const navOverlay = document.getElementById('nav-overlay');
const tocToggle = document.getElementById('toc-toggle');
const closeNav = document.getElementById('close-nav');
function toggleSidebar() {
const isOpen = navPane.classList.toggle('open');
navOverlay.classList.toggle('open', isOpen);
document.body.style.overflow = isOpen ? 'hidden' : '';
}
function closeSidebar() {
navPane.classList.remove('open');
navOverlay.classList.remove('open');
document.body.style.overflow = '';
}
tocToggle.addEventListener('click', toggleSidebar);
closeNav.addEventListener('click', closeSidebar);
navOverlay.addEventListener('click', closeSidebar);
function generateToC() {
const headings = contentEl.querySelectorAll('h1, h2, h3, h4');
const tocList = document.getElementById('toc-list');
tocList.innerHTML = '';
// Show/hide toggle based on headings availability
tocToggle.style.display = headings.length > 0 ? 'flex' : 'none';
headings.forEach((heading, index) => {
// Ensure unique ID for anchor
if (!heading.id) {
heading.id = 'sec-' + index;
}
const link = document.createElement('a');
link.href = '#' + heading.id;
link.className = `toc-link ${heading.tagName.toLowerCase()}`;
// Clean text (remove math markers if any, though browser handles this ok usually)
link.textContent = heading.textContent;
link.addEventListener('click', (e) => {
e.preventDefault();
// Account for sticky header height
const headerHeight = document.querySelector('header').offsetHeight;
const targetPos = heading.getBoundingClientRect().top + window.pageYOffset - headerHeight - 20;
window.scrollTo({
top: targetPos,
behavior: 'smooth'
});
closeSidebar();
});
tocList.appendChild(link);
});
}
// Download function
document.getElementById('download-btn').addEventListener('click', () => {
if (!currentMarkdownContent) return;
const blob = new Blob([currentMarkdownContent], { type: 'text/markdown;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = currentMarkdownFilename || 'document.md';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
// Reset search function to clear state
function resetSearch() {
isPaginationMode = false;
isSearchOpen = false;
searchQuery = '';
searchResults = [];
currentMatchIndex = -1;
currentDocumentTags = [];
const searchContainer = document.getElementById('search-container');
if (searchContainer) {
searchContainer.classList.add('search-container-hidden');
searchContainer.classList.remove('pagination-mode');
}
const toggleBtn = document.getElementById('floating-search-toggle');
if (toggleBtn) {
toggleBtn.classList.remove('active');
}
const searchInput = document.getElementById('search-input');
if (searchInput) {
searchInput.value = '';
}
const clearBtn = document.getElementById('search-clear-btn');
if (clearBtn) {
clearBtn.style.display = 'none';
}
const resultsList = document.getElementById('search-results-list');
if (resultsList) {
resultsList.innerHTML = '';
}
const tagsContainer = document.getElementById('search-tags-container');
if (tagsContainer) {
tagsContainer.style.display = 'none';
}
const tagsList = document.getElementById('search-tags-list');
if (tagsList) {
tagsList.innerHTML = '';
}
const prevBtn = document.getElementById('search-prev-btn');
const nextBtn = document.getElementById('search-next-btn');
if (prevBtn) prevBtn.disabled = true;
if (nextBtn) nextBtn.disabled = true;
const listBtn = document.getElementById('search-list-btn');
if (listBtn) listBtn.style.display = 'none';
removeHighlights();
}
/**
* Floating Search and Pagination Feature
*/
function indexDocument() {
docSentences = [];
const textElements = findTextElements(contentEl);
let sentenceIndex = 0;
textElements.forEach(el => {
const text = getCleanText(el);
const sentences = splitIntoSentences(text);
sentences.forEach(s => {
docSentences.push({
text: s,
element: el,
index: sentenceIndex++
});
});
});
}
function findTextElements(node, list = []) {
if (!node) return list;
// Skip code blocks, math blocks, scripts, styles, page breaks
if (node.tagName === 'PRE' || node.tagName === 'CODE' ||
node.classList?.contains('katex') || node.classList?.contains('katex-display') ||
node.tagName === 'SCRIPT' || node.tagName === 'STYLE' ||
node.classList?.contains('page-break')) {
return list;
}
const searchableTags = ['P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'TD', 'TH', 'BLOCKQUOTE', 'FIGCAPTION', 'LI'];
// If it's a searchable tag, index it and do not recurse into its children
let hasSearchableChild = false;
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i];
if (searchableTags.includes(child.tagName) || child.querySelector(searchableTags.join(','))) {
hasSearchableChild = true;
break;
}
}
if (searchableTags.includes(node.tagName) && !hasSearchableChild) {
list.push(node);
} else {
for (let i = 0; i < node.children.length; i++) {
findTextElements(node.children[i], list);
}
}
return list;
}
function getCleanText(el) {
const clone = el.cloneNode(true);
const unwanted = clone.querySelectorAll('pre, code, .katex, style, script, .page-break');
unwanted.forEach(node => node.remove());
return clone.textContent;
}
function splitIntoSentences(text) {
if (!text) return [];
const cleanText = text.replace(/\s+/g, ' ').trim();
if (!cleanText) return [];
const regex = /[^.!?]+(?:[.!?]+|$)/g;
const sentences = [];
let match;
while ((match = regex.exec(cleanText)) !== null) {
const sentence = match[0].trim();
if (sentence.length > 3) { // ignore very short text snippets
sentences.push(sentence);
}
}
return sentences;
}
function parseTags(markdown) {
if (!markdown) return [];
const regex = /<!--[\s\S]*?tags:\s*([^\r\n\--->]+)[\s\S]*?-->/i;
const match = markdown.match(regex);
if (match) {
return match[1].split(',').map(t => t.trim()).filter(Boolean);
}
return [];
}
function renderTags() {
const tagsContainer = document.getElementById('search-tags-container');
const tagsList = document.getElementById('search-tags-list');
if (!tagsContainer || !tagsList) return;
if (currentDocumentTags.length > 0) {
tagsList.innerHTML = '';
currentDocumentTags.forEach(tag => {
const pill = document.createElement('span');
pill.className = 'search-tag-pill';
pill.textContent = tag;
pill.addEventListener('click', () => {
const searchInput = document.getElementById('search-input');
if (searchInput) {
searchInput.value = tag;
performSearch();
searchInput.focus();
}
});
tagsList.appendChild(pill);
});
tagsContainer.style.display = 'block';
} else {
tagsContainer.style.display = 'none';
}
}
function escapeHTML(str) {
return str.replace(/[&<>'"]/g,
tag => ({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag] || tag)
);
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function removeHighlights() {
const highlights = contentEl.querySelectorAll('mark.search-match');
highlights.forEach(mark => {
const textNode = document.createTextNode(mark.textContent);
mark.parentNode.replaceChild(textNode, mark);
});
contentEl.normalize();
}
function highlightQuery(query) {
removeHighlights();
if (!query) return;
const regex = new RegExp(escapeRegExp(query), 'gi');
const textNodes = [];
function findTextNodes(node) {
if (node.nodeType === Node.TEXT_NODE) {
if (node.textContent.trim().length > 0) {
textNodes.push(node);
}
} else {
const skipTags = ['PRE', 'CODE', 'SCRIPT', 'STYLE'];
if (skipTags.includes(node.tagName) || node.classList?.contains('katex') || node.classList?.contains('page-break')) {
return;
}
for (let child of node.childNodes) {
findTextNodes(child);
}
}
}
const textElements = findTextElements(contentEl);
textElements.forEach(el => {
for (let child of el.childNodes) {
findTextNodes(child);
}
});
for (let i = textNodes.length - 1; i >= 0; i--) {
const node = textNodes[i];
const text = node.textContent;
let match;
regex.lastIndex = 0;
const parent = node.parentNode;
if (!parent) continue;
const matches = [];
while ((match = regex.exec(text)) !== null) {
matches.push({
start: match.index,
end: regex.lastIndex,
matchText: match[0]
});
}
if (matches.length > 0) {
const fragment = document.createDocumentFragment();
let lastIndex = 0;
matches.forEach(m => {
if (m.start > lastIndex) {
fragment.appendChild(document.createTextNode(text.substring(lastIndex, m.start)));
}
const mark = document.createElement('mark');
mark.className = 'search-match';
mark.textContent = m.matchText;
fragment.appendChild(mark);
lastIndex = m.end;
});
if (lastIndex < text.length) {
fragment.appendChild(document.createTextNode(text.substring(lastIndex)));
}
parent.replaceChild(fragment, node);
}
}
}
function updatePaginationHighlights() {
highlightQuery(searchQuery);
const marks = contentEl.querySelectorAll('mark.search-match');
const prevBtn = document.getElementById('search-prev-btn');
const nextBtn = document.getElementById('search-next-btn');
if (marks.length > 0) {
if (prevBtn) prevBtn.disabled = false;
if (nextBtn) nextBtn.disabled = false;
if (currentMatchIndex < 0 || currentMatchIndex >= marks.length) {
currentMatchIndex = 0;
}
scrollToActiveMatch(marks);
} else {
if (prevBtn) prevBtn.disabled = true;
if (nextBtn) nextBtn.disabled = true;
currentMatchIndex = -1;
}
}
function scrollToActiveMatch(marks) {
if (!marks || marks.length === 0) return;
marks.forEach(m => m.classList.remove('search-match-active'));
if (currentMatchIndex < 0) currentMatchIndex = 0;
if (currentMatchIndex >= marks.length) currentMatchIndex = marks.length - 1;
const activeMark = marks[currentMatchIndex];
if (activeMark) {
activeMark.classList.add('search-match-active');
const headerHeight = document.querySelector('header').offsetHeight;
const rect = activeMark.getBoundingClientRect();
const absoluteTop = window.pageYOffset + rect.top;
const targetScroll = absoluteTop - headerHeight - 60;
window.scrollTo({
top: targetScroll,
behavior: 'smooth'
});
}
}
function navigateMatch(direction) {
const marks = contentEl.querySelectorAll('mark.search-match');
if (marks.length === 0) return;
currentMatchIndex += direction;
if (currentMatchIndex < 0) {
currentMatchIndex = marks.length - 1;
} else if (currentMatchIndex >= marks.length) {
currentMatchIndex = 0;
}
scrollToActiveMatch(marks);
}
function enterPaginationMode() {
if (!searchQuery) return;
isPaginationMode = true;
document.getElementById('search-container').classList.add('pagination-mode');
document.getElementById('search-list-btn').style.display = 'flex';
updatePaginationHighlights();
}
function exitPaginationMode() {
isPaginationMode = false;
document.getElementById('search-container').classList.remove('pagination-mode');
document.getElementById('search-list-btn').style.display = 'none';
removeHighlights();
currentMatchIndex = -1;
}
function openSearch() {
isSearchOpen = true;
document.getElementById('search-container').classList.remove('search-container-hidden');
document.getElementById('floating-search-toggle').classList.add('active');
// Sync search state UI
performSearch();
setTimeout(() => {
document.getElementById('search-input').focus();
}, 100);
if (isPaginationMode && searchQuery) {
updatePaginationHighlights();
}
}
function closeSearch() {
isSearchOpen = false;
document.getElementById('search-container').classList.add('search-container-hidden');
document.getElementById('floating-search-toggle').classList.remove('active');
removeHighlights();
}
function toggleSearch() {
if (isSearchOpen) {
closeSearch();
} else {
openSearch();
}
}
function performSearch() {
const inputVal = document.getElementById('search-input').value;
searchQuery = inputVal.trim();
const clearBtn = document.getElementById('search-clear-btn');
const resultsList = document.getElementById('search-results-list');
const prevBtn = document.getElementById('search-prev-btn');
const nextBtn = document.getElementById('search-next-btn');
const tagsContainer = document.getElementById('search-tags-container');
if (!searchQuery) {
clearBtn.style.display = 'none';
prevBtn.disabled = true;
nextBtn.disabled = true;
// Show tag suggestions if available, otherwise show standard placeholder
if (currentDocumentTags.length > 0) {
renderTags();
resultsList.innerHTML = '';
} else {
if (tagsContainer) tagsContainer.style.display = 'none';
resultsList.innerHTML = '<div class="search-no-results">Type to search sentences...</div>';
}
if (isPaginationMode) {
removeHighlights();
currentMatchIndex = -1;
}
return;
}
if (tagsContainer) tagsContainer.style.display = 'none';
clearBtn.style.display = 'flex';
const queryLower = searchQuery.toLowerCase();
searchResults = docSentences.filter(s => s.text.toLowerCase().includes(queryLower));
resultsList.innerHTML = '';
if (searchResults.length === 0) {
prevBtn.disabled = true;
nextBtn.disabled = true;
resultsList.innerHTML = '<div class="search-no-results">No matching sentences found.</div>';
if (isPaginationMode) {
removeHighlights();
currentMatchIndex = -1;
}
} else {
prevBtn.disabled = false;
nextBtn.disabled = false;
const escapedQuery = escapeRegExp(searchQuery);
const regex = new RegExp(`(${escapedQuery})`, 'gi');
searchResults.forEach(match => {
const escapedText = escapeHTML(match.text);
const highlightedText = escapedText.replace(regex, '<mark class="match-highlight">$1</mark>');
const item = document.createElement('div');
item.className = 'search-result-item';
item.innerHTML = highlightedText;
item.addEventListener('click', () => {
const headerHeight = document.querySelector('header').offsetHeight;
const rect = match.element.getBoundingClientRect();
const absoluteTop = window.pageYOffset + rect.top;
const targetScroll = absoluteTop - headerHeight - 60;
window.scrollTo({
top: targetScroll,
behavior: 'smooth'
});
match.element.classList.remove('flash-highlight');
void match.element.offsetWidth; // trigger reflow
match.element.classList.add('flash-highlight');
setTimeout(() => {
match.element.classList.remove('flash-highlight');
}, 1500);
});
resultsList.appendChild(item);
});
if (isPaginationMode) {
updatePaginationHighlights();
}
}
}
// Setup Event Listeners for Search Panel & Theme Toggle
function setupEventListeners() {
const toggleBtn = document.getElementById('floating-search-toggle');
const searchInput = document.getElementById('search-input');
const clearBtn = document.getElementById('search-clear-btn');
const closeBtn = document.getElementById('search-close-btn');
const listBtn = document.getElementById('search-list-btn');
const prevBtn = document.getElementById('search-prev-btn');
const nextBtn = document.getElementById('search-next-btn');
const themeToggleBtn = document.getElementById('theme-toggle-btn');
if (toggleBtn) toggleBtn.addEventListener('click', toggleSearch);
if (closeBtn) closeBtn.addEventListener('click', closeSearch);
if (themeToggleBtn) themeToggleBtn.addEventListener('click', toggleTheme);
if (searchInput) searchInput.addEventListener('input', performSearch);
if (clearBtn) {
clearBtn.addEventListener('click', () => {
searchInput.value = '';
performSearch();
searchInput.focus();
});
}
if (listBtn) listBtn.addEventListener('click', exitPaginationMode);
if (prevBtn) {
prevBtn.addEventListener('click', () => {
if (!isPaginationMode) {
enterPaginationMode();
currentMatchIndex = -1;
navigateMatch(-1);
} else {
navigateMatch(-1);
}
});
}
if (nextBtn) {
nextBtn.addEventListener('click', () => {
if (!isPaginationMode) {
enterPaginationMode();
currentMatchIndex = -1;
navigateMatch(1);
} else {
navigateMatch(1);
}
});
}
document.addEventListener('keydown', (e) => {
if (!isSearchOpen) return;
if (e.key === 'Escape') {
closeSearch();
return;
}
if (isPaginationMode) {
if (e.key === 'ArrowDown' || e.key === 'Enter') {
e.preventDefault();
navigateMatch(1);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
navigateMatch(-1);
}
} else {
if (e.key === 'Enter' && searchQuery) {
e.preventDefault();
enterPaginationMode();
}
}
});
}
// Theme Helper Functions
function setTheme(theme) {
localStorage.setItem('theme', theme);
updateThemeUI(theme);
}
function updateThemeUI(theme) {
const themeToggleIcon = document.getElementById('theme-toggle-icon');
if (theme === 'light') {
document.body.classList.add('light-theme');
document.body.classList.remove('dark-theme');
if (themeToggleIcon) {
themeToggleIcon.className = 'fa-solid fa-moon';
}
} else {
document.body.classList.add('dark-theme');
document.body.classList.remove('light-theme');
if (themeToggleIcon) {
themeToggleIcon.className = 'fa-solid fa-sun';
}
}
}
// Toggle theme between light and dark
function toggleTheme() {
let currentTheme = localStorage.getItem('theme');
if (!currentTheme) {
const systemPrefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
currentTheme = systemPrefersDark ? 'dark' : 'light';
}
const nextTheme = currentTheme === 'dark' ? 'light' : 'dark';
setTheme(nextTheme);
}
// Theme Sync on Initial Load
function syncTheme() {
let storedTheme = localStorage.getItem('theme');
if (!storedTheme) {
const systemPrefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
storedTheme = systemPrefersDark ? 'dark' : 'light';
}
updateThemeUI(storedTheme);
}
// Initial Load
syncTheme();
setupEventListeners();
window.addEventListener('popstate', () => {
const urlParams = new URLSearchParams(window.location.search);
loadMarkdown(urlParams.get('file'));
});
const urlParams = new URLSearchParams(window.location.search);
loadMarkdown(urlParams.get('file'));