-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhraseBox.test.tsx
More file actions
1185 lines (1057 loc) · 46 KB
/
Copy pathPhraseBox.test.tsx
File metadata and controls
1185 lines (1057 loc) · 46 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 PhraseBox component. */
/// <reference types="jest" />
/// <reference types="@testing-library/jest-dom" />
import { useLocalizedStrings } from '@papi/frontend/react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactElement } from 'react';
import type { PhraseAnalysisLink, Token } from 'interlinearizer';
import { AnalysisStoreProvider } from '../../components/AnalysisStore';
import { PhraseBox } from '../../components/PhraseBox';
import {
PhraseStripProvider,
type PhraseStripContextValue,
} from '../../components/PhraseStripContext';
import { makePhraseStripContext, makeWordToken } from '../test-helpers';
/** Stable mock fns for AnalysisStore hooks — reset between tests via resetMocks. */
const mockUseGloss = jest.fn<string, [string]>().mockReturnValue('');
const mockUseGlossDispatch = jest.fn().mockReturnValue(jest.fn());
const mockUsePhraseLinkForToken = jest.fn().mockReturnValue(undefined);
const mockUsePhraseDispatch = jest.fn().mockReturnValue({
createPhrase: jest.fn(),
updatePhrase: jest.fn(),
deletePhrase: jest.fn(),
});
const mockUsePhraseGloss = jest.fn<string, [string]>().mockReturnValue('');
const mockUsePhraseGlossDispatch = jest.fn().mockReturnValue(jest.fn());
jest.mock('../../components/AnalysisStore', () => ({
__esModule: true,
/**
* Pass-through AnalysisStoreProvider stub.
*
* @param props - Component props.
* @param props.children - Children to render.
* @returns Children unchanged.
*/
AnalysisStoreProvider({ children }: Readonly<{ children: import('react').ReactNode }>) {
return children;
},
useGloss: (...args: Parameters<typeof mockUseGloss>) => mockUseGloss(...args),
useGlossDispatch: () => mockUseGlossDispatch(),
usePhraseLinkForToken: (...args: Parameters<typeof mockUsePhraseLinkForToken>) =>
mockUsePhraseLinkForToken(...args),
usePhraseDispatch: () => mockUsePhraseDispatch(),
usePhraseGloss: (...args: Parameters<typeof mockUsePhraseGloss>) => mockUsePhraseGloss(...args),
usePhraseGlossDispatch: () => mockUsePhraseGlossDispatch(),
useReportGlossEditing: () => {},
}));
jest.mock('../../components/TokenChip', () => {
/**
* Minimal TokenChip stub that renders the token's surface text, a controlled gloss input, and an
* optional remove button. Lets PhraseBox tests verify gloss-forwarding, focus callbacks, and
* token-removal interactions without pulling in the real TokenChip implementation.
*
* @param props - Component props.
* @param props.onFocus - Called when the gloss input receives focus.
* @param props.token - The word token to render.
* @param props.isSplitFree - When true, marks the chip as a would-be-free token.
* @param props.onRemove - Called when the remove button is clicked; omitted for edge tokens.
* @param props.showMorphology - Exposed as a data attribute so tests can verify every PhraseBox
* render path forwards the strip-wide morphology toggle. When true, also renders a
* `data-morpheme-gloss` input before the main gloss input, mirroring the real chip's DOM order
* so focus-routing tests exercise the morpheme-exclusion selector.
* @returns A span containing the surface text, a gloss input, and an optional remove button.
*/
function MockTokenChip({
onFocus,
token,
isSplitFree,
onRemove,
showMorphology,
}: Readonly<{
onFocus?: () => void;
token: Token;
isSplitFree?: boolean;
onRemove?: () => void;
showMorphology?: boolean;
}>) {
const gloss = mockUseGloss(token.ref);
const dispatch = mockUseGlossDispatch();
return (
<span
data-testid={`token-${token.ref}`}
data-split-free={isSplitFree ? 'true' : 'false'}
data-show-morphology={showMorphology ? 'true' : 'false'}
>
{token.surfaceText}
{showMorphology && (
<input
aria-label={`Gloss for morpheme ${token.surfaceText}`}
data-morpheme-gloss="true"
/>
)}
<input
aria-label={`Gloss for ${token.surfaceText}`}
onChange={(e) => dispatch(token.ref, token.surfaceText, e.target.value)}
onFocus={onFocus}
value={gloss}
/>
{onRemove && (
<button aria-label={`Remove ${token.surfaceText}`} onClick={onRemove} type="button">
×
</button>
)}
</span>
);
}
/**
* Minimal InertTokenChip stub rendering the token's surface text.
*
* @param props - Component props.
* @param props.token - The non-word token to render.
* @returns A span containing the surface text.
*/
function MockInertTokenChip({ token }: Readonly<{ token: Token }>) {
return <span data-testid={`inert-${token.ref}`}>{token.surfaceText}</span>;
}
return { __esModule: true, default: MockTokenChip, InertTokenChip: MockInertTokenChip };
});
jest.mock('../../components/modals/UnlinkPhraseConfirm', () => ({
__esModule: true,
/**
* Minimal UnlinkPhraseConfirm stub that renders confirm/cancel buttons.
*
* @param props - Component props.
* @param props.setPhraseMode - Called to exit confirm-unlink mode.
* @returns A stub div with confirm and cancel buttons.
*/
default: ({
setPhraseMode,
}: Readonly<{ phraseId: string; setPhraseMode: (m: unknown) => void }>) => (
<div data-testid="unlink-confirm">
<button
data-testid="unlink-confirm-yes"
onClick={() => setPhraseMode({ kind: 'view' })}
type="button"
>
Unlink
</button>
<button
data-testid="unlink-confirm-cancel"
onClick={() => setPhraseMode({ kind: 'view' })}
type="button"
>
Cancel
</button>
</div>
),
}));
/** Pre-built test token */
const TEST_TOKEN = {
ref: 'token-1',
surfaceText: 'Hello',
writingSystem: 'en',
type: 'word',
charStart: 0,
charEnd: 5,
} satisfies Token;
/** Second test token */
const TEST_TOKEN_2 = {
ref: 'token-2',
surfaceText: 'World',
writingSystem: 'en',
type: 'word',
charStart: 6,
charEnd: 11,
} satisfies Token;
/** Punctuation token rendered between the two word tokens of a phrase. */
const TEST_PUNCT: Token = {
ref: 'punct-1',
surfaceText: ',',
writingSystem: 'en',
type: 'punctuation',
charStart: 5,
charEnd: 6,
};
/**
* An approved phrase link fixture used by phrase-mode tests. Includes TEST_TOKEN so
* `usePhraseLinkForToken` returns this link when mocked.
*/
const TEST_PHRASE_LINK: PhraseAnalysisLink = {
analysisId: 'phrase-1',
status: 'approved',
tokens: [
{ tokenRef: 'token-1', surfaceText: 'Hello' },
{ tokenRef: 'token-2', surfaceText: 'World' },
],
};
/** Shared props shape used by the helper function. */
type PhraseBoxTestProps = {
isFocused: boolean;
groupKey: string;
onFocusPhrase: (groupKey: string) => void;
tokens: (Token & { type: 'word' })[];
phraseLink: undefined;
};
/**
* Minimal required props for PhraseBox. Spread into render calls so tests only need to override
* what they actually care about.
*
* @returns An object containing all required PhraseBox props set to no-op stubs.
*/
function requiredProps(): PhraseBoxTestProps {
return {
isFocused: false,
groupKey: 'test-group',
onFocusPhrase: jest.fn(),
tokens: [TEST_TOKEN],
phraseLink: undefined,
};
}
/**
* Renders a `PhraseBox` wrapped in both the analysis store and strip-context providers. Strip-wide
* state (phrase mode, edit context, hover callbacks) now comes from `PhraseStripContext`, so tests
* pass those as `context` overrides rather than as props.
*
* @param ui - The `PhraseBox` element to render.
* @param context - Partial strip-context overrides (phraseMode, edit context, hover callbacks).
* @returns The Testing Library render result.
*/
function renderBox(ui: ReactElement, context: Partial<PhraseStripContextValue> = {}) {
return render(
<AnalysisStoreProvider analysisLanguage="und">
<PhraseStripProvider value={makePhraseStripContext(context)}>{ui}</PhraseStripProvider>
</AnalysisStoreProvider>,
);
}
describe('PhraseBox', () => {
beforeEach(() => {
// Restore key-as-value behavior cleared by resetMocks: true, so the gloss placeholder resolves.
jest
.mocked(useLocalizedStrings)
.mockImplementation((keys: readonly string[]) => [
Object.fromEntries(keys.map((k) => [k, k])),
false,
]);
mockUseGloss.mockReturnValue('');
mockUseGlossDispatch.mockReturnValue(jest.fn());
mockUsePhraseGloss.mockReturnValue('');
mockUsePhraseGlossDispatch.mockReturnValue(jest.fn());
mockUsePhraseLinkForToken.mockReturnValue(undefined);
mockUsePhraseDispatch.mockReturnValue({
createPhrase: jest.fn(),
updatePhrase: jest.fn(),
deletePhrase: jest.fn(),
});
});
it('renders the box as a non-label div so clicks are not forwarded to the first labelable control', () => {
renderBox(<PhraseBox {...requiredProps()} />);
const phraseBox = document.querySelector('[data-phrase-box="true"]');
expect(phraseBox?.tagName).toBe('DIV');
});
it('renders one TokenChip per token in the tokens array', () => {
renderBox(<PhraseBox {...requiredProps()} tokens={[TEST_TOKEN, TEST_TOKEN_2]} />);
expect(screen.getByTestId('token-token-1')).toBeInTheDocument();
expect(screen.getByTestId('token-token-2')).toBeInTheDocument();
});
it('clicking the outer container focuses the first gloss input', async () => {
renderBox(<PhraseBox {...requiredProps()} tokens={[TEST_TOKEN, TEST_TOKEN_2]} />);
const phraseBox = document.querySelector('[data-phrase-box="true"]');
await userEvent.click(phraseBox ?? document.body);
expect(screen.getByRole('textbox', { name: 'Gloss for Hello' })).toHaveFocus();
});
it('forwards box-click focus with preventScroll so the list never realigns under the click', async () => {
const focusSpy = jest.spyOn(HTMLElement.prototype, 'focus');
renderBox(<PhraseBox {...requiredProps()} tokens={[TEST_TOKEN, TEST_TOKEN_2]} />);
const phraseBox = document.querySelector('[data-phrase-box="true"]');
await userEvent.click(phraseBox ?? document.body);
// The clicked box is already on screen; the browser's default scroll-focused-input-into-view
// would realign the segment list (the first input can sit on another wrapped row), so the
// forwarded focus must opt out of scrolling.
expect(focusSpy).toHaveBeenCalledWith({ preventScroll: true });
});
it('clicking a nested non-chip element inside the box also focuses the first gloss input', async () => {
const onFocusPhrase = jest.fn();
renderBox(
<PhraseBox
{...requiredProps()}
onFocusPhrase={onFocusPhrase}
tokens={[TEST_TOKEN, TEST_TOKEN_2]}
/>,
);
// The token-row wrapper span is a descendant of the box container, not the container itself, so
// the old `target === currentTarget` guard ignored clicks on it. Such clicks must still focus the
// phrase (forwarding to the first gloss input, which fires onFocusPhrase) rather than doing
// nothing — otherwise the click fell through to the segment background and focused the wrong
// phrase.
const tokenRow = document.querySelector('[data-phrase-box="true"] .tw\\:phrase-token-row');
if (!tokenRow) throw new Error('Expected a nested token-row span inside the phrase box');
await userEvent.click(tokenRow);
expect(screen.getByRole('textbox', { name: 'Gloss for Hello' })).toHaveFocus();
expect(onFocusPhrase).toHaveBeenCalledWith('test-group');
});
it('clicking the box with morphology shown focuses the token gloss input, not the preceding morpheme gloss input', async () => {
const onFocusPhrase = jest.fn();
renderBox(
<PhraseBox
{...requiredProps()}
onFocusPhrase={onFocusPhrase}
tokens={[TEST_TOKEN, TEST_TOKEN_2]}
/>,
{ showMorphology: true },
);
const phraseBox = document.querySelector('[data-phrase-box="true"]');
await userEvent.click(phraseBox ?? document.body);
// Morpheme gloss inputs precede the token gloss input in DOM order; the box-click handler must
// skip them — only the token gloss input fires onFocus → onFocusPhrase.
expect(screen.getByRole('textbox', { name: 'Gloss for Hello' })).toHaveFocus();
expect(onFocusPhrase).toHaveBeenCalledWith('test-group');
});
it('Enter on the box container with morphology shown focuses the token gloss input, not the morpheme gloss input', async () => {
renderBox(<PhraseBox {...requiredProps()} />, { showMorphology: true });
const box = document.querySelector('[data-phrase-box="true"]');
expect(box).not.toBeNull();
if (box instanceof HTMLElement) box.focus();
await userEvent.keyboard('{Enter}');
expect(screen.getByRole('textbox', { name: 'Gloss for Hello' })).toHaveFocus();
expect(screen.getByRole('textbox', { name: 'Gloss for morpheme Hello' })).not.toHaveFocus();
});
it('applies focused border and background when isFocused is true', () => {
renderBox(<PhraseBox {...requiredProps()} isFocused />);
const phraseBox = document.querySelector('[data-phrase-box="true"]');
expect(phraseBox).toHaveAttribute('data-focus-state', 'focused');
expect(phraseBox).toHaveClass('tw:phrase-focused');
});
it('applies default border and background when isFocused is false', () => {
renderBox(<PhraseBox {...requiredProps()} isFocused={false} />);
const phraseBox = document.querySelector('[data-phrase-box="true"]');
expect(phraseBox).toHaveAttribute('data-focus-state', 'default');
expect(phraseBox).toHaveClass('tw:phrase-dimmed');
});
it('reddens only the chips whose refs are in splitFreeTokenRefs, leaving the box border neutral', () => {
renderBox(
<PhraseBox
{...requiredProps()}
tokens={[TEST_TOKEN, TEST_TOKEN_2]}
splitFreeTokenRefs={new Set(['token-2'])}
/>,
);
// Only one of the two tokens would become free, so the box border stays neutral and just the
// affected chip is flagged.
const phraseBox = document.querySelector('[data-phrase-box="true"]');
expect(phraseBox).not.toHaveClass('tw:phrase-destructive');
expect(screen.getByTestId('token-token-1')).toHaveAttribute('data-split-free', 'false');
expect(screen.getByTestId('token-token-2')).toHaveAttribute('data-split-free', 'true');
});
it('reddens both chips (not the box) for a multi-token box where every token would become free', () => {
renderBox(
<PhraseBox
{...requiredProps()}
tokens={[TEST_TOKEN, TEST_TOKEN_2]}
splitFreeTokenRefs={new Set(['token-1', 'token-2'])}
/>,
);
// A 2-token phrase splits into two free tokens; each is shown on its own chip, never as a
// whole-box border (that would draw a single border around both rather than per token).
const phraseBox = document.querySelector('[data-phrase-box="true"]');
expect(phraseBox).not.toHaveClass('tw:phrase-destructive');
expect(screen.getByTestId('token-token-1')).toHaveAttribute('data-split-free', 'true');
expect(screen.getByTestId('token-token-2')).toHaveAttribute('data-split-free', 'true');
});
it('reddens the whole box (not the chip) for a lone single-token fragment that would become free', () => {
renderBox(
<PhraseBox
{...requiredProps()}
tokens={[TEST_TOKEN]}
splitFreeTokenRefs={new Set(['token-1'])}
/>,
);
// A single-token fragment (e.g. one run of a discontiguous phrase) reddens at the box level;
// per-chip flagging is suppressed so the border isn't drawn twice.
const phraseBox = document.querySelector('[data-phrase-box="true"]');
expect(phraseBox).toHaveClass('tw:phrase-destructive');
expect(screen.getByTestId('token-token-1')).toHaveAttribute('data-split-free', 'false');
});
it('phrase box does not override cursor on gap areas', () => {
renderBox(<PhraseBox {...requiredProps()} isFocused />);
const phraseBox = document.querySelector('[data-phrase-box="true"]');
expect(phraseBox).not.toHaveClass('tw:cursor-text');
});
it('renders tokens in the order they appear in the tokens array', () => {
renderBox(<PhraseBox {...requiredProps()} tokens={[TEST_TOKEN, TEST_TOKEN_2]} />);
const tokens = document.querySelectorAll('[data-testid^="token-"]');
expect(tokens[0]).toHaveAttribute('data-testid', 'token-token-1');
expect(tokens[1]).toHaveAttribute('data-testid', 'token-token-2');
});
it('passes the gloss for each token from the store', () => {
mockUseGloss.mockImplementation((ref) => (ref === 'token-1' ? 'hello' : 'world'));
renderBox(<PhraseBox {...requiredProps()} tokens={[TEST_TOKEN, TEST_TOKEN_2]} />);
expect(screen.getByRole('textbox', { name: 'Gloss for Hello' })).toHaveValue('hello');
expect(screen.getByRole('textbox', { name: 'Gloss for World' })).toHaveValue('world');
});
it('shows an empty string when the token id is absent from the store', () => {
renderBox(<PhraseBox {...requiredProps()} />);
expect(screen.getByRole('textbox', { name: 'Gloss for Hello' })).toHaveValue('');
});
it('updates the store when a gloss input changes', async () => {
const spy = jest.fn();
mockUseGlossDispatch.mockReturnValue(spy);
renderBox(<PhraseBox {...requiredProps()} />);
await userEvent.type(screen.getByRole('textbox', { name: 'Gloss for Hello' }), 'hi');
expect(spy).toHaveBeenCalledTimes(2);
expect(spy).toHaveBeenNthCalledWith(1, 'token-1', 'Hello', 'h');
expect(spy).toHaveBeenNthCalledWith(2, 'token-1', 'Hello', 'i');
});
it('calls onFocusPhrase with groupKey when a gloss input receives focus', async () => {
const handleFocus = jest.fn();
renderBox(<PhraseBox {...requiredProps()} groupKey="my-group" onFocusPhrase={handleFocus} />);
await userEvent.click(screen.getByRole('textbox', { name: 'Gloss for Hello' }));
expect(handleFocus).toHaveBeenCalledTimes(1);
expect(handleFocus).toHaveBeenCalledWith('my-group');
});
it('hides phrase gloss input when showGlossInput is false', () => {
mockUsePhraseLinkForToken.mockReturnValue(TEST_PHRASE_LINK);
renderBox(
<PhraseBox {...requiredProps()} phraseLink={TEST_PHRASE_LINK} showGlossInput={false} />,
);
expect(screen.queryByTestId('phrase-gloss-input')).not.toBeInTheDocument();
});
it('shows phrase gloss input when showGlossInput is true (default)', () => {
mockUsePhraseLinkForToken.mockReturnValue(TEST_PHRASE_LINK);
renderBox(<PhraseBox {...requiredProps()} phraseLink={TEST_PHRASE_LINK} />);
expect(screen.getByTestId('phrase-gloss-input')).toBeInTheDocument();
});
it('shows edit and unlink buttons when phraseLink is set and mode is view', () => {
mockUsePhraseLinkForToken.mockReturnValue(TEST_PHRASE_LINK);
renderBox(<PhraseBox {...requiredProps()} phraseLink={TEST_PHRASE_LINK} />);
expect(screen.getByTestId('edit-phrase-btn')).toBeInTheDocument();
expect(screen.getByTestId('unlink-phrase-btn')).toBeInTheDocument();
});
it('does not show edit/unlink buttons when phraseLink is undefined', () => {
renderBox(<PhraseBox {...requiredProps()} phraseLink={undefined} />);
expect(screen.queryByTestId('edit-phrase-btn')).not.toBeInTheDocument();
expect(screen.queryByTestId('unlink-phrase-btn')).not.toBeInTheDocument();
});
it('clicking edit sets phraseMode to edit for this phrase', async () => {
mockUsePhraseLinkForToken.mockReturnValue(TEST_PHRASE_LINK);
const setPhraseMode = jest.fn();
renderBox(<PhraseBox {...requiredProps()} phraseLink={TEST_PHRASE_LINK} />, {
setPhraseMode,
});
await userEvent.click(screen.getByTestId('edit-phrase-btn'));
expect(setPhraseMode).toHaveBeenCalledWith({
kind: 'edit',
phraseId: 'phrase-1',
originalTokens: TEST_PHRASE_LINK.tokens,
});
});
it('clicking unlink sets phraseMode to confirm-unlink', async () => {
mockUsePhraseLinkForToken.mockReturnValue(TEST_PHRASE_LINK);
const setPhraseMode = jest.fn();
renderBox(<PhraseBox {...requiredProps()} phraseLink={TEST_PHRASE_LINK} />, {
setPhraseMode,
});
await userEvent.click(screen.getByTestId('unlink-phrase-btn'));
expect(setPhraseMode).toHaveBeenCalledWith({ kind: 'confirm-unlink', phraseId: 'phrase-1' });
});
it('renders punctuation between tokens in view mode', () => {
renderBox(
<PhraseBox
{...requiredProps()}
tokens={[TEST_TOKEN, TEST_TOKEN_2]}
punctuationBetween={[[TEST_PUNCT]]}
/>,
);
expect(screen.getByText(',')).toBeInTheDocument();
});
it('renders punctuation between tokens in edit-target mode', () => {
mockUsePhraseLinkForToken.mockReturnValue(TEST_PHRASE_LINK);
renderBox(
<PhraseBox
{...requiredProps()}
phraseLink={TEST_PHRASE_LINK}
tokens={[TEST_TOKEN, TEST_TOKEN_2]}
punctuationBetween={[[TEST_PUNCT]]}
/>,
{
phraseMode: { kind: 'edit', phraseId: 'phrase-1', originalTokens: TEST_PHRASE_LINK.tokens },
},
);
expect(screen.getByTestId('inert-punct-1')).toBeInTheDocument();
});
it('renders punctuation between tokens for a non-edit-target box during edit mode', () => {
renderBox(
<PhraseBox
{...requiredProps()}
tokens={[TEST_TOKEN, TEST_TOKEN_2]}
punctuationBetween={[[TEST_PUNCT]]}
/>,
// Edit mode is active for a different phrase, so this free box renders via the fallback path.
{ phraseMode: { kind: 'edit', phraseId: 'other-phrase', originalTokens: [] } },
);
expect(screen.getByTestId('inert-punct-1')).toBeInTheDocument();
});
it('forwards showMorphology to chips in a non-edit-target box during edit mode', () => {
renderBox(
<PhraseBox {...requiredProps()} tokens={[TEST_TOKEN, TEST_TOKEN_2]} />,
// Edit mode is active for a different phrase, so this free box renders via the fallback
// path; its chips must keep their morpheme rows rather than collapsing while editing.
{
phraseMode: { kind: 'edit', phraseId: 'other-phrase', originalTokens: [] },
showMorphology: true,
},
);
expect(screen.getByTestId('token-token-1')).toHaveAttribute('data-show-morphology', 'true');
expect(screen.getByTestId('token-token-2')).toHaveAttribute('data-show-morphology', 'true');
});
it('renders punctuation between tokens in confirm-unlink mode', () => {
mockUsePhraseLinkForToken.mockReturnValue(TEST_PHRASE_LINK);
renderBox(
<PhraseBox
{...requiredProps()}
phraseLink={TEST_PHRASE_LINK}
tokens={[TEST_TOKEN, TEST_TOKEN_2]}
punctuationBetween={[[TEST_PUNCT]]}
/>,
{ phraseMode: { kind: 'confirm-unlink', phraseId: 'phrase-1' } },
);
expect(screen.getByText(',')).toBeInTheDocument();
});
it('omits data-last-token-ref for a free (non-phrase) box in confirm-unlink mode', () => {
mockUsePhraseLinkForToken.mockReturnValue(undefined);
renderBox(
// A free box (no phraseLink) still renders dimmed during another phrase's confirm-unlink.
<PhraseBox {...requiredProps()} tokens={[TEST_TOKEN, TEST_TOKEN_2]} />,
{ phraseMode: { kind: 'confirm-unlink', phraseId: 'other-phrase' } },
);
const box = document.querySelector('[data-phrase-box="true"]');
expect(box).not.toHaveAttribute('data-last-token-ref');
});
it('renders phrase normally (not replaced) when phraseMode is confirm-unlink for this phrase', () => {
mockUsePhraseLinkForToken.mockReturnValue(TEST_PHRASE_LINK);
renderBox(<PhraseBox {...requiredProps()} phraseLink={TEST_PHRASE_LINK} />, {
phraseMode: { kind: 'confirm-unlink', phraseId: 'phrase-1' },
});
// UnlinkPhraseConfirm is now rendered at toolbar level, not inside PhraseBox.
expect(screen.queryByTestId('unlink-confirm')).not.toBeInTheDocument();
expect(document.querySelector('[data-phrase-box="true"]')).toBeInTheDocument();
});
it('hides edit/unlink buttons in confirm-unlink mode', () => {
mockUsePhraseLinkForToken.mockReturnValue(TEST_PHRASE_LINK);
renderBox(<PhraseBox {...requiredProps()} phraseLink={TEST_PHRASE_LINK} />, {
phraseMode: { kind: 'confirm-unlink', phraseId: 'other-phrase' },
});
expect(screen.queryByTestId('edit-phrase-btn')).not.toBeInTheDocument();
expect(screen.queryByTestId('unlink-phrase-btn')).not.toBeInTheDocument();
expect(screen.queryByTestId('unlink-confirm')).not.toBeInTheDocument();
});
it('renders as selected when token is in edit target phrase', () => {
mockUsePhraseLinkForToken.mockReturnValue(TEST_PHRASE_LINK);
renderBox(<PhraseBox {...requiredProps()} phraseLink={TEST_PHRASE_LINK} />, {
phraseMode: {
kind: 'edit',
phraseId: 'phrase-1',
originalTokens: TEST_PHRASE_LINK.tokens,
},
});
const phraseBox = document.querySelector('[data-phrase-box="true"]');
expect(phraseBox).toHaveClass('tw:border-ring');
});
it('calls updatePhrase when clicked in edit mode for the target phrase', async () => {
const updatePhraseSpy = jest.fn();
mockUsePhraseLinkForToken.mockReturnValue(TEST_PHRASE_LINK);
mockUsePhraseDispatch.mockReturnValue({
createPhrase: jest.fn(),
updatePhrase: updatePhraseSpy,
deletePhrase: jest.fn(),
});
renderBox(<PhraseBox {...requiredProps()} phraseLink={TEST_PHRASE_LINK} />, {
phraseMode: {
kind: 'edit',
phraseId: 'phrase-1',
originalTokens: TEST_PHRASE_LINK.tokens,
},
});
await userEvent.click(document.querySelector('[role="button"]') ?? document.body);
expect(updatePhraseSpy).toHaveBeenCalledWith(
'phrase-1',
TEST_PHRASE_LINK.tokens.filter((t) => t.tokenRef !== 'token-1'),
);
});
it('does not remove the last remaining token of the edited phrase (would empty it)', async () => {
// A single-token phrase: removing its only token would leave zero tokens — the early-return
// guard keeps the phrase alive so the user can add more tokens before committing.
const singleTokenLink: PhraseAnalysisLink = {
analysisId: 'phrase-1',
status: 'approved',
tokens: [{ tokenRef: 'token-1', surfaceText: 'Hello' }],
};
mockUsePhraseLinkForToken.mockReturnValue(singleTokenLink);
const updatePhraseSpy = jest.fn();
mockUsePhraseDispatch.mockReturnValue({
createPhrase: jest.fn(),
updatePhrase: updatePhraseSpy,
deletePhrase: jest.fn(),
});
renderBox(<PhraseBox {...requiredProps()} phraseLink={singleTokenLink} />, {
phraseMode: {
kind: 'edit',
phraseId: 'phrase-1',
originalTokens: singleTokenLink.tokens,
},
});
await userEvent.click(document.querySelector('[role="button"]') ?? document.body);
expect(updatePhraseSpy).not.toHaveBeenCalled();
});
it('does not call updatePhrase in edit mode when token is not in the target phrase', async () => {
// token-1 belongs to TEST_PHRASE_LINK (phrase-1), but phraseMode targets a different phrase
mockUsePhraseLinkForToken.mockReturnValue(TEST_PHRASE_LINK);
const updatePhraseSpy = jest.fn();
mockUsePhraseDispatch.mockReturnValue({
createPhrase: jest.fn(),
updatePhrase: updatePhraseSpy,
deletePhrase: jest.fn(),
});
renderBox(<PhraseBox {...requiredProps()} phraseLink={TEST_PHRASE_LINK} />, {
phraseMode: { kind: 'edit', phraseId: 'other-phrase', originalTokens: [] },
});
await userEvent.click(document.querySelector('[role="button"]') ?? document.body);
expect(updatePhraseSpy).not.toHaveBeenCalled();
});
it('adds a token to an existing phrase in edit mode when token is not already in the phrase', async () => {
// token-1 is free (not in any phrase); editPhraseTokens provides the current phrase token list
const existingPhraseTokens: PhraseAnalysisLink['tokens'] = [
{ tokenRef: 'token-2', surfaceText: 'World' },
];
mockUsePhraseLinkForToken.mockReturnValue(undefined);
const updatePhraseSpy = jest.fn();
mockUsePhraseDispatch.mockReturnValue({
createPhrase: jest.fn(),
updatePhrase: updatePhraseSpy,
deletePhrase: jest.fn(),
});
renderBox(<PhraseBox {...requiredProps()} phraseLink={undefined} />, {
editPhraseTokens: existingPhraseTokens,
phraseMode: { kind: 'edit', phraseId: 'phrase-2', originalTokens: existingPhraseTokens },
});
await userEvent.click(document.querySelector('[role="button"]') ?? document.body);
expect(updatePhraseSpy).toHaveBeenCalledWith('phrase-2', [
{ tokenRef: 'token-2', surfaceText: 'World' },
{ tokenRef: 'token-1', surfaceText: 'Hello' },
]);
});
it('splits a discontiguous phrase at the last intra-box boundary in document order even when the stored token list is scrambled', async () => {
// Phrase displayed as [A,C,D,E] (A discontiguous, [C,D,E] a contiguous run) but STORED out of
// document order — the bug that frees the wrong tokens. The split must use document order, so
// clicking the last intra-box boundary (D|E) frees E and keeps [A,C,D].
const phraseLink: PhraseAnalysisLink = {
analysisId: 'phrase-x',
status: 'approved',
tokens: [
{ tokenRef: 'A', surfaceText: 'A' },
{ tokenRef: 'E', surfaceText: 'E' },
{ tokenRef: 'D', surfaceText: 'D' },
{ tokenRef: 'C', surfaceText: 'C' },
],
};
const docOrder = new Map([
['A', 0],
['C', 1],
['D', 2],
['E', 3],
]);
mockUsePhraseLinkForToken.mockReturnValue(phraseLink);
const updatePhraseSpy = jest.fn();
const createPhraseSpy = jest.fn();
const deletePhraseSpy = jest.fn();
mockUsePhraseDispatch.mockReturnValue({
createPhrase: createPhraseSpy,
updatePhrase: updatePhraseSpy,
deletePhrase: deletePhraseSpy,
});
renderBox(
<PhraseBox
{...requiredProps()}
isHighlighted
phraseLink={phraseLink}
tokens={[makeWordToken('C'), makeWordToken('D'), makeWordToken('E')]}
/>,
{ tokenDocOrder: docOrder },
);
const unlinkBtns = screen.getAllByTestId('token-unlink-btn');
// Click the LAST intra-box button (boundary between D and E in document order).
await userEvent.click(unlinkBtns[unlinkBtns.length - 1]);
// Expect: phrase shrinks to [A,C,D] (document order), E freed — not the scrambled stored order.
expect(updatePhraseSpy).toHaveBeenCalledWith('phrase-x', [
{ tokenRef: 'A', surfaceText: 'A' },
{ tokenRef: 'C', surfaceText: 'C' },
{ tokenRef: 'D', surfaceText: 'D' },
]);
expect(createPhraseSpy).not.toHaveBeenCalled();
});
it('hovering an intra-phrase unlink button reports the would-be-free tokens to onHoverSplitFreeTokens', async () => {
// Splitting a two-token phrase leaves both halves length-1, so both tokens would become free.
// The intra-phrase icon must forward that preview up so the parent can redden the chips.
const phraseLink: PhraseAnalysisLink = {
analysisId: 'phrase-x',
status: 'approved',
tokens: [
{ tokenRef: 'A', surfaceText: 'A' },
{ tokenRef: 'B', surfaceText: 'B' },
],
};
const docOrder = new Map([
['A', 0],
['B', 1],
]);
mockUsePhraseLinkForToken.mockReturnValue(phraseLink);
const onHoverSplitFreeTokens = jest.fn();
renderBox(
<PhraseBox
{...requiredProps()}
isHighlighted
phraseLink={phraseLink}
tokens={[makeWordToken('A'), makeWordToken('B')]}
/>,
{ tokenDocOrder: docOrder, onHoverSplitFreeTokens },
);
const unlinkBtn = screen.getByTestId('token-unlink-btn');
await userEvent.hover(unlinkBtn);
expect(onHoverSplitFreeTokens).toHaveBeenCalledWith(['A', 'B']);
await userEvent.unhover(unlinkBtn);
expect(onHoverSplitFreeTokens).toHaveBeenLastCalledWith(undefined);
});
it('clicking an inline unlink button does not pop out any other token (no label click-forwarding)', async () => {
// The phrase box used to be a <label>, which forwards a click on any descendant to the box's
// first labelable control — the first token's remove-✕ — firing a phantom pop-out. With a plain
// <div>, clicking the unlink button between B and C must split there and never call deletePhrase
// (no token popped out) nor produce an updatePhrase that drops an unrelated token.
const phraseLink: PhraseAnalysisLink = {
analysisId: 'phrase-x',
status: 'approved',
tokens: [
{ tokenRef: 'A', surfaceText: 'A' },
{ tokenRef: 'B', surfaceText: 'B' },
{ tokenRef: 'C', surfaceText: 'C' },
{ tokenRef: 'D', surfaceText: 'D' },
],
};
const docOrder = new Map([
['A', 0],
['B', 1],
['C', 2],
['D', 3],
]);
mockUsePhraseLinkForToken.mockReturnValue(phraseLink);
const updatePhraseSpy = jest.fn();
const deletePhraseSpy = jest.fn();
mockUsePhraseDispatch.mockReturnValue({
createPhrase: jest.fn(),
updatePhrase: updatePhraseSpy,
deletePhrase: deletePhraseSpy,
});
renderBox(
<PhraseBox
{...requiredProps()}
isHighlighted
phraseLink={phraseLink}
tokens={[makeWordToken('A'), makeWordToken('B'), makeWordToken('C'), makeWordToken('D')]}
/>,
{ tokenDocOrder: docOrder },
);
// Click the B|C unlink button (second intra-box boundary). Both halves are length 2, so the
// split shrinks the phrase to [A,B] and creates [C,D]; crucially nothing is popped out.
const unlinkBtns = screen.getAllByTestId('token-unlink-btn');
await userEvent.click(unlinkBtns[1]);
expect(deletePhraseSpy).not.toHaveBeenCalled();
expect(updatePhraseSpy).toHaveBeenCalledTimes(1);
expect(updatePhraseSpy).toHaveBeenCalledWith('phrase-x', [
{ tokenRef: 'A', surfaceText: 'A' },
{ tokenRef: 'B', surfaceText: 'B' },
]);
});
it('inserts an added token in document order when tokenDocOrder places it before existing tokens', async () => {
// token-1 (the rendered free token) sits before token-2 in the document, so adding it to a
// phrase that already contains token-2 must produce [token-1, token-2], not [token-2, token-1].
const existingPhraseTokens: PhraseAnalysisLink['tokens'] = [
{ tokenRef: 'token-2', surfaceText: 'World' },
];
mockUsePhraseLinkForToken.mockReturnValue(undefined);
const updatePhraseSpy = jest.fn();
mockUsePhraseDispatch.mockReturnValue({
createPhrase: jest.fn(),
updatePhrase: updatePhraseSpy,
deletePhrase: jest.fn(),
});
renderBox(<PhraseBox {...requiredProps()} phraseLink={undefined} />, {
editPhraseTokens: existingPhraseTokens,
phraseMode: { kind: 'edit', phraseId: 'phrase-2', originalTokens: existingPhraseTokens },
tokenDocOrder: new Map([
['token-1', 0],
['token-2', 1],
]),
});
await userEvent.click(document.querySelector('[role="button"]') ?? document.body);
expect(updatePhraseSpy).toHaveBeenCalledWith('phrase-2', [
{ tokenRef: 'token-1', surfaceText: 'Hello' },
{ tokenRef: 'token-2', surfaceText: 'World' },
]);
});
it('does nothing in edit mode when token is free (no phrase link)', async () => {
// token is not in any phrase — tokenPhraseLinkFromStore returns undefined
// phraseMode targets some other phrase
mockUsePhraseLinkForToken.mockReturnValue(undefined);
const updatePhraseSpy = jest.fn();
mockUsePhraseDispatch.mockReturnValue({
createPhrase: jest.fn(),
updatePhrase: updatePhraseSpy,
deletePhrase: jest.fn(),
});
renderBox(<PhraseBox {...requiredProps()} phraseLink={undefined} />, {
phraseMode: { kind: 'edit', phraseId: 'phrase-1', originalTokens: [] },
});
await userEvent.click(document.querySelector('[role="button"]') ?? document.body);
expect(updatePhraseSpy).not.toHaveBeenCalled();
});
it('calls Enter key on the box container to focus the first gloss input', async () => {
renderBox(<PhraseBox {...requiredProps()} />);
const box = document.querySelector('[data-phrase-box="true"]');
expect(box).not.toBeNull();
// Focus the box container, then press Enter → the keydown handler forwards focus to the first
// gloss input. Asserting toHaveFocus makes the test fail if the Enter branch of
// focusFirstGlossOnSelfKeyDown is broken or removed.
if (box instanceof HTMLElement) box.focus();
await userEvent.keyboard('{Enter}');
expect(screen.getByRole('textbox', { name: 'Gloss for Hello' })).toHaveFocus();
});
it('pops out a middle token from a 3+ token phrase in view mode (updatePhrase)', async () => {
// A 4-token phrase: remove the middle non-edge token (token-2). The phrase shrinks to 3 tokens.
const fourTokenPhrase: PhraseAnalysisLink = {
analysisId: 'phrase-big',
status: 'approved',
tokens: [
{ tokenRef: 'token-1', surfaceText: 'Hello' },
{ tokenRef: 'token-2', surfaceText: 'World' },
{ tokenRef: 'token-3', surfaceText: 'foo' },
{ tokenRef: 'token-4', surfaceText: 'bar' },
],
};
mockUsePhraseLinkForToken.mockReturnValue(fourTokenPhrase);
const updatePhraseSpy = jest.fn();
mockUsePhraseDispatch.mockReturnValue({
createPhrase: jest.fn(),
updatePhrase: updatePhraseSpy,
deletePhrase: jest.fn(),
});
renderBox(
<PhraseBox
{...requiredProps()}
isHighlighted
phraseLink={fourTokenPhrase}
tokens={[
makeWordToken('token-1', 'Hello'),
makeWordToken('token-2', 'World'),
makeWordToken('token-3', 'foo'),
makeWordToken('token-4', 'bar'),
]}
/>,
);
// token-2 is a middle token (not first, not last of the link) → its Remove button is rendered.
const removeBtn = screen.getByRole('button', { name: 'Remove World' });
await userEvent.click(removeBtn);
expect(updatePhraseSpy).toHaveBeenCalledWith('phrase-big', [
{ tokenRef: 'token-1', surfaceText: 'Hello' },
{ tokenRef: 'token-3', surfaceText: 'foo' },
{ tokenRef: 'token-4', surfaceText: 'bar' },
]);
});
it('with simplifyPhrases on, hides (but keeps mounted) intra-phrase unlink icons and omits remove-token buttons on a non-focused phrase', () => {
const fourTokenPhrase: PhraseAnalysisLink = {
analysisId: 'phrase-big',
status: 'approved',
tokens: [
{ tokenRef: 'token-1', surfaceText: 'Hello' },
{ tokenRef: 'token-2', surfaceText: 'World' },
{ tokenRef: 'token-3', surfaceText: 'foo' },
{ tokenRef: 'token-4', surfaceText: 'bar' },
],
};
mockUsePhraseLinkForToken.mockReturnValue(fourTokenPhrase);
renderBox(
<PhraseBox