-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTokenChip.tsx
More file actions
562 lines (538 loc) · 27 KB
/
Copy pathTokenChip.tsx
File metadata and controls
562 lines (538 loc) · 27 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
import type { Token } from 'interlinearizer';
import { useLocalizedStrings } from '@papi/frontend/react';
import { Plus, X } from 'lucide-react';
import { Popover, PopoverAnchor } from 'platform-bible-react';
import {
type KeyboardEvent,
memo,
type MouseEventHandler,
useCallback,
useEffect,
useId,
useMemo,
useRef,
useState,
} from 'react';
import { resolvedOrEmpty } from '../utils/localized-strings';
import { glossedSuggestionEntries } from '../utils/suggestion-engine';
import {
useAnalysisLanguage,
useApproveAnalysisDispatch,
useGloss,
useGlossDispatch,
useMorphemeBreakdownDispatch,
useMorphemeDeleteDispatch,
useMorphemes,
useReportGlossEditing,
useResolvedTokenAnalysis,
useShowSuggestions,
useSuggestionAfterClearing,
} from './AnalysisStore';
import { MorphemeBox } from './MorphemeBox';
import { MorphemeBreakdownPopover } from './MorphemeEditor';
import SuggestionDropdown from './SuggestionDropdown';
const STRING_KEYS = [
'%interlinearizer_tokenChip_defineMorphemes%',
'%interlinearizer_glossInput_placeholder%',
] as const satisfies `%${string}%`[];
/**
* Renders a single word token as an inline chip with an editable gloss input below the surface
* text. Gloss value and dispatch are read from {@link AnalysisStoreProvider} context via
* {@link useGloss} and {@link useGlossDispatch}. The gloss is written to the store only on blur, and
* only when the draft differs from the committed value, to avoid creating empty analysis entries on
* focus/blur cycles with no edits.
*
* When `showMorphology` is true, the morpheme breakdown is shown below the surface text. For
* analyzed tokens this is a boxed grid ({@link MorphemeBox}) aligning each morpheme form over its
* gloss field; for unanalyzed tokens it is a muted "define breakdown" button showing the surface
* text. Clicking either opens an inline popover where the user can define, edit, or delete the
* morpheme breakdown.
*
* @param props - Component props
* @param props.token - The word token to render.
* @param props.onFocus - Called when the gloss input receives focus.
* @param props.disabled - When true, the gloss input is read-only and non-interactive.
* @param props.onRemove - When provided, renders a small X button in the top-right corner of the
* chip; clicking it calls this callback to remove the token from its phrase.
* @param props.isSplitFree - When true, this token would become free (solo) if the currently
* hovered split/unlink button were clicked; previewed with a destructive border on the chip.
* @param props.showMorphology - When true, morpheme breakdown and per-morpheme glosses are shown
* below the surface text.
* @returns A styled label containing the surface text, optionally morpheme rows, and a gloss input.
*/
export function TokenChip({
token,
onFocus,
disabled = false,
onRemove,
isSplitFree = false,
showMorphology = false,
}: Readonly<{
token: Token & { type: 'word' };
onFocus: () => void;
disabled?: boolean;
onRemove?: () => void;
isSplitFree?: boolean;
showMorphology?: boolean;
}>) {
const [localizedStrings] = useLocalizedStrings(STRING_KEYS);
const committedGloss = useGloss(token.ref);
const onGlossChange = useGlossDispatch();
const morphemes = useMorphemes(token.ref);
const analysisLanguage = useAnalysisLanguage();
const dispatchMorphemeBreakdown = useMorphemeBreakdownDispatch();
const dispatchMorphemeDelete = useMorphemeDeleteDispatch();
const showSuggestions = useShowSuggestions();
// Only resolve the pool when suggestions are actually shown; off, this does no per-token lookup.
const resolved = useResolvedTokenAnalysis(token.ref, token.surfaceText, showSuggestions);
const approveAnalysis = useApproveAnalysisDispatch();
const [draft, setDraft] = useState(committedGloss);
// While the user has emptied an approved token's gloss, the deletion only commits on blur, so the
// store still reports the token as approved. Without this, the dropdown would offer only that
// approved payload's alternatives (e.g. the minority homograph) until blur, then snap to the
// pool's best pick once the empty value commits. Preview that post-commit suggestion now — derived
// as if this token's approval were already gone — so the row and ghost placeholder stay consistent
// across the blur. Gated to the one token being cleared so no other chip does the extra lookup.
const clearingApprovedGloss =
showSuggestions && !disabled && resolved?.status === 'approved' && draft === '';
const clearedSuggestion = useSuggestionAfterClearing(
token.ref,
token.surfaceText,
clearingApprovedGloss,
);
const suggestionSource = clearingApprovedGloss ? clearedSuggestion : resolved;
const [popoverOpen, setPopoverOpen] = useState(false);
const glossInputId = useId();
const glossInputRef = useRef<HTMLInputElement | undefined>(undefined);
// The suggestion combobox: an `activeIndex` of -1 means no row is highlighted, so a bare Enter
// commits the top suggestion. Focusing (clicking) the gloss opens the dropdown whenever the token
// has suggestions — clicking the gloss is the primary way in — and typing closes it again (it
// reopens when the field is emptied or via ArrowDown). The "+" button is shown only for a token
// with more than one suggestion, both as a marker that alternatives exist and as a re-summon
// affordance over typed text; `inputFocused` / `chipHovered` gate its visibility.
const listboxId = useId();
const [suggestionsOpen, setSuggestionsOpen] = useState(false);
const [activeIndex, setActiveIndex] = useState(-1);
const [inputFocused, setInputFocused] = useState(false);
const [chipHovered, setChipHovered] = useState(false);
// Tracks whether the X button itself is hovered, so only that button hover reddens the border.
const [isRemoveHovered, setIsRemoveHovered] = useState(false);
// Reset remove-hover state when onRemove is cleared so the red border doesn't linger.
const prevOnRemoveRef = useRef(onRemove);
useEffect(() => {
if (prevOnRemoveRef.current !== onRemove) {
prevOnRemoveRef.current = onRemove;
if (!onRemove && isRemoveHovered) setIsRemoveHovered(false);
}
}, [onRemove, isRemoveHovered]);
// Keep local draft in sync when the committed value changes externally (e.g. project switch).
useEffect(() => {
setDraft(committedGloss);
}, [committedGloss]);
// Surface uncommitted typing to the unsaved indicator before the gloss commits on blur.
useReportGlossEditing(!disabled && draft !== committedGloss);
// The popover tree unmounts with the morpheme row when showMorphology turns off, but this state
// lives on the chip and would survive — silently reopening the popover when morphology is shown
// again. Clearing it on hide also closes the popover. We also close it when the chip becomes
// disabled: the popover content renders on `popoverOpen` alone (it isn't gated on `disabled`), so
// a chip whose popover is open while it transitions to disabled would otherwise stay editable.
useEffect(() => {
if (!showMorphology || disabled) setPopoverOpen(false);
}, [showMorphology, disabled]);
/**
* Intercepts mouse-down on the gloss input to suppress the browser's built-in focus-and-scroll,
* then re-focuses the input with `preventScroll` so only the React-controlled smooth
* scrollIntoView fires.
*
* @param e - The gloss input's mouse-down event.
*/
const handleMouseDown: MouseEventHandler<HTMLInputElement> = (e) => {
// Prevent the browser's built-in focus-and-scroll so only the React-controlled
// smooth scrollIntoView fires. We re-focus manually with preventScroll instead.
e.preventDefault();
e.currentTarget.focus({ preventScroll: true });
};
/**
* Intercepts mouse-down on the chip's label (the surface text and padding) so the label's native
* activation — which forwards focus to the gloss input with the browser's default
* scroll-into-view — can never scroll the list under the click. Focuses the input directly with
* `preventScroll` instead; the native forwarding then finds it already focused and does nothing.
* The input is looked up by id rather than `querySelector('input')` because the morpheme gloss
* inputs precede it inside the label when morphology is shown. A mouse-down on any input is left
* to that input's own handling ({@link handleMouseDown} for the gloss input, which bubbles here
* after already handling it); a mouse-down on the first morpheme form cell or the unanalyzed
* "define" trigger (both real `button`s) is left to that button's own click handler. The
* remaining morpheme form cells are `span`s that stop their own mousedown from bubbling here
* instead (see {@link MorphemeBox}).
*
* @param e - The label's mouse-down event.
*/
const handleLabelMouseDown: MouseEventHandler<HTMLLabelElement> = (e) => {
if (e.target instanceof Element && e.target.closest('input, button')) return;
e.preventDefault();
document.getElementById(glossInputId)?.focus({ preventScroll: true });
};
/**
* Commits the morpheme breakdown from the popover input, splitting on whitespace.
*
* @param value - The raw text from the popover input.
*/
const handleMorphemeSave = (value: string) => {
const forms = value.split(/\s+/).filter(Boolean);
if (forms.length > 0) {
dispatchMorphemeBreakdown(token.ref, token.surfaceText, forms, token.writingSystem);
}
};
const hasMorphemes = morphemes.length > 0;
// Pool entries for the suggestion dropdown: for a suggested token, the top pick (blue "accept")
// plus candidates (grey "promote"); for an approved token, the pool alternatives only (the
// already-approved payload excluded) — or, while that approved gloss is being cleared, the
// post-deletion preview from `suggestionSource`. Blank-in-active-language entries are dropped
// rather than shown as empty rows. Memoized on the (reference-stable) source read and active
// language so typing a non-empty gloss — which only changes local draft state — never re-runs the
// flatten/filter; clearing the field swaps `suggestionSource` and recomputes once.
const glossedRanked = useMemo(
() => glossedSuggestionEntries(suggestionSource, analysisLanguage),
[suggestionSource, analysisLanguage],
);
// Whether this token has anything to suggest: gated on the demo toggle (via the resolve short-
// circuit) and editability. The dropdown only ever appears when this is true.
const hasSuggestions = showSuggestions && !disabled && glossedRanked.length > 0;
// The "+" button is offered only when there is a real choice — more than one suggestion. With a
// single suggestion the ghost placeholder already advertises it and focusing the gloss opens the
// dropdown to accept it, so a button would be redundant.
const hasMultipleSuggestions = hasSuggestions && glossedRanked.length > 1;
// Top pick (row 0, the blue "suggested") shown as ghost placeholder text so the row reveals
// which tokens have a suggestion at a glance — without focus or hover. Once the user types, the
// typed value replaces it.
const suggestedGloss = hasSuggestions ? glossedRanked[0].gloss : undefined;
const showSuggestedPlaceholder = suggestedGloss !== undefined && draft === '';
/**
* Returns the listbox option id for `index`; kept in sync with `aria-activedescendant` so
* assistive tech follows the keyboard-highlighted row.
*
* @param index - The row's index in {@link glossedRanked}.
* @returns The option element id.
*/
const optionId = useCallback((index: number) => `${listboxId}-opt-${index}`, [listboxId]);
/** Closes the suggestion dropdown and clears the keyboard highlight, leaving focus untouched. */
const closeSuggestions = useCallback(() => {
setSuggestionsOpen(false);
setActiveIndex(-1);
}, []);
/** Commits the draft gloss only when it differs from the committed value. */
const commitDraft = () => {
if (draft !== committedGloss) {
onGlossChange(token.ref, token.surfaceText, draft);
}
};
/**
* Approves the chosen suggestion payload for this token and closes the dropdown. Any typed draft
* is discarded: the approval updates `committedGloss`, which the sync effect mirrors back into
* the input so the selection wins.
*
* @param id - The chosen payload's id (the suggested pick or a promoted candidate).
*/
const selectSuggestion = (id: string) => {
approveAnalysis(token.ref, token.surfaceText, id);
closeSuggestions();
};
/**
* Drives the gloss input as a combobox. While the dropdown is open, arrow keys move the highlight
* (stopping at the ends; Up returns to the no-highlight state), Enter commits the highlighted row
* or the top row, and Escape closes without committing. While closed, ArrowDown opens the
* dropdown (the keyboard way to reopen it after typing has closed it, without clearing the field)
* and Enter commits the typed draft.
*
* @param e - The gloss input's key-down event.
*/
const handleGlossKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (suggestionsOpen) {
if (e.key === 'ArrowDown') {
e.preventDefault();
setActiveIndex((i) => Math.min(i + 1, glossedRanked.length - 1));
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setActiveIndex((i) => Math.max(i - 1, -1));
} else if (e.key === 'Escape') {
e.preventDefault();
closeSuggestions();
} else if (e.key === 'Enter') {
e.preventDefault();
// activeIndex -1 (nothing highlighted) falls back to the top row. The list is normally
// non-empty while open, but glossedRanked can empty out after open (a row approved away),
// leaving suggestionsOpen stale while the dropdown is unmounted — guard so Enter closes
// rather than dereferencing an absent pick.
const pick = glossedRanked[activeIndex] ?? glossedRanked[0];
if (pick) selectSuggestion(pick.id);
/* v8 ignore next -- defensive: the empty-pick race above is not reachable from the call sites */ else
closeSuggestions();
}
} else if (e.key === 'ArrowDown' && hasSuggestions) {
e.preventDefault();
setActiveIndex(-1);
setSuggestionsOpen(true);
} else if (e.key === 'Enter') {
e.preventDefault();
commitDraft();
}
};
/**
* Handles gloss-input focus: runs the parent's focus side effect (scroll-into-view), marks the
* input focused so the "+" button can show, and opens the suggestion dropdown whenever the token
* has suggestions — so clicking the gloss (which focuses it) summons the list on both empty and
* already-glossed tokens.
*/
const handleFocus = () => {
onFocus();
setInputFocused(true);
if (hasSuggestions) {
setActiveIndex(-1);
setSuggestionsOpen(true);
}
};
/**
* Handles gloss-input typing: updates the draft, and re-opens the dropdown when the field is
* emptied back out or closes it as soon as the user types a gloss (which overrides the
* suggestion).
*
* @param value - The new input value.
*/
const handleDraftChange = (value: string) => {
setDraft(value);
if (value === '') {
if (hasSuggestions) setSuggestionsOpen(true);
} else {
closeSuggestions();
}
};
/** Toggles the dropdown from the "+" button, focusing the input so keyboard navigation works. */
const handleAddClick = () => {
const willOpen = !suggestionsOpen;
setActiveIndex(-1);
setSuggestionsOpen(willOpen);
// Focus after setting open so the focus handler's auto-open agrees with willOpen (both want
// open); on close we leave focus where it is.
if (willOpen) glossInputRef.current?.focus({ preventScroll: true });
};
/**
* Ref callback that stores the gloss input element for focus control (from the "+" button) and as
* the dropdown's positioning anchor. Normalizes React's `null` on unmount to `undefined` to match
* the repo's ref-typing convention.
*
* @param el - The mounted input, or `null` on unmount.
*/
const setGlossInputRef = (el: HTMLInputElement | null) => {
glossInputRef.current = el ?? undefined;
};
// Whether the dropdown is actually mounted: open AND still has rows (a row may have been approved
// away). When false the input's combobox attributes collapse to the closed state.
const dropdownShown = suggestionsOpen && hasSuggestions;
// Whether the "+" button is faded in. Its layout slot (the input's reserved end-padding) is
// always present, so this governs only opacity/interactivity — the chip never reflows as it
// appears.
const addVisible = inputFocused || chipHovered;
// The X button is positioned outside the <label>, and the label is bound to the gloss input with
// an explicit htmlFor, so clicking the chip body always focuses the gloss input. Without the
// explicit binding, the label's implicit control would be its first labelable descendant — the X
// button, or the morpheme trigger button when showMorphology is on — and clicking anywhere on
// the chip (label-association behavior) would activate that button instead.
return (
<span className="tw:relative tw:inline-flex tw:shrink-0">
{onRemove && (
<button
aria-label={`Remove ${token.surfaceText} from phrase`}
className={`tw:absolute tw:-top-1.5 tw:-right-1.5 tw:z-10 tw:flex tw:h-3.5 tw:w-3.5 tw:items-center tw:justify-center tw:rounded-full tw:border tw:bg-background${isRemoveHovered ? ' tw:border-destructive tw:text-destructive' : ' tw:border-border tw:text-muted-foreground'}`}
tabIndex={-1}
type="button"
onClick={(e) => {
e.preventDefault();
onRemove();
}}
onMouseEnter={() => setIsRemoveHovered(true)}
onMouseLeave={() => setIsRemoveHovered(false)}
>
<X className="tw:h-2.5 tw:w-2.5" />
</button>
)}
<label
className={`tw:inline-flex tw:flex-col tw:items-center tw:rounded tw:border tw:bg-muted tw:px-0.5 tw:py-0.5${isRemoveHovered || isSplitFree ? ' tw:border-destructive' : ' tw:border-border'}${disabled ? ' tw:pointer-events-none' : ''}`}
onMouseDown={disabled ? undefined : handleLabelMouseDown}
onMouseEnter={() => setChipHovered(true)}
onMouseLeave={() => setChipHovered(false)}
htmlFor={glossInputId}
>
<span className="tw:whitespace-nowrap tw:font-mono tw:text-sm tw:text-foreground tw:cursor-text">
{token.surfaceText}
</span>
{showMorphology && (
// The morpheme row is the popover anchor; the panel itself is portaled to document.body
// by PopoverContent, so it escapes both the clipping of ancestor scroll viewports (e.g.
// the continuous view's token strip) and the `token-row` stacking contexts that would
// otherwise paint later segment rows over it. The popover is modal so interactions
// outside the panel are blocked while it is open. The popover component is mounted only
// while open so its draft state re-initializes from the current forms on every open.
//
// `onOpenChange` is intentionally omitted: this consumer owns every dismissal path
// (onEscapeKeyDown, onInteractOutside, explicit button clicks), so Radix's internal close
// requests aren't needed. Don't wire onOpenChange without also removing those, or closes
// would double-fire.
<Popover modal open={popoverOpen}>
{hasMorphemes ? (
<MorphemeBox
analysisLanguage={analysisLanguage}
disabled={disabled}
morphemes={morphemes}
onEditBreakdown={() => setPopoverOpen(true)}
popoverOpen={popoverOpen}
token={token}
/>
) : (
<PopoverAnchor asChild>
<button
aria-label={localizedStrings[
'%interlinearizer_tokenChip_defineMorphemes%'
].replace('{token}', token.surfaceText)}
className={`tw:flex tw:flex-row tw:items-center tw:rounded tw:px-0.5 tw:font-mono tw:text-xs tw:italic tw:text-muted-foreground/50 tw:transition-colors${disabled ? '' : ' tw:cursor-pointer tw:hover:bg-accent'}`}
tabIndex={-1}
type="button"
onClick={(e) => {
e.preventDefault();
if (!disabled) setPopoverOpen(true);
}}
>
<span className="tw:whitespace-nowrap">{token.surfaceText}</span>
</button>
</PopoverAnchor>
)}
{popoverOpen && (
<MorphemeBreakdownPopover
glossInputId={glossInputId}
initialValue={
hasMorphemes ? morphemes.map((m) => m.form).join(' ') : token.surfaceText
}
onClose={() => setPopoverOpen(false)}
onDelete={hasMorphemes ? () => dispatchMorphemeDelete(token.ref) : undefined}
onSave={handleMorphemeSave}
surfaceText={token.surfaceText}
/>
)}
</Popover>
)}
{/* The gloss input acts as the combobox; the "+" button is a mouse affordance to summon the
dropdown over already-typed text, shown only for a token with more than one suggestion
and rendered as a trailing in-field decoration that only fades into view on focus/hover.
The input reserves symmetric end-padding (sized to clear the button) on EVERY chip —
whether or not this token has a suggestion, and whether or not the feature is on — so the
gloss text stays centered, the chip never reflows as the button appears, and widths never
differ between tokens that do and don't have suggestions. The button stays out of the tab
order so tabbing across the interlinear row hits one stop per token — the input. */}
<span className="tw:relative tw:mt-0.5 tw:inline-flex tw:items-center">
<input
ref={setGlossInputRef}
// Combobox semantics apply only when this token actually has a suggestion popup; without
// suggestions it stays a plain text input.
aria-activedescendant={
dropdownShown && activeIndex >= 0 ? optionId(activeIndex) : undefined
}
aria-autocomplete={hasSuggestions ? 'none' : undefined}
aria-controls={dropdownShown ? listboxId : undefined}
aria-expanded={hasSuggestions ? dropdownShown : undefined}
aria-label={`Gloss for ${token.surfaceText}`}
// When the empty input is showing a suggested gloss as its placeholder, color that ghost
// text via the same `gloss-suggested` utility the dropdown's accept row uses (one source
// of truth for the suggested blue) and italicize it, at full opacity, so it reads
// clearly as a suggestion rather than a faint generic hint.
className={`tw:gloss-input${showSuggestedPlaceholder ? ' tw:placeholder:gloss-suggested tw:placeholder:italic tw:placeholder:opacity-100' : ''}`}
disabled={disabled}
id={glossInputId}
placeholder={
showSuggestedPlaceholder
? suggestedGloss
: resolvedOrEmpty(localizedStrings['%interlinearizer_glossInput_placeholder%'])
}
role={hasSuggestions ? 'combobox' : undefined}
// Inline padding overrides the `gloss-input` utility's default px to reserve room for the
// trailing "+" button symmetrically (keeping the gloss text centered) without a separate
// spacer element. The utility's top margin moves to the wrapping span (which now carries
// the gap above the input) and is zeroed here so the span's box matches the input
// exactly — letting the absolutely-positioned button center on the input rather than on a
// box inflated at the top by the margin.
style={{
fieldSizing: 'content',
marginTop: 0,
minWidth: '5ch',
paddingLeft: '0.75rem',
paddingRight: '0.75rem',
}}
value={draft}
onBlur={
disabled
? undefined
: () => {
setInputFocused(false);
closeSuggestions();
commitDraft();
}
}
onChange={(e) => handleDraftChange(e.target.value)}
onFocus={disabled ? undefined : handleFocus}
onKeyDown={disabled ? undefined : handleGlossKeyDown}
onMouseDown={disabled ? undefined : handleMouseDown}
type="text"
/>
{hasMultipleSuggestions && (
<button
aria-controls={dropdownShown ? listboxId : undefined}
aria-expanded={dropdownShown}
aria-hidden={!addVisible}
aria-label={`Show suggestions for ${token.surfaceText}`}
// Absolutely positioned inside the input's reserved end-padding so it never affects
// layout; we toggle only opacity, fading the button in on focus/hover. When hidden it
// is also made non-interactive so an invisible button can't swallow clicks.
className={`tw:absolute tw:right-0.5 tw:top-1/2 tw:flex tw:h-2.5 tw:w-2.5 tw:-translate-y-1/2 tw:items-center tw:justify-center tw:rounded tw:text-muted-foreground tw:cursor-pointer tw:transition-opacity tw:hover:bg-accent${addVisible ? '' : ' tw:pointer-events-none tw:opacity-0'}`}
data-testid="suggestion-add"
tabIndex={-1}
type="button"
onClick={handleAddClick}
// Suppress the mouse-down focus shift so clicking the button never blurs the input.
onMouseDown={(e) => e.preventDefault()}
>
<Plus className="tw:h-2.5 tw:w-2.5" />
</button>
)}
</span>
{dropdownShown && (
<SuggestionDropdown
activeIndex={activeIndex}
anchorRef={glossInputRef}
entries={glossedRanked}
listboxId={listboxId}
optionId={optionId}
surfaceText={token.surfaceText}
onActiveIndexChange={setActiveIndex}
onRequestClose={closeSuggestions}
onSelect={selectSuggestion}
/>
)}
</label>
</span>
);
}
/**
* Renders a non-word token (e.g. punctuation) as muted inline monospace text with no gloss input.
*
* @param props - Component props
* @param props.token - The non-word token to render.
* @returns A muted inline span.
*/
export function InertTokenChip({ token }: Readonly<{ token: Token }>) {
return (
<span className="tw:inline-block tw:font-mono tw:text-sm tw:text-muted-foreground tw:pt-0.5">
{token.surfaceText}
</span>
);
}
/** Memoized version of {@link TokenChip}; use in render-stable token lists. */
const MemoizedTokenChip = memo(TokenChip);
export default MemoizedTokenChip;