@open-mercato/ui 0.11.1-develop.8298.1.5323e2aa15 → 0.11.1-develop.8317.1.dde3d38b64

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.
@@ -0,0 +1,148 @@
1
+ import * as React from 'react'
2
+ import { act, fireEvent, screen, waitFor } from '@testing-library/react'
3
+ import { renderWithProviders } from '@open-mercato/shared/lib/testing/renderWithProviders'
4
+ import { createFallbackTranslator } from '@open-mercato/shared/lib/i18n/translate'
5
+ import customerPolish from '@open-mercato/core/modules/customers/i18n/pl.json'
6
+ import staffPolish from '@open-mercato/core/modules/staff/i18n/pl.json'
7
+ import { flash } from '@open-mercato/ui/backend/FlashMessages'
8
+ import { Button } from '@open-mercato/ui/primitives/button'
9
+ import { AddressTiles, type AddressValue } from '../AddressTiles'
10
+ import { AddressesSection, type AddressDataAdapter, type AddressSummary } from '../AddressesSection'
11
+ import type { AddressTypeOption, AddressTypesAdapter } from '../AddressEditor'
12
+ import { registerTelemetryErrorReporter } from '@open-mercato/shared/lib/telemetry/runtime'
13
+
14
+ const mockReportError = jest.fn()
15
+ let disposeReporter: () => void
16
+
17
+ jest.mock('next/navigation', () => ({
18
+ usePathname: () => '/backend/staff/team-members/member-1',
19
+ useSearchParams: () => new URLSearchParams(),
20
+ }))
21
+ jest.mock('@open-mercato/ui/backend/FlashMessages', () => ({ flash: jest.fn() }))
22
+ jest.mock('@open-mercato/ui/backend/detail', () => ({
23
+ LoadingMessage: ({ label }: { label: string }) => <div role="status">{label}</div>,
24
+ TabEmptyState: ({ action }: { action: { label: string; onClick: () => void } }) => (
25
+ <Button type="button" onClick={action.onClick}>{action.label}</Button>
26
+ ),
27
+ }))
28
+ jest.mock('../../injection/useRegisteredComponent', () => ({
29
+ useRegisteredComponent: (_handle: string, fallback: React.ComponentType) => fallback,
30
+ }))
31
+
32
+ const customerTranslator = createFallbackTranslator(customerPolish)
33
+ const address: AddressValue = { id: 'address-1', name: 'Biuro W47', purpose: 'office', addressLine1: 'Długa 1' }
34
+ const emptyAdapter: AddressDataAdapter = {
35
+ list: async () => [],
36
+ create: async () => undefined,
37
+ update: async () => undefined,
38
+ delete: async () => undefined,
39
+ }
40
+
41
+ function tiles(adapter?: AddressTypesAdapter<string>, context?: string) {
42
+ return (
43
+ <AddressTiles
44
+ addresses={[address, { ...address, id: 'address-2', name: 'Custom', purpose: 'legacy-type' }]}
45
+ onCreate={async () => undefined}
46
+ t={customerTranslator}
47
+ emptyLabel="Brak adresów"
48
+ addressTypesAdapter={adapter}
49
+ addressTypesContext={context}
50
+ />
51
+ )
52
+ }
53
+
54
+ function section(prefix: string, adapter = emptyAdapter) {
55
+ return (
56
+ <AddressesSection
57
+ entityId="member-1"
58
+ emptyLabel="Brak adresów"
59
+ addActionLabel="Dodaj adres"
60
+ emptyState={{ title: 'Brak adresów', actionLabel: 'Dodaj adres' }}
61
+ dataAdapter={adapter}
62
+ labelPrefix={prefix}
63
+ />
64
+ )
65
+ }
66
+
67
+ describe('localized shared addresses', () => {
68
+ beforeEach(() => {
69
+ jest.mocked(flash).mockClear()
70
+ mockReportError.mockReset()
71
+ disposeReporter = registerTelemetryErrorReporter(mockReportError)
72
+ })
73
+
74
+ afterEach(() => disposeReporter())
75
+
76
+ it('shows dictionary labels on cards and preserves unknown type values', async () => {
77
+ const list = jest.fn(async () => [{ value: 'office', label: 'Biuro' }])
78
+ renderWithProviders(tiles({ list }, 'organization-1'))
79
+
80
+ expect(await screen.findByText('Biuro')).toBeInTheDocument()
81
+ expect(screen.queryByText('office')).not.toBeInTheDocument()
82
+ expect(screen.getByText('legacy-type')).toBeInTheDocument()
83
+ expect(list).toHaveBeenCalledWith('organization-1')
84
+ expect(mockReportError).not.toHaveBeenCalled()
85
+ })
86
+
87
+ it('keeps addresses readable without a dictionary adapter', () => {
88
+ renderWithProviders(tiles())
89
+ expect(screen.getByText('office')).toBeInTheDocument()
90
+ })
91
+
92
+ it.each(['active', 'disabled', 'throwing'] as const)('keeps addresses readable and localizes a dictionary load failure with %s telemetry', async (telemetry) => {
93
+ const error = new Error('[internal] dictionary unavailable')
94
+ if (telemetry === 'disabled') disposeReporter()
95
+ if (telemetry === 'throwing') {
96
+ mockReportError.mockImplementation(() => { throw new Error('[internal] telemetry unavailable') })
97
+ }
98
+ renderWithProviders(tiles({ list: async () => { throw error } }))
99
+ await waitFor(() => expect(flash).toHaveBeenCalledWith('Nie udało się wczytać typów adresów', 'error'))
100
+ if (telemetry === 'disabled') {
101
+ expect(mockReportError).not.toHaveBeenCalled()
102
+ } else {
103
+ expect(mockReportError).toHaveBeenCalledTimes(1)
104
+ expect(mockReportError).toHaveBeenCalledWith(error, {
105
+ module: 'ui',
106
+ code: 'ui.address_types_load_failed',
107
+ })
108
+ }
109
+ expect(screen.getByText('Biuro W47')).toBeInTheDocument()
110
+ expect(screen.getByText('office')).toBeInTheDocument()
111
+ })
112
+
113
+ it('ignores a previous context lookup that finishes after the current lookup', async () => {
114
+ let resolvePrevious: (options: AddressTypeOption[]) => void = () => undefined
115
+ const previous = new Promise<AddressTypeOption[]>((resolve) => { resolvePrevious = resolve })
116
+ const adapter: AddressTypesAdapter<string> = {
117
+ list: async (context) => context === 'previous' ? previous : [{ value: 'office', label: 'Nowe biuro' }],
118
+ }
119
+ const view = renderWithProviders(tiles(adapter, 'previous'))
120
+ view.rerender(tiles(adapter, 'current'))
121
+ expect(await screen.findByText('Nowe biuro')).toBeInTheDocument()
122
+
123
+ await act(async () => resolvePrevious([{ value: 'office', label: 'Poprzednie biuro' }]))
124
+ expect(screen.getByText('Nowe biuro')).toBeInTheDocument()
125
+ expect(screen.queryByText('Poprzednie biuro')).not.toBeInTheDocument()
126
+ })
127
+
128
+ it.each([
129
+ ['customers.people.detail.addresses', customerPolish],
130
+ ['staff.teamMembers.detail.addresses', staffPolish],
131
+ ])('shows Polish loading copy for %s', (prefix, dictionary) => {
132
+ const pending = new Promise<AddressSummary[]>(() => undefined)
133
+ renderWithProviders(section(prefix, { ...emptyAdapter, list: () => pending }), { locale: 'pl', dict: dictionary })
134
+ expect(screen.getByRole('status')).toHaveTextContent('Ładowanie adresów')
135
+ expect(screen.queryByText('Loading addresses…')).not.toBeInTheDocument()
136
+ })
137
+
138
+ it.each([
139
+ ['customers.people.detail.addresses', customerPolish, 'Format zgodny z ustawieniami adresów'],
140
+ ['staff.teamMembers.detail.addresses', staffPolish, 'Format oparty na ustawieniach adresu'],
141
+ ])('uses Polish format and cancel copy in the %s form', async (prefix, dictionary, hint) => {
142
+ renderWithProviders(section(prefix), { locale: 'pl', dict: dictionary })
143
+ fireEvent.click(await screen.findByRole('button', { name: 'Dodaj adres' }))
144
+ expect(screen.getByText(hint)).toBeInTheDocument()
145
+ expect(screen.getByRole('button', { name: 'Anuluj' })).toBeInTheDocument()
146
+ expect(screen.queryByText('Format based on address settings')).not.toBeInTheDocument()
147
+ })
148
+ })
@@ -89,7 +89,7 @@ export function LookupSelect({
89
89
  const resolvedStartTypingLabel = startTypingLabel ?? t('ui.lookupSelect.startTyping', 'Start typing to search.')
90
90
  const resolvedMinQueryHintLabel = minQueryHintLabel ?? t(
91
91
  'ui.lookupSelect.minQueryHint',
92
- 'Type at least {minQuery} characters or paste an id to search.',
92
+ 'Minimum characters to search: {minQuery}. You can also paste an id.',
93
93
  { minQuery: String(minQuery) }
94
94
  )
95
95
  const [query, setQuery] = React.useState('')
@@ -571,7 +571,7 @@ export function LookupSelect({
571
571
  </IconButton>
572
572
  )}
573
573
  </div>
574
- ) : hasTyped ? (
574
+ ) : hasTyped && minQuery > 0 ? (
575
575
  <p className="text-xs text-muted-foreground">
576
576
  {resolvedMinQueryHintLabel}
577
577
  </p>
@@ -0,0 +1,73 @@
1
+ /** @jest-environment jsdom */
2
+
3
+ import * as React from 'react'
4
+ import { fireEvent, render, screen } from '@testing-library/react'
5
+ import { I18nProvider } from '@open-mercato/shared/lib/i18n/context'
6
+ import en from '../../../../../../apps/mercato/src/i18n/en.json'
7
+ import pl from '../../../../../../apps/mercato/src/i18n/pl.json'
8
+ import es from '../../../../../../apps/mercato/src/i18n/es.json'
9
+ import { LookupSelect } from '../LookupSelect'
10
+
11
+ describe('LookupSelect minimum-query guidance', () => {
12
+ it('shows generic guidance instead of a zero-character minimum when opened or cleared', () => {
13
+ render(
14
+ <I18nProvider locale="en" dict={en}>
15
+ <LookupSelect value={null} onChange={jest.fn()} minQuery={0} defaultOpen options={[]} />
16
+ </I18nProvider>,
17
+ )
18
+
19
+ expect(screen.getByText('Start typing to search.')).toBeInTheDocument()
20
+ expect(screen.queryByText(/Minimum characters/)).not.toBeInTheDocument()
21
+
22
+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'missing' } })
23
+ fireEvent.change(screen.getByRole('combobox'), { target: { value: '' } })
24
+
25
+ expect(screen.getByText('Start typing to search.')).toBeInTheDocument()
26
+ expect(screen.queryByText(/Minimum characters/)).not.toBeInTheDocument()
27
+ })
28
+
29
+ it.each([
30
+ ['en', en, 'Minimum characters to search: 1. You can also paste an id.'],
31
+ ['pl', pl, 'Minimalna liczba znaków do wyszukiwania: 1. Możesz też wkleić identyfikator.'],
32
+ ['es', es, 'Caracteres mínimos para buscar: 1. También puedes pegar un id.'],
33
+ ] as const)('uses grammatical one-character guidance in %s', (locale, dict, hint) => {
34
+ render(
35
+ <I18nProvider locale={locale} dict={dict}>
36
+ <LookupSelect value={null} onChange={jest.fn()} minQuery={1} defaultOpen options={[]} />
37
+ </I18nProvider>,
38
+ )
39
+
40
+ expect(screen.getByText(hint)).toBeInTheDocument()
41
+ })
42
+
43
+ it('keeps positive-minimum guidance and custom hint overrides', () => {
44
+ const { rerender } = render(
45
+ <I18nProvider locale="en" dict={en}>
46
+ <LookupSelect value={null} onChange={jest.fn()} minQuery={2} options={[]} />
47
+ </I18nProvider>,
48
+ )
49
+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'a' } })
50
+ expect(screen.getByText('Minimum characters to search: 2. You can also paste an id.')).toBeInTheDocument()
51
+
52
+ rerender(
53
+ <I18nProvider locale="en" dict={en}>
54
+ <LookupSelect value={null} onChange={jest.fn()} minQuery={2} options={[]} minQueryHintLabel="Custom guidance" />
55
+ </I18nProvider>,
56
+ )
57
+ expect(screen.getByText('Custom guidance')).toBeInTheDocument()
58
+ })
59
+
60
+ it('still loads and selects results without a minimum query', async () => {
61
+ const fetchItems = jest.fn(async () => [{ id: 'variant', title: 'Available variant' }])
62
+ const onChange = jest.fn()
63
+ render(
64
+ <I18nProvider locale="en" dict={en}>
65
+ <LookupSelect value={null} onChange={onChange} minQuery={0} defaultOpen fetchItems={fetchItems} />
66
+ </I18nProvider>,
67
+ )
68
+
69
+ fireEvent.click(await screen.findByRole('option', { name: /Available variant/ }))
70
+ expect(fetchItems).toHaveBeenCalledWith('')
71
+ expect(onChange).toHaveBeenCalledWith('variant')
72
+ })
73
+ })