@asteby/metacore-runtime-react 53.26.0 → 53.27.0

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.
Files changed (50) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/action-modal-dispatcher.d.ts.map +1 -1
  3. package/dist/action-modal-dispatcher.js +5 -0
  4. package/dist/dialogs/dynamic-record.d.ts +10 -0
  5. package/dist/dialogs/dynamic-record.d.ts.map +1 -1
  6. package/dist/dialogs/dynamic-record.js +6 -0
  7. package/dist/dynamic-form.d.ts.map +1 -1
  8. package/dist/dynamic-form.js +7 -0
  9. package/dist/dynamic-line-items.d.ts.map +1 -1
  10. package/dist/dynamic-line-items.js +5 -0
  11. package/dist/dynamic-multi-select-field.d.ts.map +1 -1
  12. package/dist/dynamic-multi-select-field.js +5 -5
  13. package/dist/host-api-client.d.ts +17 -0
  14. package/dist/host-api-client.d.ts.map +1 -1
  15. package/dist/host-api-client.js +10 -4
  16. package/dist/host-api.d.ts +14 -0
  17. package/dist/host-api.d.ts.map +1 -1
  18. package/dist/host-api.js +23 -3
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/record-picker.d.ts +5 -0
  23. package/dist/record-picker.d.ts.map +1 -1
  24. package/dist/record-picker.js +14 -4
  25. package/dist/searchable-select-field.d.ts +33 -0
  26. package/dist/searchable-select-field.d.ts.map +1 -0
  27. package/dist/searchable-select-field.js +50 -0
  28. package/dist/searchable-select.d.ts +45 -0
  29. package/dist/searchable-select.d.ts.map +1 -0
  30. package/dist/searchable-select.js +72 -0
  31. package/dist/types.d.ts +12 -0
  32. package/dist/types.d.ts.map +1 -1
  33. package/dist/use-host-api-client.js +1 -1
  34. package/package.json +5 -5
  35. package/src/__tests__/host-api-client.test.tsx +12 -0
  36. package/src/__tests__/host-api.test.ts +41 -0
  37. package/src/__tests__/searchable-select.test.tsx +247 -0
  38. package/src/action-modal-dispatcher.tsx +16 -0
  39. package/src/dialogs/dynamic-record.tsx +26 -0
  40. package/src/dynamic-form.tsx +17 -0
  41. package/src/dynamic-line-items.tsx +17 -0
  42. package/src/dynamic-multi-select-field.tsx +5 -4
  43. package/src/host-api-client.ts +24 -5
  44. package/src/host-api.ts +28 -3
  45. package/src/index.ts +1 -1
  46. package/src/record-picker.tsx +32 -3
  47. package/src/searchable-select-field.tsx +134 -0
  48. package/src/searchable-select.ts +87 -0
  49. package/src/types.ts +12 -0
  50. package/src/use-host-api-client.ts +1 -1
@@ -0,0 +1,247 @@
1
+ // @vitest-environment happy-dom
2
+ //
3
+ // Searchable select: a STATIC `select` with many options (or `searchable: true`)
4
+ // renders a combobox with a search box instead of a flat dropdown.
5
+ // - pure rules: threshold, accent/case-insensitive filter by label, code and
6
+ // description, ranking, windowing;
7
+ // - the component: filters while typing, highlights, "Sin resultados",
8
+ // keyboard (arrows / Enter / Esc), selection mark, clear when optional;
9
+ // - wiring: EditField (DynamicRecordDialog) and DynamicForm choose combobox vs
10
+ // flat select by option count and `searchable`.
11
+ import { useState } from 'react'
12
+ import { afterEach, describe, expect, it, vi } from 'vitest'
13
+ import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
14
+
15
+ vi.mock('react-i18next', () => {
16
+ const t = (k: string, o?: Record<string, any>) => o?.defaultValue ?? k
17
+ const value = { t, i18n: { language: 'es' } }
18
+ return { useTranslation: () => value }
19
+ })
20
+
21
+ import {
22
+ SEARCHABLE_SELECT_THRESHOLD,
23
+ filterSearchableOptions,
24
+ isSearchableSelect,
25
+ windowOptions,
26
+ } from '../searchable-select'
27
+ import { SearchableSelectField } from '../searchable-select-field'
28
+ import { EditField } from '../dialogs/dynamic-record'
29
+ import { DynamicForm } from '../dynamic-form'
30
+
31
+ afterEach(cleanup)
32
+
33
+ const REGIMENES = [
34
+ ['601', 'General de Ley Personas Morales'],
35
+ ['603', 'Personas Morales con Fines no Lucrativos'],
36
+ ['605', 'Sueldos y Salarios e Ingresos Asimilados a Salarios'],
37
+ ['606', 'Arrendamiento'],
38
+ ['607', 'Régimen de Enajenación o Adquisición de Bienes'],
39
+ ['608', 'Demás ingresos'],
40
+ ['610', 'Residentes en el Extranjero sin Establecimiento Permanente en México'],
41
+ ['611', 'Ingresos por Dividendos (socios y accionistas)'],
42
+ ['612', 'Personas Físicas con Actividades Empresariales y Profesionales'],
43
+ ['614', 'Ingresos por intereses'],
44
+ ['615', 'Régimen de los ingresos por obtención de premios'],
45
+ ['616', 'Sin obligaciones fiscales'],
46
+ ['620', 'Sociedades Cooperativas de Producción que optan por diferir sus ingresos'],
47
+ ['621', 'Incorporación Fiscal'],
48
+ ['622', 'Actividades Agrícolas, Ganaderas, Silvícolas y Pesqueras'],
49
+ ['623', 'Opcional para Grupos de Sociedades'],
50
+ ['624', 'Coordinados'],
51
+ ['625', 'Actividades Empresariales con ingresos a través de Plataformas Tecnológicas'],
52
+ ['626', 'Régimen Simplificado de Confianza'],
53
+ ['628', 'Hidrocarburos'],
54
+ ['629', 'De los Regímenes Fiscales Preferentes y de las Empresas Multinacionales'],
55
+ ['630', 'Enajenación de acciones en bolsa de valores'],
56
+ ].map(([value, label]) => ({ value, label: `${value} - ${label}` }))
57
+
58
+ describe('isSearchableSelect (umbral)', () => {
59
+ it('por defecto solo por encima de 8 opciones', () => {
60
+ expect(SEARCHABLE_SELECT_THRESHOLD).toBe(8)
61
+ expect(isSearchableSelect({}, 8)).toBe(false)
62
+ expect(isSearchableSelect({}, 9)).toBe(true)
63
+ expect(isSearchableSelect(undefined, 3)).toBe(false)
64
+ })
65
+ it('searchable explícito gana en ambos sentidos', () => {
66
+ expect(isSearchableSelect({ searchable: true }, 2)).toBe(true)
67
+ expect(isSearchableSelect({ searchable: false }, 500)).toBe(false)
68
+ })
69
+ it('searchThreshold por campo; valores inválidos caen al default', () => {
70
+ expect(isSearchableSelect({ searchThreshold: 3 }, 4)).toBe(true)
71
+ expect(isSearchableSelect({ searchThreshold: 30 }, 25)).toBe(false)
72
+ expect(isSearchableSelect({ searchThreshold: -1 }, 5)).toBe(false)
73
+ expect(isSearchableSelect({ searchThreshold: Number.NaN }, 9)).toBe(true)
74
+ })
75
+ })
76
+
77
+ describe('filterSearchableOptions', () => {
78
+ it('encuentra por código, palabra y sin acentos', () => {
79
+ expect(filterSearchableOptions(REGIMENES, '630').map((o) => o.value)).toEqual(['630'])
80
+ expect(filterSearchableOptions(REGIMENES, 'BOLSA').map((o) => o.value)).toEqual(['630'])
81
+ expect(filterSearchableOptions(REGIMENES, 'enajenacion').map((o) => o.value)).toEqual(['607', '630'])
82
+ expect(filterSearchableOptions(REGIMENES, 'regimen simplificado').map((o) => o.value)).toEqual(['626'])
83
+ })
84
+ it('busca también en description', () => {
85
+ const opts = [
86
+ { value: 'a', label: 'Alpha', description: 'primer elemento' },
87
+ { value: 'b', label: 'Beta', description: 'segundo' },
88
+ ]
89
+ expect(filterSearchableOptions(opts, 'SEGUNDO').map((o) => o.value)).toEqual(['b'])
90
+ })
91
+ it('sin resultados devuelve vacío; query vacía no filtra ni muta', () => {
92
+ expect(filterSearchableOptions(REGIMENES, 'zzzz')).toEqual([])
93
+ const all = filterSearchableOptions(REGIMENES, ' ')
94
+ expect(all).toHaveLength(REGIMENES.length)
95
+ expect(all).not.toBe(REGIMENES)
96
+ })
97
+ it('ordena: empieza con la consulta antes que contiene', () => {
98
+ const opts = [
99
+ { value: '1', label: 'Fiscal general' },
100
+ { value: '2', label: 'General de ley' },
101
+ { value: '3', label: 'Regimen general' },
102
+ ]
103
+ expect(filterSearchableOptions(opts, 'general').map((o) => o.value)).toEqual(['2', '1', '3'])
104
+ })
105
+ })
106
+
107
+ describe('windowOptions', () => {
108
+ it('no recorta bajo el tope; recorta y conserva la opción seleccionada', () => {
109
+ const rows = Array.from({ length: 300 }, (_, i) => i)
110
+ expect(windowOptions(rows.slice(0, 50), 100, () => false)).toEqual({ rows: rows.slice(0, 50), hidden: 0 })
111
+ const w = windowOptions(rows, 100, (n) => n === 250)
112
+ expect(w.rows).toHaveLength(101)
113
+ expect(w.rows).toContain(250)
114
+ expect(w.hidden).toBe(199)
115
+ })
116
+ })
117
+
118
+ function Harness({ required = false, initial = '' }: { required?: boolean; initial?: string }) {
119
+ const [v, setV] = useState(initial)
120
+ return (
121
+ <>
122
+ <SearchableSelectField
123
+ id="regimen"
124
+ ariaLabel="Régimen fiscal"
125
+ options={REGIMENES}
126
+ value={v}
127
+ onChange={setV}
128
+ required={required}
129
+ />
130
+ <output data-testid="value">{v}</output>
131
+ </>
132
+ )
133
+ }
134
+
135
+ const open = () => fireEvent.click(screen.getByRole('combobox', { name: 'Régimen fiscal' }))
136
+ const search = () => screen.getAllByRole('combobox').find((el) => el.tagName === 'INPUT') as HTMLInputElement
137
+ const type = (text: string) => fireEvent.change(search(), { target: { value: text } })
138
+
139
+ describe('SearchableSelectField', () => {
140
+ it('abre con buscador, filtra por código y por palabra sin acentos, y resalta', () => {
141
+ render(<Harness />)
142
+ open()
143
+ expect(screen.getAllByRole('option').length).toBe(REGIMENES.length)
144
+ type('630')
145
+ const opts = screen.getAllByRole('option')
146
+ expect(opts).toHaveLength(1)
147
+ expect(opts[0]!.textContent).toContain('Enajenación de acciones en bolsa de valores')
148
+ expect(opts[0]!.querySelector('mark')?.textContent).toBe('630')
149
+ type('bolsa')
150
+ expect(screen.getAllByRole('option')).toHaveLength(1)
151
+ expect(screen.getByRole('option').querySelector('mark')?.textContent).toBe('bolsa')
152
+ type('ENAJENACION')
153
+ expect(screen.getAllByRole('option')).toHaveLength(2)
154
+ expect(screen.getAllByRole('option')[1]!.querySelector('mark')?.textContent).toBe('Enajenación')
155
+ })
156
+
157
+ it('muestra "Sin resultados" cuando nada coincide', () => {
158
+ render(<Harness />)
159
+ open()
160
+ type('qwerty')
161
+ expect(screen.queryAllByRole('option')).toHaveLength(0)
162
+ expect(screen.getByText('Sin resultados')).toBeTruthy()
163
+ })
164
+
165
+ it('teclado: flechas + Enter eligen, Esc cierra, ARIA listbox/combobox', () => {
166
+ render(<Harness />)
167
+ open()
168
+ const input = search()
169
+ expect(input.getAttribute('aria-autocomplete')).toBe('list')
170
+ expect(screen.getByRole('listbox', { name: 'Régimen fiscal' })).toBeTruthy()
171
+ type('ingresos')
172
+ fireEvent.keyDown(input, { key: 'ArrowDown' })
173
+ const active = input.getAttribute('aria-activedescendant')
174
+ expect(active).toBeTruthy()
175
+ expect(document.getElementById(active!)?.getAttribute('data-active')).toBe('true')
176
+ fireEvent.keyDown(input, { key: 'Enter' })
177
+ expect(screen.getByTestId('value').textContent).not.toBe('')
178
+ expect(screen.queryByRole('listbox')).toBeNull()
179
+ })
180
+
181
+ it('elegir marca la opción y reabrir la deja seleccionada y activa', () => {
182
+ render(<Harness initial="626" />)
183
+ const trigger = screen.getByRole('combobox', { name: 'Régimen fiscal' })
184
+ expect(trigger.textContent).toContain('626 - Régimen Simplificado de Confianza')
185
+ fireEvent.click(trigger)
186
+ const sel = screen.getAllByRole('option').find((o) => o.getAttribute('data-selected') === 'true')
187
+ expect(sel?.textContent).toContain('626')
188
+ expect(sel?.getAttribute('data-active')).toBe('true')
189
+ })
190
+
191
+ it('limpiar solo cuando no es requerido', () => {
192
+ const { unmount } = render(<Harness initial="601" />)
193
+ fireEvent.click(screen.getByLabelText('Quitar selección'))
194
+ expect(screen.getByTestId('value').textContent).toBe('')
195
+ unmount()
196
+ render(<Harness initial="601" required />)
197
+ expect(screen.queryByLabelText('Quitar selección')).toBeNull()
198
+ })
199
+
200
+ it('lista enorme: se ventanea y avisa cuántas hay', () => {
201
+ const big = Array.from({ length: 400 }, (_, i) => ({ value: `v${i}`, label: `Opción ${i}` }))
202
+ render(<SearchableSelectField options={big} value="v399" onChange={() => {}} ariaLabel="Grande" />)
203
+ fireEvent.click(screen.getByRole('combobox', { name: 'Grande' }))
204
+ expect(screen.getAllByRole('option')).toHaveLength(101)
205
+ expect(screen.getByText(/Mostrando 101 de 400/)).toBeTruthy()
206
+ expect(screen.getAllByRole('option').some((o) => o.getAttribute('data-selected') === 'true')).toBe(true)
207
+ })
208
+ })
209
+
210
+ describe('cableado por umbral', () => {
211
+ const opts = (n: number) => Array.from({ length: n }, (_, i) => ({ value: `v${i}`, label: `Opción ${i}` }))
212
+
213
+ it('EditField: 25 opciones => combobox con buscador', () => {
214
+ render(<EditField field={{ key: 'regimen', label: 'Régimen fiscal', type: 'select', options: REGIMENES }} value="" onChange={() => {}} />)
215
+ fireEvent.click(screen.getByRole('combobox'))
216
+ expect(search()).toBeTruthy()
217
+ })
218
+
219
+ it('EditField: pocas opciones => select plano (sin buscador)', () => {
220
+ render(<EditField field={{ key: 'k', label: 'K', type: 'select', options: opts(5) }} value="" onChange={() => {}} />)
221
+ const trigger = screen.getByRole('combobox')
222
+ expect(trigger.getAttribute('aria-haspopup')).not.toBe('listbox') // Radix Select, no RecordPicker
223
+ expect(trigger.closest('[data-slot="searchable-select"]')).toBeNull()
224
+ })
225
+
226
+ it('EditField: searchable true fuerza el buscador con pocas; false lo quita con muchas', () => {
227
+ const { unmount } = render(
228
+ <EditField field={{ key: 'k', label: 'K', type: 'select', options: opts(3), searchable: true }} value="" onChange={() => {}} />,
229
+ )
230
+ expect(document.querySelector('[data-slot="searchable-select"]')).toBeTruthy()
231
+ unmount()
232
+ render(<EditField field={{ key: 'k', label: 'K', type: 'select', options: opts(40), searchable: false }} value="" onChange={() => {}} />)
233
+ expect(document.querySelector('[data-slot="searchable-select"]')).toBeNull()
234
+ })
235
+
236
+ it('DynamicForm: el campo select largo usa el combobox', () => {
237
+ render(
238
+ <DynamicForm
239
+ fields={[{ key: 'regimen', label: 'Régimen fiscal', type: 'select', options: REGIMENES }]}
240
+ onSubmit={() => {}}
241
+ />,
242
+ )
243
+ const scope = within(document.body)
244
+ expect(scope.getByRole('combobox', { name: 'Régimen fiscal' })).toBeTruthy()
245
+ expect(document.querySelector('[data-slot="searchable-select"]')).toBeTruthy()
246
+ })
247
+ })
@@ -67,6 +67,8 @@ import { DynamicIcon } from './dynamic-icon'
67
67
  import { DynamicLineItems } from './dynamic-line-items'
68
68
  import { DynamicRelations } from './dynamic-relations'
69
69
  import { DynamicSelectField } from './dynamic-select-field'
70
+ import { SearchableSelectField } from './searchable-select-field'
71
+ import { isSearchableSelect } from './searchable-select'
70
72
  import { DynamicDateField } from './dynamic-date-field'
71
73
  import { UploadField } from './upload-field'
72
74
  import { isLineItemsField, resolveWidget, resolveDependsValue, getDependsOn, getFieldRef, applyOptionWhen } from './dynamic-form-schema'
@@ -1884,6 +1886,20 @@ export function renderField(
1884
1886
  const stale = !!value && !options.some((o) => String(o.value) === String(value))
1885
1887
  const selectInvalid = invalid || stale
1886
1888
  const selectCls = selectInvalid ? 'border-destructive ring-1 ring-destructive/30 focus-visible:ring-destructive' : ''
1889
+ if (isSearchableSelect(field, options.length)) {
1890
+ return (
1891
+ <SearchableSelectField
1892
+ id={field.key}
1893
+ ariaLabel={field.label || field.key}
1894
+ options={options}
1895
+ value={stale ? '' : value}
1896
+ onChange={onChange}
1897
+ placeholder={field.placeholder || undefined}
1898
+ required={!!field.required}
1899
+ invalid={selectInvalid}
1900
+ />
1901
+ )
1902
+ }
1887
1903
  return (
1888
1904
  <Select value={stale ? '' : value || ''} onValueChange={onChange}>
1889
1905
  <SelectTrigger className={'w-full' + (selectCls ? ` ${selectCls}` : '')} aria-invalid={selectInvalid || undefined} data-stale-option={stale || undefined}><SelectValue placeholder={field.placeholder || 'Seleccionar...'} /></SelectTrigger>
@@ -54,6 +54,8 @@ import { useBranchCreateGate } from '../branch-create-gate'
54
54
  import { toastServerError, extractFieldErrors, localizeFieldIssue, localizeFieldErrorMap } from '../server-error'
55
55
  import { DynamicSelectField, OptionLead, OptionThumb } from '../dynamic-select-field'
56
56
  import { RecordPicker } from '../record-picker'
57
+ import { SearchableSelectField } from '../searchable-select-field'
58
+ import { isSearchableSelect } from '../searchable-select'
57
59
  import { DynamicMultiSelectField } from '../dynamic-multi-select-field'
58
60
  import { UploadField, validateUploadFile } from '../upload-field'
59
61
  import { DynamicRelations } from '../dynamic-relations'
@@ -117,6 +119,8 @@ export interface FieldOption {
117
119
  color?: string
118
120
  icon?: string
119
121
  image?: string
122
+ /** Secondary text; also matched by the searchable select search box. */
123
+ description?: string
120
124
  }
121
125
 
122
126
  export interface FieldDef {
@@ -131,6 +135,14 @@ export interface FieldDef {
131
135
  */
132
136
  nullable?: boolean
133
137
  options?: FieldOption[]
138
+ /**
139
+ * Searchable select: `true` always renders the combobox with a search box,
140
+ * `false` always the flat select, unset = combobox when the field has more
141
+ * than SEARCHABLE_SELECT_THRESHOLD (8) options. Served by the kernel as
142
+ * `searchable`. `searchThreshold` overrides the 8.
143
+ */
144
+ searchable?: boolean
145
+ searchThreshold?: number
134
146
  defaultValue?: any
135
147
  placeholder?: string
136
148
  readonly?: boolean
@@ -2587,6 +2599,20 @@ export function EditField({ field, value, onChange, record, invalid, error, labe
2587
2599
  }
2588
2600
 
2589
2601
  if (field.type === 'select' && field.options?.length) {
2602
+ // Long static list (or `searchable: true`): combobox with a search box.
2603
+ if (isSearchableSelect(field, field.options.length)) {
2604
+ return (
2605
+ <SearchableSelectField
2606
+ id={field.key}
2607
+ ariaLabel={field.label || field.key}
2608
+ options={field.options}
2609
+ value={value}
2610
+ onChange={onChange}
2611
+ required={!!field.required}
2612
+ invalid={invalid}
2613
+ />
2614
+ )
2615
+ }
2590
2616
  return (
2591
2617
  <Select value={String(value ?? '')} onValueChange={onChange}>
2592
2618
  <SelectTrigger className={cn("w-full", invalidCls)} aria-invalid={invalid || undefined}>
@@ -34,6 +34,8 @@ import { getOptionFilter } from './option-filter'
34
34
  import { useOptionsResolver, type ResolvedOption } from './use-options-resolver'
35
35
  import { DynamicLineItems } from './dynamic-line-items'
36
36
  import { DynamicSelectField } from './dynamic-select-field'
37
+ import { SearchableSelectField } from './searchable-select-field'
38
+ import { isSearchableSelect } from './searchable-select'
37
39
  import { DynamicMultiSelectField } from './dynamic-multi-select-field'
38
40
  import { DynamicDateField } from './dynamic-date-field'
39
41
  import { UploadField } from './upload-field'
@@ -538,6 +540,21 @@ function FieldRenderer({
538
540
  )
539
541
  case 'select': {
540
542
  const opts = effectiveOptions ?? field.options
543
+ // Long static list (or `searchable: true`): combobox with a search box
544
+ // instead of a flat dropdown the user has to scroll.
545
+ if (isSearchableSelect(field, opts?.length ?? 0)) {
546
+ return (
547
+ <SearchableSelectField
548
+ id={field.key}
549
+ ariaLabel={field.label || field.key}
550
+ options={opts ?? []}
551
+ value={value}
552
+ onChange={onChange}
553
+ placeholder={field.placeholder || undefined}
554
+ required={!!field.required}
555
+ />
556
+ )
557
+ }
541
558
  return (
542
559
  <Select value={value || ''} onValueChange={guardEmptySelect(value, onChange, (opts ?? []).map((o) => o.value))}>
543
560
  <SelectTrigger className="w-full"><SelectValue placeholder={field.placeholder || 'Seleccionar...'} /></SelectTrigger>
@@ -38,6 +38,8 @@ import {
38
38
  applyOptionWhen,
39
39
  } from './dynamic-form-schema'
40
40
  import { DynamicSelectField, DEFAULT_DEPENDS_HINT } from './dynamic-select-field'
41
+ import { SearchableSelectField } from './searchable-select-field'
42
+ import { isSearchableSelect } from './searchable-select'
41
43
  import { getOptionFilter } from './option-filter'
42
44
  import { useOptionsResolver, type ResolvedOption } from './use-options-resolver'
43
45
 
@@ -503,6 +505,21 @@ function CellRenderer({ field, value, onChange, onPick, disabled, formValues, ro
503
505
  const opts = effectiveOptions ?? field.options
504
506
  // No option applies under the current sibling value → hide the cell.
505
507
  if (effectiveOptions && effectiveOptions.length === 0) return null
508
+ if (isSearchableSelect(field, opts?.length ?? 0)) {
509
+ return (
510
+ <SearchableSelectField
511
+ id={field.key}
512
+ ariaLabel={field.label || field.key}
513
+ options={opts ?? []}
514
+ value={value}
515
+ onChange={onChange}
516
+ placeholder={field.placeholder || undefined}
517
+ required={!!field.required}
518
+ disabled={off}
519
+ invalid={invalid}
520
+ />
521
+ )
522
+ }
506
523
  return (
507
524
  <Select value={value || ''} onValueChange={onChange} disabled={off}>
508
525
  <SelectTrigger className={'w-full' + (invalidCls ? ` ${invalidCls}` : '')} aria-invalid={invalid || undefined}>
@@ -22,6 +22,7 @@
22
22
  // with ONE `?ids=` lookup (useResolveOptionIds): a chip reads "Cargando…" while
23
23
  // it resolves and "(registro eliminado)" when the record is gone — never the id.
24
24
  import { useMemo, useState } from 'react'
25
+ import { filterSearchableOptions } from './searchable-select'
25
26
  import { getOptionFilter } from './option-filter'
26
27
  import { RecordPicker } from './record-picker'
27
28
  import { OptionLead } from './record-picker-option'
@@ -89,10 +90,9 @@ export function DynamicMultiSelectField({ field, value, onChange, staticOptions
89
90
  const label = useStatic ? id : !r ? 'Cargando…' : r.status === 'missing' ? DELETED_RECORD_LABEL : id
90
91
  return { id, value: id, label, name: label }
91
92
  })
92
- const shown = useMemo(() => {
93
- const q = query.trim().toLowerCase()
94
- return q ? options.filter((o) => String(o.label ?? '').toLowerCase().includes(q)) : options
95
- }, [options, query])
93
+ // Case/accent-insensitive, by label, code and description (shared with the
94
+ // single searchable select); order kept inside each relevance rank.
95
+ const shown = useMemo(() => filterSearchableOptions(options, query), [options, query])
96
96
 
97
97
  const toggle = (o: ResolvedOption) => {
98
98
  const id = String(o.id)
@@ -110,6 +110,7 @@ export function DynamicMultiSelectField({ field, value, onChange, staticOptions
110
110
  getLabel={(o) => o.label}
111
111
  renderLead={(o) => <OptionLead option={o} size={20} />}
112
112
  getDescription={(o) => o.description}
113
+ highlightQuery
113
114
  value={selected}
114
115
  selected={selectedItems}
115
116
  onSelect={toggle}
@@ -28,11 +28,26 @@ export interface HostRequestConfig {
28
28
  * and the other headers it owns; they can never be overridden from here.
29
29
  */
30
30
  headers?: Record<string, string>
31
+ /**
32
+ * Per-call timeout (ms) for slow operations; overrides `defaultTimeout`.
33
+ * Finite number >= 0, else ignored. The host clamps it to its ceiling, so
34
+ * `0` means that ceiling (never unlimited unless the host allows it).
35
+ * A timeout rejects the call but the server may still have applied it.
36
+ */
37
+ timeout?: number
38
+ /**
39
+ * `'network'`: never serve this read from the host's offline cache (use for
40
+ * money-critical reads). Rejects on network failure. Enforced only by hosts
41
+ * that honor it (ops does not yet unless it reads `metacoreFreshness`).
42
+ */
43
+ freshness?: 'network'
31
44
  }
32
45
 
33
46
  export interface HostApiClientOptions {
34
47
  /** Headers sent on every call; per-call `headers` win over them. */
35
48
  defaultHeaders?: Record<string, string>
49
+ /** Timeout (ms) for every call; a per-call `timeout` wins. */
50
+ defaultTimeout?: number
36
51
  }
37
52
 
38
53
  /** Minimal axios-like surface (what DynamicSelectField & co. call). */
@@ -64,7 +79,7 @@ export interface HostApiClient {
64
79
  path: string,
65
80
  file: File | Blob | FormData,
66
81
  fields?: Record<string, string>,
67
- opts?: { fileField?: string; signal?: AbortSignal },
82
+ opts?: { fileField?: string; signal?: AbortSignal; timeout?: number; headers?: Record<string, string> },
68
83
  ): Promise<T>
69
84
  /**
70
85
  * Axios-like adapter for runtime-react fields that expect `{ data }` with
@@ -96,10 +111,14 @@ function toApiError(e: unknown, signal?: AbortSignal): Error {
96
111
  /** Build the client over the host-injected {@link HostApi}. */
97
112
  export function createHostApiClient(api: HostApi, options: HostApiClientOptions = {}): HostApiClient {
98
113
  const defaults = options.defaultHeaders
99
- // Additive: without defaults or per-call headers the config is untouched.
114
+ const defaultTimeout = options.defaultTimeout
115
+ // Additive: without defaults or per-call options the config is untouched.
100
116
  const cfg = <C extends HostRequestConfig | undefined>(c: C): C => {
101
- if (!defaults) return c
102
- return { ...(c ?? {}), headers: { ...defaults, ...(c?.headers ?? {}) } } as C
117
+ if (!defaults && defaultTimeout === undefined) return c
118
+ const out: HostRequestConfig = { ...(c ?? {}) }
119
+ if (defaults) out.headers = { ...defaults, ...(c?.headers ?? {}) }
120
+ if (defaultTimeout !== undefined && c?.timeout === undefined) out.timeout = defaultTimeout
121
+ return out as C
103
122
  }
104
123
  const run = async <R,>(p: () => Promise<R>, signal?: AbortSignal): Promise<R> => {
105
124
  try {
@@ -130,7 +149,7 @@ export function createHostApiClient(api: HostApi, options: HostApiClientOptions
130
149
  form.append(opts?.fileField ?? 'file', file as Blob)
131
150
  for (const [k, v] of Object.entries(fields ?? {})) form.append(k, v)
132
151
  }
133
- return body(() => api.post(path, form, cfg(opts?.signal ? { signal: opts.signal } : undefined)), opts?.signal)
152
+ return body(() => api.post(path, form, cfg(opts?.signal || opts?.timeout !== undefined || opts?.headers ? { signal: opts.signal, timeout: opts.timeout, headers: opts.headers } : undefined)), opts?.signal)
134
153
  },
135
154
  axiosLike: () => {
136
155
  // Envelope kept (the runtime-react fields unwrap it themselves),
package/src/host-api.ts CHANGED
@@ -33,6 +33,12 @@ export interface CreateHostApiOptions {
33
33
  * batches.
34
34
  */
35
35
  batchGets?: boolean
36
+ /**
37
+ * Ceiling (ms) for a remote's per-call `timeout`. Default 600000 (10 min).
38
+ * A remote asking for more, or for `0`, gets this ceiling. `0` here means
39
+ * the host admits no ceiling (remote `0` = no limit).
40
+ */
41
+ maxTimeoutMs?: number
36
42
  }
37
43
 
38
44
  type AxiosLikeError = {
@@ -127,12 +133,30 @@ export function sanitizeRemoteHeaders(
127
133
  return Object.keys(out).length ? out : undefined
128
134
  }
129
135
 
130
- function toConfig(opts?: HostApiRequestOptions): Record<string, unknown> | undefined {
136
+ export const DEFAULT_MAX_TIMEOUT_MS = 600_000
137
+
138
+ /** Request-config key the host transport reads to bypass its offline cache. */
139
+ export const HOST_FRESHNESS_KEY = 'metacoreFreshness'
140
+
141
+ /**
142
+ * Validate a requested timeout: finite number >= 0 else `undefined` (ignored);
143
+ * clamp to `max` (0 or above max => max; `max === 0` => no ceiling).
144
+ */
145
+ export function normalizeTimeout(t: unknown, max: number = DEFAULT_MAX_TIMEOUT_MS): number | undefined {
146
+ if (typeof t !== 'number' || !Number.isFinite(t) || t < 0) return undefined
147
+ if (max > 0 && (t === 0 || t > max)) return max
148
+ return t
149
+ }
150
+
151
+ function toConfig(opts?: HostApiRequestOptions, maxTimeoutMs?: number): Record<string, unknown> | undefined {
131
152
  if (!opts) return undefined
132
153
  const config: Record<string, unknown> = {}
133
154
  if (opts.params) config.params = opts.params
134
155
  if (opts.signal) config.signal = opts.signal
135
156
  if (opts.responseType === 'blob') config.responseType = 'blob'
157
+ const timeout = normalizeTimeout(opts.timeout, maxTimeoutMs)
158
+ if (timeout !== undefined) config.timeout = timeout
159
+ if (opts.freshness === 'network') config[HOST_FRESHNESS_KEY] = 'network'
136
160
  const headers = sanitizeRemoteHeaders(opts.headers)
137
161
  if (headers) config.headers = headers
138
162
  return config
@@ -174,7 +198,7 @@ async function bodyOf<T>(p: Promise<{ data: unknown }>, opts?: HostApiRequestOpt
174
198
  export function createHostApi(client: ApiClient, options: CreateHostApiOptions = {}): HostApi {
175
199
  const capabilityPath = options.capabilityPath ?? '/capabilities/query'
176
200
  const withConfig = <A extends unknown[]>(args: A, opts?: HostApiRequestOptions) => {
177
- const config = toConfig(opts)
201
+ const config = toConfig(opts, options.maxTimeoutMs)
178
202
  return config ? ([...args, config] as unknown[]) : (args as unknown[])
179
203
  }
180
204
  const patch = (client as ApiClient & {
@@ -184,7 +208,8 @@ export function createHostApi(client: ApiClient, options: CreateHostApiOptions =
184
208
  get: <T,>(path: string, opts?: HostApiRequestOptions) => {
185
209
  const args = withConfig([path], opts) as [string, { params?: Record<string, unknown> }?]
186
210
  // A GET with per-call headers cannot share a POST /q: it goes on its own.
187
- const batch = options.batchGets && opts?.responseType !== 'blob' && !sanitizeRemoteHeaders(opts?.headers)
211
+ const batch = options.batchGets && opts?.responseType !== 'blob' && !sanitizeRemoteHeaders(opts?.headers) &&
212
+ opts?.timeout === undefined && opts?.freshness !== 'network'
188
213
  return bodyOf<T>(batch ? batchGet(client, ...args) : client.get(...args), opts)
189
214
  },
190
215
  post: <T,>(path: string, body?: unknown, opts?: HostApiRequestOptions) =>
package/src/index.ts CHANGED
@@ -304,7 +304,7 @@ export {
304
304
  type PageChromeState,
305
305
  type PageChromeStore,
306
306
  } from './addon-page-host'
307
- export { createHostApi, toHostApiError, sanitizeRemoteHeaders, PROTECTED_HOST_HEADERS, type CreateHostApiOptions } from './host-api'
307
+ export { createHostApi, toHostApiError, sanitizeRemoteHeaders, PROTECTED_HOST_HEADERS, normalizeTimeout, DEFAULT_MAX_TIMEOUT_MS, HOST_FRESHNESS_KEY, type CreateHostApiOptions } from './host-api'
308
308
  export { HostApiProvider, type HostApiProviderProps } from './host-api-context'
309
309
  export {
310
310
  createHostApiClient,
@@ -47,6 +47,7 @@ import {
47
47
  PopoverContent,
48
48
  PopoverTrigger,
49
49
  } from '@asteby/metacore-ui/primitives'
50
+ import { splitHighlight } from '@asteby/metacore-ui/lib'
50
51
  import { JOINED_TRIGGER_CLASS, RecordPickerAction, hasRecordPickerAction } from './record-picker-actions'
51
52
  import { useDebouncedValue } from './use-debounced-value'
52
53
 
@@ -131,6 +132,25 @@ export function useRecordSearch<T>(
131
132
  return { results, loading, error, pending: enabled && trimmed.length >= minChars && doneFor !== trimmed }
132
133
  }
133
134
 
135
+ /** Label text with the query matches wrapped in <mark> (themed, accent-insensitive). */
136
+ function Highlighted({ text, query }: { text: string; query: string }) {
137
+ const parts = splitHighlight(text, query)
138
+ if (parts.length === 1 && !parts[0]!.match) return <>{text}</>
139
+ return (
140
+ <>
141
+ {parts.map((p, i) =>
142
+ p.match ? (
143
+ <mark key={i} className="rounded-[2px] bg-primary/15 px-0 font-semibold text-foreground" data-slot="record-picker-match">
144
+ {p.text}
145
+ </mark>
146
+ ) : (
147
+ <span key={i}>{p.text}</span>
148
+ ),
149
+ )}
150
+ </>
151
+ )
152
+ }
153
+
134
154
  const NO_SEARCH = () => Promise.resolve([] as never[])
135
155
 
136
156
  /**
@@ -215,6 +235,11 @@ export interface RecordPickerProps<T> {
215
235
  isItemDisabled?: (item: T) => boolean
216
236
  /** Check mark column. Default: true in button mode. */
217
237
  showCheck?: boolean
238
+ /**
239
+ * Highlight the typed text inside the default option label / description
240
+ * (case and accent insensitive). Ignored when `renderItem` is set. Default false.
241
+ */
242
+ highlightQuery?: boolean
218
243
 
219
244
  // --- copy -------------------------------------------------------------
220
245
  placeholder?: string
@@ -326,6 +351,7 @@ export function RecordPicker<T>(props: RecordPickerProps<T>) {
326
351
  loadingText = 'Buscando…',
327
352
  errorText = 'No se pudo buscar. Inténtalo de nuevo.',
328
353
  minCharsText,
354
+ highlightQuery = false,
329
355
  clearLabel = 'Quitar selección',
330
356
  listLabel,
331
357
  entityLabel = '',
@@ -552,7 +578,8 @@ export function RecordPicker<T>(props: RecordPickerProps<T>) {
552
578
 
553
579
  const optionClass = (on: boolean, dis: boolean) =>
554
580
  cx(
555
- 'relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden',
581
+ // Coarse pointers (touch) get a 44px row; mouse keeps the compact one.
582
+ 'relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden [@media(pointer:coarse)]:min-h-11',
556
583
  on && 'bg-accent text-accent-foreground',
557
584
  dis && 'pointer-events-none opacity-50',
558
585
  )
@@ -607,9 +634,11 @@ export function RecordPicker<T>(props: RecordPickerProps<T>) {
607
634
  ) : null}
608
635
  {renderLead?.(item, 'option')}
609
636
  <span className="flex min-w-0 flex-1 flex-col">
610
- <span className="line-clamp-2 break-words">{getLabel(item)}</span>
637
+ <span className="line-clamp-2 break-words">{highlightQuery ? <Highlighted text={getLabel(item)} query={trimmed} /> : getLabel(item)}</span>
611
638
  {desc != null && desc !== '' ? (
612
- <span className="truncate text-xs text-muted-foreground">{desc}</span>
639
+ <span className="truncate text-xs text-muted-foreground">
640
+ {highlightQuery && typeof desc === 'string' ? <Highlighted text={desc} query={trimmed} /> : desc}
641
+ </span>
613
642
  ) : null}
614
643
  </span>
615
644
  {renderTrailing ? (