-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1499 lines (1265 loc) · 50.3 KB
/
content.js
File metadata and controls
1499 lines (1265 loc) · 50.3 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
class NotionPresentationMode {
constructor() {
this.isActive = false;
this.currentSlideIndex = 0;
this.slides = [];
this.settings = {
presentationMode: false,
showSlideNumbers: true,
showProgressBar: false,
showNavigationButtons: true,
hideNotesContent: false,
showNotesControls: true
};
this.slideNumberElement = null;
this.progressBarElement = null;
this.presentationIndicator = null;
this.notesBlockIds = new Set(); // Track Notes block IDs
// Flag to avoid reacting to our own programmatic scrolls
this.programmaticScroll = false;
// Coalesce rapid next/prev key presses into a single scroll
this.navTimer = null;
this.navBaseIndex = null;
this.navDelta = 0;
// Track suppression and pending timers for scroll operations
this.programmaticScrollTimeoutId = null;
this._pendingScrollTimers = [];
// Navigation coalescing and scroll suppression helpers (arrow funcs to avoid parsing issues)
this.queueNavigation = (delta) => {
if (!this.isActive || this.slides.length === 0) return;
if (this.navTimer == null) {
this.navBaseIndex = this.currentSlideIndex;
this.navDelta = 0;
}
this.navDelta += delta;
if (this.navTimer) clearTimeout(this.navTimer);
this.navTimer = setTimeout(() => {
let target = this.navBaseIndex + this.navDelta;
target = Math.max(0, Math.min(this.slides.length - 1, target));
this.navTimer = null;
this.navBaseIndex = null;
this.navDelta = 0;
if (target !== this.currentSlideIndex) {
this.currentSlideIndex = target;
this.clearPendingScrollTimers();
this.scrollToSlide(target);
this.updateSlideIndicators();
} else {
this.highlightCurrentSlide();
}
}, 80);
};
this.beginProgrammaticScroll = (duration = 700) => {
this.programmaticScroll = true;
if (this.programmaticScrollTimeoutId) clearTimeout(this.programmaticScrollTimeoutId);
this.programmaticScrollTimeoutId = setTimeout(() => {
this.programmaticScroll = false;
this.programmaticScrollTimeoutId = null;
}, duration);
};
this.clearPendingScrollTimers = () => {
if (Array.isArray(this._pendingScrollTimers)) {
this._pendingScrollTimers.forEach((id) => clearTimeout(id));
this._pendingScrollTimers = [];
}
};
this.trackTimer = (id) => {
if (!this._pendingScrollTimers) this._pendingScrollTimers = [];
if (id != null) this._pendingScrollTimers.push(id);
return id;
};
this.init();
}
async init() {
console.log('Notion Presentation Mode: Initializing...');
// Load settings
await this.loadSettings();
// Set up message listener
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('Notion Presentation Mode: Received message', request);
this.handleMessage(request, sender, sendResponse);
});
// Wait for page to load
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => this.setupPage());
} else {
this.setupPage();
}
// Set up keyboard listeners
this.setupKeyboardListeners();
// Set up scroll listener
this.setupScrollListener();
// Watch for dynamic content changes
this.setupMutationObserver();
// Add a simple way to test the extension
console.log('Notion Presentation Mode: To test, run: window.notionPresentation.enablePresentationMode()');
console.log('Notion Presentation Mode: To debug Notes, run: window.notionPresentation.debugNotes()');
window.notionPresentation = this;
console.log('Notion Presentation Mode: Initialization complete');
}
async loadSettings() {
try {
this.settings = await new Promise((resolve, reject) => {
chrome.runtime.sendMessage({ action: 'getSettings' }, (response) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
resolve(response);
}
});
});
if (this.settings && this.settings.presentationMode) {
this.enablePresentationMode();
}
} catch (error) {
console.log('Could not load settings, using defaults:', error);
// Use default settings if communication fails
this.settings = {
presentationMode: false,
showSlideNumbers: true,
showProgressBar: false,
showNavigationButtons: true,
hideNotesContent: false,
showNotesControls: true
};
}
}
setupPage() {
console.log('Notion Presentation Mode: Setting up page...');
// Find all horizontal dividers and content blocks
this.findSlides();
// Create UI elements
this.createSlideNumber();
this.createProgressBar();
this.createNavigationControls();
this.createNotesControls();
// Update visibility based on settings
this.updateUIVisibility();
this.applyNotesSettings();
// Initial tracking of Notes blocks
this.updateNotesTracking();
console.log('Notion Presentation Mode: Page setup complete');
}
findSlides() {
console.log('Notion Presentation Mode: Finding slides...');
this.slides = [];
// Look for various types of horizontal dividers in Notion
const dividerSelectors = [
'.notion-divider-block',
'.notion-divider_divider',
'[data-block-id] > div[style*="border-top"]',
'hr',
'.notion-hr_hr',
// More modern Notion selectors
'[data-content-editable-leaf="true"][data-block-id] hr',
'div[style*="border-top: 1px solid"]',
'div[style*="border-top:1px solid"]',
'div[role="separator"]'
];
const dividers = document.querySelectorAll(dividerSelectors.join(', '));
console.log('Notion Presentation Mode: Found dividers:', dividers.length, dividers);
// If no dividers found, treat each top-level block as a slide
if (dividers.length === 0) {
console.log('Notion Presentation Mode: No dividers found, using content blocks as slides');
const blocks = document.querySelectorAll('[data-block-id]');
console.log('Notion Presentation Mode: Found blocks:', blocks.length);
blocks.forEach((block, index) => {
if (this.isTopLevelBlock(block)) {
this.slides.push({
element: block,
index: index,
type: 'block'
});
}
});
} else {
console.log('Notion Presentation Mode: Creating slides based on dividers');
// Create slides based on dividers
let currentSlideContent = [];
const allElements = Array.from(document.querySelectorAll('[data-block-id]'));
allElements.forEach((element) => {
if (this.isDivider(element)) {
if (currentSlideContent.length > 0) {
this.slides.push({
elements: [...currentSlideContent],
divider: element,
index: this.slides.length,
type: 'section'
});
currentSlideContent = [];
}
} else {
// Only include top-level blocks
if (this.isTopLevelBlock(element)) {
currentSlideContent.push(element);
}
}
});
// Add remaining content as last slide
if (currentSlideContent.length > 0) {
this.slides.push({
elements: [...currentSlideContent],
index: this.slides.length,
type: 'section'
});
}
}
console.log(`Notion Presentation Mode: Found ${this.slides.length} slides`, this.slides);
}
isTopLevelBlock(element) {
// Check if this is a top-level content block (not nested)
const parent = element.closest('[data-block-id]');
return parent === element;
}
isDivider(element) {
return element.classList.contains('notion-divider-block') ||
element.classList.contains('notion-divider_divider') ||
element.tagName === 'HR' ||
element.classList.contains('notion-hr_hr') ||
element.getAttribute('role') === 'separator' ||
(element.style && element.style.borderTop) ||
element.querySelector('[role="separator"]');
}
setupKeyboardListeners() {
console.log('Notion Presentation Mode: Setting up keyboard listeners...');
document.addEventListener('keydown', (event) => {
console.log('Notion Presentation Mode: Key pressed:', event.code, 'Active:', this.isActive);
// Check for presentation mode toggle (Ctrl/Cmd + Shift + P)
if (event.code === 'KeyP' && event.shiftKey && (event.ctrlKey || event.metaKey)) {
console.log('Notion Presentation Mode: Toggle shortcut pressed');
event.preventDefault();
event.stopPropagation();
if (this.isActive) {
this.disablePresentationMode();
} else {
this.enablePresentationMode();
}
return;
}
if (!this.isActive) return;
// Prevent default behavior for presentation keys (avoid native page scroll / history nav)
const presentationKeys = ['ArrowRight', 'ArrowLeft', 'Backspace', 'Space', 'Enter', 'Home'];
if (presentationKeys.includes(event.code)) {
console.log('Notion Presentation Mode: Preventing default for presentation key:', event.code);
event.preventDefault();
event.stopPropagation();
}
switch (event.code) {
case 'ArrowRight':
case 'Space':
case 'Enter':
console.log('Notion Presentation Mode: Next slide triggered');
this.nextSlide();
break;
case 'ArrowLeft':
case 'Backspace':
console.log('Notion Presentation Mode: Previous slide triggered by key:', event.code);
this.previousSlide();
break;
case 'Home':
console.log('Notion Presentation Mode: Home key pressed, going to first slide');
this.goToFirstSlide();
break;
case 'Escape':
console.log('Notion Presentation Mode: Escape pressed, disabling presentation mode');
this.disablePresentationMode();
break;
}
}, true);
}
setupScrollListener() {
console.log('Notion Presentation Mode: Setting up scroll listener...');
let scrollTimeout;
window.addEventListener('scroll', () => {
if (!this.isActive || this.slides.length === 0) return;
// Ignore scroll events caused by our own programmatic scrolls
if (this.programmaticScroll) return;
// Debounce scroll events
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(() => {
this.updateCurrentSlideFromScroll();
}, 100);
});
}
updateCurrentSlideFromScroll() {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
// If we're near the absolute top, force slide index 0
if (scrollTop <= 100) {
if (this.currentSlideIndex !== 0) {
console.log('Notion Presentation Mode: Near top, forcing current slide to 0');
this.currentSlideIndex = 0;
this.updateSlideIndicators();
this.highlightCurrentSlide();
}
return;
}
const windowHeight = window.innerHeight;
const viewportCenter = scrollTop + windowHeight / 2;
let closestSlideIndex = 0;
let closestDistance = Infinity;
this.slides.forEach((slide, index) => {
let slideElement;
if (slide.type === 'block') {
slideElement = slide.element;
} else if (slide.type === 'section' && slide.elements.length > 0) {
slideElement = slide.elements[0];
}
if (slideElement) {
const rect = slideElement.getBoundingClientRect();
const elementTop = rect.top + scrollTop;
const distance = Math.abs(elementTop - viewportCenter);
if (distance < closestDistance) {
closestDistance = distance;
closestSlideIndex = index;
}
/*
// Coalesce rapid next/prev commands and harden programmatic scroll suppression
queueNavigation(delta) {
if (!this.isActive || this.slides.length === 0) return;
if (this.navTimer == null) {
this.navBaseIndex = this.currentSlideIndex;
this.navDelta = 0;
}
this.navDelta += delta;
if (this.navTimer) clearTimeout(this.navTimer);
this.navTimer = setTimeout(() => {
let target = this.navBaseIndex + this.navDelta;
target = Math.max(0, Math.min(this.slides.length - 1, target));
this.navTimer = null;
this.navBaseIndex = null;
this.navDelta = 0;
if (target !== this.currentSlideIndex) {
this.currentSlideIndex = target;
this.clearPendingScrollTimers();
this.scrollToSlide(target);
this.updateSlideIndicators();
} else {
this.highlightCurrentSlide();
}
}, 80);
}
beginProgrammaticScroll(duration = 700) {
this.programmaticScroll = true;
if (this.programmaticScrollTimeoutId) clearTimeout(this.programmaticScrollTimeoutId);
this.programmaticScrollTimeoutId = setTimeout(() => {
this.programmaticScroll = false;
this.programmaticScrollTimeoutId = null;
}, duration);
}
clearPendingScrollTimers() {
if (Array.isArray(this._pendingScrollTimers)) {
this._pendingScrollTimers.forEach((id) => clearTimeout(id));
this._pendingScrollTimers = [];
}
}
trackTimer(id) {
if (!this._pendingScrollTimers) this._pendingScrollTimers = [];
if (id != null) this._pendingScrollTimers.push(id);
return id;
}
*/
}
});
if (closestSlideIndex !== this.currentSlideIndex) {
console.log('Notion Presentation Mode: Scroll detected, updating slide from', this.currentSlideIndex, 'to', closestSlideIndex);
this.currentSlideIndex = closestSlideIndex;
this.updateSlideIndicators();
this.highlightCurrentSlide();
}
}
/*
// Navigation coalescing and scroll suppression helpers
queueNavigation(delta) {
if (!this.isActive || this.slides.length === 0) return;
if (this.navTimer == null) {
this.navBaseIndex = this.currentSlideIndex;
this.navDelta = 0;
}
this.navDelta += delta;
if (this.navTimer) clearTimeout(this.navTimer);
this.navTimer = setTimeout(() => {
let target = this.navBaseIndex + this.navDelta;
target = Math.max(0, Math.min(this.slides.length - 1, target));
this.navTimer = null;
this.navBaseIndex = null;
this.navDelta = 0;
if (target !== this.currentSlideIndex) {
this.currentSlideIndex = target;
this.clearPendingScrollTimers();
this.scrollToSlide(target);
this.updateSlideIndicators();
} else {
this.highlightCurrentSlide();
}
}, 80);
}
beginProgrammaticScroll(duration = 700) {
this.programmaticScroll = true;
if (this.programmaticScrollTimeoutId) clearTimeout(this.programmaticScrollTimeoutId);
this.programmaticScrollTimeoutId = setTimeout(() => {
this.programmaticScroll = false;
this.programmaticScrollTimeoutId = null;
}, duration);
}
clearPendingScrollTimers() {
if (Array.isArray(this._pendingScrollTimers)) {
this._pendingScrollTimers.forEach((id) => clearTimeout(id));
this._pendingScrollTimers = [];
}
}
trackTimer(id) {
if (!this._pendingScrollTimers) this._pendingScrollTimers = [];
if (id != null) this._pendingScrollTimers.push(id);
return id;
}
*/
setupMutationObserver() {
const observer = new MutationObserver((mutations) => {
let shouldRefresh = false;
mutations.forEach((mutation) => {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
// Check if new content blocks were added
for (let node of mutation.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE &&
(node.hasAttribute('data-block-id') || node.querySelector('[data-block-id]'))) {
shouldRefresh = true;
break;
}
}
}
});
if (shouldRefresh) {
setTimeout(() => this.findSlides(), 500);
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
}
createSlideNumber() {
console.log('Notion Presentation Mode: Creating slide number element...');
this.slideNumberElement = document.createElement('div');
this.slideNumberElement.className = 'notion-slide-number';
this.slideNumberElement.textContent = '1 / 1';
document.body.appendChild(this.slideNumberElement);
console.log('Notion Presentation Mode: Slide number element created and added to body');
}
createNavigationControls() {
console.log('Notion Presentation Mode: Creating navigation controls...');
// Create container
this.navigationElement = document.createElement('div');
this.navigationElement.className = 'notion-navigation-controls';
// Previous button
const prevButton = document.createElement('button');
prevButton.className = 'notion-nav-button notion-nav-prev';
prevButton.innerHTML = '<';
prevButton.title = 'Previous slide (← or Backspace)';
prevButton.addEventListener('click', () => {
console.log('Notion Presentation Mode: Previous button clicked');
this.previousSlide();
});
// Next button
const nextButton = document.createElement('button');
nextButton.className = 'notion-nav-button notion-nav-next';
nextButton.innerHTML = '>';
nextButton.title = 'Next slide (→)';
nextButton.addEventListener('click', () => {
console.log('Notion Presentation Mode: Next button clicked');
this.nextSlide();
});
// Add buttons to container
this.navigationElement.appendChild(prevButton);
this.navigationElement.appendChild(nextButton);
// Add to page
document.body.appendChild(this.navigationElement);
console.log('Notion Presentation Mode: Navigation controls created and added to body');
}
createNotesControls() {
console.log('Notion Presentation Mode: Creating notes controls...');
// Create container for notes controls
this.notesControlsElement = document.createElement('div');
this.notesControlsElement.className = 'notion-notes-controls';
// Hide/Show Notes button
const hideNotesButton = document.createElement('button');
hideNotesButton.className = 'notion-notes-button notion-hide-notes-btn';
hideNotesButton.innerHTML = '👁️';
hideNotesButton.title = 'Toggle Notes visibility';
hideNotesButton.addEventListener('click', () => {
console.log('Notion Presentation Mode: Hide/Show Notes button clicked');
this.toggleNotesVisibility();
});
// Open Notes in new window button
const openNotesButton = document.createElement('button');
openNotesButton.className = 'notion-notes-button notion-open-notes-btn';
openNotesButton.innerHTML = '🗗';
openNotesButton.title = 'Open Notes in new window';
openNotesButton.addEventListener('click', () => {
console.log('Notion Presentation Mode: Open Notes button clicked');
this.openNotesInNewWindow();
});
// Add buttons to container
this.notesControlsElement.appendChild(hideNotesButton);
this.notesControlsElement.appendChild(openNotesButton);
// Add to page
document.body.appendChild(this.notesControlsElement);
console.log('Notion Presentation Mode: Notes controls created and added to body');
}
createProgressBar() {
console.log('Notion Presentation Mode: Creating progress bar element...');
this.progressBarElement = document.createElement('div');
this.progressBarElement.className = 'notion-progress-bar';
const fill = document.createElement('div');
fill.className = 'notion-progress-bar-fill';
this.progressBarElement.appendChild(fill);
document.body.appendChild(this.progressBarElement);
console.log('Notion Presentation Mode: Progress bar element created and added to body');
}
updateUIVisibility() {
if (this.slideNumberElement) {
this.slideNumberElement.classList.toggle('hidden', !this.settings.showSlideNumbers || !this.isActive);
}
if (this.progressBarElement) {
this.progressBarElement.classList.toggle('hidden', !this.settings.showProgressBar || !this.isActive);
}
if (this.navigationElement) {
this.navigationElement.classList.toggle('hidden', !this.settings.showNavigationButtons || !this.isActive);
}
if (this.notesControlsElement) {
this.notesControlsElement.classList.toggle('hidden', !this.settings.showNotesControls || !this.isActive);
}
}
applyPresentationToggles() {
// Toggle editability in presentation mode
// We implement by toggling a CSS class that disables pointer-events and caret
const root = document.body;
root.classList.toggle('notion-presentation-editable', !!this.settings.allowEditInPresentation);
// Toggle horizontal line visibility via class
root.classList.toggle('notion-presentation-show-hlines', !!this.settings.showHlinesInPresentation);
}
applyNotesSettings() {
// Apply notes visibility settings
const root = document.body;
root.classList.toggle('notion-hide-notes-content', !!this.settings.hideNotesContent);
// Update Notes blocks tracking and apply dynamic CSS
this.updateNotesTracking();
this.applyDynamicNotesCSS();
}
updateNotesTracking() {
// Clear previous tracking
this.notesBlockIds.clear();
// Find and track current Notes blocks (without modifying DOM)
const notesBlocks = this.findNotesBlocks();
console.log('Notion Presentation Mode: Tracking', notesBlocks.length, 'Notes blocks');
notesBlocks.forEach((block, index) => {
const blockId = block.getAttribute('data-block-id');
if (blockId) {
this.notesBlockIds.add(blockId);
console.log('Notion Presentation Mode: Tracking Notes block', index + 1, 'with ID:', blockId);
}
});
console.log('Notion Presentation Mode: Total tracked Notes blocks:', this.notesBlockIds.size);
}
applyDynamicNotesCSS() {
// Remove existing dynamic CSS
const existingStyle = document.getElementById('notion-notes-dynamic-css');
if (existingStyle) {
existingStyle.remove();
}
// Only apply CSS if we have Notes blocks to hide
if (this.notesBlockIds.size === 0 || !this.settings.hideNotesContent) {
return;
}
// Create dynamic CSS targeting specific block IDs
const cssRules = [];
this.notesBlockIds.forEach(blockId => {
// Target the content container within each Notes block
cssRules.push(`
.notion-hide-notes-content [data-block-id="${blockId}"] [id^=":r"][style*="display: flex"] {
display: none !important;
}
.notion-hide-notes-content [data-block-id="${blockId}"] > div > div:last-child {
display: none !important;
}
.notion-hide-notes-content [data-block-id="${blockId}"] > div > div > div:last-child {
display: none !important;
}
`);
});
// Inject the dynamic CSS
const styleElement = document.createElement('style');
styleElement.id = 'notion-notes-dynamic-css';
styleElement.textContent = cssRules.join('\n');
document.head.appendChild(styleElement);
console.log('Notion Presentation Mode: Applied dynamic CSS for', this.notesBlockIds.size, 'Notes blocks');
}
findNotesBlocks() {
// Find all Notes toggle blocks - only those with "Notes:" in the header
const notesBlocks = [];
// Look for toggle blocks that specifically contain "Notes:" text
const toggleBlocks = document.querySelectorAll('.notion-toggle-block');
toggleBlocks.forEach(block => {
// Look for the title element - should be the first editable element in the toggle
const titleElement = block.querySelector('[data-content-editable-leaf="true"]');
if (titleElement) {
const text = titleElement.textContent.trim().toLowerCase();
// Match blocks that contain "notes:" or are exactly "notes"
// This excludes things like "Example:", "Details:", etc.
if (text.includes('notes:') || text === 'notes') {
notesBlocks.push(block);
console.log('Notion Presentation Mode: Found Notes block with title:', titleElement.textContent.trim());
}
}
});
console.log('Notion Presentation Mode: Found Notes blocks:', notesBlocks.length);
return notesBlocks;
}
toggleNotesVisibility() {
this.settings.hideNotesContent = !this.settings.hideNotesContent;
this.applyNotesSettings();
// Update button appearance
const hideButton = document.querySelector('.notion-hide-notes-btn');
if (hideButton) {
hideButton.innerHTML = this.settings.hideNotesContent ? '🙈' : '👁️';
hideButton.title = this.settings.hideNotesContent ? 'Show Notes content' : 'Hide Notes content';
}
// If we're showing notes, ensure they're expanded so they're visible
if (!this.settings.hideNotesContent) {
this.ensureNotesExpanded();
}
console.log('Notion Presentation Mode: Notes visibility toggled:', !this.settings.hideNotesContent);
}
ensureNotesExpanded() {
const notesBlocks = this.findNotesBlocks();
notesBlocks.forEach((block, index) => {
const expandButton = block.querySelector('[role="button"][aria-expanded]');
const isExpanded = expandButton ? expandButton.getAttribute('aria-expanded') === 'true' : true;
// If collapsed, expand it so the content becomes visible
if (!isExpanded && expandButton) {
console.log('Notion Presentation Mode: Auto-expanding Notes block for visibility', index + 1);
expandButton.click();
}
});
}
openNotesInNewWindow() {
const notesBlocks = this.findNotesBlocks();
if (notesBlocks.length === 0) {
console.log('Notion Presentation Mode: No Notes blocks found');
return;
}
// Store original states and expand collapsed blocks
const originalStates = [];
notesBlocks.forEach((block, index) => {
const expandButton = block.querySelector('[role="button"][aria-expanded]');
const isExpanded = expandButton ? expandButton.getAttribute('aria-expanded') === 'true' : true;
originalStates[index] = isExpanded;
// If collapsed, expand it
if (!isExpanded && expandButton) {
console.log('Notion Presentation Mode: Expanding collapsed Notes block', index + 1);
expandButton.click();
}
});
// Wait a moment for the expansion animation to complete
setTimeout(() => {
// Collect all notes content
let notesContent = '';
notesBlocks.forEach((block) => {
const titleElement = block.querySelector('[data-content-editable-leaf="true"]');
const contentContainer = block.querySelector('[id^=":r"][style*="display: flex"]') ||
block.querySelector('[style*="display: flex"] > div:last-child');
if (titleElement) {
const titleText = titleElement.textContent.trim();
notesContent += `<h3>${titleText}</h3>\n`;
}
if (contentContainer) {
notesContent += this.extractNotesContent(contentContainer);
}
notesContent += '<hr>\n';
});
// Restore original states
this.restoreNotesStates(notesBlocks, originalStates);
// Open the new window with content
this.createNotesWindow(notesContent);
}, 300); // Wait for expansion animation
}
restoreNotesStates(notesBlocks, originalStates) {
notesBlocks.forEach((block, index) => {
const expandButton = block.querySelector('[role="button"][aria-expanded]');
const currentlyExpanded = expandButton ? expandButton.getAttribute('aria-expanded') === 'true' : true;
const shouldBeExpanded = originalStates[index];
// If the state needs to be restored (was collapsed but we expanded it)
if (!shouldBeExpanded && currentlyExpanded && expandButton) {
console.log('Notion Presentation Mode: Restoring collapsed state for Notes block', index + 1);
setTimeout(() => {
expandButton.click();
}, 100); // Small delay to ensure the content extraction is complete
}
});
}
extractNotesContent(contentContainer) {
let content = '';
// Find all content blocks within the container
const contentBlocks = contentContainer.querySelectorAll('[data-block-id]');
contentBlocks.forEach(contentBlock => {
const blockClasses = contentBlock.className;
const textElement = contentBlock.querySelector('[data-content-editable-leaf="true"]');
if (!textElement) return;
const text = textElement.textContent.trim();
if (!text) return;
// Handle different types of blocks
if (blockClasses.includes('notion-text-block')) {
// Regular text paragraph
content += `<p>${this.escapeHtml(text)}</p>\n`;
} else if (blockClasses.includes('notion-bulleted_list-block')) {
// Bulleted list item
content += `<li>${this.escapeHtml(text)}</li>\n`;
} else if (blockClasses.includes('notion-numbered_list-block')) {
// Numbered list item
content += `<li>${this.escapeHtml(text)}</li>\n`;
} else if (blockClasses.includes('notion-to_do-block')) {
// To-do item
const isChecked = contentBlock.querySelector('[data-content-editable-void="true"] [role="button"]')?.getAttribute('aria-checked') === 'true';
const checkbox = isChecked ? '☑️' : '☐';
content += `<p>${checkbox} ${this.escapeHtml(text)}</p>\n`;
} else if (blockClasses.includes('notion-header-block')) {
// Header block
content += `<h4>${this.escapeHtml(text)}</h4>\n`;
} else if (blockClasses.includes('notion-quote-block')) {
// Quote block
content += `<blockquote>${this.escapeHtml(text)}</blockquote>\n`;
} else {
// Fallback for any other block type
content += `<p>${this.escapeHtml(text)}</p>\n`;
}
});
// Wrap consecutive list items in proper list tags
content = this.wrapListItems(content);
return content;
}
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
wrapListItems(content) {
// Wrap consecutive <li> items in <ul> tags
let wrappedContent = content;
// Replace sequences of <li> items with proper <ul> wrapping
wrappedContent = wrappedContent.replace(/(<li>.*?<\/li>\n)+/g, (match) => {
return `<ul>\n${match}</ul>\n`;
});
return wrappedContent;
}
createNotesWindow(notesContent) {
// Create new window with notes content
const newWindow = window.open('', '_blank', 'width=600,height=800,scrollbars=yes,resizable=yes');
if (newWindow) {
const htmlContent = `
<!DOCTYPE html>
<html>
<head>
<title>Notion Notes</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
line-height: 1.6;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #fff;
}
h1 {
color: #2d3748;
border-bottom: 3px solid #4299e1;
padding-bottom: 15px;
margin-bottom: 30px;
}
h3 {
color: #2d3748;
border-bottom: 2px solid #e2e8f0;
padding-bottom: 10px;
margin-top: 30px;
margin-bottom: 15px;
}
p {
margin: 10px 0;
color: #4a5568;
line-height: 1.7;
}
ul, ol {
margin: 15px 0;
padding-left: 25px;
color: #4a5568;
}
li {
margin: 8px 0;
line-height: 1.6;
}
h4 {
color: #2d3748;
margin: 20px 0 10px 0;
font-size: 1.1em;
}
blockquote {
border-left: 4px solid #e2e8f0;
margin: 15px 0;
padding: 10px 0 10px 15px;
color: #718096;
font-style: italic;
background: #f7fafc;
}
hr {
border: none;
border-top: 1px solid #e2e8f0;
margin: 20px 0;
}
.timestamp {
color: #718096;
font-size: 12px;
text-align: right;
margin-top: 20px;
border-top: 1px solid #f7fafc;
padding-top: 10px;
}
</style>
</head>
<body>
<h1>📝 Notion Notes</h1>
${notesContent}
<div class="timestamp">
Extracted on ${new Date().toLocaleString()}
</div>
</body>
</html>
`;
newWindow.document.open();
newWindow.document.write(htmlContent);
newWindow.document.close();
console.log('Notion Presentation Mode: Notes opened in new window');
} else {
console.log('Notion Presentation Mode: Failed to open new window (popup blocked?)');
}
}
enablePresentationMode() {
console.log('Notion Presentation Mode: Enabling presentation mode...');
this.isActive = true;
document.body.classList.add('notion-presentation-mode');