-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterlinearizer.test.tsx
More file actions
1223 lines (1101 loc) · 41.5 KB
/
Copy pathInterlinearizer.test.tsx
File metadata and controls
1223 lines (1101 loc) · 41.5 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
/** @file Unit tests for components/Interlinearizer.tsx. */
/// <reference types="jest" />
/// <reference types="@testing-library/jest-dom" />
import type { SerializedVerseRef } from '@sillsdev/scripture';
import { act, render, screen } from '@testing-library/react';
import type { Book, ScriptureRef, Segment, Token } from 'interlinearizer';
import type { ReactNode } from 'react';
import { useState } from 'react';
import Interlinearizer from '../../components/Interlinearizer';
import { InterlinearNavProvider } from '../../components/InterlinearNavContext';
import type { SegmentDisplayMode } from '../../components/SegmentView';
import { RECENTER_FADE_MS } from '../../components/recenter-fade';
import { defaultScrRef, GEN_1_1_BOOK } from '../test-helpers';
import { allFalseViewOptions } from './test-helpers';
jest.mock('lucide-react', () => ({
__esModule: true,
/**
* Stub for the LocateFixed icon; renders a minimal SVG so icon-presence assertions work.
*
* @returns An SVG element with `data-testid="locate-fixed-icon"`.
*/
LocateFixed: () => <svg data-testid="locate-fixed-icon" />,
}));
/**
* Props captured from ContinuousView renders so tests can assert on what Interlinearizer passes
* down.
*/
type CapturedContinuousViewProps = {
/** The full tokenized book. */
book: Book;
/** The `Token.ref` string of the currently focused token, if any. */
focusedTokenRef: string | undefined;
/** Called when the strip changes focus via arrow nav or click. */
onFocusedTokenRefChange: (ref: string) => void;
/** Token ref → segment id lookup. */
tokenSegmentMap: ReadonlyMap<string, string>;
/** Word token ref → token lookup. */
wordTokenByRef: ReadonlyMap<string, Token & { type: 'word' }>;
};
let capturedContinuousViewProps: CapturedContinuousViewProps | undefined;
/** Props captured from SegmentView renders so tests can assert on what Interlinearizer passes down. */
type CapturedSegmentViewProps = {
/** The segment the component is asked to render. */
segment: Segment;
/** Controls whether tokens are rendered as chips or as raw baseline text. */
displayMode: SegmentDisplayMode;
/** The `Token.ref` string of the currently focused token, if any. */
focusedTokenRef: string | undefined;
/** Whether this segment corresponds to the currently active verse. */
isActive: boolean;
/** Called when the user selects a token. */
onSelect: (ref: ScriptureRef, tokenRef?: string) => void;
/** PhraseId currently hovered anywhere in the interlinearizer. */
hoveredPhraseId: string | undefined;
/** Called when the pointer enters or leaves a phrase box. */
onHoverPhrase: (phraseId: string | undefined) => void;
};
let capturedSegmentViewPropsList: CapturedSegmentViewProps[] = [];
/** Stable spy for `updatePhrase` — reset between tests via resetMocks. */
const mockUpdatePhrase = jest.fn();
jest.mock('../../components/AnalysisStore', () => ({
__esModule: true,
/**
* Pass-through provider stub that renders children directly, keeping AnalysisStore.tsx out of
* scope.
*
* @param props - Component props.
* @param props.children - Child nodes to render.
* @returns The children unchanged.
*/
AnalysisStoreProvider({ children }: Readonly<{ children: ReactNode }>) {
return children;
},
/**
* Returns a fixed empty gloss string for any token.
*
* @returns An empty string.
*/
useGloss: () => '',
/**
* Returns a no-op dispatch function.
*
* @returns A function that accepts any arguments and does nothing.
*/
useGlossDispatch: () => () => {},
/**
* Returns an empty map; cross-segment arc logic is a layout effect that no-ops in jsdom.
*
* @returns An empty `Map`.
*/
usePhraseLinkMap: () => new Map(),
usePhraseLinkByIdMap: () => new Map(),
usePhraseDispatch: () => ({
createPhrase: () => {},
updatePhrase: (...args: Parameters<typeof mockUpdatePhrase>) => mockUpdatePhrase(...args),
deletePhrase: () => {},
}),
}));
jest.mock('../../components/ContinuousView', () => ({
__esModule: true,
default: (props: CapturedContinuousViewProps) => {
capturedContinuousViewProps = props;
return (
<div data-focused-token-ref={props.focusedTokenRef ?? ''} data-testid="continuous-view" />
);
},
}));
jest.mock('../../components/SegmentView', () => ({
__esModule: true,
/**
* Named export stub for SegmentView; captures received props and renders a minimal div.
*
* @param props - The props passed by Interlinearizer.
* @param props.segment - The segment being rendered.
* @param props.isActive - Whether this segment is the active verse.
* @param props.hoveredPhraseId - PhraseId currently hovered.
* @param props.onHoverPhrase - Hover callback.
* @param props.rest - Any additional props forwarded from the parent.
* @returns A div with `data-testid="segment-view"` and the segment id.
*/
SegmentView: ({
segment,
isActive,
hoveredPhraseId,
onHoverPhrase,
...rest
}: CapturedSegmentViewProps) => {
capturedSegmentViewPropsList.push({
segment,
isActive,
hoveredPhraseId,
onHoverPhrase,
...rest,
});
return (
<div
aria-current={isActive ? 'true' : undefined}
data-testid="segment-view"
data-segment-id={segment.id}
/>
);
},
/**
* Default export stub for SegmentView; captures received props and renders a minimal div.
*
* @param props - The props passed by Interlinearizer.
* @param props.segment - The segment being rendered.
* @param props.isActive - Whether this segment is the active verse.
* @param props.hoveredPhraseId - PhraseId currently hovered.
* @param props.onHoverPhrase - Hover callback.
* @param props.rest - Any additional props forwarded from the parent.
* @returns A div with `data-testid="segment-view"` and the segment id.
*/
default: ({
segment,
isActive,
hoveredPhraseId,
onHoverPhrase,
...rest
}: CapturedSegmentViewProps) => {
capturedSegmentViewPropsList.push({
segment,
isActive,
hoveredPhraseId,
onHoverPhrase,
...rest,
});
return (
<div
aria-current={isActive ? 'true' : undefined}
data-testid="segment-view"
data-segment-id={segment.id}
/>
);
},
}));
jest.mock('../../components/controls/EditPhraseControls', () => ({
__esModule: true,
/**
* Minimal EditPhraseControls stub exposing the done button the toolbar tests assert on.
*
* @returns A stub div carrying the `done-edit-btn` test id.
*/
default: () => (
<div data-testid="edit-phrase-controls">
<button data-testid="done-edit-btn" type="button">
Done
</button>
</div>
),
}));
jest.mock('../../components/modals/UnlinkPhraseConfirm', () => ({
__esModule: true,
/**
* Minimal UnlinkPhraseConfirm stub exposing the confirm container the toolbar tests assert on.
*
* @returns A stub div carrying the `unlink-confirm` test id.
*/
default: () => <div data-testid="unlink-confirm" />,
}));
/** Pre-built Book with no segments — used by the no-verse-data test. */
const GEN_EMPTY_BOOK: Book = { id: 'GEN', bookRef: 'GEN', textVersion: 'v1', segments: [] };
/**
* Builds a GEN book with `count` single-token verses in chapter 1. Used to exercise the segment
* window's recenter fade, which only triggers when the new active verse is outside the rendered
* window — impossible with the small fixtures above.
*
* @param count - Number of verses to generate.
* @returns A {@link Book} with `count` chapter-1 segments.
*/
function makeLargeBook(count: number): Book {
const segments: Segment[] = [];
for (let v = 1; v <= count; v += 1) {
segments.push({
id: `GEN 1:${v}`,
startRef: { book: 'GEN', chapter: 1, verse: v },
endRef: { book: 'GEN', chapter: 1, verse: v },
baselineText: 'word',
tokens: [
{
ref: `GEN 1:${v}:0`,
surfaceText: 'word',
writingSystem: 'en',
type: 'word',
charStart: 0,
charEnd: 4,
},
],
});
}
return { id: 'GEN', bookRef: 'GEN', textVersion: 'v1', segments };
}
/** Book with two segments in GEN 1 — used by chapter-display tests. */
const GEN_1_MULTI_BOOK: Book = {
id: 'GEN',
bookRef: 'GEN',
textVersion: 'v1',
segments: [
{
id: 'GEN 1:1',
startRef: { book: 'GEN', chapter: 1, verse: 1 },
endRef: { book: 'GEN', chapter: 1, verse: 1 },
baselineText: 'In the beginning.',
tokens: [
{
ref: 'GEN 1:1:0',
surfaceText: 'In',
writingSystem: 'en',
type: 'word',
charStart: 0,
charEnd: 2,
},
],
},
{
id: 'GEN 1:2',
startRef: { book: 'GEN', chapter: 1, verse: 2 },
endRef: { book: 'GEN', chapter: 1, verse: 2 },
baselineText: 'And the earth.',
tokens: [
{
ref: 'GEN 1:2:0',
surfaceText: 'And',
writingSystem: 'en',
type: 'word',
charStart: 0,
charEnd: 3,
},
],
},
],
};
/**
* Two-chapter GEN book: chapter 1 has verses 1-2, chapter 2 has verses 1-2. Used to exercise the
* focus-reseed guard when the host echoes a click back at chapter granularity (verse-0 / first
* verse), which a verse-exact guard would misread as the chapter's first segment.
*/
const GEN_TWO_CHAPTER_BOOK: Book = {
id: 'GEN',
bookRef: 'GEN',
textVersion: 'v1',
segments: [1, 2].flatMap((chapter) =>
[1, 2].map((verse) => ({
id: `GEN ${chapter}:${verse}`,
startRef: { book: 'GEN', chapter, verse },
endRef: { book: 'GEN', chapter, verse },
baselineText: 'Word.',
tokens: [
{
ref: `GEN ${chapter}:${verse}:0`,
surfaceText: 'Word',
writingSystem: 'en',
type: 'word' as const,
charStart: 0,
charEnd: 4,
},
],
})),
),
};
/** GEN book whose chapter 1 opens with a verse-0 superscription segment before verse 1. */
const GEN_SUPERSCRIPTION_BOOK: Book = {
id: 'GEN',
bookRef: 'GEN',
textVersion: 'v1',
segments: [
{
id: 'GEN 1:0',
startRef: { book: 'GEN', chapter: 1, verse: 0 },
endRef: { book: 'GEN', chapter: 1, verse: 0 },
baselineText: 'A song.',
tokens: [
{
ref: 'GEN 1:0:0',
surfaceText: 'A',
writingSystem: 'en',
type: 'word',
charStart: 0,
charEnd: 1,
},
],
},
{
id: 'GEN 1:1',
startRef: { book: 'GEN', chapter: 1, verse: 1 },
endRef: { book: 'GEN', chapter: 1, verse: 1 },
baselineText: 'In the beginning.',
tokens: [
{
ref: 'GEN 1:1:0',
surfaceText: 'In',
writingSystem: 'en',
type: 'word',
charStart: 0,
charEnd: 2,
},
],
},
],
};
/**
* Wraps an `<Interlinearizer>` element in an {@link InterlinearNavProvider} so the component's
* `useInterlinearNav` call resolves. `Interlinearizer` now writes the reference through the
* context's `navigate` (which calls the scroll-group hook's setter), so navigation assertions hang
* off the `navigate` spy supplied here rather than a `setScrRef` prop.
*
* @param ui - The `<Interlinearizer>` element to wrap.
* @param navigate - Spy wired as the scroll-group hook's setter; receives the reference each
* `navigate` call writes. Defaults to a noop.
* @returns The element wrapped in a nav provider.
*/
function withNav(ui: ReactNode, navigate: (r: SerializedVerseRef) => void = () => {}): ReactNode {
const scrollGroupHook = (): [
SerializedVerseRef,
(r: SerializedVerseRef) => void,
number | undefined,
(id: number | undefined) => void,
] => [defaultScrRef, navigate, undefined, () => {}];
return (
<InterlinearNavProvider useWebViewScrollGroupScrRef={scrollGroupHook}>
{ui}
</InterlinearNavProvider>
);
}
/**
* Renders an Interlinearizer component with sensible defaults, allowing individual props to be
* overridden per test. Wrapped in an {@link InterlinearNavProvider} via {@link withNav}; `navigate`
* is the spy that captures references the component writes through the context.
*
* @param options - Partial props to merge over the defaults.
* @returns The render result from @testing-library/react.
*/
function renderInterlinearizer({
book = GEN_1_1_BOOK,
continuousScroll = false,
scrRef = defaultScrRef,
navigate = () => {},
hideInactiveLinkButtons = false,
simplifyPhrases = false,
chapterLabelInVerse = false,
showMorphology = false,
showFreeTranslation = false,
}: {
book?: Book;
continuousScroll?: boolean;
scrRef?: SerializedVerseRef;
navigate?: (r: SerializedVerseRef) => void;
hideInactiveLinkButtons?: boolean;
simplifyPhrases?: boolean;
chapterLabelInVerse?: boolean;
showMorphology?: boolean;
showFreeTranslation?: boolean;
} = {}) {
return render(
withNav(
<Interlinearizer
book={book}
continuousScroll={continuousScroll}
scrRef={scrRef}
analysisLanguage="und"
phraseMode={{ kind: 'view' }}
setPhraseMode={() => {}}
viewOptions={{
hideInactiveLinkButtons,
simplifyPhrases,
chapterLabelInVerse,
showMorphology,
showFreeTranslation,
}}
/>,
navigate,
),
);
}
beforeEach(() => {
// jsdom does not implement scrollIntoView; stub it globally so components that call it don't throw.
Element.prototype.scrollIntoView = jest.fn();
});
describe('Interlinearizer', () => {
beforeEach(() => {
capturedContinuousViewProps = undefined;
capturedSegmentViewPropsList = [];
});
it('renders a SegmentView when the tokenized book has a segment for the current reference', () => {
renderInterlinearizer();
expect(screen.getAllByTestId('segment-view')).toHaveLength(1);
});
it('shows a no-verse message when the tokenized book has no segments at all', () => {
renderInterlinearizer({ book: GEN_EMPTY_BOOK });
expect(screen.getByText(/no verse data for gen 1\./i)).toBeInTheDocument();
});
it('renders a SegmentView for every segment in the current chapter', () => {
renderInterlinearizer({ book: GEN_1_MULTI_BOOK });
expect(screen.getAllByTestId('segment-view')).toHaveLength(2);
expect(capturedSegmentViewPropsList[0].segment.id).toBe('GEN 1:1');
expect(capturedSegmentViewPropsList[1].segment.id).toBe('GEN 1:2');
});
it('passes isActive=true only to the segment matching the current verse', () => {
renderInterlinearizer({ book: GEN_1_MULTI_BOOK });
// defaultScrRef is GEN 1:1
expect(capturedSegmentViewPropsList[0].isActive).toBe(true);
expect(capturedSegmentViewPropsList[1].isActive).toBeFalsy();
});
it('renders all segments when the reference names a verse absent from the data', () => {
const missingVerseRef: SerializedVerseRef = { book: 'GEN', chapterNum: 1, verseNum: 99 };
renderInterlinearizer({ book: GEN_1_MULTI_BOOK, scrRef: missingVerseRef });
expect(screen.getAllByTestId('segment-view')).toHaveLength(2);
});
it('calls setScrRef with the segment ref when a segment fires onSelect', () => {
const mockNavigate = jest.fn();
renderInterlinearizer({ book: GEN_1_MULTI_BOOK, navigate: mockNavigate });
capturedSegmentViewPropsList[1].onSelect?.({ book: 'GEN', chapter: 1, verse: 2 });
expect(mockNavigate).toHaveBeenCalledWith({ book: 'GEN', chapterNum: 1, verseNum: 2 });
});
it('passes displayMode="baseline-text" to all SegmentViews when continuousScroll is true', () => {
renderInterlinearizer({ book: GEN_1_MULTI_BOOK, continuousScroll: true });
capturedSegmentViewPropsList.forEach((p) => expect(p.displayMode).toBe('baseline-text'));
});
it('renders ContinuousView when continuousScroll is true', () => {
renderInterlinearizer({ continuousScroll: true });
expect(screen.getByTestId('continuous-view')).toBeInTheDocument();
});
it('does not render ContinuousView when continuousScroll is false', () => {
renderInterlinearizer({ continuousScroll: false });
expect(screen.queryByTestId('continuous-view')).not.toBeInTheDocument();
});
it('renders ContinuousView above the chapter segment rows when both are present', () => {
const { container } = renderInterlinearizer({
book: GEN_1_MULTI_BOOK,
continuousScroll: true,
});
const continuousView = screen.getByTestId('continuous-view');
const allElements = Array.from(
container.querySelectorAll('[data-testid="continuous-view"], [data-testid="segment-view"]'),
);
expect(allElements[0]).toBe(continuousView);
});
it('calls setScrRef with the segment ref when a token is clicked', () => {
const mockNavigate = jest.fn();
renderInterlinearizer({
book: GEN_1_MULTI_BOOK,
navigate: mockNavigate,
});
act(() => {
capturedSegmentViewPropsList[1].onSelect?.(
{ book: 'GEN', chapter: 1, verse: 2 },
'GEN 1:2:0',
);
});
expect(mockNavigate).toHaveBeenCalledWith({ book: 'GEN', chapterNum: 1, verseNum: 2 });
});
it('writes a verse-0 reference to the host when a verse-0 token is selected', () => {
// Selecting a superscription token navigates the host to verse 0 like any other verse; the
// internal-nav marker keeps the host's chapter echo from bouncing the view (the stickiness
// exception in InterlinearNavContext). Default scrRef is GEN 1:1, so this is a real verse change.
const mockNavigate = jest.fn();
renderInterlinearizer({ book: GEN_SUPERSCRIPTION_BOOK, navigate: mockNavigate });
act(() => {
capturedSegmentViewPropsList[0].onSelect?.(
{ book: 'GEN', chapter: 1, verse: 0 },
'GEN 1:0:0',
);
});
expect(mockNavigate).toHaveBeenCalledWith({ book: 'GEN', chapterNum: 1, verseNum: 0 });
});
it('writes a verse-0 reference to the host when a verse-0 token is focused from the strip', () => {
const mockNavigate = jest.fn();
renderInterlinearizer({
book: GEN_SUPERSCRIPTION_BOOK,
continuousScroll: true,
navigate: mockNavigate,
});
if (!capturedContinuousViewProps)
throw new Error('Expected ContinuousView to have been rendered');
const { onFocusedTokenRefChange } = capturedContinuousViewProps;
act(() => {
onFocusedTokenRefChange('GEN 1:0:0');
});
expect(mockNavigate).toHaveBeenCalledWith({ book: 'GEN', chapterNum: 1, verseNum: 0 });
expect(capturedContinuousViewProps.focusedTokenRef).toBe('GEN 1:0:0');
});
it('moves the active-segment highlight to a verse-0 segment when its token is focused', () => {
renderInterlinearizer({
book: GEN_SUPERSCRIPTION_BOOK,
scrRef: { book: 'GEN', chapterNum: 1, verseNum: 1 },
});
// Active verse (1) is highlighted; the verse-0 superscription is not, yet.
const before = Object.fromEntries(
capturedSegmentViewPropsList.map((p) => [p.segment.id, p.isActive]),
);
expect(before['GEN 1:0']).toBeFalsy();
expect(before['GEN 1:1']).toBe(true);
const { onSelect } = capturedSegmentViewPropsList[0];
capturedSegmentViewPropsList = [];
act(() => {
onSelect({ book: 'GEN', chapter: 1, verse: 0 }, 'GEN 1:0:0');
});
// Focusing the superscription's token moves the active highlight onto its segment.
const after = Object.fromEntries(
capturedSegmentViewPropsList.map((p) => [p.segment.id, p.isActive]),
);
expect(after['GEN 1:0']).toBe(true);
expect(after['GEN 1:1']).toBeFalsy();
});
it('passes the clicked token through to ContinuousView as focusedTokenRef', () => {
jest.useFakeTimers();
try {
// Render in token-chip mode first so onSelect is available on SegmentView props.
const { rerender } = renderInterlinearizer({
book: GEN_1_MULTI_BOOK,
continuousScroll: false,
});
const { onSelect } = capturedSegmentViewPropsList[1];
if (typeof onSelect !== 'function') throw new Error('Expected onSelect to be a function');
act(() => {
onSelect({ book: 'GEN', chapter: 1, verse: 2 }, 'GEN 1:2:0');
});
// Switch to continuous-scroll mode so ContinuousView is rendered and its props captured. The
// strip mount is gated behind the recenter fade, so advance past it.
capturedSegmentViewPropsList = [];
rerender(
withNav(
<Interlinearizer
book={GEN_1_MULTI_BOOK}
continuousScroll
scrRef={{ book: 'GEN', chapterNum: 1, verseNum: 2 }}
analysisLanguage="und"
phraseMode={{ kind: 'view' }}
setPhraseMode={() => {}}
viewOptions={{ ...allFalseViewOptions }}
/>,
),
);
act(() => jest.advanceTimersByTime(RECENTER_FADE_MS));
if (!capturedContinuousViewProps)
throw new Error('Expected ContinuousView to have been rendered');
expect(capturedContinuousViewProps.focusedTokenRef).toBe('GEN 1:2:0');
} finally {
jest.useRealTimers();
}
});
it('updates scrRef when ContinuousView reports focus moving into a different verse', () => {
const mockNavigate = jest.fn();
renderInterlinearizer({
book: GEN_1_MULTI_BOOK,
continuousScroll: true,
navigate: mockNavigate,
});
if (!capturedContinuousViewProps)
throw new Error('Expected ContinuousView to have been rendered');
const { onFocusedTokenRefChange } = capturedContinuousViewProps;
act(() => {
// GEN 1:2:0 belongs to verse 2, which differs from the current scrRef (verse 1).
onFocusedTokenRefChange('GEN 1:2:0');
});
expect(mockNavigate).toHaveBeenCalledWith({ book: 'GEN', chapterNum: 1, verseNum: 2 });
});
it('does not echo scrRef when the focused token belongs to a different book than scrRef', () => {
// During an external book change scrRef names the new book before its data loads, so the
// mounted book (and its focused token) still belong to the previous book. The echo-back effect
// must not fire that stale book's verse back as scrRef. Here the mounted book is GEN but scrRef
// names EXO, so a GEN focus move must not call setScrRef.
const mockNavigate = jest.fn();
renderInterlinearizer({
book: GEN_1_MULTI_BOOK,
continuousScroll: true,
scrRef: { book: 'EXO', chapterNum: 1, verseNum: 1 },
navigate: mockNavigate,
});
if (!capturedContinuousViewProps)
throw new Error('Expected ContinuousView to have been rendered');
mockNavigate.mockClear();
const { onFocusedTokenRefChange } = capturedContinuousViewProps;
act(() => {
// GEN 1:2:0 is in book GEN, which differs from the current scrRef's book (EXO).
onFocusedTokenRefChange('GEN 1:2:0');
});
expect(mockNavigate).not.toHaveBeenCalled();
});
it('does not update scrRef when ContinuousView focus stays within the current verse', () => {
const mockNavigate = jest.fn();
renderInterlinearizer({
book: GEN_1_MULTI_BOOK,
continuousScroll: true,
scrRef: { book: 'GEN', chapterNum: 1, verseNum: 1 },
navigate: mockNavigate,
});
if (!capturedContinuousViewProps)
throw new Error('Expected ContinuousView to have been rendered');
mockNavigate.mockClear();
const { onFocusedTokenRefChange } = capturedContinuousViewProps;
act(() => {
onFocusedTokenRefChange('GEN 1:1:0');
});
expect(mockNavigate).not.toHaveBeenCalled();
});
it('carries the strip focus into segment view when switching off continuousScroll', () => {
jest.useFakeTimers();
try {
const { rerender } = renderInterlinearizer({
book: GEN_1_MULTI_BOOK,
continuousScroll: true,
});
if (!capturedContinuousViewProps)
throw new Error('Expected ContinuousView to have been rendered');
const { onFocusedTokenRefChange } = capturedContinuousViewProps;
act(() => {
onFocusedTokenRefChange('GEN 1:2:0');
});
// Switch to segment view — Interlinearizer should carry the strip focus over. The display mode
// is gated behind the recenter fade, so advance past it for the segments to render in
// token-chip mode with the focus applied.
capturedSegmentViewPropsList = [];
rerender(
withNav(
<Interlinearizer
book={GEN_1_MULTI_BOOK}
continuousScroll={false}
scrRef={{ book: 'GEN', chapterNum: 1, verseNum: 2 }}
analysisLanguage="und"
phraseMode={{ kind: 'view' }}
setPhraseMode={() => {}}
viewOptions={{ ...allFalseViewOptions }}
/>,
),
);
act(() => jest.advanceTimersByTime(RECENTER_FADE_MS));
const focused = capturedSegmentViewPropsList.find((p) => p.focusedTokenRef === 'GEN 1:2:0');
expect(focused).toBeDefined();
} finally {
jest.useRealTimers();
}
});
it('falls back to the active-verse first word when switching off continuousScroll with no strip position', () => {
jest.useFakeTimers();
try {
// Start in continuous mode without ContinuousView ever calling onFocusPhraseIndexChange.
const { rerender } = renderInterlinearizer({
book: GEN_1_MULTI_BOOK,
continuousScroll: true,
scrRef: { book: 'GEN', chapterNum: 1, verseNum: 1 },
});
// Switch to segment view without any strip position having been reported.
capturedSegmentViewPropsList = [];
rerender(
withNav(
<Interlinearizer
book={GEN_1_MULTI_BOOK}
continuousScroll={false}
scrRef={{ book: 'GEN', chapterNum: 1, verseNum: 1 }}
analysisLanguage="und"
phraseMode={{ kind: 'view' }}
setPhraseMode={() => {}}
viewOptions={{ ...allFalseViewOptions }}
/>,
),
);
act(() => jest.advanceTimersByTime(RECENTER_FADE_MS));
// The fallback focuses the first word of GEN 1:1 ('GEN 1:1:0').
const focused = capturedSegmentViewPropsList.find((p) => p.focusedTokenRef === 'GEN 1:1:0');
expect(focused).toBeDefined();
} finally {
jest.useRealTimers();
}
});
it('preserves an existing focusedTokenRef when switching off continuousScroll with no strip position', () => {
// Start in segment mode and focus a specific token.
const { rerender } = renderInterlinearizer({
book: GEN_1_MULTI_BOOK,
continuousScroll: false,
});
// Click a token to set focusedTokenRef to 'GEN 1:2:0'.
const { onSelect } = capturedSegmentViewPropsList[1];
if (typeof onSelect !== 'function') throw new Error('Expected onSelect to be a function');
act(() => {
onSelect({ book: 'GEN', chapter: 1, verse: 2 }, 'GEN 1:2:0');
});
// Switch to continuous mode (without strip reporting any position).
capturedSegmentViewPropsList = [];
rerender(
withNav(
<Interlinearizer
book={GEN_1_MULTI_BOOK}
continuousScroll
scrRef={defaultScrRef}
analysisLanguage="und"
phraseMode={{ kind: 'view' }}
setPhraseMode={() => {}}
viewOptions={{ ...allFalseViewOptions }}
/>,
),
);
// Switch back to segment mode — existing focusedTokenRef should be preserved.
capturedSegmentViewPropsList = [];
rerender(
withNav(
<Interlinearizer
book={GEN_1_MULTI_BOOK}
continuousScroll={false}
scrRef={defaultScrRef}
analysisLanguage="und"
phraseMode={{ kind: 'view' }}
setPhraseMode={() => {}}
viewOptions={{ ...allFalseViewOptions }}
/>,
),
);
// 'GEN 1:2:0' was already focused, so the fallback must not overwrite it.
const stillFocused = capturedSegmentViewPropsList.find(
(p) => p.focusedTokenRef === 'GEN 1:2:0',
);
expect(stillFocused).toBeDefined();
});
it('keeps the clicked token focused when the host echoes the click back as the clicked verse', () => {
// Active verse starts at GEN 1:1. Click a token in a later chapter/verse (GEN 2:2): focus is set
// to 'GEN 2:2:0'. The host echoes the navigation back as the actual clicked verse (GEN 2:2). The
// verse-exact reseed guard must see focus already in the active verse and leave the deliberately
// clicked token alone — never reseeding to the verse's (here, the only) first word from scratch.
const { rerender } = renderInterlinearizer({
book: GEN_TWO_CHAPTER_BOOK,
continuousScroll: false,
});
const clicked = capturedSegmentViewPropsList.find((p) => p.segment.id === 'GEN 2:2');
if (!clicked || typeof clicked.onSelect !== 'function') {
throw new Error('Expected an onSelect for the GEN 2:2 segment');
}
act(() => {
clicked.onSelect?.({ book: 'GEN', chapter: 2, verse: 2 }, 'GEN 2:2:0');
});
// Host delivers the echo of the actual clicked verse.
capturedSegmentViewPropsList = [];
rerender(
withNav(
<Interlinearizer
book={GEN_TWO_CHAPTER_BOOK}
continuousScroll={false}
scrRef={{ book: 'GEN', chapterNum: 2, verseNum: 2 }}
analysisLanguage="und"
phraseMode={{ kind: 'view' }}
setPhraseMode={() => {}}
viewOptions={{ ...allFalseViewOptions }}
/>,
),
);
// Focus must remain on the deliberately clicked token.
const stillFocused = capturedSegmentViewPropsList.find(
(p) => p.focusedTokenRef === 'GEN 2:2:0',
);
expect(stillFocused).toBeDefined();
});
it('reseeds focus to the first word of the active verse on an external within-chapter jump', () => {
// A genuine external jump within a long chapter (here GEN 2:1 → GEN 2:2) must move focus to the
// newly-named verse — a chapter-wide guard would wrongly strand focus on the old verse. Focus
// starts at the active verse's first word; after the jump it must point at the new verse's word.
// The segment view's focus highlight lags through the recenter fade, so advance past it.
jest.useFakeTimers();
try {
const { rerender } = renderInterlinearizer({
book: GEN_TWO_CHAPTER_BOOK,
scrRef: { book: 'GEN', chapterNum: 2, verseNum: 1 },
continuousScroll: false,
});
capturedSegmentViewPropsList = [];
rerender(
withNav(
<Interlinearizer
book={GEN_TWO_CHAPTER_BOOK}
continuousScroll={false}
scrRef={{ book: 'GEN', chapterNum: 2, verseNum: 2 }}
analysisLanguage="und"
phraseMode={{ kind: 'view' }}
setPhraseMode={() => {}}
viewOptions={{ ...allFalseViewOptions }}
/>,
),
);
act(() => jest.advanceTimersByTime(RECENTER_FADE_MS));
const reseeded = capturedSegmentViewPropsList.find((p) => p.focusedTokenRef === 'GEN 2:2:0');
expect(reseeded).toBeDefined();
} finally {
jest.useRealTimers();
}
});
it('renders an inline chapter header above the first verse of each chapter', () => {
renderInterlinearizer({
book: GEN_TWO_CHAPTER_BOOK,
scrRef: { book: 'GEN', chapterNum: 1, verseNum: 1 },
continuousScroll: false,
});
// One header per chapter, rendered by the list (not inside SegmentView) at each boundary.
expect(screen.getByText('Chapter 1')).toBeInTheDocument();
expect(screen.getByText('Chapter 2')).toBeInTheDocument();
expect(screen.queryByText('Chapter 3')).not.toBeInTheDocument();
});
it('omits inline chapter headers when chapterLabelInVerse is set', () => {
renderInterlinearizer({
book: GEN_TWO_CHAPTER_BOOK,
scrRef: { book: 'GEN', chapterNum: 1, verseNum: 1 },
continuousScroll: false,
chapterLabelInVerse: true,
});
expect(screen.queryByText('Chapter 1')).not.toBeInTheDocument();
expect(screen.queryByText('Chapter 2')).not.toBeInTheDocument();
});
it('renders the snap-to-active-verse button when segments are present', () => {
renderInterlinearizer({ book: GEN_1_MULTI_BOOK });
expect(screen.getByRole('button', { name: /scroll to active verse/i })).toBeInTheDocument();
});
it('does not render the snap-to-active-verse button when there are no segments', () => {
renderInterlinearizer({ book: GEN_EMPTY_BOOK });
expect(
screen.queryByRole('button', { name: /scroll to active verse/i }),
).not.toBeInTheDocument();
});
it('snap button fades, recenters, then scrolls the active segment to the top', () => {
jest.useFakeTimers();
try {
renderInterlinearizer({ book: GEN_1_1_BOOK });
act(() => {
screen.getByRole('button', { name: /scroll to active verse/i }).click();
});
// The button always fade-recenters (so a verse outside the window still comes into view), so the
// snap only lands after the fade timeout rebuilds the window behind the curtain.
act(() => {
jest.advanceTimersByTime(RECENTER_FADE_MS);
});
expect(Element.prototype.scrollIntoView).toHaveBeenCalledWith({
behavior: 'auto',
block: 'start',
});
} finally {
jest.useRealTimers();
}
});
it('leaves focusedTokenRef undefined when switching off continuousScroll with no strip position and no matching segment', () => {
// scrRef points to verse 99 which does not exist in GEN_1_MULTI_BOOK.
const { rerender } = renderInterlinearizer({
book: GEN_1_MULTI_BOOK,
continuousScroll: true,
scrRef: { book: 'GEN', chapterNum: 1, verseNum: 99 },
});
capturedSegmentViewPropsList = [];
rerender(
withNav(
<Interlinearizer
book={GEN_1_MULTI_BOOK}
continuousScroll={false}
scrRef={{ book: 'GEN', chapterNum: 1, verseNum: 99 }}
analysisLanguage="und"
phraseMode={{ kind: 'view' }}
setPhraseMode={() => {}}
viewOptions={{ ...allFalseViewOptions }}
/>,
),
);