@open-mercato/ui 0.10.1-develop.8129.1.149839452c → 0.10.1-develop.8143.1.bf633ea932
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/backend/CrudForm.js +65 -35
- package/dist/backend/CrudForm.js.map +2 -2
- package/dist/backend/detail/NotesSection.js +3 -2
- package/dist/backend/detail/NotesSection.js.map +2 -2
- package/dist/backend/inputs/ComboboxInput.js +1 -1
- package/dist/backend/inputs/ComboboxInput.js.map +2 -2
- package/dist/backend/inputs/LookupSelect.js +117 -35
- package/dist/backend/inputs/LookupSelect.js.map +2 -2
- package/package.json +3 -3
- package/src/backend/CrudForm.tsx +168 -100
- package/src/backend/__tests__/CrudForm.accessibleLabels.test.tsx +108 -0
- package/src/backend/__tests__/CrudForm.doubleSubmit.test.tsx +85 -1
- package/src/backend/__tests__/CrudForm.injectionLifecycle.test.tsx +5 -2
- package/src/backend/__tests__/NotesSection.test.tsx +48 -1
- package/src/backend/detail/NotesSection.tsx +3 -2
- package/src/backend/inputs/ComboboxInput.tsx +2 -2
- package/src/backend/inputs/LookupSelect.tsx +166 -53
- package/src/backend/inputs/__tests__/ComboboxInput.test.tsx +22 -0
- package/src/backend/inputs/__tests__/LookupSelect.test.tsx +209 -23
|
@@ -7,11 +7,14 @@ jest.mock('next/navigation', () => ({
|
|
|
7
7
|
useSearchParams: () => new URLSearchParams(),
|
|
8
8
|
}))
|
|
9
9
|
jest.mock('remark-gfm', () => ({ __esModule: true, default: {} }))
|
|
10
|
+
// A shared, per-test-overridable mock so the onBeforeNavigate-denial test below
|
|
11
|
+
// can simulate a blocking injection widget without a real injection spot.
|
|
12
|
+
const triggerInjectionEventMock = jest.fn(async () => ({ ok: true }))
|
|
10
13
|
jest.mock('../injection/InjectionSpot', () => ({
|
|
11
14
|
__esModule: true,
|
|
12
15
|
InjectionSpot: () => null,
|
|
13
16
|
useInjectionWidgets: () => ({ widgets: [], loading: false, error: null }),
|
|
14
|
-
useInjectionSpotEvents: () => ({ triggerEvent:
|
|
17
|
+
useInjectionSpotEvents: () => ({ triggerEvent: triggerInjectionEventMock }),
|
|
15
18
|
}))
|
|
16
19
|
jest.mock('../injection/useInjectionDataWidgets', () => ({
|
|
17
20
|
__esModule: true,
|
|
@@ -26,6 +29,10 @@ import { CrudForm, type CrudField } from '../CrudForm'
|
|
|
26
29
|
describe('CrudForm double-submit protection (issue #1539)', () => {
|
|
27
30
|
const fields: CrudField[] = [{ id: 'name', label: 'Name', type: 'text' }]
|
|
28
31
|
|
|
32
|
+
afterEach(() => {
|
|
33
|
+
triggerInjectionEventMock.mockReset().mockImplementation(async () => ({ ok: true }))
|
|
34
|
+
})
|
|
35
|
+
|
|
29
36
|
it('ignores rapid repeated submits while the first onSubmit is still running', async () => {
|
|
30
37
|
let resolveSubmit: (() => void) | null = null
|
|
31
38
|
const onSubmit = jest.fn(
|
|
@@ -91,4 +98,81 @@ describe('CrudForm double-submit protection (issue #1539)', () => {
|
|
|
91
98
|
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(2))
|
|
92
99
|
})
|
|
93
100
|
|
|
101
|
+
it('ignores a second submit after a successful save that redirects, before the route unmounts the form (issue #8645)', async () => {
|
|
102
|
+
let resolveSubmit: (() => void) | null = null
|
|
103
|
+
const onSubmit = jest.fn(
|
|
104
|
+
() =>
|
|
105
|
+
new Promise<void>((resolve) => {
|
|
106
|
+
resolveSubmit = resolve
|
|
107
|
+
}),
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
const { container } = renderWithProviders(
|
|
111
|
+
<CrudForm
|
|
112
|
+
title="Form"
|
|
113
|
+
fields={fields}
|
|
114
|
+
initialValues={{ name: 'alpha' }}
|
|
115
|
+
onSubmit={onSubmit}
|
|
116
|
+
successRedirect="/somewhere"
|
|
117
|
+
/>,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
const form = container.querySelector('form') as HTMLFormElement
|
|
121
|
+
|
|
122
|
+
await act(async () => {
|
|
123
|
+
fireEvent.submit(form)
|
|
124
|
+
})
|
|
125
|
+
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
|
|
126
|
+
|
|
127
|
+
// Resolve the save. The mocked router's push() never unmounts the form,
|
|
128
|
+
// mirroring the real window between router.push resolving and the route
|
|
129
|
+
// actually unmounting. By the time this act() settles, the success path
|
|
130
|
+
// (including the success-redirect call) has fully run.
|
|
131
|
+
await act(async () => {
|
|
132
|
+
resolveSubmit?.()
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
// A second submit fired in that window must not call onSubmit again.
|
|
136
|
+
await act(async () => {
|
|
137
|
+
fireEvent.submit(form)
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
expect(onSubmit).toHaveBeenCalledTimes(1)
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
it('releases the lock when onBeforeNavigate blocks the success redirect, so the next submit proceeds normally', async () => {
|
|
144
|
+
triggerInjectionEventMock.mockImplementation(async (eventName: unknown) =>
|
|
145
|
+
eventName === 'onBeforeNavigate' ? { ok: false, message: 'blocked' } : { ok: true },
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
const onSubmit = jest.fn(() => Promise.resolve())
|
|
149
|
+
|
|
150
|
+
const { container } = renderWithProviders(
|
|
151
|
+
<CrudForm
|
|
152
|
+
title="Form"
|
|
153
|
+
fields={fields}
|
|
154
|
+
initialValues={{ name: 'alpha' }}
|
|
155
|
+
onSubmit={onSubmit}
|
|
156
|
+
successRedirect="/somewhere"
|
|
157
|
+
injectionSpotId="test:crudform-nav-guard"
|
|
158
|
+
/>,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
const form = container.querySelector('form') as HTMLFormElement
|
|
162
|
+
|
|
163
|
+
await act(async () => {
|
|
164
|
+
fireEvent.submit(form)
|
|
165
|
+
})
|
|
166
|
+
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
|
|
167
|
+
|
|
168
|
+
// navigateWithGuard's canNavigateTo refused the target, so
|
|
169
|
+
// redirectNavigationStarted stays false and both finally blocks release
|
|
170
|
+
// the lock immediately — unlike the allowed-redirect case above, a second
|
|
171
|
+
// submit right away must go through rather than being swallowed.
|
|
172
|
+
await act(async () => {
|
|
173
|
+
fireEvent.submit(form)
|
|
174
|
+
})
|
|
175
|
+
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(2))
|
|
176
|
+
})
|
|
177
|
+
|
|
94
178
|
})
|
|
@@ -386,9 +386,12 @@ it('does not emit a save failure when the post-save success callback throws', as
|
|
|
386
386
|
const { container } = renderForm({ onSubmit, onSubmitSuccess, successRedirect: '/saved' })
|
|
387
387
|
fireEvent.submit(container.querySelector('form')!)
|
|
388
388
|
await waitFor(() => expect(onSubmitSuccess).toHaveBeenCalledTimes(1))
|
|
389
|
-
await waitFor(() => expect(container.querySelector('button[type="submit"]')).not.toBeDisabled())
|
|
390
|
-
expect(onSubmit).toHaveBeenCalledTimes(1)
|
|
391
389
|
await waitFor(() => expect(mockPush).toHaveBeenCalledWith('/saved'))
|
|
390
|
+
expect(onSubmit).toHaveBeenCalledTimes(1)
|
|
391
|
+
// A successful save that redirects keeps the submit lock held until the
|
|
392
|
+
// route actually unmounts the form (issue #8645) — the button stays
|
|
393
|
+
// disabled rather than re-opening a window for a duplicate submit.
|
|
394
|
+
expect(container.querySelector('button[type="submit"]')).toBeDisabled()
|
|
392
395
|
expect(saveError).not.toHaveBeenCalled()
|
|
393
396
|
expect(container.textContent).not.toContain('refresh failed')
|
|
394
397
|
} finally {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** @jest-environment jsdom */
|
|
2
2
|
|
|
3
3
|
import * as React from 'react'
|
|
4
|
-
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
|
4
|
+
import { fireEvent, screen, waitFor, within } from '@testing-library/react'
|
|
5
5
|
import { renderWithProviders } from '@open-mercato/shared/lib/testing/renderWithProviders'
|
|
6
6
|
import { NotesSection, type NotesDataAdapter } from '../detail/NotesSection'
|
|
7
7
|
import { dismissRecordConflict, getRecordConflictForTest } from '../conflicts'
|
|
@@ -398,6 +398,53 @@ describe('NotesSection', () => {
|
|
|
398
398
|
})
|
|
399
399
|
})
|
|
400
400
|
|
|
401
|
+
it.each(['optimistic_lock_conflict', 'record_lock_conflict'])('keeps %s out of the content editor after surfacing its banner', async (code) => {
|
|
402
|
+
const conflict = Object.assign(new Error('record_modified'), {
|
|
403
|
+
status: 409,
|
|
404
|
+
body: { code, error: 'record_modified', currentUpdatedAt: '2026-06-02T00:00:00.000Z', expectedUpdatedAt: '2026-06-01T00:00:00.000Z' },
|
|
405
|
+
})
|
|
406
|
+
const adapter = createDataAdapter()
|
|
407
|
+
adapter.update = jest.fn(async () => { throw conflict })
|
|
408
|
+
renderWithProviders(<NotesSection {...baseProps(adapter)} disableMarkdown />)
|
|
409
|
+
fireEvent.click(await screen.findByRole('button', { name: 'Existing note' }))
|
|
410
|
+
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Edited note' } })
|
|
411
|
+
fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter', ctrlKey: true })
|
|
412
|
+
await waitFor(() => expect(adapter.update).toHaveBeenCalledTimes(1))
|
|
413
|
+
await waitFor(() => expect(getRecordConflictForTest()).not.toBeNull())
|
|
414
|
+
expect(screen.queryByText('record_modified')).not.toBeInTheDocument()
|
|
415
|
+
expect(screen.getByRole('textbox')).toHaveValue('Edited note')
|
|
416
|
+
})
|
|
417
|
+
|
|
418
|
+
it('keeps optimistic conflicts out of the appearance dialog after surfacing its banner', async () => {
|
|
419
|
+
const conflict = Object.assign(new Error('record_modified'), {
|
|
420
|
+
status: 409,
|
|
421
|
+
body: { code: OPTIMISTIC_LOCK_CONFLICT_CODE, error: 'record_modified', currentUpdatedAt: '2026-06-02T00:00:00.000Z', expectedUpdatedAt: '2026-06-01T00:00:00.000Z' },
|
|
422
|
+
})
|
|
423
|
+
const adapter = createDataAdapter()
|
|
424
|
+
adapter.update = jest.fn(async () => { throw conflict })
|
|
425
|
+
const { container } = renderWithProviders(<NotesSection {...baseProps(adapter)} disableMarkdown />)
|
|
426
|
+
await screen.findByText('Existing note')
|
|
427
|
+
const trigger = container.querySelector('svg.lucide-palette')?.closest('button')
|
|
428
|
+
expect(trigger).toBeInstanceOf(HTMLButtonElement)
|
|
429
|
+
fireEvent.click(trigger as HTMLButtonElement)
|
|
430
|
+
const dialog = await screen.findByRole('dialog')
|
|
431
|
+
fireEvent.keyDown(dialog, { key: 'Enter', ctrlKey: true })
|
|
432
|
+
await waitFor(() => expect(adapter.update).toHaveBeenCalledTimes(1))
|
|
433
|
+
await waitFor(() => expect(getRecordConflictForTest()).not.toBeNull())
|
|
434
|
+
expect(within(dialog).queryByText('record_modified')).not.toBeInTheDocument()
|
|
435
|
+
})
|
|
436
|
+
|
|
437
|
+
it('preserves ordinary inline validation errors', async () => {
|
|
438
|
+
const adapter = createDataAdapter()
|
|
439
|
+
adapter.update = jest.fn(async () => { throw new Error('Validation refused') })
|
|
440
|
+
renderWithProviders(<NotesSection {...baseProps(adapter)} disableMarkdown />)
|
|
441
|
+
fireEvent.click(await screen.findByRole('button', { name: 'Existing note' }))
|
|
442
|
+
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Edited note' } })
|
|
443
|
+
fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter', ctrlKey: true })
|
|
444
|
+
expect(await screen.findByText('Validation refused')).toBeInTheDocument()
|
|
445
|
+
expect(getRecordConflictForTest()).toBeNull()
|
|
446
|
+
})
|
|
447
|
+
|
|
401
448
|
it('surfaces the unified conflict bar when a write fails with a 409', async () => {
|
|
402
449
|
const conflict = {
|
|
403
450
|
status: 409,
|
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
} from '@open-mercato/ui/primitives/select'
|
|
19
19
|
import { flash } from '../FlashMessages'
|
|
20
20
|
import { surfaceRecordConflict } from '../conflicts'
|
|
21
|
+
import { extractOptimisticLockConflict, extractRecordLockConflict } from '../utils/optimisticLock'
|
|
21
22
|
import { SwitchableMarkdownInput } from '../inputs/SwitchableMarkdownInput'
|
|
22
23
|
import { ErrorMessage } from './ErrorMessage'
|
|
23
24
|
import { LoadingMessage } from './LoadingMessage'
|
|
@@ -898,7 +899,7 @@ function NotesSectionImpl<C = unknown>({
|
|
|
898
899
|
err instanceof Error
|
|
899
900
|
? err.message
|
|
900
901
|
: label('appearance.error', 'Failed to update appearance.')
|
|
901
|
-
setAppearanceDialogError(message)
|
|
902
|
+
setAppearanceDialogError(extractOptimisticLockConflict(err) || extractRecordLockConflict(err) ? null : message)
|
|
902
903
|
} finally {
|
|
903
904
|
setAppearanceDialogSaving(false)
|
|
904
905
|
}
|
|
@@ -925,7 +926,7 @@ function NotesSectionImpl<C = unknown>({
|
|
|
925
926
|
} catch (err) {
|
|
926
927
|
const message =
|
|
927
928
|
err instanceof Error ? err.message : label('updateError', 'Failed to update note')
|
|
928
|
-
setContentError(message)
|
|
929
|
+
setContentError(extractOptimisticLockConflict(err) || extractRecordLockConflict(err) ? null : message)
|
|
929
930
|
} finally {
|
|
930
931
|
setContentSavingId(null)
|
|
931
932
|
}
|
|
@@ -14,6 +14,7 @@ export type ComboboxOption = {
|
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
export type ComboboxInputProps = {
|
|
17
|
+
id?: string
|
|
17
18
|
value: string
|
|
18
19
|
onChange: (next: string) => void
|
|
19
20
|
placeholder?: string
|
|
@@ -33,7 +34,6 @@ export type ComboboxInputProps = {
|
|
|
33
34
|
allowCustomValues?: boolean
|
|
34
35
|
clearable?: boolean
|
|
35
36
|
clearLabel?: string
|
|
36
|
-
id?: string
|
|
37
37
|
'aria-describedby'?: string
|
|
38
38
|
'aria-invalid'?: boolean
|
|
39
39
|
'aria-required'?: boolean
|
|
@@ -70,6 +70,7 @@ function areOptionsEqual(a: ComboboxOption[], b: ComboboxOption[]): boolean {
|
|
|
70
70
|
}
|
|
71
71
|
|
|
72
72
|
export function ComboboxInput({
|
|
73
|
+
id,
|
|
73
74
|
value,
|
|
74
75
|
onChange,
|
|
75
76
|
placeholder,
|
|
@@ -83,7 +84,6 @@ export function ComboboxInput({
|
|
|
83
84
|
allowCustomValues = true,
|
|
84
85
|
clearable = false,
|
|
85
86
|
clearLabel,
|
|
86
|
-
id,
|
|
87
87
|
'aria-describedby': ariaDescribedBy,
|
|
88
88
|
'aria-invalid': ariaInvalid,
|
|
89
89
|
'aria-required': ariaRequired,
|
|
@@ -4,6 +4,7 @@ import * as React from 'react'
|
|
|
4
4
|
import { Check, Loader2, Search, X } from 'lucide-react'
|
|
5
5
|
import { useT } from '@open-mercato/shared/lib/i18n/context'
|
|
6
6
|
import { Button } from '../../primitives/button'
|
|
7
|
+
import { IconButton } from '../../primitives/icon-button'
|
|
7
8
|
import { cn } from '@open-mercato/shared/lib/utils'
|
|
8
9
|
import { createLogger } from '@open-mercato/shared/lib/logger'
|
|
9
10
|
|
|
@@ -84,6 +85,7 @@ export function LookupSelect({
|
|
|
84
85
|
const resolvedLoadingLabel = loadingLabel ?? t('ui.lookupSelect.searching', 'Searching…')
|
|
85
86
|
const resolvedSelectLabel = selectLabel ?? t('ui.lookupSelect.select', 'Select')
|
|
86
87
|
const resolvedSelectedLabel = selectedLabel ?? t('ui.lookupSelect.selected', 'Selected')
|
|
88
|
+
const resolvedChangeLabel = t('ui.lookupSelect.change', 'Change')
|
|
87
89
|
const resolvedStartTypingLabel = startTypingLabel ?? t('ui.lookupSelect.startTyping', 'Start typing to search.')
|
|
88
90
|
const resolvedMinQueryHintLabel = minQueryHintLabel ?? t(
|
|
89
91
|
'ui.lookupSelect.minQueryHint',
|
|
@@ -97,11 +99,16 @@ export function LookupSelect({
|
|
|
97
99
|
// enough here: Escape empties the query but the fetched `items` linger, so the
|
|
98
100
|
// list would stay open and the collapsed summary — the branch that keeps a raw
|
|
99
101
|
// record id out of the DOM (TC-EUDR-013) — would never render.
|
|
100
|
-
|
|
102
|
+
// A value that is already there when the lookup mounts (hydrated, or seeded by the host,
|
|
103
|
+
// e.g. the deal owner defaulting to the current user) is a finished selection: it starts
|
|
104
|
+
// collapsed on the summary instead of an open list with one row checked (#5109).
|
|
105
|
+
// `defaultOpen` keeps the list on screen regardless (pickers that browse a short list).
|
|
106
|
+
const [collapsed, setCollapsed] = React.useState(() => Boolean(value) && !defaultOpen)
|
|
101
107
|
const [hasTyped, setHasTyped] = React.useState(defaultOpen)
|
|
102
108
|
const [error, setError] = React.useState<string | null>(null)
|
|
103
109
|
const [fetchKey, setFetchKey] = React.useState(0)
|
|
104
110
|
const [activeIndex, setActiveIndex] = React.useState(-1)
|
|
111
|
+
const [selectedItem, setSelectedItem] = React.useState<LookupSelectItem | null>(null)
|
|
105
112
|
const listboxId = React.useId()
|
|
106
113
|
const fetchItemsRef = React.useRef(fetchItems ?? fetchOptions)
|
|
107
114
|
const setQueryRef = React.useRef(setQuery)
|
|
@@ -109,6 +116,10 @@ export function LookupSelect({
|
|
|
109
116
|
const optionsWasArrayRef = React.useRef(Array.isArray(options))
|
|
110
117
|
const valueRef = React.useRef(value)
|
|
111
118
|
const selectedItemRef = React.useRef<LookupSelectItem | null>(null)
|
|
119
|
+
const inputRef = React.useRef<HTMLInputElement>(null)
|
|
120
|
+
const pendingCommitRef = React.useRef<string | null>(null)
|
|
121
|
+
const changeButtonRef = React.useRef<HTMLButtonElement>(null)
|
|
122
|
+
const focusSummaryRef = React.useRef(false)
|
|
112
123
|
|
|
113
124
|
React.useEffect(() => {
|
|
114
125
|
fetchItemsRef.current = fetchItems ?? fetchOptions
|
|
@@ -137,9 +148,9 @@ export function LookupSelect({
|
|
|
137
148
|
if (onReadyRef.current) onReadyRef.current({ setQuery })
|
|
138
149
|
}, [setQuery])
|
|
139
150
|
|
|
140
|
-
// A set `value`
|
|
141
|
-
//
|
|
142
|
-
//
|
|
151
|
+
// A set `value` keeps the lookup live: the list (or, once collapsed after a
|
|
152
|
+
// pick, the summary) is where the selection, its checkmark and the clear control
|
|
153
|
+
// render, so a selection is never invisible. This used to also require an
|
|
143
154
|
// `options` prop, which left every caller that resolves its selection through
|
|
144
155
|
// `fetchItems` blind whenever minQuery kept the list shut.
|
|
145
156
|
const shouldSearch = defaultOpen || query.trim().length >= minQuery || Boolean(value)
|
|
@@ -180,7 +191,61 @@ export function LookupSelect({
|
|
|
180
191
|
}
|
|
181
192
|
}, [activeIndex, optionDomId])
|
|
182
193
|
|
|
183
|
-
const listboxVisible = shouldSearch && !disabled
|
|
194
|
+
const listboxVisible = shouldSearch && !disabled && !collapsed
|
|
195
|
+
|
|
196
|
+
const finishSelection = React.useCallback(() => {
|
|
197
|
+
pendingCommitRef.current = null
|
|
198
|
+
focusSummaryRef.current = true
|
|
199
|
+
setCollapsed(true)
|
|
200
|
+
setQuery('')
|
|
201
|
+
setHasTyped(false)
|
|
202
|
+
setActiveIndex(-1)
|
|
203
|
+
}, [])
|
|
204
|
+
|
|
205
|
+
// Picking a result ends the interaction (#6196): the list closes and the collapsed
|
|
206
|
+
// summary takes over, but only once the parent has adopted the id. A host that keeps
|
|
207
|
+
// `value` at null and collects picks itself (multi-add pickers) keeps browsing.
|
|
208
|
+
const commitSelection = React.useCallback((item: LookupSelectItem) => {
|
|
209
|
+
selectedItemRef.current = item
|
|
210
|
+
setSelectedItem(item)
|
|
211
|
+
if (valueRef.current === item.id) {
|
|
212
|
+
finishSelection()
|
|
213
|
+
return
|
|
214
|
+
}
|
|
215
|
+
pendingCommitRef.current = item.id
|
|
216
|
+
onChange(item.id)
|
|
217
|
+
}, [finishSelection, onChange])
|
|
218
|
+
|
|
219
|
+
React.useEffect(() => {
|
|
220
|
+
if (pendingCommitRef.current) {
|
|
221
|
+
if (value === pendingCommitRef.current) finishSelection()
|
|
222
|
+
else if (value) pendingCommitRef.current = null
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
// The host adopted a value the user never picked here (seeded after mount): treat it
|
|
226
|
+
// like a finished pick as long as the user is not mid-search.
|
|
227
|
+
if (value && !hasTyped && query.length === 0) setCollapsed(true)
|
|
228
|
+
}, [finishSelection, hasTyped, query, value])
|
|
229
|
+
|
|
230
|
+
// The search box is not in the DOM while the summary row stands in for it, so the focus
|
|
231
|
+
// moves once the box has mounted again.
|
|
232
|
+
const focusAfterReopenRef = React.useRef(false)
|
|
233
|
+
const reopenList = React.useCallback(() => {
|
|
234
|
+
focusAfterReopenRef.current = true
|
|
235
|
+
focusSummaryRef.current = false
|
|
236
|
+
setCollapsed(false)
|
|
237
|
+
}, [])
|
|
238
|
+
const clearSelection = React.useCallback(() => {
|
|
239
|
+
focusAfterReopenRef.current = true
|
|
240
|
+
focusSummaryRef.current = false
|
|
241
|
+
onChange(null)
|
|
242
|
+
}, [onChange])
|
|
243
|
+
|
|
244
|
+
// With nothing selected there is no summary to collapse onto, so the browse list comes back.
|
|
245
|
+
React.useEffect(() => {
|
|
246
|
+
if (!value) setCollapsed(false)
|
|
247
|
+
}, [value])
|
|
248
|
+
|
|
184
249
|
const handleInputKeyDown = React.useCallback((event: React.KeyboardEvent<HTMLInputElement>) => {
|
|
185
250
|
if (!listboxVisible) return
|
|
186
251
|
if (event.key === 'ArrowDown') {
|
|
@@ -198,8 +263,7 @@ export function LookupSelect({
|
|
|
198
263
|
const item = items[activeIndex]
|
|
199
264
|
if (!isInteractiveItem(item)) return
|
|
200
265
|
event.preventDefault()
|
|
201
|
-
|
|
202
|
-
setActiveIndex(-1)
|
|
266
|
+
commitSelection(item)
|
|
203
267
|
return
|
|
204
268
|
}
|
|
205
269
|
if (event.key === 'Escape') {
|
|
@@ -208,9 +272,10 @@ export function LookupSelect({
|
|
|
208
272
|
event.stopPropagation()
|
|
209
273
|
setQuery('')
|
|
210
274
|
setActiveIndex(-1)
|
|
275
|
+
focusSummaryRef.current = Boolean(value)
|
|
211
276
|
setCollapsed(true)
|
|
212
277
|
}
|
|
213
|
-
}, [activeIndex, items, isInteractiveItem, listboxVisible, moveActiveIndex,
|
|
278
|
+
}, [activeIndex, commitSelection, items, isInteractiveItem, listboxVisible, moveActiveIndex, query, value])
|
|
214
279
|
React.useEffect(() => {
|
|
215
280
|
if (disabled) {
|
|
216
281
|
setItems(options ?? [])
|
|
@@ -261,8 +326,6 @@ export function LookupSelect({
|
|
|
261
326
|
}
|
|
262
327
|
}, [query, shouldSearch, fetchKey])
|
|
263
328
|
|
|
264
|
-
const [selectedItem, setSelectedItem] = React.useState<LookupSelectItem | null>(null)
|
|
265
|
-
|
|
266
329
|
React.useEffect(() => {
|
|
267
330
|
if (!value) {
|
|
268
331
|
selectedItemRef.current = null
|
|
@@ -277,29 +340,50 @@ export function LookupSelect({
|
|
|
277
340
|
}, [items, value])
|
|
278
341
|
|
|
279
342
|
/*
|
|
280
|
-
* The collapsed summary
|
|
281
|
-
* `selectedHintLabel`
|
|
282
|
-
*
|
|
283
|
-
*
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
*
|
|
343
|
+
* The collapsed summary needs a label it can trust: the consumer's
|
|
344
|
+
* `selectedHintLabel` when it resolves to a name, otherwise the title of the
|
|
345
|
+
* item that was actually fetched or picked. A resolver that falls back to the
|
|
346
|
+
* id (`known.get(id) ?? id`) or embeds it ("Selected customer: <id>") is
|
|
347
|
+
* treated as unresolved — a record id must never reach the DOM as a label.
|
|
348
|
+
* With neither (a hydrated value whose lookup returned nothing) there is no
|
|
349
|
+
* summary, so consumers rendering their own label never get a second one.
|
|
287
350
|
*/
|
|
288
351
|
const collapsedSelectionLabel = React.useMemo(() => {
|
|
289
|
-
if (!value
|
|
290
|
-
const hinted = selectedHintLabel(value)
|
|
291
|
-
if (hinted && hinted !== value) return hinted
|
|
352
|
+
if (!value) return null
|
|
353
|
+
const hinted = selectedHintLabel?.(value)
|
|
354
|
+
if (hinted && hinted !== value && !hinted.includes(value)) return hinted
|
|
292
355
|
const fetchedTitle = selectedItem && selectedItem.id === value ? selectedItem.title : null
|
|
293
356
|
return fetchedTitle && fetchedTitle !== value ? fetchedTitle : null
|
|
294
357
|
}, [selectedHintLabel, selectedItem, value])
|
|
358
|
+
const collapsedSelectionSubtitle = selectedItem && selectedItem.id === value ? selectedItem.subtitle ?? null : null
|
|
359
|
+
// Once collapsed on a resolved selection the summary row IS the control: the search box
|
|
360
|
+
// comes back only when the user asks to change the pick, so the field stays one row tall
|
|
361
|
+
// and fits a narrow column (#5109).
|
|
362
|
+
const showSummaryOnly = collapsed && Boolean(collapsedSelectionLabel)
|
|
363
|
+
|
|
364
|
+
// The search box and the summary row replace each other, so whichever held the focus is
|
|
365
|
+
// gone from the DOM: keyboard users continue on the control that took its place.
|
|
366
|
+
React.useEffect(() => {
|
|
367
|
+
if (showSummaryOnly) {
|
|
368
|
+
if (!focusSummaryRef.current) return
|
|
369
|
+
focusSummaryRef.current = false
|
|
370
|
+
changeButtonRef.current?.focus()
|
|
371
|
+
return
|
|
372
|
+
}
|
|
373
|
+
if (!focusAfterReopenRef.current) return
|
|
374
|
+
focusAfterReopenRef.current = false
|
|
375
|
+
inputRef.current?.focus()
|
|
376
|
+
}, [showSummaryOnly])
|
|
295
377
|
|
|
296
378
|
return (
|
|
297
379
|
<div className="space-y-3">
|
|
380
|
+
{showSummaryOnly ? null : (
|
|
298
381
|
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
|
|
299
382
|
<div className="relative flex-1">
|
|
300
383
|
<Search className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
|
301
384
|
<input
|
|
302
|
-
|
|
385
|
+
ref={inputRef}
|
|
386
|
+
className="w-full h-9 rounded-lg border border-input bg-background pl-10 pr-3 text-sm shadow-xs transition-colors outline-none placeholder:text-muted-foreground hover:border-foreground/20 focus-visible:shadow-focus focus-visible:border-foreground disabled:bg-bg-disabled disabled:border-border-disabled disabled:text-muted-foreground disabled:cursor-not-allowed"
|
|
303
387
|
value={query}
|
|
304
388
|
onChange={(event) => {
|
|
305
389
|
setQuery(event.target.value)
|
|
@@ -318,6 +402,7 @@ export function LookupSelect({
|
|
|
318
402
|
</div>
|
|
319
403
|
{actionSlot && !disabled ? <div className="sm:self-start">{actionSlot}</div> : null}
|
|
320
404
|
</div>
|
|
405
|
+
)}
|
|
321
406
|
{/*
|
|
322
407
|
* `shouldSearch` decides whether to FETCH; this decides whether to RENDER a
|
|
323
408
|
* list. They differ for a set value whose lookup comes back empty: develop's
|
|
@@ -353,24 +438,24 @@ export function LookupSelect({
|
|
|
353
438
|
key={item.id}
|
|
354
439
|
id={optionDomId(index)}
|
|
355
440
|
className={cn(
|
|
356
|
-
'group flex items-center gap-
|
|
441
|
+
'group flex items-center gap-3 rounded-lg border px-3 py-2 transition-all duration-150 focus-visible:outline-none focus-visible:shadow-focus',
|
|
357
442
|
isInteractive ? 'cursor-pointer' : 'cursor-not-allowed opacity-60',
|
|
358
443
|
isSelected
|
|
359
|
-
? 'border-
|
|
360
|
-
: 'border-input bg-card hover:border-foreground/20 hover:bg-muted/30
|
|
444
|
+
? 'border-accent-indigo bg-accent-indigo/5'
|
|
445
|
+
: 'border-input bg-card hover:border-foreground/20 hover:bg-muted/30',
|
|
361
446
|
isActive && !isSelected ? 'border-foreground/20 bg-muted/30 shadow-sm' : null
|
|
362
447
|
)}
|
|
363
448
|
role="option"
|
|
364
449
|
tabIndex={isInteractive ? 0 : -1}
|
|
365
450
|
onClick={() => {
|
|
366
451
|
if (!isInteractive) return
|
|
367
|
-
|
|
452
|
+
commitSelection(item)
|
|
368
453
|
}}
|
|
369
454
|
onKeyDown={(event) => {
|
|
370
455
|
if (event.key === 'Enter' || event.key === ' ') {
|
|
371
456
|
event.preventDefault()
|
|
372
457
|
if (!isInteractive) return
|
|
373
|
-
|
|
458
|
+
commitSelection(item)
|
|
374
459
|
}
|
|
375
460
|
}}
|
|
376
461
|
aria-selected={isSelected}
|
|
@@ -378,22 +463,22 @@ export function LookupSelect({
|
|
|
378
463
|
title={isSelected ? resolvedSelectedLabel : isInteractive ? resolvedSelectLabel : undefined}
|
|
379
464
|
>
|
|
380
465
|
{item.icon ? (
|
|
381
|
-
<div className="flex h-
|
|
466
|
+
<div className="flex h-8 w-8 shrink-0 items-center justify-center overflow-hidden [&>svg]:size-5 [&_svg]:text-muted-foreground">
|
|
382
467
|
{item.icon}
|
|
383
468
|
</div>
|
|
384
469
|
) : (
|
|
385
470
|
<div className={cn(
|
|
386
|
-
'flex h-
|
|
471
|
+
'flex h-8 w-8 shrink-0 items-center justify-center overflow-hidden rounded-md border transition-colors',
|
|
387
472
|
isSelected
|
|
388
|
-
? 'border-
|
|
473
|
+
? 'border-accent-indigo/40 bg-accent-indigo/10 text-accent-indigo'
|
|
389
474
|
: 'border-input bg-muted text-muted-foreground group-hover:border-foreground/20'
|
|
390
475
|
)}>
|
|
391
|
-
<span className="text-
|
|
476
|
+
<span className="text-sm font-medium uppercase">{item.title.slice(0, 1)}</span>
|
|
392
477
|
</div>
|
|
393
478
|
)}
|
|
394
479
|
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
|
395
480
|
<div className="flex items-center justify-between gap-3">
|
|
396
|
-
<div className="truncate text-sm font-
|
|
481
|
+
<div className="truncate text-sm font-medium text-foreground">{item.title}</div>
|
|
397
482
|
{item.rightLabel ? (
|
|
398
483
|
<div className="shrink-0 text-overline font-medium uppercase tracking-wider text-muted-foreground">
|
|
399
484
|
{item.rightLabel}
|
|
@@ -407,9 +492,12 @@ export function LookupSelect({
|
|
|
407
492
|
<div className="text-xs text-muted-foreground/70 truncate">{item.description}</div>
|
|
408
493
|
) : null}
|
|
409
494
|
</div>
|
|
410
|
-
<div className="flex shrink-0 items-center justify-center">
|
|
495
|
+
<div className="flex shrink-0 items-center justify-center gap-1.5">
|
|
411
496
|
{isSelected ? (
|
|
412
|
-
|
|
497
|
+
<>
|
|
498
|
+
<span className="text-xs font-medium text-foreground">{resolvedSelectedLabel}</span>
|
|
499
|
+
<Check className="size-4 text-accent-indigo" aria-hidden="true" />
|
|
500
|
+
</>
|
|
413
501
|
) : (
|
|
414
502
|
<div className="size-5" aria-hidden="true" />
|
|
415
503
|
)}
|
|
@@ -433,30 +521,55 @@ export function LookupSelect({
|
|
|
433
521
|
</div>
|
|
434
522
|
) : collapsedSelectionLabel ? (
|
|
435
523
|
/*
|
|
436
|
-
* The
|
|
437
|
-
*
|
|
438
|
-
* then collapsed left the control looking empty even though the form
|
|
439
|
-
* held the id. `selectedHintLabel` existed for exactly this and was
|
|
440
|
-
* never rendered.
|
|
524
|
+
* The selection as a single row: the name is the control that reopens the
|
|
525
|
+
* search (Change), the icon clears. No second search box above it.
|
|
441
526
|
*/
|
|
442
527
|
<div
|
|
443
|
-
className=
|
|
528
|
+
className={cn(
|
|
529
|
+
'flex h-9 items-center gap-1 rounded-lg border border-accent-indigo bg-accent-indigo/5 pl-1 pr-1',
|
|
530
|
+
disabled && 'border-border-disabled bg-bg-disabled',
|
|
531
|
+
)}
|
|
444
532
|
data-testid="lookup-select-selected"
|
|
445
533
|
>
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
534
|
+
{disabled ? (
|
|
535
|
+
<span className="flex h-7 min-w-0 flex-1 items-center gap-2 px-2 text-muted-foreground">
|
|
536
|
+
<Check className="size-4 shrink-0" aria-hidden="true" />
|
|
537
|
+
<span className="truncate text-sm">{collapsedSelectionLabel}</span>
|
|
538
|
+
{collapsedSelectionSubtitle ? (
|
|
539
|
+
<span className="hidden truncate text-xs sm:inline">{collapsedSelectionSubtitle}</span>
|
|
540
|
+
) : null}
|
|
541
|
+
</span>
|
|
542
|
+
) : (
|
|
543
|
+
<Button
|
|
544
|
+
ref={changeButtonRef}
|
|
545
|
+
type="button"
|
|
546
|
+
variant="ghost"
|
|
547
|
+
size="sm"
|
|
548
|
+
className="h-7 min-w-0 flex-1 justify-start gap-2 px-2 text-left font-normal hover:bg-accent-indigo/10 hover:text-accent-indigo"
|
|
549
|
+
onClick={reopenList}
|
|
550
|
+
aria-label={resolvedChangeLabel}
|
|
551
|
+
title={resolvedChangeLabel}
|
|
552
|
+
>
|
|
553
|
+
<Check className="size-4 shrink-0 text-accent-indigo" aria-hidden="true" />
|
|
554
|
+
<span className="truncate text-sm text-foreground">{collapsedSelectionLabel}</span>
|
|
555
|
+
{collapsedSelectionSubtitle ? (
|
|
556
|
+
<span className="hidden truncate text-xs text-muted-foreground sm:inline">{collapsedSelectionSubtitle}</span>
|
|
557
|
+
) : null}
|
|
558
|
+
</Button>
|
|
559
|
+
)}
|
|
560
|
+
{disabled ? null : (
|
|
561
|
+
<IconButton
|
|
562
|
+
type="button"
|
|
563
|
+
variant="ghost"
|
|
564
|
+
size="sm"
|
|
565
|
+
className="shrink-0 text-muted-foreground hover:bg-accent-indigo/10 hover:text-accent-indigo"
|
|
566
|
+
onClick={clearSelection}
|
|
567
|
+
aria-label={resolvedClearLabel}
|
|
568
|
+
title={resolvedClearLabel}
|
|
569
|
+
>
|
|
570
|
+
<X className="size-4" aria-hidden="true" />
|
|
571
|
+
</IconButton>
|
|
572
|
+
)}
|
|
460
573
|
</div>
|
|
461
574
|
) : hasTyped ? (
|
|
462
575
|
<p className="text-xs text-muted-foreground">
|
|
@@ -48,6 +48,28 @@ function blurAndFlush(input: HTMLElement) {
|
|
|
48
48
|
})
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
it('associates the input with its label and accessibility description', () => {
|
|
52
|
+
render(
|
|
53
|
+
<>
|
|
54
|
+
<label htmlFor="color-input">Color</label>
|
|
55
|
+
<span id="color-help">Choose a color</span>
|
|
56
|
+
<Harness
|
|
57
|
+
id="color-input"
|
|
58
|
+
aria-describedby="color-help"
|
|
59
|
+
aria-invalid
|
|
60
|
+
aria-required
|
|
61
|
+
/>
|
|
62
|
+
</>
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
const input = screen.getByRole('combobox', { name: 'Color' })
|
|
66
|
+
expect(screen.getByLabelText('Color')).toBe(input)
|
|
67
|
+
expect(input).toHaveAttribute('id', 'color-input')
|
|
68
|
+
expect(input).toHaveAccessibleDescription('Choose a color')
|
|
69
|
+
expect(input).toHaveAttribute('aria-invalid', 'true')
|
|
70
|
+
expect(input).toHaveAttribute('aria-required', 'true')
|
|
71
|
+
})
|
|
72
|
+
|
|
51
73
|
describe('ComboboxInput clearable behavior', () => {
|
|
52
74
|
beforeEach(() => {
|
|
53
75
|
jest.useFakeTimers()
|