forked from inattendu/dashreader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrsvp-engine.ts
More file actions
1160 lines (941 loc) · 36.7 KB
/
Copy pathrsvp-engine.ts
File metadata and controls
1160 lines (941 loc) · 36.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
import { DashReaderSettings, WordChunk, HeadingInfo, HeadingContext } from './types';
import { TimeoutManager } from './services/timeout-manager';
import { MicropauseService } from './services/micropause-service';
type HistoryEntry = { index: number; tMs: number };
export class RSVPEngine {
private words: string[] = [];
private currentIndex: number = 0;
private isPlaying: boolean = false;
private timer: number | null = null;
private settings: DashReaderSettings;
private timeoutManager: TimeoutManager;
private micropauseService: MicropauseService;
private onWordChange: (chunk: WordChunk) => void;
private startTime: number = 0;
private startWpm: number = 0;
private pausedTime: number = 0;
private lastPauseTime: number = 0;
private headings: HeadingInfo[] = [];
private wordsReadInSession: number = 0;
// virtual-time history for time-based rewind/forward
private history: HistoryEntry[] = [];
private historyCursor: number = -1;
private playbackMs: number = 0;
private virtualTimeAtIndexMs: number[] = [];
private virtualTotalMs: number = 0;
private tickGen = 0;
private nextDueMs: number | null = null;
private static readonly MAX_HISTORY_MS = 10 * 60_000; // keep ~10 minutes
private static readonly MAX_HISTORY_ENTRIES = 20_000; // safety cap
private useMobileProfile = false;
private nowMs(): number {
// performance.now() is monotonic and better for scheduling; fall back to Date.now().
return (typeof performance !== 'undefined' && typeof performance.now === 'function')
? performance.now()
: Date.now();
}
constructor(
settings: DashReaderSettings,
onWordChange: (chunk: WordChunk) => void,
timeoutManager: TimeoutManager
) {
this.settings = settings;
this.onWordChange = onWordChange;
this.timeoutManager = timeoutManager;
this.micropauseService = new MicropauseService(settings, this.getEnableMicropauseSetting());
}
setText(text: string, startPosition?: number, startWordIndex?: number): void {
// Nettoyer et diviser le texte en mots
// Important: preserve line breaks by replacing them with a marker FIRST
const cleaned = text
.replace(/\n+/g, ' §§LINEBREAK§§ ') // Replace line breaks FIRST
.replace(/[ \t]+/g, ' ') // Then clean up spaces/tabs (NOT \n!)
.trim();
this.words = cleaned.split(/\s+/);
// Extraire les headings avec leur position (before replacing markers)
this.extractHeadings();
// Replace line break markers with actual line breaks for display
this.words = this.words.map(word =>
word === '§§LINEBREAK§§' ? '\n' : word
);
this.rebuildVirtualTimeline();
// Utiliser l'index du mot si fourni (prioritaire)
if (startWordIndex !== undefined) {
this.currentIndex = Math.max(0, Math.min(startWordIndex, this.words.length - 1));
} else if (startPosition !== undefined && startPosition > 0) {
// Fallback: calculer depuis la position (deprecated)
const textUpToCursor = text.substring(0, startPosition);
const wordsBeforeCursor = textUpToCursor.trim().split(/\s+/).length;
this.currentIndex = Math.min(wordsBeforeCursor, this.words.length - 1);
} else {
this.currentIndex = 0;
}
this.resetHistory();
this.seedHistoryAtCurrentIndex(); // anchor playbackMs to this index's virtual time
}
setUseMobileProfile(useMobile: boolean): void {
this.useMobileProfile = useMobile;
this.micropauseService.updateSettings(this.settings, this.getEnableMicropauseSetting());
this.rebuildVirtualTimeline();
}
play(): void {
if (this.isPlaying) return;
if (this.currentIndex >= this.words.length) {
this.currentIndex = 0;
}
this.tickGen += 1;
this.isPlaying = true;
this.nextDueMs = null; // reset schedule anchor on every play/resume
// Initialiser le temps de début et le WPM de départ
if (this.startTime === 0) {
this.startTime = Date.now();
this.startWpm = this.getWpmSetting();
this.wordsReadInSession = 0; // Reset slow start counter
} else if (this.lastPauseTime > 0) {
// Si on reprend après une pause, ajouter le temps de pause
this.pausedTime += Date.now() - this.lastPauseTime;
this.lastPauseTime = 0;
}
this.displayNextWord();
}
pause(): void {
this.tickGen += 1;
this.isPlaying = false;
if (this.timer !== null) {
this.timeoutManager.clearTimeout(this.timer);
this.timer = null;
}
this.nextDueMs = null;
// Enregistrer le moment de la pause
this.lastPauseTime = Date.now();
}
stop(): void {
this.pause();
this.nextDueMs = null;
this.currentIndex = 0;
// Réinitialiser les temps
this.startTime = 0;
this.pausedTime = 0;
this.lastPauseTime = 0;
this.startWpm = 0;
this.wordsReadInSession = 0; // Reset slow start counter
this.resetHistory();
}
reset(): void {
this.stop();
}
private resetHistory(): void {
this.history = [];
this.historyCursor = -1;
this.playbackMs = 0;
}
private getWpmAtElapsedSeconds(elapsedSec: number): number {
if (!this.settings.enableAcceleration) return this.getWpmSetting();
const startWpm = this.getWpmSetting(); // same as play() initial startWpm for deterministic model
const target = this.settings.accelerationTargetWpm;
const dur = Math.max(1, this.settings.accelerationDuration);
if (elapsedSec >= dur) return Math.round(target);
const progress = elapsedSec / dur;
return Math.round(startWpm + (target - startWpm) * progress);
}
private rebuildVirtualTimeline(): void {
const n = this.words.length;
this.virtualTimeAtIndexMs = new Array(n).fill(0);
this.virtualTotalMs = 0;
if (n === 0) return;
let tMs = 0;
let sessionCount = 0;
const SLOW_START_WORDS = 5;
for (let i = 0; i < n; i++) {
// record time-at-index even for linebreaks (they map to nearest time)
this.virtualTimeAtIndexMs[i] = tMs;
const w = this.words[i];
if (w === '\n') continue; // playback skips these with 0 delay
// virtual WPM from virtual time, not Date.now()
const wpm = this.getWpmAtElapsedSeconds(tMs / 1000);
const baseDelay = (60 / wpm) * 1000;
let delayToken = w;
// mirror getChunk(): paragraph pause applies to the word before '\n'
if (i + 1 < n && this.words[i + 1] === '\n') {
delayToken += '\n';
}
const mult = this.micropauseService.calculateMultiplier(delayToken);
let delay = baseDelay * mult;
if (this.getEnableSlowStartSetting() && sessionCount < SLOW_START_WORDS) {
const remainingSlowWords = SLOW_START_WORDS - sessionCount;
const slowStartMultiplier = 1 + (remainingSlowWords / SLOW_START_WORDS);
delay *= slowStartMultiplier;
}
sessionCount += 1;
tMs += Math.max(0, delay);
}
this.virtualTotalMs = tMs;
}
private recordHistory(index: number, delayMs: number): void {
// If user rewound and then resumes reading, discard "future" history.
if (this.historyCursor < this.history.length - 1) {
this.history = this.history.slice(0, this.historyCursor + 1);
}
// If the last entry is exactly this same moment/index (e.g. after a seek anchor),
// don't add a duplicate. Just advance time by delay.
const last = this.history[this.history.length - 1];
if (last && last.index === index && last.tMs === this.playbackMs) {
this.playbackMs += Math.max(0, delayMs);
return;
}
// tMs = time at which this word was displayed (virtual reading time)
this.history.push({ index, tMs: this.playbackMs });
this.historyCursor = this.history.length - 1;
this.playbackMs += Math.max(0, delayMs);
// Trim old history window
while (
this.history.length > RSVPEngine.MAX_HISTORY_ENTRIES ||
(this.history.length > 0 && this.playbackMs - this.history[0].tMs > RSVPEngine.MAX_HISTORY_MS)
) {
this.history.shift();
this.historyCursor -= 1;
}
if (this.historyCursor < -1) this.historyCursor = -1;
}
private getCursorTimeMs(): number {
if (this.history.length === 0 || this.historyCursor < 0) return 0;
return this.history[this.historyCursor].tMs;
}
private findLastAtOrBefore(tMs: number): number {
if (this.history.length === 0) return -1;
let lo = 0, hi = this.history.length - 1, ans = -1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (this.history[mid].tMs <= tMs) { ans = mid; lo = mid + 1; }
else { hi = mid - 1; }
}
return ans;
}
private findFirstAtOrAfter(tMs: number): number {
if (this.history.length === 0) return -1;
let lo = 0, hi = this.history.length - 1, ans = -1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (this.history[mid].tMs >= tMs) { ans = mid; hi = mid - 1; }
else { lo = mid + 1; }
}
return ans;
}
private seekToHistoryCursor(cursor: number): void {
if (cursor < 0 || cursor >= this.history.length) return;
this.historyCursor = cursor;
this.currentIndex = this.history[cursor].index;
this.playbackMs = this.history[cursor].tMs;
}
private isSentenceBoundaryToken(word: string): boolean {
if (!word) return false;
if (word === '\n') return true;
if (/^\[H\d\]/.test(word) || /^\[CALLOUT:/.test(word)) return true;
return /[.!?]["')\]]?$/.test(word);
}
private alignToSentenceStart(index: number): number {
let i = Math.max(0, Math.min(index, this.words.length - 1));
while (i > 0 && !this.isSentenceBoundaryToken(this.words[i - 1])) i -= 1;
while (i < this.words.length && this.words[i] === '\n') i += 1;
return i;
}
rewind(steps: number = 20): void {
this.moveByWords(-steps);
if (this.isPlaying) {
this.pause();
this.play();
} else {
this.displayCurrentWord();
}
}
forward(steps: number = 20): void {
this.moveByWords(steps);
if (this.isPlaying) {
this.pause();
this.play();
} else {
this.displayCurrentWord();
}
}
private moveByWords(wordDelta: number): void {
if (this.words.length === 0 || wordDelta === 0) return;
let i = this.currentIndex;
// If we're sitting on a linebreak, normalize first:
if (wordDelta < 0) {
while (i > 0 && this.words[i] === '\n') i -= 1;
} else {
while (i < this.words.length && this.words[i] === '\n') i += 1;
}
let remaining = Math.abs(wordDelta);
if (wordDelta < 0) {
// Move backward counting only non-linebreak tokens
while (i > 0 && remaining > 0) {
i -= 1;
if (this.words[i] !== '\n') remaining -= 1;
}
// Ensure we don't end on a linebreak
while (i > 0 && this.words[i] === '\n') i -= 1;
} else {
// Move forward counting only non-linebreak tokens
while (i < this.words.length - 1 && remaining > 0) {
i += 1;
if (this.words[i] !== '\n') remaining -= 1;
}
// Ensure we don't end on a linebreak
while (i < this.words.length - 1 && this.words[i] === '\n') i += 1;
}
this.currentIndex = Math.max(0, Math.min(i, this.words.length - 1));
}
rewindSeconds(seconds: number = 10, snapToSentence: boolean = false): void {
const wasPlaying = this.isPlaying;
if (wasPlaying) this.pause();
const curMs =
(this.history.length > 0 && this.historyCursor >= 0)
? this.history[this.historyCursor].tMs
: (this.virtualTimeAtIndexMs[this.currentIndex] ?? 0);
const targetMs = Math.max(0, curMs - seconds * 1000);
const canUseHistory =
this.history.length >= 2 &&
this.historyCursor >= 0 &&
this.history[0].tMs <= targetMs;
// If history can’t reach the target (common right after heading jumps), use the virtual timeline.
if (!canUseHistory) {
this.currentIndex = this.findVirtualIndexAtOrBeforeMs(targetMs);
if (snapToSentence) this.currentIndex = this.alignToSentenceStart(this.currentIndex);
this.resetHistory();
this.seedHistoryAtCurrentIndex();
if (wasPlaying) this.play();
else this.displayCurrentWord();
return;
}
const cursor = this.findLastAtOrBefore(targetMs);
if (cursor === -1) {
// Defensive fallback (shouldn’t happen if canUseHistory is true)
this.currentIndex = this.findVirtualIndexAtOrBeforeMs(targetMs);
if (snapToSentence) this.currentIndex = this.alignToSentenceStart(this.currentIndex);
this.resetHistory();
this.seedHistoryAtCurrentIndex();
if (wasPlaying) this.play();
else this.displayCurrentWord();
return;
}
this.seekToHistoryCursor(cursor);
if (snapToSentence) {
const aligned = this.alignToSentenceStart(this.currentIndex);
// If sentence alignment goes earlier than our recorded window, fall back cleanly.
if (this.history.length > 0 && aligned < this.history[0].index) {
this.currentIndex = aligned;
this.resetHistory();
this.seedHistoryAtCurrentIndex();
} else {
while (this.historyCursor > 0 && this.history[this.historyCursor].index > aligned) {
this.historyCursor -= 1;
}
this.currentIndex = aligned;
this.playbackMs = this.history[this.historyCursor]?.tMs ?? (this.virtualTimeAtIndexMs[this.currentIndex] ?? 0);
}
}
if (wasPlaying) this.play();
else this.displayCurrentWord();
}
forwardSeconds(seconds: number = 10): void {
const wasPlaying = this.isPlaying;
if (wasPlaying) this.pause();
// If history is empty/too short (e.g. just jumped), seek via the virtual timeline.
if (this.history.length < 2) {
const curMs = this.virtualTimeAtIndexMs[this.currentIndex] ?? 0;
const targetMs = curMs + seconds * 1000;
this.currentIndex = this.findVirtualIndexAtOrAfterMs(targetMs);
this.resetHistory();
this.seedHistoryAtCurrentIndex();
if (wasPlaying) this.play();
else this.displayCurrentWord();
return;
}
// If we rewound into the past, move forward within recorded history (undo seek)
if (this.history.length > 0 && this.historyCursor >= 0 && this.historyCursor < this.history.length - 1) {
const target = this.getCursorTimeMs() + seconds * 1000;
const nextCursor = this.findFirstAtOrAfter(target);
this.seekToHistoryCursor(nextCursor !== -1 ? nextCursor : this.history.length - 1);
if (wasPlaying) this.play();
else this.displayCurrentWord();
return;
}
// Otherwise simulate forward using the same delay rules (micropause + accel + slow start)
let acc = 0;
let i = this.currentIndex;
let sessionCount = this.wordsReadInSession;
const SLOW_START_WORDS = 5;
while (i < this.words.length && acc < seconds * 1000) {
if (this.words[i] === '\n') { i += 1; continue; }
let delay = this.getChunk(i).delay;
if (this.getEnableSlowStartSetting() && sessionCount < SLOW_START_WORDS) {
const remainingSlowWords = SLOW_START_WORDS - sessionCount;
const slowStartMultiplier = 1 + (remainingSlowWords / SLOW_START_WORDS);
delay *= slowStartMultiplier;
}
acc += delay;
sessionCount += 1;
i += 1;
}
this.currentIndex = Math.min(this.words.length - 1, i);
// Preserve history so rewind still works after a forward jump.
// We "anchor" the new position at (old playbackMs + acc).
const newT = this.playbackMs + acc;
// If we were in the past (shouldn't happen in this branch), discard future.
if (this.historyCursor < this.history.length - 1) {
this.history = this.history.slice(0, this.historyCursor + 1);
}
this.playbackMs = newT;
// Add an anchor entry at the new position/time
this.history.push({ index: this.currentIndex, tMs: this.playbackMs });
this.historyCursor = this.history.length - 1;
// Trim window
while (
this.history.length > RSVPEngine.MAX_HISTORY_ENTRIES ||
(this.history.length > 0 && this.playbackMs - this.history[0].tMs > RSVPEngine.MAX_HISTORY_MS)
) {
this.history.shift();
this.historyCursor -= 1;
}
if (this.historyCursor < -1) this.historyCursor = -1;
if (wasPlaying) this.play();
else this.displayCurrentWord();
}
private getWpmSetting(): number {
return this.useMobileProfile ? this.settings.mobileWpm : this.settings.wpm;
}
private setWpmSetting(v: number): void {
if (this.useMobileProfile) this.settings.mobileWpm = v;
else this.settings.wpm = v;
}
private getChunkSizeSetting(): number {
return this.useMobileProfile ? this.settings.mobileChunkSize : this.settings.chunkSize;
}
private setChunkSizeSetting(v: number): void {
if (this.useMobileProfile) this.settings.mobileChunkSize = v;
else this.settings.chunkSize = v;
}
private getEnableSlowStartSetting(): boolean {
return this.useMobileProfile ? this.settings.mobileEnableSlowStart : this.settings.enableSlowStart;
}
private getEnableMicropauseSetting(): boolean {
return this.useMobileProfile ? this.settings.mobileEnableMicropause : this.settings.enableMicropause;
}
private displayCurrentWord(): void {
while (this.currentIndex < this.words.length && this.words[this.currentIndex] === '\n') {
this.currentIndex += 1;
}
if (this.currentIndex >= this.words.length) {
return;
}
const chunk = this.getChunk(this.currentIndex);
this.onWordChange(chunk);
}
private displayNextWord(): void {
if (!this.isPlaying) return;
const gen = this.tickGen;
// Skip linebreak tokens so we always advance through real words
while (this.currentIndex < this.words.length && this.words[this.currentIndex] === '\n') {
this.currentIndex += 1;
}
if (this.currentIndex >= this.words.length) {
this.isPlaying = false;
return;
}
const chunk = this.getChunk(this.currentIndex);
this.onWordChange(chunk);
let delay = chunk.delay;
if (this.getEnableSlowStartSetting()) {
const SLOW_START_WORDS = 5;
if (this.wordsReadInSession < SLOW_START_WORDS) {
const remainingSlowWords = SLOW_START_WORDS - this.wordsReadInSession;
const slowStartMultiplier = 1 + (remainingSlowWords / SLOW_START_WORDS);
delay *= slowStartMultiplier;
}
}
this.wordsReadInSession += 1;
// record the *actual* scheduled delay for time-based seeking
this.recordHistory(this.currentIndex, delay);
// CRITICAL: advance by ONE token every tick (not chunkSize)
this.currentIndex += 1;
const now = this.nowMs();
const delayMs = Math.max(0, delay);
// Initialise anchor on first tick after play()
if (this.nextDueMs == null) this.nextDueMs = now;
// Set the next due-time based on intended delay
this.nextDueMs += delayMs;
let waitMs = this.nextDueMs - now;
// If we’re massively behind (tab stall / throttling), resync to avoid turbo bursts.
if (waitMs < -250) {
this.nextDueMs = now + delayMs;
waitMs = delayMs;
}
this.timer = this.timeoutManager.setTimeout(() => {
if (gen !== this.tickGen) return; // stale callback; ignore
this.displayNextWord();
}, Math.max(0, waitMs));
}
private getChunk(startIndex: number): WordChunk {
const chunkSize = Math.max(1, this.getChunkSizeSetting() || 1);
const chunkWords: string[] = [];
let i = startIndex;
while (i < this.words.length && chunkWords.length < chunkSize) {
const w = this.words[i];
if (w !== '\n') chunkWords.push(w);
i++;
}
const text = chunkWords.join(' ');
const focusWordRaw = chunkWords[0] ?? '';
let delayToken = focusWordRaw;
// If this word is immediately followed by a linebreak token, fold that into the delay
// so paragraph micropauses apply like they did when '\n' existed inside the evaluated token/string.
if (startIndex + 1 < this.words.length && this.words[startIndex + 1] === '\n') {
delayToken += '\n';
}
const delay = this.calculateDelay(delayToken);
return {
text,
index: startIndex,
delay,
isEnd: startIndex >= this.words.length - 1,
headingContext: this.getCurrentHeadingContext(startIndex)
};
}
private getCurrentWpm(): number {
// Si l'accélération n'est pas activée, retourner le WPM normal
if (!this.settings.enableAcceleration || this.startTime === 0) {
return this.getWpmSetting();
}
// Calculer le temps écoulé (en secondes)
const now = this.isPlaying ? Date.now() : (this.lastPauseTime || Date.now());
const elapsed = (now - this.startTime - this.pausedTime) / 1000;
// Si on a dépassé la durée d'accélération, retourner le WPM cible
if (elapsed >= this.settings.accelerationDuration) {
return this.settings.accelerationTargetWpm;
}
// Calculer le WPM progressif
const progress = elapsed / this.settings.accelerationDuration;
const wpmDiff = this.settings.accelerationTargetWpm - this.startWpm;
const currentWpm = this.startWpm + (wpmDiff * progress);
return Math.round(currentWpm);
}
private calculateDelay(text: string): number {
const currentWpm = this.getCurrentWpm();
const baseDelay = (60 / currentWpm) * 1000;
// Calculate micropause multiplier using service
const multiplier = this.micropauseService.calculateMultiplier(text);
return baseDelay * multiplier;
}
/**
* Extract all headings and callouts from the words array
* Headings are marked with [H1], [H2], etc.
* Callouts are marked with [CALLOUT:type] by the markdown parser
*
* Since text is split into words, we need to collect all words
* that belong to the same heading/callout title.
*/
private extractHeadings(): void {
this.headings = [];
for (let i = 0; i < this.words.length; i++) {
const word = this.words[i];
// Check for regular headings [H1], [H2], etc.
const headingMatch = word.match(/^\[H(\d)\](.+)/);
if (headingMatch) {
const level = parseInt(headingMatch[1]);
const firstWord = headingMatch[2];
// Collect following words until we hit a line break marker
// Headings are single-line, so we stop at §§LINEBREAK§§
const titleWords = [firstWord];
let j = i + 1;
while (j < this.words.length) {
const nextWord = this.words[j];
// Stop if we hit the line break marker
if (nextWord === '§§LINEBREAK§§') {
break;
}
// Stop if we hit another marker
if (/^\[H\d\]/.test(nextWord) || /^\[CALLOUT:/.test(nextWord)) {
break;
}
// Add word to title
titleWords.push(nextWord);
j++;
// Safety limit: max 20 words for a heading
if (titleWords.length >= 20) {
break;
}
}
const text = titleWords.join(' ').trim();
this.headings.push({
level,
text,
wordIndex: i
});
continue;
}
// Check for callouts [CALLOUT:type]Title
const calloutMatch = word.match(/^\[CALLOUT:([\w-]+)\](.+)/);
if (calloutMatch) {
const calloutType = calloutMatch[1];
const firstWord = calloutMatch[2];
// Collect following words until we hit a line break marker
// Callout titles are single-line, so we stop at §§LINEBREAK§§
const titleWords = [firstWord];
let j = i + 1;
while (j < this.words.length) {
const nextWord = this.words[j];
// Stop if we hit the line break marker
if (nextWord === '§§LINEBREAK§§') {
break;
}
// Stop if we hit another marker
if (/^\[H\d\]/.test(nextWord) || /^\[CALLOUT:/.test(nextWord)) {
break;
}
// Add word to title
titleWords.push(nextWord);
j++;
// Safety limit: max 20 words for a callout title
if (titleWords.length >= 20) {
break;
}
}
const text = titleWords.join(' ').trim();
this.headings.push({
level: 7, // Callouts are LOWER priority than H6 (H1..H6)
text,
wordIndex: i,
calloutType
});
}
}
}
/**
* Get the current heading context (breadcrumb) for a given word index
* Returns the hierarchical path of headings leading to the current position
*
* @param wordIndex - Word index to get context for
* @returns Heading context with breadcrumb path and current heading
*/
getCurrentHeadingContext(wordIndex: number): HeadingContext {
if (this.headings.length === 0) {
return { breadcrumb: [], current: null };
}
// Find all headings before or at the current position
const relevantHeadings = this.headings.filter(h => h.wordIndex <= wordIndex);
if (relevantHeadings.length === 0) {
return { breadcrumb: [], current: null };
}
// Build hierarchical breadcrumb
const breadcrumb: HeadingInfo[] = [];
let currentLevel = 0;
for (const heading of relevantHeadings) {
// If this heading is at a lower or equal level than current, reset the breadcrumb up to this level
if (heading.level <= currentLevel) {
// Remove all headings from this level onwards
while (breadcrumb.length > 0 && breadcrumb[breadcrumb.length - 1].level >= heading.level) {
breadcrumb.pop();
}
}
breadcrumb.push(heading);
currentLevel = heading.level;
}
return {
breadcrumb,
current: breadcrumb[breadcrumb.length - 1] || null
};
}
getProgress(): number {
return this.words.length > 0
? (this.currentIndex / this.words.length) * 100
: 0;
}
getCurrentIndex(): number {
return this.currentIndex;
}
getTotalWords(): number {
return this.words.length;
}
getIsPlaying(): boolean {
return this.isPlaying;
}
setWpm(wpm: number): void {
this.setWpmSetting(Math.max(50, Math.min(5000, wpm)));
this.rebuildVirtualTimeline();
}
getWpm(): number {
return this.getWpmSetting();
}
setChunkSize(size: number): void {
this.setChunkSizeSetting(Math.max(1, Math.min(5, size)));
}
getChunkSize(): number {
return this.getChunkSizeSetting();
}
// ---------------------------------------------------------------------------
// Line-based context (replaces old word-based context)
// ---------------------------------------------------------------------------
private isLineBreakToken(t: string | undefined): boolean {
return t === '\n' || t === '§§LINEBREAK§§';
}
private findLineStart(index: number): number {
// start = first token AFTER the previous '\n'
let i = Math.max(0, Math.min(index, this.words.length));
while (i > 0 && !this.isLineBreakToken(this.words[i - 1])) i--;
return i;
}
private findLineEnd(index: number): number {
// end = index of '\n' OR words.length (exclusive end)
let i = Math.max(0, Math.min(index, this.words.length));
while (i < this.words.length && !this.isLineBreakToken(this.words[i])) i++;
return i;
}
private getPrevLineRange(currentLineStart: number): { start: number; end: number; prevSeparator: number } | null {
// currentLineStart is first token of current line.
// The separator before current line is at currentLineStart - 1 (may be '\n' or -1).
let sep = currentLineStart - 1;
if (sep < 0) return null;
// sep points to '\n' (or multiple '\n' for blank lines).
// Previous line ends at sep (exclusive).
const end = sep;
// Find previous separator (or start)
while (sep > 0 && !this.isLineBreakToken(this.words[sep - 1])) sep--;
const start = sep;
return { start, end, prevSeparator: start - 1 };
}
private getNextLineRange(currentLineEnd: number): { start: number; end: number; nextSeparator: number } | null {
// currentLineEnd is index of '\n' or words.length.
if (currentLineEnd >= this.words.length) return null;
// currentLineEnd points at '\n'. Next line starts after it.
const start = currentLineEnd + 1;
if (start > this.words.length) return null;
// Find next '\n' (or end)
let end = start;
while (end < this.words.length && !this.isLineBreakToken(this.words[end])) end++;
return { start, end, nextSeparator: end };
}
private getActiveChunkEndOnThisLine(startIndex: number): number {
// Chunk is the active phrase. We clamp it to THIS LINE so anchor semantics remain line-based.
const chunkSize = Math.max(1, this.getChunkSizeSetting() || 1);
const lineEnd = this.findLineEnd(startIndex);
let count = 0;
let i = startIndex;
let last = startIndex;
while (i < lineEnd && count < chunkSize) {
const w = this.words[i];
if (!this.isLineBreakToken(w)) {
last = i;
count++;
}
i++;
}
return last;
}
/**
* Returns line-based context around the active chunk:
* - BEFORE: N full lines above + anchor-before (words before active chunk on current line)
* - AFTER : anchor-after (words after active chunk on current line) + N full lines below
*
* `lines` is 0..10 (0 means anchor line only).
*/
public getContextLines(startIndex: number, lines: number): { before: string[]; after: string[] } {
const idx = Math.max(0, Math.min(startIndex, this.words.length - 1));
const n = Math.max(0, Math.floor(lines));
const lineStart = this.findLineStart(idx);
const lineEnd = this.findLineEnd(idx);
const chunkEnd = this.getActiveChunkEndOnThisLine(idx);
// Anchor line (split)
const anchorBefore = this.words.slice(lineStart, idx).filter(t => !this.isLineBreakToken(t));
const anchorAfter = this.words.slice(idx + 1, lineEnd).filter(t => !this.isLineBreakToken(t));
// Collect N lines above (oldest -> nearest)
const aboveLines: string[][] = [];
let cursorStart = lineStart;
for (let k = 0; k < n; k++) {
const prev = this.getPrevLineRange(cursorStart);
if (!prev) break;
aboveLines.unshift(this.words.slice(prev.start, prev.end).filter(t => !this.isLineBreakToken(t)));
cursorStart = prev.start;
}
// Collect N lines below (nearest -> further)
const belowLines: string[][] = [];
let cursorEnd = lineEnd;
for (let k = 0; k < n; k++) {
const next = this.getNextLineRange(cursorEnd);
if (!next) break;
belowLines.push(this.words.slice(next.start, next.end).filter(t => !this.isLineBreakToken(t)));
cursorEnd = next.end;
}
// Flatten with explicit '\n' between lines
const before: string[] = [];
for (let i = 0; i < aboveLines.length; i++) {
before.push(...aboveLines[i]);
before.push('\n');
}
// anchor-before is always the final line in BEFORE (can be empty)
before.push(...anchorBefore);
const after: string[] = [];
// anchor-after is always the first line in AFTER (can be empty)
after.push(...anchorAfter);
for (let i = 0; i < belowLines.length; i++) {
after.push('\n');
after.push(...belowLines[i]);
}
return { before, after };
}
/**
* Returns a token window around the current word for UI-level (wrapped) context rendering.
* Includes explicit line break tokens ('\n') and internal markers; the view layer formats it.
*/
public getContextTokenWindow(
index: number,
backTokens: number,
forwardTokens: number
): { before: string[]; after: string[] } {
const len = this.words.length;
if (len === 0) return { before: [], after: [] };
const idx = Math.max(0, Math.min(index, len - 1));
const back = Math.max(0, Math.floor(backTokens));
const fwd = Math.max(0, Math.floor(forwardTokens));
const start = Math.max(0, idx - back);
// BEFORE: exclude the focused word; trim trailing line breaks
const before = this.words.slice(start, idx);
while (before.length && before[before.length - 1] === '\n') before.pop();
// AFTER: start immediately after the focused word (NOT after the full displayed chunk)
let afterStart = Math.min(len, idx + 1);
while (afterStart < len && this.words[afterStart] === '\n') afterStart += 1;
const end = Math.min(len, afterStart + fwd);
const after = this.words.slice(afterStart, end);
return { before, after };
}
public getVirtualTotalSeconds(): number {