-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContinuousView.test.tsx
More file actions
1477 lines (1313 loc) · 53.7 KB
/
Copy pathContinuousView.test.tsx
File metadata and controls
1477 lines (1313 loc) · 53.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
/** @file Unit tests for components/ContinuousView.tsx. */
/// <reference types="jest" />
/// <reference types="@testing-library/jest-dom" />
import { useLocalizedStrings } from '@papi/frontend/react';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { Book, PhraseAnalysisLink, Token } from 'interlinearizer';
import { useState, type ReactNode } from 'react';
import type { PhraseDispatch } from '../../components/AnalysisStore';
import ContinuousView from '../../components/ContinuousView';
import { isWordToken } from '../../types/type-guards';
import type { ViewOptions } from '../../types/view-options';
import { allFalseViewOptions, withAnalysisStore } from './test-helpers';
// ---------------------------------------------------------------------------
// AnalysisStore mock — pass-through provider so AnalysisStore.tsx stays out of scope
// ---------------------------------------------------------------------------
/**
* Stable module-level phrase-link map returned by `usePhraseLinkMap` across renders. Mutated by
* individual tests to simulate phrase membership; reset in `beforeEach`.
*/
const phraseLinkMap = new Map<string, PhraseAnalysisLink>();
const mockUsePhraseDispatch = jest.fn<jest.MockedObject<PhraseDispatch>, []>().mockReturnValue({
createPhrase: jest.fn(),
updatePhrase: jest.fn(),
deletePhrase: jest.fn(),
mergePhrases: jest.fn(),
});
jest.mock('../../components/AnalysisStore', () => ({
__esModule: true,
AnalysisStoreProvider({ children }: Readonly<{ children: ReactNode; analysisLanguage: string }>) {
return children;
},
useGloss: () => '',
useGlossDispatch: () => () => {},
usePhraseLinkMap: () => phraseLinkMap,
usePhraseLinkByIdMap: () =>
new Map([...new Set(phraseLinkMap.values())].map((l) => [l.analysisId, l])),
usePhraseLinkForToken: () => undefined,
usePhraseDispatch: () => mockUsePhraseDispatch(),
usePhraseGloss: () => '',
usePhraseGlossDispatch: () => () => {},
}));
// The shared hover-preview state is covered in full by usePhraseHoverState.test.ts. Stub it here so
// ContinuousView's tests don't redundantly re-exercise the hook's internals; the view only forwards
// its handlers, which a no-op stub satisfies.
const mockCandidateTokenRefs = { current: new Set<string>() };
jest.mock('../../hooks/usePhraseHoverState', () => ({
__esModule: true,
usePhraseHoverState: () => ({
hoveredGroupKey: undefined,
setHoveredGroupKey: () => {},
candidateTokenRefs: mockCandidateTokenRefs.current,
setCandidateTokenRefs: () => {},
splitFreeTokenRefs: new Set<string>(),
handleSplitHoverChange: () => {},
handleHoverSplitFreeTokens: () => {},
clearAll: () => {},
}),
}));
jest.mock('../../components/TokenChip');
/**
* Spy invoked once per rendered link icon (mounted, whether suppressed or not). Rendering a span
* with data attributes encoding the token refs lets DOM queries check suppression state via the
* parent wrapper's style. Cleared in `beforeEach`.
*/
const tokenLinkIconSpy = jest.fn();
jest.mock('../../components/TokenLinkIcon', () => ({
__esModule: true,
default: (props: Readonly<{ prevToken?: { ref: string }; nextToken?: { ref: string } }>) => {
tokenLinkIconSpy(props);
return (
<span
data-testid="mock-link-icon"
data-prev-ref={props.prevToken?.ref}
data-next-ref={props.nextToken?.ref}
/>
);
},
}));
jest.mock('../../components/ArcOverlay', () => ({
__esModule: true,
// Surface the props ContinuousView derives and forwards (hoveredPhraseId, candidatePhraseIds) as
// data attributes so DOM queries can assert on values that otherwise only live inside ArcOverlay.
default: ({
onArcSplit,
hoveredPhraseId,
candidatePhraseIds,
}: Readonly<{
onArcSplit: (phraseId: string, splitAfterTokenRef: string) => void;
hoveredPhraseId: string | undefined;
candidatePhraseIds: ReadonlySet<string>;
}>) => (
<button
type="button"
data-testid="arc-split-btn"
data-hovered-phrase-id={hoveredPhraseId ?? ''}
data-candidate-phrase-ids={[...candidatePhraseIds].join(',')}
onClick={() => onArcSplit('phrase-1', 'tok-0')}
>
split
</button>
),
}));
jest.mock('../../components/PhraseBox', () => ({
__esModule: true,
default: ({
groupKey,
isFocused = false,
onFocusPhrase,
tokens,
phraseLink,
showGlossInput = true,
}: Readonly<{
groupKey: string;
isFocused: boolean;
onFocusPhrase: (groupKey: string) => void;
tokens: (Token & { type: 'word' })[];
phraseMode: unknown;
setPhraseMode: unknown;
phraseLink: { analysisId: string } | undefined;
showGlossInput?: boolean;
}>) => (
<button
data-focus-state={isFocused ? 'focused' : 'default'}
data-phrase-box="true"
data-phrase-id={phraseLink?.analysisId}
data-show-gloss={showGlossInput}
onClick={() => onFocusPhrase(groupKey)}
type="button"
>
{tokens.map((t) => (
<span key={t.ref}>{t.surfaceText}</span>
))}
</button>
),
}));
// ---------------------------------------------------------------------------
// Test fixtures
// ---------------------------------------------------------------------------
/** Factory for a single-chapter book with two segments each having two word tokens. */
function makeBook(overrides?: Partial<Book>): Book {
return {
id: 'GEN',
bookRef: 'GEN',
textVersion: '1',
segments: [
{
id: 'GEN 1:1',
startRef: { book: 'GEN', chapter: 1, verse: 1 },
endRef: { book: 'GEN', chapter: 1, verse: 1 },
baselineText: 'In the',
tokens: [
{
ref: 'tok-0',
surfaceText: 'In',
writingSystem: 'en',
type: 'word',
charStart: 0,
charEnd: 2,
},
{
ref: 'tok-1',
surfaceText: 'the',
writingSystem: 'en',
type: 'word',
charStart: 3,
charEnd: 6,
},
],
},
{
id: 'GEN 1:2',
startRef: { book: 'GEN', chapter: 1, verse: 2 },
endRef: { book: 'GEN', chapter: 1, verse: 2 },
baselineText: 'beginning God',
tokens: [
{
ref: 'tok-2',
surfaceText: 'beginning',
writingSystem: 'en',
type: 'word',
charStart: 0,
charEnd: 9,
},
{
ref: 'tok-3',
surfaceText: 'God',
writingSystem: 'en',
type: 'word',
charStart: 10,
charEnd: 13,
},
],
},
],
...overrides,
};
}
/** Builds a two-chapter Book fixture used to exercise cross-chapter navigation. */
function makeTwoChapterBook(): Book {
return {
id: 'GEN',
bookRef: 'GEN',
textVersion: '1',
segments: [
{
id: 'GEN 1:1',
startRef: { book: 'GEN', chapter: 1, verse: 1 },
endRef: { book: 'GEN', chapter: 1, verse: 1 },
baselineText: 'Alpha',
tokens: [
{
ref: 'ch1-tok-0',
surfaceText: 'Alpha',
writingSystem: 'en',
type: 'word',
charStart: 0,
charEnd: 5,
},
],
},
{
id: 'GEN 2:1',
startRef: { book: 'GEN', chapter: 2, verse: 1 },
endRef: { book: 'GEN', chapter: 2, verse: 1 },
baselineText: 'Beta',
tokens: [
{
ref: 'ch2-tok-0',
surfaceText: 'Beta',
writingSystem: 'en',
type: 'word',
charStart: 0,
charEnd: 4,
},
],
},
],
};
}
/** Builds a Book with exactly one word token in one segment. */
function makeSingleTokenBook(): Book {
return {
id: 'GEN',
bookRef: 'GEN',
textVersion: '1',
segments: [
{
id: 'GEN 1:1',
startRef: { book: 'GEN', chapter: 1, verse: 1 },
endRef: { book: 'GEN', chapter: 1, verse: 1 },
baselineText: 'Word',
tokens: [
{
ref: 'tok-only',
surfaceText: 'Word',
writingSystem: 'en',
type: 'word',
charStart: 0,
charEnd: 4,
},
],
},
],
};
}
/** A book whose GEN 1:1 segment has word tokens and whose GEN 1:2 segment has only punctuation. */
function makeMixedBook(): Book {
return {
id: 'GEN',
bookRef: 'GEN',
textVersion: '1',
segments: [
{
id: 'GEN 1:1',
startRef: { book: 'GEN', chapter: 1, verse: 1 },
endRef: { book: 'GEN', chapter: 1, verse: 1 },
baselineText: 'In the',
tokens: [
{
ref: 'mix-tok-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: '.',
tokens: [
{
ref: 'mix-punct-0',
surfaceText: '.',
writingSystem: 'en',
type: 'punctuation',
charStart: 0,
charEnd: 1,
},
],
},
],
};
}
/** Builds a Book whose only token is punctuation. */
function makeWordFreeBook(): Book {
return {
id: 'GEN',
bookRef: 'GEN',
textVersion: '1',
segments: [
{
id: 'GEN 1:1',
startRef: { book: 'GEN', chapter: 1, verse: 1 },
endRef: { book: 'GEN', chapter: 1, verse: 1 },
baselineText: '...',
tokens: [
{
ref: 'wf-punct-0',
surfaceText: '.',
writingSystem: 'en',
type: 'punctuation',
charStart: 0,
charEnd: 1,
},
],
},
],
};
}
/** Builds a Book with `count` word tokens spread across one segment per token. */
function makeLargeBook(count: number): Book {
return {
id: 'GEN',
bookRef: 'GEN',
textVersion: '1',
segments: Array.from({ length: count }, (_, i) => ({
id: `GEN 1:${i + 1}`,
startRef: { book: 'GEN', chapter: 1, verse: i + 1 },
endRef: { book: 'GEN', chapter: 1, verse: i + 1 },
baselineText: `word${i}`,
tokens: [
{
ref: `large-tok-${i}`,
surfaceText: `word${i}`,
writingSystem: 'en',
type: 'word',
charStart: 0,
charEnd: String(`word${i}`).length,
},
],
})),
};
}
// ---------------------------------------------------------------------------
const scrollIntoViewMock = jest.fn();
/**
* Builds the lookup maps that ContinuousView's parent supplies, derived from a Book.
*
* @param book - The book to scan.
* @returns The token-segment-id lookup and word-token-ref lookup.
*/
function buildLookups(book: Book): {
tokenSegmentMap: ReadonlyMap<string, string>;
tokenDocOrder: ReadonlyMap<string, number>;
wordTokenByRef: ReadonlyMap<string, Token & { type: 'word' }>;
} {
const tokenSegmentMap = new Map<string, string>();
const tokenDocOrder = new Map<string, number>();
const wordTokenByRef = new Map<string, Token & { type: 'word' }>();
let wordIndex = 0;
book.segments.forEach((seg) => {
seg.tokens.forEach((t) => {
tokenSegmentMap.set(t.ref, seg.id);
if (isWordToken(t)) {
wordTokenByRef.set(t.ref, t);
tokenDocOrder.set(t.ref, wordIndex);
wordIndex += 1;
}
});
});
return { tokenSegmentMap, tokenDocOrder, wordTokenByRef };
}
/**
* Minimal required props for ContinuousView. Spread into render calls so tests only need to
* override what they actually care about. The lookup maps are derived from `book` so they always
* agree with what's rendered.
*
* @param book - The book the test will render with.
* @param overrides - Optional prop overrides.
* @returns A complete ContinuousView props object.
*/
function requiredProps(
book: Book,
overrides?: { focusedTokenRef?: string | undefined },
): {
book: Book;
editPhraseSegmentId: string | undefined;
focusedTokenRef: string | undefined;
onFocusedTokenRefChange: jest.Mock;
phraseMode: { kind: 'view' };
setPhraseMode: jest.Mock;
tokenSegmentMap: ReadonlyMap<string, string>;
tokenDocOrder: ReadonlyMap<string, number>;
wordTokenByRef: ReadonlyMap<string, Token & { type: 'word' }>;
viewOptions: ViewOptions;
} {
const { tokenSegmentMap, tokenDocOrder, wordTokenByRef } = buildLookups(book);
return {
book,
editPhraseSegmentId: undefined,
focusedTokenRef: overrides?.focusedTokenRef,
onFocusedTokenRefChange: jest.fn(),
phraseMode: { kind: 'view' },
setPhraseMode: jest.fn(),
tokenSegmentMap,
tokenDocOrder,
wordTokenByRef,
viewOptions: { ...allFalseViewOptions },
};
}
beforeAll(() => {
// jsdom does not implement scrollIntoView.
HTMLElement.prototype.scrollIntoView = scrollIntoViewMock;
});
beforeEach(() => {
jest
.mocked(useLocalizedStrings)
.mockImplementation((keys: readonly string[]) => [
Object.fromEntries(keys.map((k) => [k, k])),
false,
]);
scrollIntoViewMock.mockClear();
tokenLinkIconSpy.mockClear();
phraseLinkMap.clear();
mockUsePhraseDispatch.mockReturnValue({
createPhrase: jest.fn(),
updatePhrase: jest.fn(),
deletePhrase: jest.fn(),
mergePhrases: jest.fn(),
});
mockCandidateTokenRefs.current = new Set();
});
// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------
describe('ContinuousView initial render', () => {
it('renders all tokens from all segments as a flat list', () => {
const book = makeBook();
render(<ContinuousView {...requiredProps(book)} />, withAnalysisStore);
expect(screen.getByText('In')).toBeInTheDocument();
expect(screen.getByText('the')).toBeInTheDocument();
expect(screen.getByText('beginning')).toBeInTheDocument();
expect(screen.getByText('God')).toBeInTheDocument();
});
it('does not render any verse label or segment separator', () => {
const book = makeBook();
render(<ContinuousView {...requiredProps(book)} />, withAnalysisStore);
expect(screen.queryByText('1:1')).not.toBeInTheDocument();
expect(screen.queryByText('1:2')).not.toBeInTheDocument();
expect(screen.queryByText('GEN 1:1')).not.toBeInTheDocument();
});
it('renders a Previous token button and a Next token button', () => {
const book = makeBook();
render(<ContinuousView {...requiredProps(book)} />, withAnalysisStore);
expect(screen.getByRole('button', { name: 'Previous token' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Next token' })).toBeInTheDocument();
});
it('renders a non-word token via InertTokenChip within the strip', () => {
const book = makeMixedBook();
render(<ContinuousView {...requiredProps(book)} />, withAnalysisStore);
expect(screen.getByText('In')).toBeInTheDocument();
expect(screen.getByText('.')).toBeInTheDocument();
});
it('renders without crashing when book has no word tokens', () => {
const book = makeWordFreeBook();
render(<ContinuousView {...requiredProps(book)} />, withAnalysisStore);
expect(screen.getByText('.')).toBeInTheDocument();
});
it('notifies the parent of the initially-focused token on mount when no focus prop is set', () => {
const book = makeBook();
const props = requiredProps(book);
render(<ContinuousView {...props} />, withAnalysisStore);
expect(props.onFocusedTokenRefChange).toHaveBeenCalledWith('tok-0');
});
it('does not notify the parent on mount when focusedTokenRef is already set', () => {
const book = makeBook();
const props = requiredProps(book, { focusedTokenRef: 'tok-1' });
render(<ContinuousView {...props} />, withAnalysisStore);
expect(props.onFocusedTokenRefChange).not.toHaveBeenCalled();
});
it('marks the phrase containing focusedTokenRef as focused', () => {
const book = makeBook();
render(
<ContinuousView {...requiredProps(book, { focusedTokenRef: 'tok-2' })} />,
withAnalysisStore,
);
const focusedBox = screen.getByText('beginning').closest('[data-phrase-box="true"]');
expect(focusedBox).toHaveAttribute('data-focus-state', 'focused');
});
it('falls back to focusedTokenRef when the lagging displayed ref is from another book', () => {
// During a book change displayFocusedTokenRef lags by one fade, so it briefly names a token from
// the previous book that no longer exists in the new book. The focus must follow the live
// focusedTokenRef (the new book's active verse) rather than collapsing to the book's first phrase.
const book = makeBook();
const { rerender } = render(
<ContinuousView {...requiredProps(book, { focusedTokenRef: 'tok-2' })} />,
withAnalysisStore,
);
// Swap to a different book whose token refs share none of the previous book's. The displayed ref
// ('tok-2') is now absent; focusedTokenRef points at the new book's *second* phrase.
const otherBook: Book = {
id: 'MAT',
bookRef: 'MAT',
textVersion: '1',
segments: [
{
id: 'MAT 1:1',
startRef: { book: 'MAT', chapter: 1, verse: 1 },
endRef: { book: 'MAT', chapter: 1, verse: 1 },
baselineText: 'Alpha',
tokens: [
{
ref: 'mat-tok-0',
surfaceText: 'Alpha',
writingSystem: 'en',
type: 'word',
charStart: 0,
charEnd: 5,
},
],
},
{
id: 'MAT 1:2',
startRef: { book: 'MAT', chapter: 1, verse: 2 },
endRef: { book: 'MAT', chapter: 1, verse: 2 },
baselineText: 'Beta',
tokens: [
{
ref: 'mat-tok-1',
surfaceText: 'Beta',
writingSystem: 'en',
type: 'word',
charStart: 0,
charEnd: 4,
},
],
},
],
};
scrollIntoViewMock.mockClear();
rerender(<ContinuousView {...requiredProps(otherBook, { focusedTokenRef: 'mat-tok-1' })} />);
// The scroll target is resolved through focusPhraseIndex, which falls back to focusedTokenRef
// ('mat-tok-1', the second phrase) rather than collapsing to phrase 0. So the element scrolled
// into view is the one containing "Beta", never "Alpha".
const scrolledTexts = scrollIntoViewMock.mock.contexts.map((el) =>
el instanceof HTMLElement ? el.textContent : undefined,
);
expect(scrolledTexts.some((t) => t?.includes('Beta'))).toBe(true);
expect(scrolledTexts.some((t) => t?.includes('Alpha'))).toBe(false);
});
});
// ---------------------------------------------------------------------------
// Click → focus change
// ---------------------------------------------------------------------------
describe('ContinuousView focus changes', () => {
it('notifies the parent when an out-of-focus phrase box is clicked', async () => {
const book = makeBook();
const props = requiredProps(book, { focusedTokenRef: 'tok-0' });
render(<ContinuousView {...props} />, withAnalysisStore);
const clickedPhraseBox = screen.getByText('beginning').closest('[data-phrase-box="true"]');
if (!clickedPhraseBox) throw new Error('Expected phrase box wrapper for token');
await userEvent.click(clickedPhraseBox);
expect(props.onFocusedTokenRefChange).toHaveBeenCalledWith('tok-2');
});
it('does not notify the parent when clicking the already-focused phrase box', async () => {
const book = makeBook();
const props = requiredProps(book, { focusedTokenRef: 'tok-0' });
render(<ContinuousView {...props} />, withAnalysisStore);
const firstPhraseBox = screen.getByText('In').closest('[data-phrase-box="true"]');
if (!firstPhraseBox) throw new Error('Expected phrase box wrapper for token');
await userEvent.click(firstPhraseBox);
expect(props.onFocusedTokenRefChange).not.toHaveBeenCalled();
});
it('does not notify the parent when clicking the group of an already-focused non-first token', async () => {
// Group tok-0 and tok-1 into one phrase box (keyed by tok-0), then focus tok-1 — the second
// token of the group, as a segment-view click on a middle token would. Clicking the box must
// stay a no-op even though its groupKey (tok-0) differs from focusedTokenRef (tok-1).
const phraseLink: PhraseAnalysisLink = {
analysisId: 'phrase-1',
status: 'approved',
tokens: [
{ tokenRef: 'tok-0', surfaceText: 'In' },
{ tokenRef: 'tok-1', surfaceText: 'the' },
],
};
phraseLinkMap.set('tok-0', phraseLink);
phraseLinkMap.set('tok-1', phraseLink);
const book = makeBook();
const props = requiredProps(book, { focusedTokenRef: 'tok-1' });
render(<ContinuousView {...props} />, withAnalysisStore);
const groupedBox = screen.getByText('In').closest('[data-phrase-box="true"]');
if (!groupedBox) throw new Error('Expected phrase box wrapper for grouped tokens');
await userEvent.click(groupedBox);
expect(props.onFocusedTokenRefChange).not.toHaveBeenCalled();
});
it('notifies the parent when clicking a phrase box while nothing is focused', async () => {
const book = makeBook();
const props = requiredProps(book, { focusedTokenRef: undefined });
render(<ContinuousView {...props} />, withAnalysisStore);
const firstPhraseBox = screen.getByText('In').closest('[data-phrase-box="true"]');
if (!firstPhraseBox) throw new Error('Expected phrase box wrapper for token');
await userEvent.click(firstPhraseBox);
expect(props.onFocusedTokenRefChange).toHaveBeenCalledWith('tok-0');
});
});
// ---------------------------------------------------------------------------
// Arrow disabled states
// ---------------------------------------------------------------------------
describe('ContinuousView arrow disabled states', () => {
it('disables the prev arrow when focus is on the first phrase', () => {
const book = makeBook();
render(
<ContinuousView {...requiredProps(book, { focusedTokenRef: 'tok-0' })} />,
withAnalysisStore,
);
expect(screen.getByRole('button', { name: 'Previous token' })).toBeDisabled();
});
it('enables the prev arrow when focus is on a non-first phrase', () => {
const book = makeBook();
render(
<ContinuousView {...requiredProps(book, { focusedTokenRef: 'tok-2' })} />,
withAnalysisStore,
);
expect(screen.getByRole('button', { name: 'Previous token' })).toBeEnabled();
});
it('disables the next arrow when focus is on the last phrase', () => {
const book = makeBook();
render(
<ContinuousView {...requiredProps(book, { focusedTokenRef: 'tok-3' })} />,
withAnalysisStore,
);
expect(screen.getByRole('button', { name: 'Next token' })).toBeDisabled();
});
it('enables the next arrow when focus is on a non-last phrase', () => {
const book = makeBook();
render(
<ContinuousView {...requiredProps(book, { focusedTokenRef: 'tok-0' })} />,
withAnalysisStore,
);
expect(screen.getByRole('button', { name: 'Next token' })).toBeEnabled();
});
it('disables both arrows when the book has a single token', () => {
const book = makeSingleTokenBook();
render(
<ContinuousView {...requiredProps(book, { focusedTokenRef: 'tok-only' })} />,
withAnalysisStore,
);
expect(screen.getByRole('button', { name: 'Previous token' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'Next token' })).toBeDisabled();
});
it('disables both arrows when the book has no word tokens', () => {
const book = makeWordFreeBook();
render(<ContinuousView {...requiredProps(book)} />, withAnalysisStore);
expect(screen.getByRole('button', { name: 'Previous token' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'Next token' })).toBeDisabled();
});
});
// ---------------------------------------------------------------------------
// Arrow nav
// ---------------------------------------------------------------------------
describe('ContinuousView arrow navigation', () => {
it('notifies the parent of the next phrase ref when Next is clicked', async () => {
const book = makeBook();
const props = requiredProps(book, { focusedTokenRef: 'tok-0' });
render(<ContinuousView {...props} />, withAnalysisStore);
await userEvent.click(screen.getByRole('button', { name: 'Next token' }));
expect(props.onFocusedTokenRefChange).toHaveBeenCalledWith('tok-1');
});
it('notifies the parent of the previous phrase ref when Previous is clicked', async () => {
const book = makeBook();
const props = requiredProps(book, { focusedTokenRef: 'tok-1' });
render(<ContinuousView {...props} />, withAnalysisStore);
await userEvent.click(screen.getByRole('button', { name: 'Previous token' }));
expect(props.onFocusedTokenRefChange).toHaveBeenCalledWith('tok-0');
});
it('crosses verse boundaries via the Next arrow', async () => {
const book = makeBook();
const props = requiredProps(book, { focusedTokenRef: 'tok-1' });
render(<ContinuousView {...props} />, withAnalysisStore);
await userEvent.click(screen.getByRole('button', { name: 'Next token' }));
expect(props.onFocusedTokenRefChange).toHaveBeenCalledWith('tok-2');
});
it('crosses chapter boundaries via the Next arrow', async () => {
const book = makeTwoChapterBook();
const props = requiredProps(book, { focusedTokenRef: 'ch1-tok-0' });
render(<ContinuousView {...props} />, withAnalysisStore);
await userEvent.click(screen.getByRole('button', { name: 'Next token' }));
expect(props.onFocusedTokenRefChange).toHaveBeenCalledWith('ch2-tok-0');
});
it('advances two groups on rapid double-click before re-render', async () => {
const book = makeBook();
const props = requiredProps(book, { focusedTokenRef: 'tok-0' });
render(<ContinuousView {...props} />, withAnalysisStore);
const next = screen.getByRole('button', { name: 'Next token' });
await userEvent.click(next);
await userEvent.click(next);
expect(props.onFocusedTokenRefChange).toHaveBeenNthCalledWith(1, 'tok-1');
expect(props.onFocusedTokenRefChange).toHaveBeenNthCalledWith(2, 'tok-2');
});
it('steps from the externally-imposed focus, not the stale pending index, after an external change interrupts an in-flight internal nav', async () => {
// Sequence: an external nav (tok-3) starts its fade while tok-1 is still displayed; the user
// clicks Next during the fade (internal nav in flight — this parent never echoes it); then a
// second external change lands back on the still-displayed tok-1. Because that value equals the
// displayed ref, the focus-change effect early-returns without clearing the in-flight marker,
// so only the render-phase external-override detection resyncs the pending index. Without it,
// the next step would advance from the stale pending index (group 2 → tok-1) instead of the
// externally-imposed position (group 1 → tok-0).
const book = makeBook();
const props = requiredProps(book, { focusedTokenRef: 'tok-1' });
const { rerender } = render(<ContinuousView {...props} />, withAnalysisStore);
// External nav while idle: the fade starts; the displayed focus is still tok-1.
rerender(<ContinuousView {...props} focusedTokenRef="tok-3" />);
// Internal nav in flight: Next from the displayed group (tok-1) emits tok-2.
await userEvent.click(screen.getByRole('button', { name: 'Next token' }));
expect(props.onFocusedTokenRefChange).toHaveBeenNthCalledWith(1, 'tok-2');
// The parent imposes an external position (not the tok-2 echo) that matches the displayed ref.
rerender(<ContinuousView {...props} focusedTokenRef="tok-1" />);
await userEvent.click(screen.getByRole('button', { name: 'Previous token' }));
expect(props.onFocusedTokenRefChange).toHaveBeenNthCalledWith(2, 'tok-0');
});
});
// ---------------------------------------------------------------------------
// Scroll behavior
// ---------------------------------------------------------------------------
describe('ContinuousView scroll behavior', () => {
it('calls scrollIntoView on initial mount', () => {
const book = makeBook();
render(<ContinuousView {...requiredProps(book)} />, withAnalysisStore);
expect(scrollIntoViewMock).toHaveBeenCalledWith({
behavior: 'auto',
block: 'nearest',
inline: 'center',
});
});
it('uses instant scroll when focusedTokenRef changes externally', () => {
const book = makeBook();
const props = requiredProps(book, { focusedTokenRef: 'tok-0' });
const { rerender } = render(<ContinuousView {...props} />, withAnalysisStore);
scrollIntoViewMock.mockClear();
act(() => {
jest.useFakeTimers();
});
rerender(<ContinuousView {...{ ...props, focusedTokenRef: 'tok-3' }} />);
act(() => {
jest.advanceTimersByTime(600);
jest.useRealTimers();
});
expect(scrollIntoViewMock).toHaveBeenCalledWith(expect.objectContaining({ behavior: 'auto' }));
});
it('snaps the link slots (no transition) during an external jump so they do not slide after the fade-in', () => {
const book = makeBook();
const props = requiredProps(book, { focusedTokenRef: 'tok-0' });
const { container, rerender } = render(<ContinuousView {...props} />, withAnalysisStore);
act(() => {
jest.useFakeTimers();
});
// External nav into the other verse: the active segment commits instantly behind the fade, so
// the slots must snap to their new widths rather than animating (which would slide the boxes for
// ~200ms after the strip fades back in).
rerender(<ContinuousView {...{ ...props, focusedTokenRef: 'tok-3' }} />);
const slotWrapper = container.querySelector('[data-link-slot] > span');
if (!(slotWrapper instanceof HTMLElement)) throw new Error('Expected a link-slot wrapper span');
expect(slotWrapper.style.transitionDuration).toBe('0ms');
act(() => {
jest.advanceTimersByTime(600);
jest.useRealTimers();
});
});
it('smooth-scrolls for internal nav once the parent echoes the ref back synchronously', async () => {
// The smooth-scroll path requires the displayed focus to already agree with the prop and the
// strip to be visible when the scroll effect runs. That only happens when a real (stateful)
// parent reflects the internal ref change straight back, so simulate one here rather than
// driving the ref via a jest.fn() that never updates the prop.
const book = makeBook();
const { tokenSegmentMap, tokenDocOrder, wordTokenByRef } = buildLookups(book);
function Parent() {
const [ref, setRef] = useState<string | undefined>('tok-0');
return (
<ContinuousView
book={book}
editPhraseSegmentId={undefined}
focusedTokenRef={ref}
onFocusedTokenRefChange={setRef}
phraseMode={{ kind: 'view' }}
setPhraseMode={jest.fn()}
tokenSegmentMap={tokenSegmentMap}
tokenDocOrder={tokenDocOrder}
wordTokenByRef={wordTokenByRef}
viewOptions={{ ...allFalseViewOptions }}
/>
);
}
render(<Parent />, withAnalysisStore);
// Wait for the initial-load requestAnimationFrame fade-in to complete (strip becomes visible)
// before navigating; the smooth path is only taken while the strip is already visible.
await waitFor(() =>
expect(screen.getByTestId('strip-fade-wrapper').className).toContain('tw:opacity-100'),
);
scrollIntoViewMock.mockClear();
await userEvent.click(screen.getByRole('button', { name: 'Next token' }));
await waitFor(() =>
expect(scrollIntoViewMock).toHaveBeenCalledWith(
expect.objectContaining({ behavior: 'smooth' }),
),
);
});
/**
* Renders ContinuousView with `hideInactiveLinkButtons` on, focused at tok-1 (the last phrase of
* GEN 1:1) so a single Next step crosses into GEN 1:2. The slot between tok-0 and tok-1 lives in
* GEN 1:1 and shows a link icon only while that segment is active, so it's a clean probe for
* whether the active-segment relayout has committed.
*
* @returns A predicate reporting whether that in-segment link icon mounted in the latest render.
*/
function renderHideInactiveCrossing(): () => boolean {
const book = makeBook();
const { tokenSegmentMap, tokenDocOrder, wordTokenByRef } = buildLookups(book);
function Parent() {
const [ref, setRef] = useState<string | undefined>('tok-1');
return (
<ContinuousView
book={book}
editPhraseSegmentId={undefined}
focusedTokenRef={ref}
onFocusedTokenRefChange={setRef}
phraseMode={{ kind: 'view' }}
setPhraseMode={jest.fn()}
tokenSegmentMap={tokenSegmentMap}
tokenDocOrder={tokenDocOrder}
wordTokenByRef={wordTokenByRef}
viewOptions={{ ...allFalseViewOptions, hideInactiveLinkButtons: true }}
/>
);
}
render(<Parent />, withAnalysisStore);
// Returns true when the tok-0/tok-1 link icon is rendered AND its wrapper is visible (not
// suppressed). Icons stay mounted but are hidden via opacity:0 when suppressed, so
// we query the DOM wrapper's style rather than spy calls.
return () => {
const icon = document.querySelector<HTMLElement>(
'[data-prev-ref="tok-0"][data-next-ref="tok-1"]',
);
if (!icon) return false;
return icon.parentElement?.style.opacity !== '0';
};
}
it('keeps the old segment’s link icon until the scroll settles, then drops it on scrollend', async () => {
// With hideInactiveLinkButtons on, crossing a boundary wants to add/remove icons — but doing so
// mid-scroll shifts every box and breaks the smooth glide. The view defers the active-segment
// switch until the scroll settles (signaled by the container's `scrollend`), so the old segment
// keeps its icon during the animation and only loses it once the scroll finishes.
const inSegmentIconMounted = renderHideInactiveCrossing();
await waitFor(() =>
expect(screen.getByTestId('strip-fade-wrapper').className).toContain('tw:opacity-100'),
);
// GEN 1:1 is active, so its in-segment slot (between tok-0 and tok-1) shows a link icon.
expect(inSegmentIconMounted()).toBe(true);
// Step into GEN 1:2. The GEN 1:1 link icon must remain while the scroll animates (no relayout).
tokenLinkIconSpy.mockClear();
fireEvent.click(screen.getByRole('button', { name: 'Next token' }));
expect(inSegmentIconMounted()).toBe(true);
// The scroll settles → `scrollend` fires on the clipping viewport (the element that actually
// scrolls) → the active segment switches to GEN 1:2 and the GEN 1:1 icon disappears (its
// in-segment slot is now inactive and suppressed).
tokenLinkIconSpy.mockClear();
act(() => {
screen.getByTestId('strip-scroll-viewport').dispatchEvent(new Event('scrollend'));
});
expect(inSegmentIconMounted()).toBe(false);
});
it('also commits when scrollend fires on the inner content row', async () => {
// The listener is attached to both the viewport and the content row, so whichever the browser
// treats as the scroller settles the relayout. Covers the content-row path.