Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
950 lines (795 loc) · 32.1 KB
/
Copy pathscript.js
File metadata and controls
950 lines (795 loc) · 32.1 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
/**
* Teleprompter Logic
* Handles Editor, Prompter Scrolling, and Dual-Window Sync
*/
// State
const state = {
content: "",
isPlaying: false,
speed: 0, // -100 to 100
fontSize: 60, // px
margin: 10, // %
isMirroredX: false,
isMirroredY: false,
mirrorExternalOnly: false,
scrollPosition: 0, // matches scrollTop
mode: 'editor',
mouseMode: false,
currentScriptId: null // For saved scripts
};
// DOM Elements
const els = {
editorContainer: document.getElementById('editor-container'),
prompterContainer: document.getElementById('prompter-container'),
prompterDisplay: document.getElementById('prompter-display'),
textEditor: document.getElementById('text-editor'),
scrollingContent: document.getElementById('scrolling-content'),
colorPalette: document.getElementById('color-palette'),
launchBtn: document.getElementById('launch-btn'),
closePrompterBtn: document.getElementById('close-prompter-btn'),
toolbar: document.getElementById('toolbar'),
helpBtn: document.getElementById('help-btn'),
closeHelpBtn: document.getElementById('close-help-btn'),
helpModal: document.getElementById('help-modal'),
// Controls
playPauseBtn: document.getElementById('play-pause-btn'),
speedSlider: document.getElementById('speed-slider'),
speedValue: document.getElementById('speed-value'),
sizeSlider: document.getElementById('size-slider'),
marginSlider: document.getElementById('margin-slider'),
mirrorX: document.getElementById('mirror-x'),
mirrorY: document.getElementById('mirror-y'),
mouseModeBtn: document.getElementById('mouse-mode-btn'),
openWindowBtn: document.getElementById('open-window-btn'),
// File Management
scriptTitle: document.getElementById('script-title'),
saveBtn: document.getElementById('save-btn'),
newScriptBtn: document.getElementById('new-script-btn'),
scriptList: document.getElementById('script-list'),
exportBtn: document.getElementById('export-btn'),
importBtn: document.getElementById('import-btn'),
importInput: document.getElementById('import-input'),
deleteAllBtn: document.getElementById('delete-all-btn'),
markerArrow: document.getElementById('marker-arrow'),
shareBtn: document.getElementById('share-prompter-btn'),
shareModal: document.getElementById('share-modal'),
closeShareBtn: document.getElementById('close-share-btn'),
shareUrlInput: document.getElementById('share-url-input'),
copyUrlBtn: document.getElementById('copy-url-btn'),
qrcodeContainer: document.getElementById('qrcode-container'),
mirrorExternalOnly: document.getElementById('mirror-external-only'),
mobileFullscreenBtn: document.getElementById('mobile-fullscreen-btn')
};
// PeerJS State
let peer = null;
let connections = []; // For Master: list of connected slaves
let masterConn = null; // For Slave: connection to master
let myPeerId = null;
// Broadcast Channel for Sync
const channel = new BroadcastChannel('teleprompter_sync');
// Constants
const PALETTE_COLORS = [
'#ffffff', '#ffff00', '#00ff00', '#00ffff', '#0000ff',
'#ff00ff', '#ff0000', '#ffa500', '#808080', '#c0c0c0',
'#800000', '#808000', '#008000', '#008080', '#000080'
];
// --- Initialization ---
function init() {
// Generate Palette
generatePalette();
const urlParams = new URLSearchParams(window.location.search);
const room = urlParams.get('room');
if (urlParams.get('mode') === 'display') {
state.mode = 'prompter-slave';
startPrompter(true);
// Initialize PeerJS for Slave
if (room) {
initPeerSlave(room);
}
// Also keep BroadcastChannel for local sync as fallback/internal
broadcast({ type: 'request-sync' });
} else {
state.mode = 'editor';
loadScriptList(); // Load saved scripts sidebar
// Initialize PeerJS for Master (generate ID)
initPeerMaster();
}
setupEventListeners();
requestAnimationFrame(gameLoop);
}
// --- PeerJS Functions ---
function initPeerMaster() {
// Generate a short ID or use random UUID
// We'll let PeerJS generate one, or we can use a custom logic.
// Letting PeerJS generate is safer for uniqueness, but long.
// Let's try to request a short random ID if possible, or just use default.
peer = new Peer();
peer.on('open', (id) => {
myPeerId = id;
console.log('My Peer ID is: ' + id);
});
peer.on('connection', (conn) => {
console.log('New connection from ' + conn.peer);
connections.push(conn);
// Send immediate sync upon connection
conn.on('open', () => {
syncState();
});
conn.on('close', () => {
connections = connections.filter(c => c !== conn);
});
});
peer.on('error', (err) => {
console.error('PeerJS Error:', err);
});
}
function initPeerSlave(hostId) {
peer = new Peer(); // We need a peer obj to connect
peer.on('open', (id) => {
console.log('Slave Peer ID: ' + id);
// Connect to Master
masterConn = peer.connect(hostId);
masterConn.on('open', () => {
console.log('Connected to Master: ' + hostId);
// Request sync? Master sends it on connect anyway
});
masterConn.on('data', (data) => {
// Handle incoming data same as BroadcastChannel
if (data.type === 'sync') {
applySyncState(data.state);
} else if (data.type === 'close') {
state.isPlaying = false;
window.close();
}
});
masterConn.on('close', () => {
alert('Connexion avec le maître perdue.');
});
});
peer.on('error', (err) => {
console.error('PeerJS Error:', err);
alert('Erreur de connexion PeerJS: ' + err.type);
});
}
// --- Storage & File Management ---
function getScripts() {
return JSON.parse(localStorage.getItem('teleprompter_scripts') || '[]');
}
function saveScript(id, title, content) {
const scripts = getScripts();
const timestamp = Date.now();
if (id) {
// Update existing
const index = scripts.findIndex(s => s.id === id);
if (index !== -1) {
scripts[index] = { ...scripts[index], title, content, timestamp };
} else {
// Should not happen, but treat as new
scripts.push({ id, title, content, timestamp });
}
} else {
// Create new
id = 'script_' + timestamp;
scripts.push({ id, title, content, timestamp });
}
localStorage.setItem('teleprompter_scripts', JSON.stringify(scripts));
return id;
}
function deleteScript(id) {
const scripts = getScripts().filter(s => s.id !== id);
localStorage.setItem('teleprompter_scripts', JSON.stringify(scripts));
}
function deleteAllScripts() {
localStorage.removeItem('teleprompter_scripts');
}
function loadScriptList() {
const scripts = getScripts(); // No sort, use array order (Oldest first naturally if we push)
els.scriptList.innerHTML = '';
if (scripts.length === 0) {
els.scriptList.innerHTML = '<div class="empty-state">Aucun script sauvegardé</div>';
return;
}
scripts.forEach((script, index) => {
const div = document.createElement('div');
div.className = `script-item ${state.currentScriptId === script.id ? 'active' : ''}`;
div.draggable = true; // Enable drag
div.dataset.index = index;
// click on row loads script
div.addEventListener('click', () => confirmLoadScript(script));
// Drag Events
div.addEventListener('dragstart', handleDragStart);
div.addEventListener('dragover', handleDragOver);
div.addEventListener('drop', handleDrop);
div.addEventListener('dragenter', handleDragEnter);
div.addEventListener('dragleave', handleDragLeave);
const nameSpan = document.createElement('span');
nameSpan.className = 'script-name';
nameSpan.textContent = script.title || 'Sans titre';
div.appendChild(nameSpan);
const delBtn = document.createElement('button');
delBtn.className = 'delete-script-btn';
delBtn.innerHTML = '🗑️';
delBtn.title = "Supprimer";
delBtn.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent loading
if (confirm(`Supprimer "${script.title}" ?`)) {
deleteScript(script.id);
loadScriptList();
if (state.currentScriptId === script.id) {
resetEditor();
}
}
});
div.appendChild(delBtn);
els.scriptList.appendChild(div);
});
}
// --- Drag & Drop Reordering ---
let dragSrcEl = null;
function handleDragStart(e) {
dragSrcEl = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.innerHTML);
this.classList.add('dragging');
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault();
}
e.dataTransfer.dropEffect = 'move';
return false;
}
function handleDragEnter(e) {
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over');
}
function handleDrop(e) {
if (e.stopPropagation) {
e.stopPropagation();
}
if (dragSrcEl !== this) {
const srcIndex = parseInt(dragSrcEl.dataset.index);
const targetIndex = parseInt(this.dataset.index);
const scripts = getScripts();
// Move item
const [movedItem] = scripts.splice(srcIndex, 1);
scripts.splice(targetIndex, 0, movedItem);
localStorage.setItem('teleprompter_scripts', JSON.stringify(scripts));
loadScriptList();
}
return false;
}
function confirmLoadScript(script) {
// If unsaved changes? For simplicity, we just load.
state.currentScriptId = script.id;
els.scriptTitle.value = script.title;
els.textEditor.innerHTML = script.content;
loadScriptList(); // Refresh active state
}
function resetEditor() {
state.currentScriptId = null;
els.scriptTitle.value = "Nouveau Script";
els.textEditor.innerHTML = "";
loadScriptList();
}
function generatePalette() {
els.colorPalette.innerHTML = '';
PALETTE_COLORS.forEach(color => {
const swatch = document.createElement('div');
swatch.className = 'color-swatch';
swatch.style.backgroundColor = color;
// Use mousedown and preventDefault to avoid losing focus from the editor
swatch.addEventListener('mousedown', (e) => {
e.preventDefault();
document.execCommand('foreColor', false, color);
});
els.colorPalette.appendChild(swatch);
});
}
// --- Event Listeners ---
function setupEventListeners() {
// Paste Cleanup (Strip formatting, keep newlines)
[els.textEditor, els.scrollingContent].forEach(el => {
el.addEventListener('paste', (e) => {
e.preventDefault();
let text = e.clipboardData.getData('text/plain') || "";
// Escape HTML characters to prevent injection
text = text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
// Convert newlines to <br> for contenteditable
const formatted = text.replace(/\r\n|\r|\n/g, '<br>');
document.execCommand('insertHTML', false, formatted);
});
});
// File Management Listeners
els.saveBtn.addEventListener('click', () => {
const title = els.scriptTitle.value || "Sans titre";
const content = els.textEditor.innerHTML;
state.currentScriptId = saveScript(state.currentScriptId, title, content);
loadScriptList();
alert("Script sauvegardé !");
});
els.newScriptBtn.addEventListener('click', () => {
resetEditor();
});
els.exportBtn.addEventListener('click', () => {
const scripts = getScripts();
const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(scripts));
const downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", "teleprompter_backup.json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
});
els.importBtn.addEventListener('click', () => els.importInput.click());
els.importInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
try {
const scripts = JSON.parse(e.target.result);
if (Array.isArray(scripts)) {
localStorage.setItem('teleprompter_scripts', JSON.stringify(scripts));
loadScriptList();
alert("Scripts importés avec succès !");
}
} catch (err) {
alert("Erreur lors de l'import : Fichier invalide.");
}
};
reader.readAsText(file);
e.target.value = ''; // Reset
});
els.deleteAllBtn.addEventListener('click', () => {
if (confirm("ATTENTION : Voulez-vous vraiment supprimer TOUS les scripts sauvegardés ? Cette action est irréversible.")) {
deleteAllScripts();
resetEditor();
// loadScriptList(); // resetEditor calls loadScriptList
}
});
// Launch
els.launchBtn.addEventListener('click', () => {
state.content = els.textEditor.innerHTML;
state.mode = 'prompter-master';
startPrompter();
// Wait for layout to ensure dimensions are non-zero
requestAnimationFrame(() => {
syncState();
});
});
// Close
els.closePrompterBtn.addEventListener('click', () => {
state.isPlaying = false; // Stop playing locally
syncState(); // Tell slave to stop playing
// Sync Back content to Editor
els.textEditor.innerHTML = state.content;
setTimeout(() => {
stopPrompter();
state.mode = 'editor';
els.editorContainer.classList.add('active');
els.prompterContainer.classList.remove('active'); // ensure active class removed
// broadcast({ type: 'close' }); // REMOVED: Keep external window open
}, 100);
});
// Toolbar Controls
els.playPauseBtn.addEventListener('click', togglePlay);
// Help Modal
els.helpBtn.addEventListener('click', () => {
els.helpModal.classList.remove('hidden');
});
els.closeHelpBtn.addEventListener('click', () => {
els.helpModal.classList.add('hidden');
});
els.speedSlider.addEventListener('input', (e) => {
state.speed = parseInt(e.target.value, 10);
els.speedValue.textContent = state.speed;
syncState();
});
els.sizeSlider.addEventListener('input', (e) => {
state.fontSize = parseInt(e.target.value, 10);
updateStyles();
syncState();
});
els.marginSlider.addEventListener('input', (e) => {
state.margin = parseInt(e.target.value, 10);
updateStyles();
syncState();
});
els.mirrorX.addEventListener('change', (e) => {
state.isMirroredX = e.target.checked;
updateStyles();
syncState();
});
els.mirrorY.addEventListener('change', (e) => {
state.isMirroredY = e.target.checked;
updateStyles();
syncState();
});
els.mirrorExternalOnly.addEventListener('change', (e) => {
state.mirrorExternalOnly = e.target.checked;
updateStyles();
syncState();
});
els.mouseModeBtn.addEventListener('click', () => {
state.mouseMode = !state.mouseMode;
els.mouseModeBtn.classList.toggle('active', state.mouseMode);
// Sync immediately regardless of state
syncState();
if (!state.mouseMode) {
state.isPlaying = false; // Stop scrolling when disabling mouse mode
els.playPauseBtn.textContent = "Lecture";
syncState();
}
});
els.openWindowBtn.addEventListener('click', () => {
window.open(window.location.href + '?mode=display', 'TeleprompterDisplay', 'width=800,height=600,menubar=no,toolbar=no');
});
els.scrollingContent.addEventListener('input', () => {
state.content = els.scrollingContent.innerHTML;
syncState();
});
// Keyboard Shortcuts
window.addEventListener('keydown', (e) => {
if (state.mode === 'editor') return;
switch (e.key) {
case ' ':
e.preventDefault();
togglePlay();
break;
case 'Tab':
e.preventDefault();
state.mouseMode = !state.mouseMode;
els.mouseModeBtn.classList.toggle('active', state.mouseMode);
if (!state.mouseMode) {
state.isPlaying = false;
els.playPauseBtn.textContent = "Lecture";
syncState();
}
break;
case 'ArrowUp':
e.preventDefault();
state.scrollPosition = Math.max(0, els.prompterDisplay.scrollTop - 50);
els.prompterDisplay.scrollTop = state.scrollPosition;
syncState();
break;
case 'ArrowDown':
e.preventDefault();
state.scrollPosition = els.prompterDisplay.scrollTop + 50;
els.prompterDisplay.scrollTop = state.scrollPosition;
syncState();
break;
case 'ArrowRight':
e.preventDefault();
state.speed = Math.min(100, state.speed + 1);
updateUIControls();
syncState();
break;
case 'ArrowLeft':
e.preventDefault();
state.speed = Math.max(-100, state.speed - 1);
updateUIControls();
syncState();
break;
}
});
// Manual Scroll Sync (when not playing)
els.prompterDisplay.addEventListener('scroll', () => {
if (state.mode === 'prompter-master' && !state.isPlaying) {
state.scrollPosition = els.prompterDisplay.scrollTop;
syncState();
}
});
window.addEventListener('mousemove', (e) => {
if (!state.mouseMode || state.mode !== 'prompter-master') return;
const h = window.innerHeight;
const y = e.clientY;
const center = h / 2;
const dist = y - center;
if (Math.abs(dist) < 50) {
if (state.isPlaying) {
state.isPlaying = false;
els.playPauseBtn.textContent = "Lecture";
state.bgSpeed = 0; // Internal tracker
syncState();
}
} else {
if (!state.isPlaying) {
state.isPlaying = true;
els.playPauseBtn.textContent = "Pause";
}
const maxDist = h / 2;
const factor = (dist - (Math.sign(dist) * 50)) / (maxDist - 50);
// Mouse down = positive speed (scroll down)
// Mouse up = negative speed (scroll up)
// Y-Mirror reversal: if Y mirrored, reverse the direction
if (state.isMirroredY && !state.mirrorExternalOnly) {
state.speed = -Math.round(factor * 100);
} else {
state.speed = Math.round(factor * 100);
}
// Update UI
els.speedValue.textContent = state.speed;
}
});
channel.onmessage = (ev) => {
const msg = ev.data;
if (msg.type === 'sync') {
applySyncState(msg.state);
} else if (msg.type === 'request-sync') {
// Master replies to new slave
if (state.mode === 'prompter-master') {
syncState();
}
} else if (msg.type === 'close') {
// Stop playing first
state.isPlaying = false;
if (state.mode === 'prompter-slave') {
window.close();
}
}
};
// Resize Listener for Slave Scaling
window.addEventListener('resize', () => {
if (state.mode === 'prompter-slave' && state.lastMasterDimensions) {
applyLayoutScaling(state.lastMasterDimensions);
updateLayoutGeometry(); // Re-apply geometry if needed (though master height hasn't changed, good to ensure)
} else if (state.mode === 'prompter-master') {
updateLayoutGeometry(); // Master resized, update its own layout
syncState(); // Send new dimensions
}
});
// Initial Layout update
updateLayoutGeometry();
// Share Button Logic
els.shareBtn.addEventListener('click', () => {
if (!myPeerId) {
alert("Erreur: ID PeerJS non généré. Vérifiez votre connexion internet.");
return;
}
const baseUrl = window.location.href.split('?')[0];
const shareUrl = `${baseUrl}?mode=display&room=${myPeerId}`;
els.shareUrlInput.value = shareUrl;
// Generate QR Code using a public API (GoQR.me)
els.qrcodeContainer.innerHTML = `<img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(shareUrl)}" alt="QR Code" style="border: 2px solid white; border-radius: 4px;">`;
els.shareModal.classList.remove('hidden');
});
els.closeShareBtn.addEventListener('click', () => {
els.shareModal.classList.add('hidden');
});
els.copyUrlBtn.addEventListener('click', () => {
els.shareUrlInput.select();
document.execCommand('copy');
// Show feedback instead of alert
const feedback = document.getElementById('copy-feedback');
if (feedback) {
feedback.style.display = 'block';
setTimeout(() => {
feedback.style.display = 'none';
}, 2000);
}
});
// Mobile Fullscreen Logic
if (state.mode === 'prompter-slave') {
// Simple check: if touch device or small screen?
// Or just always show for slave since it might be a phone
els.mobileFullscreenBtn.style.display = 'flex';
els.mobileFullscreenBtn.addEventListener('click', () => {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen().catch(err => {
console.log(`Error attempting to enable fullscreen: ${err.message}`);
});
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
}
}
});
}
}
// --- Core Functions ---
function startPrompter(isSlave = false) {
els.editorContainer.classList.remove('active');
els.prompterContainer.classList.add('active');
if (isSlave) {
els.toolbar.classList.add('hidden');
els.toolbar.style.display = 'none';
document.title = "RadioTools – Teleprompt By MrMazure";
} else {
els.toolbar.classList.remove('hidden');
els.scrollingContent.innerHTML = state.content;
}
// Reset Scroll Position
state.scrollPosition = 0;
els.prompterDisplay.scrollTop = 0;
// Check if we have Help modal open from previous session? No, default hidden.
updateLayoutGeometry();
updateStyles();
}
function stopPrompter() {
state.isPlaying = false;
state.scrollPosition = 0;
els.prompterContainer.classList.remove('active');
}
function broadcast(msg) {
channel.postMessage(msg);
}
function togglePlay() {
state.isPlaying = !state.isPlaying;
els.playPauseBtn.textContent = state.isPlaying ? "Pause" : "Lecture";
state.scrollPosition = els.prompterDisplay.scrollTop;
syncState();
}
function updateUIControls() {
els.speedSlider.value = state.speed;
els.speedValue.textContent = state.speed;
els.sizeSlider.value = state.fontSize;
els.marginSlider.value = state.margin;
els.mirrorX.checked = state.isMirroredX;
els.mirrorY.checked = state.isMirroredY;
els.mirrorExternalOnly.checked = state.mirrorExternalOnly;
}
function updateStyles() {
els.scrollingContent.style.fontSize = `${state.fontSize}px`;
els.scrollingContent.style.paddingLeft = `${state.margin}%`;
els.scrollingContent.style.paddingRight = `${state.margin}%`;
let transform = "";
// If Mirror External Only is TRUE:
// - Master: No Mirror
// - Slave: Apply Mirror
// If Mirror External Only is FALSE:
// - Master: Apply Mirror
// - Slave: Apply Mirror
const isSlave = (state.mode === 'prompter-slave');
const shouldMirror = isSlave || !state.mirrorExternalOnly;
if (shouldMirror && state.isMirroredX) transform += "scaleX(-1) ";
if (shouldMirror && state.isMirroredY) transform += "scaleY(-1) ";
// Trigger Layout Update when Mirroring changes (to fix arrow alignment)
requestAnimationFrame(() => updateLayoutGeometry());
els.prompterDisplay.style.transform = transform;
}
function gameLoop() {
if (state.isPlaying && state.mode === 'prompter-master') { // Only master simulates physics
let moveAmount = state.speed * 0.35; // Speed directly controls direction now
state.scrollPosition += moveAmount;
// Allow scrolling up to 0, but not infinitely up?
// Actually, let's keep it simple: just don't scroll past top 0
if (state.scrollPosition < 0) state.scrollPosition = 0;
// Clamp to maximum scroll height to prevent slaves from scrolling past content
// if they have a larger scrollable area due to layout differences.
const maxScroll = els.prompterDisplay.scrollHeight - els.prompterDisplay.clientHeight;
if (state.scrollPosition > maxScroll) state.scrollPosition = maxScroll;
els.prompterDisplay.scrollTop = state.scrollPosition;
syncState(); // Broadcast state every frame
} else {
if (state.mode === 'prompter-master') {
state.scrollPosition = els.prompterDisplay.scrollTop;
}
}
requestAnimationFrame(gameLoop);
}
function syncState() {
if (state.mode !== 'prompter-master') return;
const msg = {
type: 'sync',
state: {
content: state.content,
isPlaying: state.isPlaying,
speed: state.speed,
fontSize: state.fontSize,
margin: state.margin,
isMirroredX: state.isMirroredX,
isMirroredY: state.isMirroredY,
mirrorExternalOnly: state.mirrorExternalOnly,
scrollPosition: state.scrollPosition,
// direction removed, speed is signed
mouseMode: state.mouseMode, // Sync mouse mode
// Sync Dimensions for exact layout mirroring
dimensions: (els.prompterContainer.clientWidth > 0) ? {
width: els.prompterContainer.clientWidth,
height: els.prompterContainer.clientHeight
} : null
}
};
// 1. Local Sync via BroadcastChannel
channel.postMessage(msg);
// 2. Remote Sync via PeerJS
if (connections.length > 0) {
connections.forEach(conn => {
if (conn.open) {
conn.send(msg);
}
});
}
}
function applyLayoutScaling(dimensions) {
if (!dimensions || !dimensions.width) return; // Prevention
state.lastMasterDimensions = dimensions; // Store for resize events
const masterWidth = dimensions.width;
const masterHeight = dimensions.height;
const slaveWindowWidth = window.innerWidth;
const slaveWindowHeight = window.innerHeight;
// Prevent divide by zero or infinite scale
if (masterWidth <= 0) return;
const scale = slaveWindowWidth / masterWidth;
// Apply transform to container
els.prompterContainer.style.width = `${masterWidth}px`;
els.prompterContainer.style.height = `${slaveWindowHeight / scale}px`; // Adjust height to fill logical space
els.prompterContainer.style.transform = `scale(${scale})`;
els.prompterContainer.style.transformOrigin = 'top left';
// Ensure body doesn't scroll due to scaling
document.body.style.overflow = 'hidden';
// Update geometry based on new master dimensions
updateLayoutGeometry();
}
function updateLayoutGeometry() {
// Determine the "Logical Height" to use for layout (Margins, Arrow Position)
// Master: Window Height
// Slave: Master Height (synced)
let logicalHeight = window.innerHeight;
if (state.mode === 'prompter-slave') {
if (state.lastMasterDimensions && state.lastMasterDimensions.height) {
logicalHeight = state.lastMasterDimensions.height;
} else {
// Fallback before sync?
return;
}
}
// 1. Arrow Position (30% of Height)
if (els.markerArrow) {
els.markerArrow.style.top = (logicalHeight * 0.3) + "px";
}
// 2. Content Margins (Match Arrow 30% top, 50% bottom)
// We override the CSS 30vh/50vh to ensure pixel-perfect match with arrow and font size
if (els.scrollingContent) {
const isSlave = (state.mode === 'prompter-slave');
const shouldMirror = isSlave || !state.mirrorExternalOnly;
if (state.isMirroredY && shouldMirror) {
// Inverted Logic for Y-Mirror: "Top" becomes "Bottom" visually
// We need to account for the container height which might be scaled (on slave)
// Arrow is at logicalHeight * 0.3
// Visual Position = ContainerHeight - PhysicalMarginTop
// We want Visual Position == Arrow Position
// So PhysicalMarginTop = ContainerHeight - Arrow Position
const containerHeight = els.prompterContainer.clientHeight || logicalHeight;
const arrowPos = logicalHeight * 0.3;
els.scrollingContent.style.marginTop = (containerHeight - arrowPos) + "px";
els.scrollingContent.style.marginBottom = arrowPos + "px";
} else {
// Normal Mode
els.scrollingContent.style.marginTop = (logicalHeight * 0.3) + "px";
els.scrollingContent.style.marginBottom = (logicalHeight * 0.75) + "px"; // Increased to 75% to allow scrolling past end
}
}
}
function applySyncState(newState) {
// 1. Apply State
state.content = newState.content;
state.isPlaying = newState.isPlaying;
state.speed = newState.speed;
state.fontSize = newState.fontSize;
state.margin = newState.margin;
state.isMirroredX = newState.isMirroredX;
state.isMirroredY = newState.isMirroredY;
state.mirrorExternalOnly = newState.mirrorExternalOnly;
// direction removed
state.mouseMode = newState.mouseMode;
// 2. Handle Slave Layout Scaling (Force 1:1 Match with Master)
if (newState.dimensions) {
applyLayoutScaling(newState.dimensions);
}
// 3. Apply Scroll Position (After layout scaling)
state.scrollPosition = newState.scrollPosition;
// Update Content if changed
if (els.scrollingContent.innerHTML !== state.content) {
els.scrollingContent.innerHTML = state.content;
}
// Force styles update
updateStyles();
// Update Layout for Scroll (Wait for render? usually ok since we set width)
els.prompterDisplay.scrollTop = state.scrollPosition;
updateUIControls();
}
init();