-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathTeleprompterPage.ReaderPlayback.cs
More file actions
762 lines (657 loc) · 25.9 KB
/
TeleprompterPage.ReaderPlayback.cs
File metadata and controls
762 lines (657 loc) · 25.9 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
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using PrompterOne.Shared.Contracts;
using PrompterOne.Shared.Localization;
namespace PrompterOne.Shared.Pages;
public partial class TeleprompterPage
{
private const string AttachReaderCameraOperation = "Teleprompter camera attach";
private const int MinimumReaderLoopDelayMilliseconds = 120;
// Keep the C# wait budget locked to `.rd-card` transition timing in
// `10-reading-states.css` so card normalization never lags behind the
// actual visual handoff.
private const int ReaderCardTransitionMilliseconds = 700;
private Task DecreaseReaderPlaybackSpeedAsync() => ChangeReaderPlaybackSpeedAsync(-ReaderPlaybackSpeedStepWpm);
private Task IncreaseReaderPlaybackSpeedAsync() => ChangeReaderPlaybackSpeedAsync(ReaderPlaybackSpeedStepWpm);
private Task StepReaderBackwardAsync() => StepReaderWordAsync(ReaderBackwardStep);
private Task StepReaderForwardAsync() => StepReaderWordAsync(ReaderForwardStep);
private Task JumpToPreviousReaderCardAsync() => JumpReaderCardAsync(ReaderCardBackwardStep);
private Task JumpToNextReaderCardAsync() => JumpReaderCardAsync(ReaderCardForwardStep);
private async Task NavigateBackToEditorAsync()
{
StopReaderPlaybackLoop();
var route = string.IsNullOrWhiteSpace(SessionService.State.ScriptId)
? AppRoutes.Editor
: AppRoutes.EditorWithId(SessionService.State.ScriptId);
Navigation.NavigateTo(route);
await Task.CompletedTask;
}
private async Task ChangeReaderPlaybackSpeedAsync(int delta)
{
await SetReaderPlaybackSpeedAsync(_readerPlaybackSpeedWpm + delta);
}
private async Task SetReaderPlaybackSpeedAsync(int speedWpm)
{
var nextSpeedWpm = Math.Clamp(
speedWpm,
ReaderMinimumPlaybackSpeedWpm,
ReaderMaximumPlaybackSpeedWpm);
if (nextSpeedWpm == _readerPlaybackSpeedWpm)
{
return;
}
_readerPlaybackSpeedWpm = nextSpeedWpm;
await PersistCurrentReaderLayoutAsync();
if (_isReaderPlaying)
{
RestartReaderPlaybackLoop(GetCurrentWordDelayMilliseconds());
}
}
private async Task HandleReaderFontSizeInputAsync(ChangeEventArgs args)
{
var nextFontSize = ParseReaderControlValue(
args.Value,
ReaderMinFontSize,
ReaderMaxFontSize,
_readerFontSize);
if (nextFontSize == _readerFontSize)
{
return;
}
_readerFontSize = nextFontSize;
RequestReaderAlignment(instant: true);
await PersistCurrentReaderLayoutAsync();
}
private async Task HandleReaderFocalPointInputAsync(ChangeEventArgs args)
{
_readerFocalPointPercent = ParseReaderControlValue(
args.Value,
ReaderMinFocalPointPercent,
ReaderMaxFocalPointPercent,
_readerFocalPointPercent);
RequestReaderAlignment();
await PersistCurrentReaderLayoutAsync();
_isFocalGuideActive = true;
_focalGuideVersion++;
var guideVersion = _focalGuideVersion;
await Task.Delay(ReaderGuideActiveDurationMilliseconds);
if (_focalGuideVersion == guideVersion)
{
_isFocalGuideActive = false;
await InvokeAsync(StateHasChanged);
}
}
private async Task HandleReaderTextWidthInputAsync(ChangeEventArgs args)
{
_readerTextWidthPercent = ParseReaderControlValue(
args.Value,
ReaderMinTextWidthPercent,
ReaderMaxTextWidthPercent,
_readerTextWidthPercent);
RequestReaderAlignment();
await PersistCurrentReaderLayoutAsync();
_areWidthGuidesActive = true;
_widthGuideVersion++;
var widthGuideVersion = _widthGuideVersion;
await Task.Delay(ReaderGuideActiveDurationMilliseconds);
if (_widthGuideVersion == widthGuideVersion)
{
_areWidthGuidesActive = false;
await InvokeAsync(StateHasChanged);
}
}
private async Task ToggleReaderPlaybackAsync()
{
if (_cards.Count == 0 || _isReaderCountdownActive)
{
return;
}
if (_isReaderPlaying)
{
StopReaderPlaybackLoop();
return;
}
if (_activeReaderWordIndex >= 0)
{
// If we stopped mid-pause-beat, advance past the pause on
// resume instead of waiting another full word duration and
// replaying the preceding word. A minimal loop tick kicks
// the AdvanceReaderPlaybackAsync code into the "clear pause,
// activate next word" branch.
var resumeDelayMs = _activeReaderPauseChunkIndex is not null
? MinimumReaderLoopDelayMilliseconds
: GetCurrentWordDelayMilliseconds();
RestartReaderPlaybackLoop(resumeDelayMs);
return;
}
await StartReaderCountdownAsync();
}
private async Task StartReaderCountdownAsync()
{
StopReaderPlaybackLoop(keepPlaybackState: true);
_readerPlaybackCts = new CancellationTokenSource();
var cancellationToken = _readerPlaybackCts.Token;
try
{
_isReaderCountdownActive = true;
_countdownValue = null;
await InvokeAsync(StateHasChanged);
await Task.Delay(ReaderCountdownPreDelayMilliseconds, cancellationToken);
for (var countdown = 3; countdown >= 1; countdown--)
{
_countdownValue = countdown;
await InvokeAsync(StateHasChanged);
await Task.Delay(ReaderCountdownStepMilliseconds, cancellationToken);
}
_isReaderCountdownActive = false;
_countdownValue = null;
await InvokeAsync(StateHasChanged);
await Task.Delay(ReaderFirstWordDelayMilliseconds, cancellationToken);
SetReaderPlaybackState(true);
await ActivateReaderWordAsync(0, alignBeforeActivation: true);
_ = RunReaderPlaybackLoopAsync(GetCurrentWordDelayMilliseconds(), cancellationToken);
}
catch (OperationCanceledException)
{
}
}
private async Task StepReaderWordAsync(int direction)
{
if (_cards.Count == 0)
{
return;
}
var resumePlayback = _isReaderPlaying;
StopReaderPlaybackLoop(keepPlaybackState: true);
if (direction < 0)
{
if (_activeReaderWordIndex > 0)
{
await ActivateReaderWordAsync(_activeReaderWordIndex - 1, alignBeforeActivation: true);
}
}
else if (_activeReaderWordIndex < 0)
{
await ActivateReaderWordAsync(0, alignBeforeActivation: true);
}
else
{
var wordCount = GetCardWordCount(_cards[_activeReaderCardIndex]);
if (_activeReaderWordIndex < wordCount - 1)
{
await ActivateReaderWordAsync(_activeReaderWordIndex + 1, alignBeforeActivation: true);
}
else
{
// Manual forward step off the last word always advances
// upward — even on wrap-around.
await AdvanceToCardAsync(
GetNextPlaybackCardIndex(),
CancellationToken.None,
explicitDirection: ReaderCardForwardStep);
}
}
if (resumePlayback)
{
RestartReaderPlaybackLoop(GetCurrentWordDelayMilliseconds());
}
}
private async Task JumpReaderCardAsync(int direction)
{
if (_cards.Count == 0)
{
return;
}
var resumePlayback = _isReaderPlaying;
StopReaderPlaybackLoop(keepPlaybackState: true);
if (direction < 0 && _activeReaderWordIndex > 1)
{
await ActivateReaderWordAsync(0, alignBeforeActivation: true);
if (resumePlayback)
{
RestartReaderPlaybackLoop(GetCurrentWordDelayMilliseconds());
}
return;
}
var nextCardIndex = _activeReaderCardIndex + direction;
if (nextCardIndex < 0 || nextCardIndex >= _cards.Count)
{
if (resumePlayback)
{
RestartReaderPlaybackLoop(GetCurrentWordDelayMilliseconds());
}
return;
}
await AdvanceToCardAsync(nextCardIndex, CancellationToken.None);
if (resumePlayback)
{
RestartReaderPlaybackLoop(GetCurrentWordDelayMilliseconds());
}
}
private async Task ToggleReaderCameraAsync()
{
_isReaderCameraActive = !_isReaderCameraActive;
_cameraLayer = _cameraLayer with { AutoStart = _isReaderCameraActive };
if (_isReaderCameraActive)
{
await AttachReaderCameraAsync();
}
else
{
await DetachReaderCameraAsync();
}
await PersistReaderCameraPreferenceAsync();
}
private async Task AttachReaderCameraAsync()
{
var attached = await Diagnostics.RunAsync(
AttachReaderCameraOperation,
Text(UiTextKey.TeleprompterAttachCameraMessage),
() => CameraPreviewInterop.AttachCameraAsync(_cameraLayer.ElementId, _cameraLayer.DeviceId));
if (!attached)
{
_isReaderCameraActive = false;
_cameraLayer = _cameraLayer with { AutoStart = false };
}
}
private Task DetachReaderCameraAsync() =>
CameraPreviewInterop.DetachCameraAsync(_cameraLayer.ElementId);
private void RestartReaderPlaybackLoop(int initialDelayMilliseconds)
{
StopReaderPlaybackLoop(keepPlaybackState: true);
_readerPlaybackCts = new CancellationTokenSource();
SetReaderPlaybackState(true);
_ = RunReaderPlaybackLoopAsync(initialDelayMilliseconds, _readerPlaybackCts.Token);
}
private void StopReaderPlaybackLoop(bool keepPlaybackState = false)
{
_readerPlaybackCts?.Cancel();
_readerPlaybackCts?.Dispose();
_readerPlaybackCts = null;
_isReaderCountdownActive = false;
_countdownValue = null;
if (!keepPlaybackState)
{
// Pause-beat state is intentionally NOT cleared here — the
// resume path in ToggleReaderPlaybackAsync reads it so a user
// who stops mid-pause and hits play again skips past the
// already-played pause rather than re-playing the preceding
// word for its full duration (was a real bug found in a
// playback trace review).
SetReaderPlaybackState(false);
_ = ClearKineticEnvelopesAsync();
}
}
private async Task ClearKineticEnvelopesAsync()
{
try
{
await KineticInterop.ClearAsync();
}
catch (JSException) { }
catch (InvalidOperationException) { }
catch (TaskCanceledException) { }
}
private void SetReaderPlaybackState(bool isPlaying)
{
_isReaderPlaying = isPlaying;
Shell.SetTeleprompterPlaybackActive(isPlaying);
}
private async Task RunReaderPlaybackLoopAsync(int initialDelayMilliseconds, CancellationToken cancellationToken)
{
try
{
var delayMilliseconds = Math.Max(MinimumReaderLoopDelayMilliseconds, initialDelayMilliseconds);
while (!cancellationToken.IsCancellationRequested && _isReaderPlaying && _cards.Count > 0)
{
await Task.Delay(delayMilliseconds, cancellationToken);
if (cancellationToken.IsCancellationRequested || !_isReaderPlaying)
{
break;
}
var nextDelayMilliseconds = MinimumReaderLoopDelayMilliseconds;
await InvokeAsync(async () => nextDelayMilliseconds = await AdvanceReaderPlaybackAsync(cancellationToken));
delayMilliseconds = nextDelayMilliseconds;
}
}
catch (OperationCanceledException)
{
}
}
private async Task<int> AdvanceReaderPlaybackAsync(CancellationToken cancellationToken)
{
if (_cards.Count == 0)
{
return MinimumReaderLoopDelayMilliseconds;
}
var activeCard = _cards[_activeReaderCardIndex];
var cardWordCount = GetCardWordCount(activeCard);
if (cardWordCount == 0)
{
return MinimumReaderLoopDelayMilliseconds;
}
// Pause beat: the word we just finished is the last word of its
// group and is followed by a pause chunk. The pause takes over as
// the active beat (its own "word") so the operator sees the pill
// or dots light up while the previous word dims to read-state.
if (_activeReaderPauseChunkIndex is null &&
_activeReaderWordIndex >= 0 &&
FindTrailingPauseChunk(_activeReaderCardIndex, _activeReaderWordIndex) is { } pauseBeat)
{
_activeReaderPauseChunkIndex = pauseBeat.ChunkIndex;
await ClearKineticEnvelopesAsync();
UpdateReaderDisplayState(requestAlignment: false);
await InvokeAsync(StateHasChanged);
await SlideFocusLensToPauseAsync(pauseBeat.ChunkIndex);
return Math.Max(MinimumReaderLoopDelayMilliseconds, BuildScaledReaderDelayMilliseconds(pauseBeat.DurationMs));
}
// Pause beat finished — clear the marker so the next word can take
// the active slot cleanly.
_activeReaderPauseChunkIndex = null;
if (_activeReaderWordIndex < cardWordCount - 1)
{
await ActivateReaderWordAsync(_activeReaderWordIndex + 1, alignBeforeActivation: true);
return GetCurrentWordDelayMilliseconds();
}
if (!_isReaderAutoLoopEnabled && _activeReaderCardIndex == _cards.Count - 1)
{
StopReaderPlaybackLoop();
UpdateReaderDisplayState(requestAlignment: false);
await InvokeAsync(StateHasChanged);
return MinimumReaderLoopDelayMilliseconds;
}
// Playback loop always advances upward — even when wrapping
// from the last card back to index 0. Without an explicit
// direction, the wrap would compare 0 < lastIndex and fire
// the backward-descent animation during normal forward play.
await AdvanceToCardAsync(GetNextPlaybackCardIndex(), cancellationToken, explicitDirection: ReaderCardForwardStep);
return GetCurrentWordDelayMilliseconds();
}
// Locate a trailing pause that should play as its own beat after the
// given word ordinal. Returns the pause's chunk index and duration if
// the word is the last child of its group AND the next chunk is a
// pause with a real duration. Breath markers (duration 0) are treated
// as visual-only and do not stop playback.
private (int ChunkIndex, int DurationMs)? FindTrailingPauseChunk(int cardIndex, int wordOrdinal)
{
if (cardIndex < 0 || cardIndex >= _cards.Count || wordOrdinal < 0)
{
return null;
}
var card = _cards[cardIndex];
var remaining = wordOrdinal;
for (var chunkIndex = 0; chunkIndex < card.Chunks.Count; chunkIndex++)
{
if (card.Chunks[chunkIndex] is not ReaderGroupViewModel group)
{
continue;
}
if (remaining >= group.Words.Count)
{
remaining -= group.Words.Count;
continue;
}
var isLastWordOfGroup = remaining == group.Words.Count - 1;
if (!isLastWordOfGroup)
{
return null;
}
var nextChunkIndex = chunkIndex + 1;
if (nextChunkIndex < card.Chunks.Count &&
card.Chunks[nextChunkIndex] is ReaderPauseViewModel pause &&
pause.DurationMs > 0)
{
return (nextChunkIndex, pause.DurationMs);
}
return null;
}
return null;
}
private Task AdvanceToCardAsync(int nextCardIndex, CancellationToken cancellationToken) =>
AdvanceToCardAsync(nextCardIndex, cancellationToken, explicitDirection: null);
private async Task AdvanceToCardAsync(
int nextCardIndex,
CancellationToken cancellationToken,
int? explicitDirection)
{
await CancelPendingReaderCardTransitionAsync();
var previousCardIndex = _activeReaderCardIndex;
// Hide the OLD card's focus lens explicitly — otherwise the
// `.rd-focus-lens-active` class stays on it and, if the same
// card comes back into view later, the lens would be visible
// at a stale position until the first word re-activates.
await HideFocusLensAsync(previousCardIndex);
var transition = BeginReaderCardTransitionScope(cancellationToken);
await PrepareReaderCardTransitionAsync(nextCardIndex, explicitDirection);
await PrepareReaderCardAlignmentAsync(nextCardIndex, 0);
_readerTransitionSourceCardIndex = previousCardIndex;
_activeReaderCardIndex = nextCardIndex;
_activeReaderWordIndex = -1;
_activeReaderPauseChunkIndex = null;
_preparedReaderCardIndex = null;
UpdateReaderDisplayState(requestAlignment: false);
await InvokeAsync(StateHasChanged);
try
{
await Task.Delay(ReaderCardTransitionMilliseconds, transition.Token);
if (transition.Token.IsCancellationRequested)
{
return;
}
await ActivateReaderWordAsync(0, alignBeforeActivation: false);
}
catch (OperationCanceledException) when (transition.Token.IsCancellationRequested)
{
}
finally
{
CompleteReaderCardTransitionScope(transition.Source);
await FinalizeReaderCardTransitionAsync(previousCardIndex);
}
}
private int GetCurrentWordDelayMilliseconds()
{
if (_cards.Count == 0 || _activeReaderCardIndex >= _cards.Count)
{
return MinimumReaderLoopDelayMilliseconds;
}
var remainingIndex = _activeReaderWordIndex;
foreach (var chunk in _cards[_activeReaderCardIndex].Chunks)
{
if (chunk is not ReaderGroupViewModel group)
{
continue;
}
foreach (var word in group.Words)
{
if (remainingIndex == 0)
{
// PauseAfterMs is NOT added here — trailing pauses run
// as their own beat (see FindTrailingPauseChunk). The
// word's active state owns only its spoken time.
return BuildScaledReaderDelayMilliseconds(word.DurationMs);
}
remainingIndex--;
}
}
return MinimumReaderLoopDelayMilliseconds;
}
private async Task ActivateReaderWordAsync(int wordIndex, bool alignBeforeActivation)
{
if (alignBeforeActivation)
{
await AlignReaderWordBeforeActivationAsync(_activeReaderCardIndex, wordIndex);
}
// Any pending pause beat ends the moment a word takes the stage.
_activeReaderPauseChunkIndex = null;
_activeReaderWordIndex = wordIndex;
UpdateReaderDisplayState(requestAlignment: false);
await InvokeAsync(StateHasChanged);
await FireKineticWordEnvelopeAsync(wordIndex);
await SlideFocusLensToActiveWordAsync(wordIndex);
}
private async Task SlideFocusLensToActiveWordAsync(int wordIndex)
{
if (!TryGetAlignmentWordId(_activeReaderCardIndex, wordIndex, out var wordId))
{
return;
}
// Word's cue tags drive the lens transition character; its
// scaled wall-clock duration sizes the glide so the lens never
// over- or under-shoots the word's own time budget.
var word = ResolveReaderWordAt(_activeReaderCardIndex, wordIndex);
var cueTags = word is null
? Array.Empty<string>()
: ExtractKineticCueTags(word.CssClass);
var scaledWordDurationMs = word is null
? MinimumReaderLoopDelayMilliseconds
: BuildScaledReaderDelayMilliseconds(word.DurationMs);
await InvokeLensPositionAsync(wordId, cueTags, scaledWordDurationMs);
}
private Task SlideFocusLensToPauseAsync(int chunkIndex)
{
// Pauses advance the lens as their own "beat". The lens glide
// occupies ~0.9× the pause duration (default ratio), so short
// pauses get a quick slide and long silence pills get a gentle
// settle matching the operator's breathing moment.
var chunkId = UiDomIds.Teleprompter.CardChunk(_activeReaderCardIndex, chunkIndex);
var pauseDurationMs = ResolvePauseChunkDurationMs(_activeReaderCardIndex, chunkIndex);
var scaledPauseDurationMs = BuildScaledReaderDelayMilliseconds(pauseDurationMs);
return InvokeLensPositionAsync(chunkId, Array.Empty<string>(), scaledPauseDurationMs);
}
private int ResolvePauseChunkDurationMs(int cardIndex, int chunkIndex)
{
if (cardIndex < 0 || cardIndex >= _cards.Count)
{
return MinimumReaderLoopDelayMilliseconds;
}
var chunks = _cards[cardIndex].Chunks;
if (chunkIndex < 0 || chunkIndex >= chunks.Count)
{
return MinimumReaderLoopDelayMilliseconds;
}
return chunks[chunkIndex] is ReaderPauseViewModel pause
? Math.Max(MinimumReaderLoopDelayMilliseconds, pause.DurationMs)
: MinimumReaderLoopDelayMilliseconds;
}
private async Task InvokeLensPositionAsync(
string targetId,
IReadOnlyList<string> cueTags,
int targetDurationMs)
{
var lensId = UiDomIds.Teleprompter.FocusLens(_activeReaderCardIndex);
try
{
await KineticInterop.PositionLensAsync(lensId, targetId, cueTags, targetDurationMs);
}
catch (JSException) { }
catch (InvalidOperationException) { }
catch (TaskCanceledException) { }
}
private async Task HideFocusLensAsync(int cardIndex)
{
if (cardIndex < 0 || cardIndex >= _cards.Count)
{
return;
}
var lensId = UiDomIds.Teleprompter.FocusLens(cardIndex);
try
{
await KineticInterop.HideLensAsync(lensId);
}
catch (JSException) { }
catch (InvalidOperationException) { }
catch (TaskCanceledException) { }
}
// Dispatch the kinetic envelope for the freshly-activated word. The
// duration is the same scaled wall-clock budget the reader loop will
// wait before advancing, so WAAPI finishes exactly on the handoff.
// Cue tags come from the word's composed CSS class so there is one
// authoritative source for cue metadata and no stringly-typed map.
private async Task FireKineticWordEnvelopeAsync(int wordIndex)
{
var word = ResolveReaderWordAt(_activeReaderCardIndex, wordIndex);
if (word is null)
{
return;
}
var wordDuration = word.DurationMs > 0 ? word.DurationMs : MinimumReaderLoopDelayMilliseconds;
var scaledDurationMs = BuildScaledReaderDelayMilliseconds(wordDuration);
var cueTags = ExtractKineticCueTags(word.CssClass);
try
{
await KineticInterop.ActivateWordAsync(scaledDurationMs, cueTags, 1d);
}
catch (JSException)
{
// JS module not loaded yet (prerender or before index.html
// script tag settles). Safe to swallow — next word will
// pick up once the bridge is ready.
}
catch (InvalidOperationException)
{
// JSRuntime is unavailable during Blazor prerender.
}
catch (TaskCanceledException)
{
}
}
private ReaderWordViewModel? ResolveReaderWordAt(int cardIndex, int wordIndex)
{
if (cardIndex < 0 || cardIndex >= _cards.Count || wordIndex < 0)
{
return null;
}
var remaining = wordIndex;
foreach (var chunk in _cards[cardIndex].Chunks)
{
if (chunk is not ReaderGroupViewModel group)
{
continue;
}
foreach (var word in group.Words)
{
if (remaining == 0)
{
return word;
}
remaining--;
}
}
return null;
}
private static IReadOnlyList<string> ExtractKineticCueTags(string cssClass)
{
if (string.IsNullOrWhiteSpace(cssClass))
{
return Array.Empty<string>();
}
var tokens = cssClass.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var tags = new List<string>(tokens.Length);
foreach (var token in tokens)
{
if (token.StartsWith(KineticCueClassPrefix, StringComparison.Ordinal))
{
var tag = token[KineticCueClassPrefix.Length..];
if (tag.Length > 0)
{
tags.Add(tag);
}
}
}
return tags;
}
private const string KineticCueClassPrefix = "tps-";
private int GetNextPlaybackCardIndex() =>
_cards.Count == 0
? 0
: (_activeReaderCardIndex + 1) % _cards.Count;
private int BuildScaledReaderDelayMilliseconds(int rawDelayMilliseconds)
{
var safeDelay = Math.Max(MinimumReaderLoopDelayMilliseconds, rawDelayMilliseconds);
var speedRatio = _readerBaseTpsWpm / (double)_readerPlaybackSpeedWpm;
return Math.Max(
MinimumReaderLoopDelayMilliseconds,
(int)Math.Round(safeDelay * speedRatio, MidpointRounding.AwayFromZero));
}
}