@open-mercato/ui 0.6.3-develop.3838.1.7f2657a47c → 0.6.3-develop.3851.1.642df0a016

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.
@@ -1,17 +1,138 @@
1
+ /** @jest-environment jsdom */
2
+
1
3
  jest.mock('@open-mercato/shared/lib/i18n/context', () => ({
2
4
  useT: () => (_key: string, fallback: string) => fallback,
3
5
  }))
4
6
 
5
7
  import * as React from 'react'
6
- import { act, render, fireEvent, waitFor } from '@testing-library/react'
8
+ import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
7
9
  import { ComboboxInput } from '../ComboboxInput'
8
10
 
11
+ type HarnessProps = Partial<React.ComponentProps<typeof ComboboxInput>> & {
12
+ initialValue?: string
13
+ }
14
+
15
+ function Harness({ initialValue = '', onChange, ...rest }: HarnessProps) {
16
+ const [value, setValue] = React.useState(initialValue)
17
+ return (
18
+ <div>
19
+ <ComboboxInput
20
+ value={value}
21
+ onChange={(next) => {
22
+ setValue(next)
23
+ onChange?.(next)
24
+ }}
25
+ suggestions={[
26
+ { value: 'red', label: 'Red' },
27
+ { value: 'green', label: 'Green' },
28
+ ]}
29
+ {...rest}
30
+ />
31
+ <output data-testid="value">{value}</output>
32
+ </div>
33
+ )
34
+ }
35
+
9
36
  function getInput(container: HTMLElement): HTMLInputElement {
10
37
  const el = container.querySelector('input')
11
38
  if (!el) throw new Error('input not found')
12
39
  return el as HTMLInputElement
13
40
  }
14
41
 
42
+ function blurAndFlush(input: HTMLElement) {
43
+ act(() => {
44
+ fireEvent.blur(input)
45
+ })
46
+ act(() => {
47
+ jest.advanceTimersByTime(250)
48
+ })
49
+ }
50
+
51
+ describe('ComboboxInput clearable behavior', () => {
52
+ beforeEach(() => {
53
+ jest.useFakeTimers()
54
+ })
55
+
56
+ afterEach(() => {
57
+ act(() => {
58
+ jest.runOnlyPendingTimers()
59
+ })
60
+ jest.useRealTimers()
61
+ })
62
+
63
+ it('reverts to current value on blur with empty input when not clearable and custom values disallowed', () => {
64
+ const onChange = jest.fn()
65
+ render(
66
+ <Harness
67
+ initialValue="red"
68
+ clearable={false}
69
+ allowCustomValues={false}
70
+ onChange={onChange}
71
+ />
72
+ )
73
+
74
+ const input = screen.getByRole('textbox') as HTMLInputElement
75
+ expect(input.value).toBe('Red')
76
+
77
+ fireEvent.focus(input)
78
+ fireEvent.change(input, { target: { value: '' } })
79
+ expect(input.value).toBe('')
80
+
81
+ blurAndFlush(input)
82
+
83
+ expect(input.value).toBe('Red')
84
+ expect(screen.getByTestId('value')).toHaveTextContent('red')
85
+ expect(onChange).not.toHaveBeenCalled()
86
+ })
87
+
88
+ it('emits empty string on blur with empty input when clearable, regardless of allowCustomValues', () => {
89
+ const onChange = jest.fn()
90
+ render(
91
+ <Harness
92
+ initialValue="red"
93
+ clearable
94
+ allowCustomValues={false}
95
+ onChange={onChange}
96
+ />
97
+ )
98
+
99
+ const input = screen.getByRole('textbox') as HTMLInputElement
100
+ fireEvent.focus(input)
101
+ fireEvent.change(input, { target: { value: '' } })
102
+
103
+ blurAndFlush(input)
104
+
105
+ expect(onChange).toHaveBeenCalledWith('')
106
+ expect(screen.getByTestId('value')).toHaveTextContent('')
107
+ expect(input.value).toBe('')
108
+ })
109
+
110
+ it('renders a clear button when clearable and a value is set, and clears via click', () => {
111
+ const onChange = jest.fn()
112
+ render(<Harness initialValue="red" clearable onChange={onChange} />)
113
+
114
+ const input = screen.getByRole('textbox') as HTMLInputElement
115
+ expect(input.value).toBe('Red')
116
+
117
+ const clearBtn = screen.getByRole('button', { name: /clear value/i })
118
+ fireEvent.click(clearBtn)
119
+
120
+ expect(onChange).toHaveBeenCalledWith('')
121
+ expect(screen.getByTestId('value')).toHaveTextContent('')
122
+ expect(input.value).toBe('')
123
+ })
124
+
125
+ it('does not render the clear button when clearable is false', () => {
126
+ render(<Harness initialValue="red" clearable={false} />)
127
+ expect(screen.queryByRole('button', { name: /clear value/i })).toBeNull()
128
+ })
129
+
130
+ it('does not render the clear button when clearable is true but no value is set', () => {
131
+ render(<Harness initialValue="" clearable />)
132
+ expect(screen.queryByRole('button', { name: /clear value/i })).toBeNull()
133
+ })
134
+ })
135
+
15
136
  describe('ComboboxInput — eager label resolution', () => {
16
137
  it('renders the raw value when nothing can resolve it', () => {
17
138
  const { container } = render(<ComboboxInput value="uuid-123" onChange={() => {}} />)
@@ -34,7 +155,6 @@ describe('ComboboxInput — eager label resolution', () => {
34
155
  const { container } = render(
35
156
  <ComboboxInput value="uuid-123" onChange={() => {}} resolveLabel={resolveLabel} />,
36
157
  )
37
- // before the promise resolves, falls back to the raw value
38
158
  expect(getInput(container).value).toBe('uuid-123')
39
159
  await waitFor(() => expect(getInput(container).value).toBe('Resolved uuid-123'))
40
160
  expect(resolveLabel).toHaveBeenCalledWith('uuid-123')
@@ -52,6 +172,19 @@ describe('ComboboxInput — eager label resolution', () => {
52
172
  await waitFor(() => expect(getInput(container).value).toBe('Sync Label'))
53
173
  })
54
174
 
175
+ it('swallows synchronous throws from resolveLabel', async () => {
176
+ const resolveLabel = jest.fn(() => {
177
+ throw new Error('boom')
178
+ })
179
+
180
+ const { container } = render(
181
+ <ComboboxInput value="uuid-123" onChange={() => {}} resolveLabel={resolveLabel} />,
182
+ )
183
+
184
+ await waitFor(() => expect(resolveLabel).toHaveBeenCalledWith('uuid-123'))
185
+ expect(getInput(container).value).toBe('uuid-123')
186
+ })
187
+
55
188
  it('does not call resolveLabel when the value is already covered by suggestions', () => {
56
189
  const resolveLabel = jest.fn(() => 'should-not-be-used')
57
190
  render(
@@ -74,6 +207,34 @@ describe('ComboboxInput — eager label resolution', () => {
74
207
  expect(loadSuggestions).toHaveBeenCalledWith()
75
208
  })
76
209
 
210
+ it('swallows synchronous throws from loadSuggestions', async () => {
211
+ jest.useFakeTimers()
212
+ const loadSuggestions = jest.fn(() => {
213
+ throw new Error('boom')
214
+ })
215
+
216
+ try {
217
+ const { container } = render(
218
+ <ComboboxInput value="" onChange={() => {}} loadSuggestions={loadSuggestions} />,
219
+ )
220
+ const input = getInput(container)
221
+
222
+ act(() => {
223
+ fireEvent.focus(input)
224
+ fireEvent.change(input, { target: { value: 'a' } })
225
+ })
226
+
227
+ await act(async () => {
228
+ jest.advanceTimersByTime(200)
229
+ })
230
+
231
+ await waitFor(() => expect(loadSuggestions).toHaveBeenCalledWith('a'))
232
+ expect(getInput(container).value).toBe('a')
233
+ } finally {
234
+ jest.useRealTimers()
235
+ }
236
+ })
237
+
77
238
  it('does not reload suggestions after a self-labeled value is covered', async () => {
78
239
  const loadSuggestions = jest.fn(async () => [{ value: 'UTC', label: 'UTC' }])
79
240
  const { container } = render(
@@ -81,9 +242,9 @@ describe('ComboboxInput — eager label resolution', () => {
81
242
  )
82
243
 
83
244
  await waitFor(() => expect(loadSuggestions).toHaveBeenCalledTimes(1))
84
- await act(async () => {
85
- await new Promise((resolve) => setTimeout(resolve, 25))
86
- })
245
+ // flush microtask queue to let any pending effects settle
246
+ await act(async () => { await Promise.resolve() })
247
+ await act(async () => { await Promise.resolve() })
87
248
 
88
249
  expect(loadSuggestions).toHaveBeenCalledTimes(1)
89
250
  expect(getInput(container).value).toBe('UTC')
@@ -96,12 +257,85 @@ describe('ComboboxInput — eager label resolution', () => {
96
257
  )
97
258
 
98
259
  await waitFor(() => expect(loadSuggestions).toHaveBeenCalledTimes(1))
260
+ await act(async () => { await Promise.resolve() })
261
+ await act(async () => { await Promise.resolve() })
262
+
263
+ expect(loadSuggestions).toHaveBeenCalledTimes(1)
264
+ expect(getInput(container).value).toBe('UTC')
265
+ })
266
+
267
+ it('keeps the popup open when blur happens while async suggestions are still loading', async () => {
268
+ let resolveSuggestions: (items: Array<string | { value: string; label: string }>) => void = () => {}
269
+ const loadSuggestions = jest.fn(
270
+ () =>
271
+ new Promise<Array<string | { value: string; label: string }>>((resolve) => {
272
+ resolveSuggestions = resolve
273
+ }),
274
+ )
275
+
276
+ const { container, queryByText } = render(
277
+ <div>
278
+ <ComboboxInput value="" onChange={() => {}} loadSuggestions={loadSuggestions} />
279
+ </div>,
280
+ )
281
+ const input = getInput(container)
282
+
283
+ act(() => {
284
+ fireEvent.focus(input)
285
+ fireEvent.change(input, { target: { value: 'a' } })
286
+ fireEvent.blur(input)
287
+ })
288
+
289
+ await act(async () => {
290
+ await new Promise((resolve) => setTimeout(resolve, 225))
291
+ })
292
+
293
+ expect(loadSuggestions).toHaveBeenCalledWith('a')
294
+ await waitFor(() => expect(queryByText(/Loading suggestions/i)).toBeTruthy())
295
+
99
296
  await act(async () => {
297
+ resolveSuggestions([{ value: 'acme', label: 'Acme Corp' }])
298
+ await Promise.resolve()
100
299
  await new Promise((resolve) => setTimeout(resolve, 25))
101
300
  })
102
301
 
103
- expect(loadSuggestions).toHaveBeenCalledTimes(1)
104
- expect(getInput(container).value).toBe('UTC')
302
+ await waitFor(() => expect(queryByText(/Loading suggestions/i)).toBeNull())
303
+ await waitFor(() => expect(queryByText('Acme Corp')).toBeNull())
304
+ })
305
+
306
+ it('closes the popup after a bounded delay when async suggestions never finish', async () => {
307
+ jest.useFakeTimers()
308
+ const loadSuggestions = jest.fn(
309
+ () => new Promise<Array<string | { value: string; label: string }>>(() => {}),
310
+ )
311
+
312
+ try {
313
+ const { container, queryByText } = render(
314
+ <ComboboxInput value="" onChange={() => {}} loadSuggestions={loadSuggestions} />,
315
+ )
316
+ const input = getInput(container)
317
+
318
+ act(() => {
319
+ fireEvent.focus(input)
320
+ fireEvent.change(input, { target: { value: 'a' } })
321
+ fireEvent.blur(input)
322
+ })
323
+
324
+ await act(async () => {
325
+ jest.advanceTimersByTime(450)
326
+ })
327
+
328
+ expect(loadSuggestions).toHaveBeenCalledWith('a')
329
+ expect(queryByText(/Loading suggestions/i)).toBeTruthy()
330
+
331
+ await act(async () => {
332
+ jest.advanceTimersByTime(1001)
333
+ })
334
+
335
+ expect(queryByText(/Loading suggestions/i)).toBeNull()
336
+ } finally {
337
+ jest.useRealTimers()
338
+ }
105
339
  })
106
340
 
107
341
  it('keeps the resolved label after a blur revert when custom values are disallowed', async () => {
@@ -141,7 +375,6 @@ describe('ComboboxInput — eager label resolution', () => {
141
375
  />,
142
376
  )
143
377
  const input = getInput(container)
144
- // user clears the field before resolution lands, then blurs
145
378
  act(() => {
146
379
  fireEvent.change(input, { target: { value: '' } })
147
380
  fireEvent.blur(input)
@@ -149,9 +382,7 @@ describe('ComboboxInput — eager label resolution', () => {
149
382
  await act(async () => {
150
383
  await new Promise((res) => setTimeout(res, 250))
151
384
  })
152
- // the raw uuid must not have been written into the visible input
153
385
  expect(getInput(container).value).not.toBe('uuid-123')
154
- // once resolution arrives, the label shows up
155
386
  act(() => resolve('Acme Corp'))
156
387
  await waitFor(() => expect(getInput(container).value).toBe('Acme Corp'))
157
388
  })
@@ -55,17 +55,42 @@ describe('apiFetch', () => {
55
55
  jest.restoreAllMocks()
56
56
  })
57
57
 
58
- it('throws ForbiddenError when backend returns ACL hints', async () => {
58
+ it('throws ForbiddenError and flashes a non-redirecting banner when backend returns ACL hints', async () => {
59
59
  ;(window as unknown as Record<string, unknown>).__omOriginalFetch = jest.fn(async () =>
60
60
  createMockResponse(403, {
61
61
  error: 'Forbidden',
62
62
  requiredRoles: ['Admin'],
63
63
  }),
64
64
  )
65
+ const initialPath = window.location.pathname
65
66
 
66
67
  await expect(apiFetch('/api/private')).rejects.toBeInstanceOf(ForbiddenError)
67
68
  expect(flash).toHaveBeenCalledWith(
68
- 'Insufficient permissions. Redirecting to login…',
69
+ expect.stringContaining('Access denied'),
70
+ 'warning',
71
+ )
72
+ expect(flash).toHaveBeenCalledWith(
73
+ expect.stringContaining('Admin'),
74
+ 'warning',
75
+ )
76
+
77
+ // Regression for GH #2070: authenticated 403 must not redirect to /login.
78
+ jest.advanceTimersByTime(1000)
79
+ expect(window.location.pathname).toBe(initialPath)
80
+ expect(window.location.pathname).not.toContain('/login')
81
+ })
82
+
83
+ it('includes the missing feature name in the flash so the user sees the actual permission required', async () => {
84
+ ;(window as unknown as Record<string, unknown>).__omOriginalFetch = jest.fn(async () =>
85
+ createMockResponse(403, {
86
+ error: 'Forbidden',
87
+ requiredFeatures: ['sales.channels.manage'],
88
+ }),
89
+ )
90
+
91
+ await expect(apiFetch('/api/sales/channels')).rejects.toBeInstanceOf(ForbiddenError)
92
+ expect(flash).toHaveBeenCalledWith(
93
+ expect.stringContaining('sales.channels.manage'),
69
94
  'warning',
70
95
  )
71
96
  })
@@ -85,32 +85,47 @@ export function setAuthRedirectConfig(cfg: { defaultForbiddenRoles?: readonly st
85
85
  }
86
86
  }
87
87
 
88
- export function redirectToForbiddenLogin(options?: { requiredRoles?: string[] | null; requiredFeatures?: string[] | null }) {
88
+ function formatForbiddenAccessMessage(options?: { requiredRoles?: string[] | null; requiredFeatures?: string[] | null }): string {
89
+ const features = options?.requiredFeatures?.filter(Boolean) ?? []
90
+ const roles = options?.requiredRoles?.filter(Boolean) ?? []
91
+ const effectiveRoles = roles.length ? roles : DEFAULT_FORBIDDEN_ROLES.filter(Boolean)
92
+ if (features.length) {
93
+ return `Access denied: you are missing the required permission "${features.join(', ')}". Contact your administrator.`
94
+ }
95
+ if (effectiveRoles.length) {
96
+ return `Access denied: this area requires the role "${effectiveRoles.join(', ')}". Contact your administrator.`
97
+ }
98
+ return 'Access denied: you do not have permission to perform this action.'
99
+ }
100
+
101
+ /**
102
+ * Signal a forbidden access attempt for an authenticated user via a flash banner.
103
+ *
104
+ * Authenticated 403 responses must never redirect to `/login` — that creates an
105
+ * infinite loop because the login page detects the active session and bounces
106
+ * the user back to the failing destination (see GH #2070). Pages that need an
107
+ * inline banner should catch `ForbiddenError` and render `AccessDeniedMessage`
108
+ * from `@open-mercato/ui/backend/detail`.
109
+ */
110
+ export function notifyForbiddenAccess(options?: { requiredRoles?: string[] | null; requiredFeatures?: string[] | null }) {
89
111
  if (typeof window === 'undefined') return
90
- if (window.location.pathname.startsWith('/login')) return
91
- // Portal routes have their own customer auth — never redirect to staff login
112
+ // Portal routes have their own customer auth — keep the existing no-op contract.
92
113
  if (/\/[^/]+\/portal(\/|$)/.test(window.location.pathname)) return
93
114
  try {
94
- const current = window.location.pathname + window.location.search
95
- const features = options?.requiredFeatures?.filter(Boolean) ?? []
96
- const roles = options?.requiredRoles?.filter(Boolean) ?? []
97
- const fallbackRoles = DEFAULT_FORBIDDEN_ROLES.filter(Boolean)
98
- const effectiveRoles = roles.length ? roles : fallbackRoles
99
- const query = features.length
100
- ? `requireFeature=${encodeURIComponent(features.join(','))}`
101
- : effectiveRoles.length
102
- ? `requireRole=${encodeURIComponent(effectiveRoles.map(String).join(','))}`
103
- : ''
104
- const url = query
105
- ? `/login?${query}&redirect=${encodeURIComponent(current)}`
106
- : `/login?redirect=${encodeURIComponent(current)}`
107
- flash('Insufficient permissions. Redirecting to login…', 'warning')
108
- setTimeout(() => { window.location.href = url }, 60)
115
+ flash(formatForbiddenAccessMessage(options), 'warning')
109
116
  } catch {
110
117
  // no-op
111
118
  }
112
119
  }
113
120
 
121
+ /**
122
+ * @deprecated Renamed to {@link notifyForbiddenAccess}. The previous name
123
+ * implied a `/login` redirect that no longer happens (see GH #2070). Kept as an
124
+ * exported alias for one minor version so third-party module imports keep
125
+ * building; update imports to `notifyForbiddenAccess`.
126
+ */
127
+ export const redirectToForbiddenLogin = notifyForbiddenAccess
128
+
114
129
  export async function apiFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
115
130
  type FetchType = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
116
131
  const originalFetch =
@@ -191,7 +206,7 @@ export async function apiFetch(input: RequestInfo | URL, init?: RequestInit): Pr
191
206
  } catch {}
192
207
  const hasAclHints = Boolean((roles && roles.length) || (features && features.length))
193
208
  if (hasAclHints) {
194
- redirectToForbiddenLogin({ requiredRoles: roles, requiredFeatures: features })
209
+ notifyForbiddenAccess({ requiredRoles: roles, requiredFeatures: features })
195
210
  }
196
211
  let msg = 'Forbidden'
197
212
  if (aclData && typeof aclData === 'object') {
@@ -1,9 +1,10 @@
1
1
  "use client"
2
2
  import * as React from 'react'
3
3
  import { MutationCache, QueryCache, QueryClient, QueryClientProvider } from '@tanstack/react-query'
4
- import { redirectToSessionRefresh, redirectToForbiddenLogin, UnauthorizedError, ForbiddenError, apiFetch, setAuthRedirectConfig } from '../backend/utils/api'
4
+ import { redirectToSessionRefresh, notifyForbiddenAccess, UnauthorizedError, ForbiddenError, apiFetch, setAuthRedirectConfig } from '../backend/utils/api'
5
5
 
6
- // Ensure global fetch calls also respect our redirect-on-401/403 policy.
6
+ // Ensure global fetch calls also flow through apiFetch so 401 session-refresh
7
+ // and 403 access-denied flash banners fire consistently.
7
8
  function ensureGlobalFetchInterception() {
8
9
  if (typeof window === 'undefined') return
9
10
  const w = window as any
@@ -17,18 +18,18 @@ const client = new QueryClient({
17
18
  queryCache: new QueryCache({
18
19
  onError: (error) => {
19
20
  if (error instanceof UnauthorizedError) redirectToSessionRefresh()
20
- else if (error instanceof ForbiddenError) redirectToForbiddenLogin()
21
+ else if (error instanceof ForbiddenError) notifyForbiddenAccess()
21
22
  // As a fallback, try to detect common cases
22
23
  else if ((error as any)?.status === 401) redirectToSessionRefresh()
23
- else if ((error as any)?.status === 403) redirectToForbiddenLogin()
24
+ else if ((error as any)?.status === 403) notifyForbiddenAccess()
24
25
  },
25
26
  }),
26
27
  mutationCache: new MutationCache({
27
28
  onError: (error) => {
28
29
  if (error instanceof UnauthorizedError) redirectToSessionRefresh()
29
- else if (error instanceof ForbiddenError) redirectToForbiddenLogin()
30
+ else if (error instanceof ForbiddenError) notifyForbiddenAccess()
30
31
  else if ((error as any)?.status === 401) redirectToSessionRefresh()
31
- else if ((error as any)?.status === 403) redirectToForbiddenLogin()
32
+ else if ((error as any)?.status === 403) notifyForbiddenAccess()
32
33
  },
33
34
  }),
34
35
  })