-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrenderer.js
More file actions
2671 lines (2266 loc) · 89.7 KB
/
renderer.js
File metadata and controls
2671 lines (2266 loc) · 89.7 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
document.addEventListener('DOMContentLoaded', () => {
const openBtn = document.getElementById('open-btn');
const saveBtn = document.getElementById('save-btn');
const fileNameSpan = document.getElementById('file-name');
const welcomeDiv = document.getElementById('welcome');
const editorContainer = document.getElementById('editor-container');
const editorPane = document.getElementById('editor-pane');
const previewPane = document.getElementById('preview-pane');
const editor = document.getElementById('editor');
const contentDiv = document.getElementById('content');
const toggleGroup = document.getElementById('toggle-group');
const editBtn = document.getElementById('edit-btn');
const previewBtn = document.getElementById('preview-btn');
const splitBtn = document.getElementById('split-btn');
const themeToggle = document.getElementById('theme-toggle');
const lineNumbers = document.getElementById('line-numbers');
const cursorPosition = document.getElementById('cursor-position');
const wordCountSpan = document.getElementById('word-count');
const charCountSpan = document.getElementById('char-count');
const lineCountSpan = document.getElementById('line-count');
const toggleLineNumbersBtn = document.getElementById('toggle-line-numbers');
const toggleWordWrapBtn = document.getElementById('toggle-word-wrap');
const sidebar = document.getElementById('sidebar');
const toggleSidebarBtn = document.getElementById('toggle-sidebar');
const fileList = document.getElementById('file-list');
const tabsBar = document.getElementById('tabs-bar');
const rightSidebar = document.getElementById('right-sidebar');
const toggleRightSidebarBtn = document.getElementById('toggle-right-sidebar');
const outlineToggleBtn = document.getElementById('outline-toggle-btn');
const outlineList = document.getElementById('outline-list');
const currentFilePathSpan = document.getElementById('current-file-path');
const openFilesSection = document.getElementById('open-files-section');
const openFilesHeader = document.getElementById('open-files-header');
// Multi-file state management
let openFiles = new Map(); // Map of filePath -> { content, unsaved, cursorPos, scrollPos }
let activeFilePath = null;
let untitledCounter = 1;
let isDarkMode = localStorage.getItem('darkMode') === 'true';
let showLineNumbers = localStorage.getItem('showLineNumbers') !== 'false';
let sidebarCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
let wordWrap = localStorage.getItem('wordWrap') !== 'false'; // Default to true
let rightSidebarHidden = localStorage.getItem('rightSidebarHidden') === 'true';
let openFilesSectionCollapsed = localStorage.getItem('openFilesSectionCollapsed') === 'true';
let outlineCollapsedItems = JSON.parse(localStorage.getItem('outlineCollapsedItems') || '{}');
let sidebarWidth = parseInt(localStorage.getItem('sidebarWidth') || '200', 10);
let rightSidebarWidth = parseInt(localStorage.getItem('rightSidebarWidth') || '220', 10);
// Shared regex for matching YAML frontmatter
const frontmatterRegex = /^---\s*\n[\s\S]*?\n---\s*\n?/;
// Utility function to escape HTML special characters
function escapeHtml(str) {
if (str === null || str === undefined) return '';
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// Initialize theme
const lightIcon = themeToggle.querySelector('.light-icon');
const darkIcon = themeToggle.querySelector('.dark-icon');
function initTheme() {
if (isDarkMode) {
document.body.classList.add('dark');
lightIcon.classList.remove('active');
darkIcon.classList.add('active');
} else {
document.body.classList.remove('dark');
lightIcon.classList.add('active');
darkIcon.classList.remove('active');
}
}
function toggleTheme() {
isDarkMode = !isDarkMode;
localStorage.setItem('darkMode', isDarkMode);
initTheme();
// Update mermaid theme and re-render diagrams
if (typeof mermaid !== 'undefined') {
mermaid.initialize({
startOnLoad: false,
theme: isDarkMode ? 'dark' : 'default',
securityLevel: 'strict'
});
updatePreview();
}
}
// Initialize theme on load
initTheme();
// Theme toggle button
themeToggle.addEventListener('click', toggleTheme);
// Sidebar functionality
const sidebarResizeHandle = document.getElementById('sidebar-resize-handle');
const rightSidebarResizeHandle = document.getElementById('right-sidebar-resize-handle');
function initSidebar() {
if (sidebarCollapsed) {
sidebar.classList.add('collapsed');
sidebar.style.width = '';
sidebar.style.minWidth = '';
sidebarResizeHandle.style.display = 'none';
} else {
sidebar.classList.remove('collapsed');
sidebar.style.width = sidebarWidth + 'px';
sidebar.style.minWidth = sidebarWidth + 'px';
sidebarResizeHandle.style.display = '';
}
}
function toggleSidebar() {
sidebarCollapsed = !sidebarCollapsed;
localStorage.setItem('sidebarCollapsed', sidebarCollapsed);
initSidebar();
}
initSidebar();
toggleSidebarBtn.addEventListener('click', toggleSidebar);
// Sidebar resize functionality
function initSidebarWidths() {
if (!sidebarCollapsed) {
sidebar.style.width = sidebarWidth + 'px';
sidebar.style.minWidth = sidebarWidth + 'px';
}
if (!rightSidebarHidden) {
rightSidebar.style.width = rightSidebarWidth + 'px';
rightSidebar.style.minWidth = rightSidebarWidth + 'px';
}
}
function setupResizeHandlers() {
let isResizing = false;
let currentHandle = null;
let startX = 0;
let startWidth = 0;
function onMouseDown(e, handle, target, isLeft) {
isResizing = true;
currentHandle = handle;
startX = e.clientX;
startWidth = target.offsetWidth;
handle.classList.add('resizing');
document.body.classList.add('resizing');
e.preventDefault();
function onMouseMove(e) {
if (!isResizing) return;
const diff = isLeft ? e.clientX - startX : startX - e.clientX;
const newWidth = Math.max(150, Math.min(500, startWidth + diff));
target.style.width = newWidth + 'px';
target.style.minWidth = newWidth + 'px';
// Update line numbers if resizing affects editor
if (wordWrap) {
updateLineNumbers();
}
}
function onMouseUp() {
if (!isResizing) return;
isResizing = false;
currentHandle.classList.remove('resizing');
document.body.classList.remove('resizing');
// Save the new width
if (currentHandle === sidebarResizeHandle) {
sidebarWidth = sidebar.offsetWidth;
localStorage.setItem('sidebarWidth', sidebarWidth);
} else {
rightSidebarWidth = rightSidebar.offsetWidth;
localStorage.setItem('rightSidebarWidth', rightSidebarWidth);
}
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
}
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
}
sidebarResizeHandle.addEventListener('mousedown', (e) => {
if (!sidebarCollapsed) {
onMouseDown(e, sidebarResizeHandle, sidebar, true);
}
});
rightSidebarResizeHandle.addEventListener('mousedown', (e) => {
if (!rightSidebarHidden) {
onMouseDown(e, rightSidebarResizeHandle, rightSidebar, false);
}
});
}
initSidebarWidths();
setupResizeHandlers();
// Open Files section collapse
function initOpenFilesSection() {
if (openFilesSectionCollapsed) {
openFilesSection.classList.add('collapsed');
} else {
openFilesSection.classList.remove('collapsed');
}
}
function toggleOpenFilesSection() {
openFilesSectionCollapsed = !openFilesSectionCollapsed;
localStorage.setItem('openFilesSectionCollapsed', openFilesSectionCollapsed);
initOpenFilesSection();
}
initOpenFilesSection();
openFilesHeader.addEventListener('click', toggleOpenFilesSection);
// Right Sidebar (Outline) functionality
function initRightSidebar() {
if (rightSidebarHidden) {
rightSidebar.classList.add('hidden');
outlineToggleBtn.classList.remove('active');
rightSidebar.style.width = '';
rightSidebar.style.minWidth = '';
rightSidebarResizeHandle.style.display = 'none';
} else {
rightSidebar.classList.remove('hidden');
outlineToggleBtn.classList.add('active');
rightSidebar.style.width = rightSidebarWidth + 'px';
rightSidebar.style.minWidth = rightSidebarWidth + 'px';
rightSidebarResizeHandle.style.display = '';
}
}
function toggleRightSidebar() {
rightSidebarHidden = !rightSidebarHidden;
localStorage.setItem('rightSidebarHidden', rightSidebarHidden);
initRightSidebar();
}
// Right sidebar tabs
const tabOutline = document.getElementById('tab-outline');
const tabChat = document.getElementById('tab-chat');
const outlinePanel = document.getElementById('outline-panel');
const chatPanel = document.getElementById('chat-panel');
const chatMessages = document.getElementById('chat-messages');
const chatInput = document.getElementById('chat-input');
const chatSendBtn = document.getElementById('chat-send');
const chatIncludeContext = document.getElementById('chat-include-context');
const chatClearBtn = document.getElementById('chat-clear');
let chatHistory = [];
let isChatStreaming = false;
let chatAbortFn = null;
function clearChat() {
// Abort any ongoing stream
if (chatAbortFn) {
chatAbortFn();
chatAbortFn = null;
}
// Clear history
chatHistory = [];
isChatStreaming = false;
chatSendBtn.disabled = false;
// Reset UI
chatMessages.innerHTML = `
<div class="chat-welcome">
<p>Ask AI anything about your document or get writing help.</p>
</div>
`;
}
chatClearBtn.addEventListener('click', clearChat);
// Open chat links in external browser
chatMessages.addEventListener('click', (e) => {
const link = e.target.closest('a');
if (link && link.href) {
e.preventDefault();
window.electronAPI.openExternal(link.href);
}
});
function switchToTab(tabName) {
tabOutline.classList.toggle('active', tabName === 'outline');
tabChat.classList.toggle('active', tabName === 'chat');
outlinePanel.classList.toggle('active', tabName === 'outline');
chatPanel.classList.toggle('active', tabName === 'chat');
if (tabName === 'chat') {
chatInput.focus();
}
}
tabOutline.addEventListener('click', () => switchToTab('outline'));
tabChat.addEventListener('click', () => switchToTab('chat'));
// Chat functionality
function addChatMessage(role, content, isStreaming = false) {
// Remove welcome message if it exists
const welcome = chatMessages.querySelector('.chat-welcome');
if (welcome) welcome.remove();
const messageDiv = document.createElement('div');
messageDiv.className = `chat-message ${role}${isStreaming ? ' streaming' : ''}`;
if (role === 'assistant') {
messageDiv.innerHTML = `
<div class="chat-message-content"></div>
<button class="chat-copy-btn" title="Copy response">
<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2">
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
</svg>
</button>
`;
// Store raw content for copying
messageDiv.dataset.rawContent = content;
} else {
messageDiv.innerHTML = `<div class="chat-message-content"></div>`;
}
const contentDiv = messageDiv.querySelector('.chat-message-content');
if (role === 'assistant') {
// Render markdown for assistant messages
window.electronAPI.parseMarkdown(content).then(html => {
contentDiv.innerHTML = html;
});
// Add copy button handler
const copyBtn = messageDiv.querySelector('.chat-copy-btn');
copyBtn.addEventListener('click', () => {
const rawContent = messageDiv.dataset.rawContent || contentDiv.textContent;
navigator.clipboard.writeText(rawContent).then(() => {
copyBtn.classList.add('copied');
setTimeout(() => copyBtn.classList.remove('copied'), 1500);
});
});
} else {
contentDiv.textContent = content;
}
chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
return messageDiv;
}
function updateChatMessage(messageDiv, content) {
const contentDiv = messageDiv.querySelector('.chat-message-content');
// Store raw content for copying
messageDiv.dataset.rawContent = content;
window.electronAPI.parseMarkdown(content).then(html => {
contentDiv.innerHTML = html;
chatMessages.scrollTop = chatMessages.scrollHeight;
});
}
async function sendChatMessage() {
const message = chatInput.value.trim();
if (!message || isChatStreaming) return;
// Add user message
addChatMessage('user', message);
chatHistory.push({ role: 'user', content: message });
chatInput.value = '';
chatInput.style.height = 'auto';
chatSendBtn.disabled = true;
isChatStreaming = true;
// Add assistant message placeholder
const assistantDiv = addChatMessage('assistant', '', true);
try {
// Build system message with optional document context
let systemContent = 'You are a helpful AI assistant in a markdown editor. Help users with writing, editing, and answering questions. Keep responses concise and helpful. Use markdown formatting when appropriate.';
if (chatIncludeContext.checked && activeFilePath && openFiles.has(activeFilePath)) {
const fileData = openFiles.get(activeFilePath);
const fileName = getFileName(activeFilePath);
systemContent += `\n\nThe user is currently editing a document named "${fileName}". Here is the document content:\n\n---\n${fileData.content}\n---\n\nYou can reference this document when answering questions.`;
}
// Build messages array for API
const apiMessages = [
{
role: 'system',
content: systemContent
},
...chatHistory
];
let fullResponse = '';
let chunkHandlerRef, doneHandlerRef, errorHandlerRef;
const cleanup = () => {
if (chunkHandlerRef) window.pluginAPI.removeAIStreamListener('chunk', chunkHandlerRef);
if (doneHandlerRef) window.pluginAPI.removeAIStreamListener('done', doneHandlerRef);
if (errorHandlerRef) window.pluginAPI.removeAIStreamListener('error', errorHandlerRef);
chatAbortFn = null;
};
// Start the stream and get streamId
const { streamId } = await window.pluginAPI.makeAIRequestStream('ai-editor', 'chat/completions', {
messages: apiMessages
});
// Set up handlers that check for matching streamId
const chunkHandler = (data) => {
if (data.streamId === streamId) {
fullResponse += data.chunk;
updateChatMessage(assistantDiv, fullResponse);
}
};
const doneHandler = (data) => {
if (data.streamId === streamId) {
assistantDiv.classList.remove('streaming');
chatHistory.push({ role: 'assistant', content: fullResponse });
isChatStreaming = false;
chatSendBtn.disabled = false;
cleanup();
}
};
const errorHandler = (data) => {
if (data.streamId === streamId) {
assistantDiv.classList.remove('streaming');
updateChatMessage(assistantDiv, 'Error: ' + (data.error || 'Failed to get response'));
isChatStreaming = false;
chatSendBtn.disabled = false;
cleanup();
}
};
chunkHandlerRef = window.pluginAPI.onAIStreamChunk(chunkHandler);
doneHandlerRef = window.pluginAPI.onAIStreamDone(doneHandler);
errorHandlerRef = window.pluginAPI.onAIStreamError(errorHandler);
chatAbortFn = () => {
cleanup();
window.pluginAPI.abortAIRequestStream(streamId);
};
} catch (error) {
console.error('Chat error:', error);
assistantDiv.classList.remove('streaming');
updateChatMessage(assistantDiv, 'Error: ' + error.message);
isChatStreaming = false;
chatSendBtn.disabled = false;
}
}
chatSendBtn.addEventListener('click', sendChatMessage);
chatInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendChatMessage();
}
});
// Auto-resize chat input
chatInput.addEventListener('input', () => {
chatInput.style.height = 'auto';
chatInput.style.height = Math.min(chatInput.scrollHeight, 100) + 'px';
});
// Parse headings from markdown content
function parseHeadings(content) {
const headings = [];
const lines = content.split('\n');
let lineIndex = 0;
let charIndex = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const nextLine = lines[i + 1];
// ATX-style headings: # Heading
const atxMatch = line.match(/^(#{1,6})\s+(.+)$/);
if (atxMatch) {
headings.push({
level: atxMatch[1].length,
text: atxMatch[2].trim(),
line: lineIndex,
charIndex: charIndex
});
}
// Setext-style headings: Heading followed by === or ---
else if (nextLine && line.trim().length > 0) {
if (/^=+\s*$/.test(nextLine)) {
headings.push({
level: 1,
text: line.trim(),
line: lineIndex,
charIndex: charIndex
});
} else if (/^-+\s*$/.test(nextLine) && line.trim().length > 0) {
headings.push({
level: 2,
text: line.trim(),
line: lineIndex,
charIndex: charIndex
});
}
}
charIndex += line.length + 1; // +1 for newline
lineIndex++;
}
return headings;
}
// Build hierarchical tree from flat headings
function buildHeadingTree(headings) {
const root = { children: [], level: 0 };
const stack = [root];
headings.forEach((heading, index) => {
const node = { ...heading, index, children: [] };
// Pop stack until we find a parent with lower level
while (stack.length > 1 && stack[stack.length - 1].level >= heading.level) {
stack.pop();
}
// Add as child of current stack top
stack[stack.length - 1].children.push(node);
stack.push(node);
});
return root.children;
}
// Generate unique ID for a heading (for collapse state)
function getHeadingId(heading) {
return `${heading.level}-${heading.charIndex}`;
}
// Render a single outline item with its children
function renderOutlineItem(heading, depth = 0) {
const hasChildren = heading.children && heading.children.length > 0;
const headingId = getHeadingId(heading);
const isCollapsed = outlineCollapsedItems[activeFilePath]?.[headingId] === true;
const chevronHtml = hasChildren ? `
<svg class="outline-chevron ${isCollapsed ? 'collapsed' : ''}" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
` : '<span class="outline-chevron-placeholder"></span>';
const childrenHtml = hasChildren ? `
<div class="outline-children ${isCollapsed ? 'collapsed' : ''}">
${heading.children.map(child => renderOutlineItem(child, depth + 1)).join('')}
</div>
` : '';
return `
<div class="outline-item-container">
<div class="outline-item" data-level="${heading.level}" data-index="${heading.index}" data-char="${heading.charIndex}" data-id="${headingId}" title="${escapeHtml(heading.text)}">
${chevronHtml}
<span class="outline-text">${escapeHtml(heading.text)}</span>
</div>
${childrenHtml}
</div>
`;
}
// Toggle collapse state for an outline item
function toggleOutlineCollapse(headingId) {
if (!outlineCollapsedItems[activeFilePath]) {
outlineCollapsedItems[activeFilePath] = {};
}
outlineCollapsedItems[activeFilePath][headingId] = !outlineCollapsedItems[activeFilePath][headingId];
localStorage.setItem('outlineCollapsedItems', JSON.stringify(outlineCollapsedItems));
}
// Render the document outline
function renderOutline() {
if (!activeFilePath || !openFiles.has(activeFilePath)) {
outlineList.innerHTML = '<div class="outline-empty">No document open</div>';
return;
}
const fileData = openFiles.get(activeFilePath);
// Strip frontmatter before parsing headings (same as preview)
// But track the frontmatter length to adjust charIndex for editor navigation
let content = fileData.content;
const frontmatterMatch = content.match(frontmatterRegex);
const frontmatterLength = frontmatterMatch ? frontmatterMatch[0].length : 0;
content = content.replace(frontmatterRegex, '');
const headings = parseHeadings(content);
// Adjust charIndex to account for stripped frontmatter
headings.forEach(h => {
h.charIndex += frontmatterLength;
});
if (headings.length === 0) {
outlineList.innerHTML = '<div class="outline-empty">No headings found</div>';
return;
}
// Build hierarchical tree and render
const tree = buildHeadingTree(headings);
outlineList.innerHTML = tree.map(heading => renderOutlineItem(heading)).join('');
// Add click handlers for navigation and collapse toggle
outlineList.querySelectorAll('.outline-item').forEach((item) => {
const chevron = item.querySelector('.outline-chevron');
// Chevron click - toggle collapse
if (chevron) {
chevron.addEventListener('click', (e) => {
e.stopPropagation();
const headingId = item.dataset.id;
toggleOutlineCollapse(headingId);
// Update UI without full re-render
chevron.classList.toggle('collapsed');
const childrenContainer = item.parentElement.querySelector('.outline-children');
if (childrenContainer) {
childrenContainer.classList.toggle('collapsed');
}
});
}
// Item click - navigate to heading
item.addEventListener('click', () => {
const charIndex = parseInt(item.dataset.char, 10);
const headingIndex = parseInt(item.dataset.index, 10);
// Set cursor at the beginning of the heading line
editor.focus();
editor.setSelectionRange(charIndex, charIndex);
// Calculate scroll position accounting for word wrap
const scrollPosition = calculateScrollPositionForLine(charIndex);
editor.scrollTop = scrollPosition;
syncLineNumbersScroll();
// Scroll preview to the corresponding heading (by index)
scrollPreviewToHeading(headingIndex);
// Update active state
outlineList.querySelectorAll('.outline-item').forEach(el => el.classList.remove('active'));
item.classList.add('active');
updateCursorPosition();
});
});
}
// Calculate the scroll position needed to show a given character position at the top
function calculateScrollPositionForLine(charIndex) {
const lines = editor.value.substring(0, charIndex).split('\n');
const targetLineIndex = lines.length - 1;
const allLines = editor.value.split('\n');
const lineHeight = getLineHeight();
if (!wordWrap) {
// Simple calculation without word wrap
return targetLineIndex * lineHeight;
}
// With word wrap, measure actual heights of lines before target
const measure = getMeasureElement();
const editorWidth = editor.clientWidth - 40; // Subtract padding
measure.style.width = editorWidth + 'px';
let totalHeight = 0;
for (let i = 0; i < targetLineIndex; i++) {
measure.textContent = allLines[i] || ' ';
const height = measure.offsetHeight;
const visualLines = Math.max(1, Math.round(height / lineHeight));
totalHeight += visualLines * lineHeight;
}
return totalHeight;
}
// Scroll preview pane to show the heading at the top
function scrollPreviewToHeading(index) {
// Get all headings in the preview in document order
const allHeadings = contentDiv.querySelectorAll('h1, h2, h3, h4, h5, h6');
if (index >= 0 && index < allHeadings.length) {
const targetHeading = allHeadings[index];
// Get positions using getBoundingClientRect for accuracy
const paneRect = previewPane.getBoundingClientRect();
const headingRect = targetHeading.getBoundingClientRect();
// Calculate how far the heading is from the top of the visible pane area
const offsetFromPaneTop = headingRect.top - paneRect.top;
// Add that offset to current scroll position, minus a small margin
previewPane.scrollTop = previewPane.scrollTop + offsetFromPaneTop - 16;
}
}
// Update active outline item based on cursor position
function updateActiveOutlineItem() {
if (!activeFilePath || !openFiles.has(activeFilePath)) return;
const cursorPos = editor.selectionStart;
const items = outlineList.querySelectorAll('.outline-item');
let activeItem = null;
items.forEach(item => {
item.classList.remove('active');
const charIndex = parseInt(item.dataset.char, 10);
if (charIndex <= cursorPos) {
activeItem = item;
}
});
if (activeItem) {
activeItem.classList.add('active');
// Scroll outline list to show active item
const listRect = outlineList.getBoundingClientRect();
const itemRect = activeItem.getBoundingClientRect();
if (itemRect.top < listRect.top || itemRect.bottom > listRect.bottom) {
activeItem.scrollIntoView({ block: 'nearest' });
}
}
}
initRightSidebar();
toggleRightSidebarBtn.addEventListener('click', toggleRightSidebar);
outlineToggleBtn.addEventListener('click', toggleRightSidebar);
// Line numbers functionality
function initLineNumbers() {
if (showLineNumbers) {
lineNumbers.classList.remove('hidden');
toggleLineNumbersBtn.classList.add('active');
} else {
lineNumbers.classList.add('hidden');
toggleLineNumbersBtn.classList.remove('active');
}
}
// Measurement element for calculating wrapped line heights
let measureElement = null;
function getMeasureElement() {
if (!measureElement) {
measureElement = document.createElement('div');
// Copy computed styles from editor for accurate measurement
const editorStyles = getComputedStyle(editor);
measureElement.style.cssText = `
position: absolute;
visibility: hidden;
white-space: pre-wrap;
word-wrap: break-word;
font-family: ${editorStyles.fontFamily};
font-size: ${editorStyles.fontSize};
line-height: ${editorStyles.lineHeight};
letter-spacing: ${editorStyles.letterSpacing};
padding: 0;
border: none;
box-sizing: border-box;
`;
document.body.appendChild(measureElement);
}
return measureElement;
}
function getLineHeight() {
const computed = getComputedStyle(editor);
const lineHeight = parseFloat(computed.lineHeight);
// If lineHeight is NaN (e.g., "normal"), calculate from font size
if (isNaN(lineHeight)) {
return parseFloat(computed.fontSize) * 1.6;
}
return lineHeight;
}
function updateLineNumbers() {
const lines = editor.value.split('\n');
const lineHeight = getLineHeight();
// If word wrap is disabled, use simple line numbers
if (!wordWrap) {
const lineNumbersHtml = lines.map((_, i) => `<span>${i + 1}</span>`).join('');
lineNumbers.innerHTML = lineNumbersHtml;
return;
}
// Calculate visual height for each line when word wrap is enabled
const measure = getMeasureElement();
const editorWidth = editor.clientWidth - 40; // Subtract padding (20px each side)
measure.style.width = editorWidth + 'px';
const lineNumbersHtml = lines.map((line, i) => {
// Measure the height of this line when wrapped
measure.textContent = line || ' '; // Use space for empty lines
const height = measure.offsetHeight;
const visualLines = Math.max(1, Math.round(height / lineHeight));
const spanHeight = visualLines * lineHeight;
return `<span style="height: ${spanHeight}px">${i + 1}</span>`;
}).join('');
lineNumbers.innerHTML = lineNumbersHtml;
}
function syncLineNumbersScroll() {
lineNumbers.scrollTop = editor.scrollTop;
}
function toggleLineNumbersVisibility() {
showLineNumbers = !showLineNumbers;
localStorage.setItem('showLineNumbers', showLineNumbers);
initLineNumbers();
}
// Word wrap functions
function initWordWrap() {
if (wordWrap) {
editor.classList.remove('no-wrap');
toggleWordWrapBtn.classList.add('active');
} else {
editor.classList.add('no-wrap');
toggleWordWrapBtn.classList.remove('active');
}
}
function toggleWordWrap() {
wordWrap = !wordWrap;
localStorage.setItem('wordWrap', wordWrap);
initWordWrap();
updateLineNumbers(); // Recalculate line heights
}
// Sync scrolling between editor and preview
let isEditorScrolling = false;
let isPreviewScrolling = false;
function syncEditorToPreview() {
if (isPreviewScrolling) return;
isEditorScrolling = true;
const editorScrollMax = editor.scrollHeight - editor.clientHeight;
if (editorScrollMax <= 0) return;
const editorScrollPercent = editor.scrollTop / editorScrollMax;
const previewScrollMax = previewPane.scrollHeight - previewPane.clientHeight;
previewPane.scrollTop = editorScrollPercent * previewScrollMax;
setTimeout(() => { isEditorScrolling = false; }, 50);
}
function syncPreviewToEditor() {
if (isEditorScrolling) return;
isPreviewScrolling = true;
const previewScrollMax = previewPane.scrollHeight - previewPane.clientHeight;
if (previewScrollMax <= 0) return;
const previewScrollPercent = previewPane.scrollTop / previewScrollMax;
const editorScrollMax = editor.scrollHeight - editor.clientHeight;
editor.scrollTop = previewScrollPercent * editorScrollMax;
syncLineNumbersScroll();
setTimeout(() => { isPreviewScrolling = false; }, 50);
}
// Initialize line numbers and word wrap
initLineNumbers();
initWordWrap();
// Line numbers toggle button
toggleLineNumbersBtn.addEventListener('click', toggleLineNumbersVisibility);
// Word wrap toggle button
toggleWordWrapBtn.addEventListener('click', toggleWordWrap);
// Inline Formatting Toolbar in Header
const formattingToolbarInline = document.getElementById('formatting-toolbar-inline');
// Check if selected text has specific formatting
function checkFormatting(text, before, after) {
if (!text || text.length === 0) return false;
return text.startsWith(before) && text.endsWith(after) && text.length >= before.length + after.length;
}
// Check if lines have a specific prefix
function checkLinePrefix(text, prefix) {
if (!text) return false;
const lines = text.split('\n');
return lines.every(line => line.startsWith(prefix) || line.trim() === '');
}
// Check if text is a numbered list
function checkNumberedList(text) {
if (!text) return false;
const lines = text.split('\n');
return lines.every((line, i) => {
const match = line.match(/^(\d+)\.\s/);
return match || line.trim() === '';
});
}
// Update button active states based on selection
function updateToolbarState() {
const start = editor.selectionStart;
const end = editor.selectionEnd;
const value = editor.value;
const selectedText = value.substring(start, end);
// Get extended selection to check for surrounding markers
const extStart = Math.max(0, start - 3);
const extEnd = Math.min(value.length, end + 3);
const extendedContext = value.substring(extStart, extEnd);
// Check inline formatting by looking at what surrounds the selection
const beforeSel = value.substring(Math.max(0, start - 2), start);
const afterSel = value.substring(end, Math.min(value.length, end + 2));
// Bold: check for ** around selection
const isBold = (beforeSel.endsWith('**') && afterSel.startsWith('**')) ||
checkFormatting(selectedText, '**', '**');
document.getElementById('fmt-bold').classList.toggle('active', isBold);
// Italic: check for * around selection (but not **)
const isItalic = (beforeSel.endsWith('*') && !beforeSel.endsWith('**') &&
afterSel.startsWith('*') && !afterSel.startsWith('**')) ||
(checkFormatting(selectedText, '*', '*') && !checkFormatting(selectedText, '**', '**'));
document.getElementById('fmt-italic').classList.toggle('active', isItalic);
// Strikethrough
const isStrike = (beforeSel.endsWith('~~') && afterSel.startsWith('~~')) ||
checkFormatting(selectedText, '~~', '~~');
document.getElementById('fmt-strikethrough').classList.toggle('active', isStrike);
// Inline code
const isCode = (beforeSel.endsWith('`') && !beforeSel.endsWith('``') &&
afterSel.startsWith('`') && !afterSel.startsWith('``')) ||
(checkFormatting(selectedText, '`', '`') && !checkFormatting(selectedText, '```', '```'));
document.getElementById('fmt-code').classList.toggle('active', isCode);
// Get full lines for line-based formatting
let lineStart = value.lastIndexOf('\n', start - 1) + 1;
let lineEnd = value.indexOf('\n', end);
if (lineEnd === -1) lineEnd = value.length;
const fullLines = value.substring(lineStart, lineEnd);
// Heading - check specific levels
const headingMatch = fullLines.match(/^(#{1,6})\s/);
const headingLevel = headingMatch ? headingMatch[1].length : 0;
document.getElementById('fmt-h1').classList.toggle('active', headingLevel === 1);
document.getElementById('fmt-h2').classList.toggle('active', headingLevel === 2);
document.getElementById('fmt-h3').classList.toggle('active', headingLevel === 3);
document.getElementById('fmt-h4').classList.toggle('active', headingLevel === 4);
document.getElementById('fmt-h5').classList.toggle('active', headingLevel === 5);
document.getElementById('fmt-h6').classList.toggle('active', headingLevel === 6);
// Bullet list
const isBullet = checkLinePrefix(fullLines, '- ') || checkLinePrefix(fullLines, '* ');
document.getElementById('fmt-ul').classList.toggle('active', isBullet);
// Numbered list
const isNumbered = checkNumberedList(fullLines);
document.getElementById('fmt-ol').classList.toggle('active', isNumbered);
// Quote
const isQuote = checkLinePrefix(fullLines, '> ');
document.getElementById('fmt-quote').classList.toggle('active', isQuote);
// Link - check if selection or surrounding is a link
const linkRegex = /\[([^\]]*)\]\([^)]*\)/;
const isLink = linkRegex.test(selectedText) || linkRegex.test(extendedContext);
document.getElementById('fmt-link').classList.toggle('active', isLink);
// Code block
const isCodeBlock = selectedText.startsWith('```') && selectedText.endsWith('```');
document.getElementById('fmt-codeblock').classList.toggle('active', isCodeBlock);
}
// Toggle formatting (add or remove)
function toggleWrapFormatting(before, after) {