@asteby/metacore-runtime-react 53.26.0 → 53.28.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.
- package/CHANGELOG.md +20 -0
- package/dist/action-modal-dispatcher.d.ts.map +1 -1
- package/dist/action-modal-dispatcher.js +5 -0
- package/dist/business/customer-picker.d.ts +10 -1
- package/dist/business/customer-picker.d.ts.map +1 -1
- package/dist/business/customer-picker.js +3 -2
- package/dist/dialogs/create-record-dialog.d.ts +1 -1
- package/dist/dialogs/create-record-dialog.d.ts.map +1 -1
- package/dist/dialogs/create-record-dialog.js +2 -2
- package/dist/dialogs/dynamic-record.d.ts +13 -1
- package/dist/dialogs/dynamic-record.d.ts.map +1 -1
- package/dist/dialogs/dynamic-record.js +41 -23
- package/dist/dialogs/types.d.ts +2 -0
- package/dist/dialogs/types.d.ts.map +1 -1
- package/dist/dynamic-crud-page.d.ts.map +1 -1
- package/dist/dynamic-crud-page.js +3 -0
- package/dist/dynamic-form.d.ts.map +1 -1
- package/dist/dynamic-form.js +13 -5
- package/dist/dynamic-line-items.d.ts.map +1 -1
- package/dist/dynamic-line-items.js +5 -0
- package/dist/dynamic-multi-select-field.d.ts.map +1 -1
- package/dist/dynamic-multi-select-field.js +5 -5
- package/dist/field-widget-registry.d.ts +6 -0
- package/dist/field-widget-registry.d.ts.map +1 -1
- package/dist/host-api-client.d.ts +17 -0
- package/dist/host-api-client.d.ts.map +1 -1
- package/dist/host-api-client.js +10 -4
- package/dist/host-api.d.ts +14 -0
- package/dist/host-api.d.ts.map +1 -1
- package/dist/host-api.js +23 -3
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/model-labels.d.ts +26 -0
- package/dist/model-labels.d.ts.map +1 -1
- package/dist/model-labels.js +22 -5
- package/dist/record-picker-dialog.d.ts +4 -1
- package/dist/record-picker-dialog.d.ts.map +1 -1
- package/dist/record-picker-dialog.js +2 -2
- package/dist/record-picker.d.ts +11 -0
- package/dist/record-picker.d.ts.map +1 -1
- package/dist/record-picker.js +17 -4
- package/dist/searchable-select-field.d.ts +33 -0
- package/dist/searchable-select-field.d.ts.map +1 -0
- package/dist/searchable-select-field.js +50 -0
- package/dist/searchable-select.d.ts +45 -0
- package/dist/searchable-select.d.ts.map +1 -0
- package/dist/searchable-select.js +72 -0
- package/dist/types.d.ts +22 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/use-host-api-client.js +1 -1
- package/package.json +5 -5
- package/src/__tests__/dynamic-record-texts.test.tsx +22 -0
- package/src/__tests__/field-widget-set-values.test.tsx +65 -0
- package/src/__tests__/host-api-client.test.tsx +12 -0
- package/src/__tests__/host-api.test.ts +41 -0
- package/src/__tests__/model-labels.test.tsx +41 -1
- package/src/__tests__/record-picker-open-on-focus.test.tsx +49 -0
- package/src/__tests__/searchable-select.test.tsx +247 -0
- package/src/action-modal-dispatcher.tsx +16 -0
- package/src/business/customer-picker.tsx +13 -0
- package/src/dialogs/create-record-dialog.tsx +2 -0
- package/src/dialogs/dynamic-record.tsx +74 -26
- package/src/dialogs/types.ts +2 -0
- package/src/dynamic-crud-page.tsx +3 -0
- package/src/dynamic-form.tsx +26 -2
- package/src/dynamic-line-items.tsx +17 -0
- package/src/dynamic-multi-select-field.tsx +5 -4
- package/src/field-widget-registry.tsx +6 -0
- package/src/host-api-client.ts +24 -5
- package/src/host-api.ts +28 -3
- package/src/index.ts +4 -2
- package/src/model-labels.ts +45 -5
- package/src/record-picker-dialog.tsx +5 -0
- package/src/record-picker.tsx +42 -3
- package/src/searchable-select-field.tsx +134 -0
- package/src/searchable-select.ts +87 -0
- package/src/types.ts +22 -0
- package/src/use-host-api-client.ts +1 -1
package/src/model-labels.ts
CHANGED
|
@@ -16,6 +16,12 @@ import { useTranslation } from 'react-i18next'
|
|
|
16
16
|
* `models.<model>.new` exists the label is `common.new_model` interpolated
|
|
17
17
|
* with the singular name (`{{prefix}} {{name}}`), prefix overridable via
|
|
18
18
|
* `common.new`.
|
|
19
|
+
*
|
|
20
|
+
* Backend-declared names (already localized by the kernel/bridge) slot in below
|
|
21
|
+
* the host i18n keys: `singular_label` feeds the singular and `new_label` the
|
|
22
|
+
* create label, so a backend that ships "cliente"/"Nuevo cliente" never needs a
|
|
23
|
+
* per-model i18n entry. The create prefix honours grammatical gender
|
|
24
|
+
* (`common.new_f` = "Nueva", `common.new_m` = "Nuevo") before the neutral `common.new`.
|
|
19
25
|
*/
|
|
20
26
|
export type ModelLabelT = (key: string, opts?: Record<string, unknown>) => string
|
|
21
27
|
|
|
@@ -29,6 +35,12 @@ export interface ModelLabelInput {
|
|
|
29
35
|
newPrefix?: string
|
|
30
36
|
titleOverride?: string
|
|
31
37
|
newLabelOverride?: string
|
|
38
|
+
/** Backend singular noun (`singular_label`), e.g. "cliente". */
|
|
39
|
+
singularLabel?: string
|
|
40
|
+
/** Backend create label (`new_label`), e.g. "Nuevo cliente". */
|
|
41
|
+
newLabelMeta?: string
|
|
42
|
+
/** Grammatical gender of the singular ("m" | "f" | "n"); picks `common.new_<gender>`. */
|
|
43
|
+
gender?: string
|
|
32
44
|
}
|
|
33
45
|
|
|
34
46
|
export interface ModelLabels {
|
|
@@ -60,21 +72,49 @@ export function resolveModelLabels(t: ModelLabelT, input: ModelLabelInput): Mode
|
|
|
60
72
|
input.title ??
|
|
61
73
|
model
|
|
62
74
|
const singular =
|
|
63
|
-
tryKey(t, `models.${model}.singular`) ?? defaultSingular(title)
|
|
75
|
+
tryKey(t, `models.${model}.singular`) ?? input.singularLabel ?? defaultSingular(title)
|
|
64
76
|
const newLabel =
|
|
65
77
|
input.newLabelOverride ??
|
|
66
78
|
tryKey(t, `models.${model}.new`) ??
|
|
67
|
-
|
|
79
|
+
input.newLabelMeta ??
|
|
80
|
+
`${tryKey(t, input.gender ? `common.new_${input.gender}` : undefined) ?? tryKey(t, 'common.new') ?? input.newPrefix ?? 'New'} ${singular}`
|
|
68
81
|
return { title, singular, newLabel }
|
|
69
82
|
}
|
|
70
83
|
|
|
84
|
+
export interface ModelNounInput {
|
|
85
|
+
model: string
|
|
86
|
+
singularLabel?: string
|
|
87
|
+
titleKey?: string
|
|
88
|
+
title?: string
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Noun used inside dialog verbs ("Editar {noun}"). Order: host i18n
|
|
93
|
+
* `models.<model>.singular` > backend `singular_label` > translated `titleKey`
|
|
94
|
+
* > backend `title`. Empty string when nothing is known (caller falls back).
|
|
95
|
+
*/
|
|
96
|
+
export function resolveModelNoun(t: ModelLabelT, input: ModelNounInput): string {
|
|
97
|
+
return (
|
|
98
|
+
tryKey(t, input.model ? `models.${input.model}.singular` : undefined) ??
|
|
99
|
+
(input.singularLabel?.trim() || undefined) ??
|
|
100
|
+
tryKey(t, input.titleKey) ??
|
|
101
|
+
input.title ??
|
|
102
|
+
''
|
|
103
|
+
)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Dialog verb ("Crear {{name}}", "Editar {{name}}", "Eliminar {{name}}") through i18n `dynamic.<verb>_title`. */
|
|
107
|
+
export function modelVerbTitle(t: ModelLabelT, verb: 'create' | 'edit' | 'delete', name: string, fallback: string): string {
|
|
108
|
+
return t(`dynamic.${verb}_title`, { name, defaultValue: fallback })
|
|
109
|
+
}
|
|
110
|
+
|
|
71
111
|
/** Hook form of {@link resolveModelLabels}, bound to the active i18n instance. */
|
|
72
112
|
export function useModelLabels(input: ModelLabelInput): ModelLabels {
|
|
73
113
|
const { t, i18n } = useTranslation()
|
|
74
|
-
const { model, title, titleKey, newPrefix, titleOverride, newLabelOverride } = input
|
|
114
|
+
const { model, title, titleKey, newPrefix, titleOverride, newLabelOverride, singularLabel, newLabelMeta, gender } = input
|
|
75
115
|
return useMemo(
|
|
76
|
-
() => resolveModelLabels(t as unknown as ModelLabelT, { model, title, titleKey, newPrefix, titleOverride, newLabelOverride }),
|
|
116
|
+
() => resolveModelLabels(t as unknown as ModelLabelT, { model, title, titleKey, newPrefix, titleOverride, newLabelOverride, singularLabel, newLabelMeta, gender }),
|
|
77
117
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
78
|
-
[t, i18n?.language, model, title, titleKey, newPrefix, titleOverride, newLabelOverride],
|
|
118
|
+
[t, i18n?.language, model, title, titleKey, newPrefix, titleOverride, newLabelOverride, singularLabel, newLabelMeta, gender],
|
|
79
119
|
)
|
|
80
120
|
}
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import { unwrapResponse } from '@asteby/metacore-lib/envelope'
|
|
11
11
|
import { useState, type ReactNode } from 'react'
|
|
12
12
|
import { CreateRecordDialog } from './dialogs/create-record-dialog'
|
|
13
|
+
import type { FieldDef } from './dialogs/dynamic-record'
|
|
13
14
|
import { useApi } from './api-context'
|
|
14
15
|
import { withSearchPrefill } from './record-picker-actions'
|
|
15
16
|
|
|
@@ -24,6 +25,8 @@ export interface UseRecordPickerDialogOptions {
|
|
|
24
25
|
createDefaults?: Record<string, unknown>
|
|
25
26
|
/** Fields of `createDefaults` rendered locked on create. */
|
|
26
27
|
lockedCreateFields?: string[]
|
|
28
|
+
/** Fields merged into the modal schema (e.g. a `widget` field that fills siblings via `setValues`). */
|
|
29
|
+
ensureFields?: FieldDef[]
|
|
27
30
|
/** The saved record (`{ id, ...fields }`). */
|
|
28
31
|
onSaved: (record: Record<string, unknown>, kind: 'create' | 'edit') => void
|
|
29
32
|
}
|
|
@@ -43,6 +46,7 @@ export function useRecordPickerDialog({
|
|
|
43
46
|
prefillField = 'name',
|
|
44
47
|
createDefaults,
|
|
45
48
|
lockedCreateFields,
|
|
49
|
+
ensureFields,
|
|
46
50
|
onSaved,
|
|
47
51
|
}: UseRecordPickerDialogOptions): UseRecordPickerDialogResult {
|
|
48
52
|
const api = useApi()
|
|
@@ -60,6 +64,7 @@ export function useRecordPickerDialog({
|
|
|
60
64
|
endpoint={base}
|
|
61
65
|
defaults={state.recordId ? undefined : state.defaults}
|
|
62
66
|
lockedFields={state.recordId ? undefined : lockedCreateFields}
|
|
67
|
+
ensureFields={ensureFields}
|
|
63
68
|
onCreate={async (data) => {
|
|
64
69
|
const rec = unwrapRecord(await api.post(base, data))
|
|
65
70
|
onSaved(rec, 'create')
|
package/src/record-picker.tsx
CHANGED
|
@@ -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
|
|
@@ -248,6 +273,12 @@ export interface RecordPickerProps<T> {
|
|
|
248
273
|
variant?: RecordPickerVariant
|
|
249
274
|
/** Input mode: the typed text IS the value (never shows a selected display). */
|
|
250
275
|
freeText?: boolean
|
|
276
|
+
/**
|
|
277
|
+
* Input mode: open the list when the text box gains focus (no click on a
|
|
278
|
+
* chevron, no typing first). Pair with `minChars={0}` to show the first
|
|
279
|
+
* results right away.
|
|
280
|
+
*/
|
|
281
|
+
openOnFocus?: boolean
|
|
251
282
|
icon?: LucideIcon
|
|
252
283
|
id?: string
|
|
253
284
|
ariaLabel?: string
|
|
@@ -326,6 +357,7 @@ export function RecordPicker<T>(props: RecordPickerProps<T>) {
|
|
|
326
357
|
loadingText = 'Buscando…',
|
|
327
358
|
errorText = 'No se pudo buscar. Inténtalo de nuevo.',
|
|
328
359
|
minCharsText,
|
|
360
|
+
highlightQuery = false,
|
|
329
361
|
clearLabel = 'Quitar selección',
|
|
330
362
|
listLabel,
|
|
331
363
|
entityLabel = '',
|
|
@@ -351,6 +383,7 @@ export function RecordPicker<T>(props: RecordPickerProps<T>) {
|
|
|
351
383
|
className,
|
|
352
384
|
triggerClassName,
|
|
353
385
|
triggerProps,
|
|
386
|
+
openOnFocus = false,
|
|
354
387
|
inputRef,
|
|
355
388
|
minListWidth = '14rem',
|
|
356
389
|
maxListWidth,
|
|
@@ -552,7 +585,8 @@ export function RecordPicker<T>(props: RecordPickerProps<T>) {
|
|
|
552
585
|
|
|
553
586
|
const optionClass = (on: boolean, dis: boolean) =>
|
|
554
587
|
cx(
|
|
555
|
-
|
|
588
|
+
// Coarse pointers (touch) get a 44px row; mouse keeps the compact one.
|
|
589
|
+
'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
590
|
on && 'bg-accent text-accent-foreground',
|
|
557
591
|
dis && 'pointer-events-none opacity-50',
|
|
558
592
|
)
|
|
@@ -607,9 +641,11 @@ export function RecordPicker<T>(props: RecordPickerProps<T>) {
|
|
|
607
641
|
) : null}
|
|
608
642
|
{renderLead?.(item, 'option')}
|
|
609
643
|
<span className="flex min-w-0 flex-1 flex-col">
|
|
610
|
-
<span className="line-clamp-2 break-words">{getLabel(item)}</span>
|
|
644
|
+
<span className="line-clamp-2 break-words">{highlightQuery ? <Highlighted text={getLabel(item)} query={trimmed} /> : getLabel(item)}</span>
|
|
611
645
|
{desc != null && desc !== '' ? (
|
|
612
|
-
<span className="truncate text-xs text-muted-foreground">
|
|
646
|
+
<span className="truncate text-xs text-muted-foreground">
|
|
647
|
+
{highlightQuery && typeof desc === 'string' ? <Highlighted text={desc} query={trimmed} /> : desc}
|
|
648
|
+
</span>
|
|
613
649
|
) : null}
|
|
614
650
|
</span>
|
|
615
651
|
{renderTrailing ? (
|
|
@@ -778,6 +814,9 @@ export function RecordPicker<T>(props: RecordPickerProps<T>) {
|
|
|
778
814
|
setQuery(e.target.value)
|
|
779
815
|
setOpen(true)
|
|
780
816
|
}}
|
|
817
|
+
onFocus={() => {
|
|
818
|
+
if (openOnFocus) setOpen(true)
|
|
819
|
+
}}
|
|
781
820
|
onBlur={() => close()}
|
|
782
821
|
onKeyDown={onKeyDown}
|
|
783
822
|
{...triggerProps}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// SearchableSelectField - the combobox-with-search that replaces the flat
|
|
2
|
+
// <Select> when a STATIC option list is long (a tax-regime catalog with ~25
|
|
3
|
+
// entries, a country list...), so the user types instead of scrolling.
|
|
4
|
+
//
|
|
5
|
+
// It is a thin configuration of the shared <RecordPicker> (the same control
|
|
6
|
+
// DynamicSelectField and EntitySelect use), so it inherits ARIA combobox +
|
|
7
|
+
// listbox with aria-activedescendant, arrows/Home/End/Enter/Esc/Tab, type-ahead
|
|
8
|
+
// on the closed trigger, scroll-to-selected on open, a portaled collision-aware
|
|
9
|
+
// popover and light/dark theming. What it adds:
|
|
10
|
+
// - client-side filtering by label, code (value) and `description`, ignoring
|
|
11
|
+
// case and accents (a code, a word or an unaccented word find the same row);
|
|
12
|
+
// - match highlighting, a "no results" state and a windowed list when the
|
|
13
|
+
// catalog is huge;
|
|
14
|
+
// - a clear (x) when the field is not required.
|
|
15
|
+
//
|
|
16
|
+
// Who renders it: DynamicForm / DynamicRecordDialog / ActionModal / line items,
|
|
17
|
+
// via {@link isSearchableSelect}: `field.searchable === true`, or - unless
|
|
18
|
+
// `searchable === false` - more than SEARCHABLE_SELECT_THRESHOLD options.
|
|
19
|
+
import { useMemo, useState } from 'react'
|
|
20
|
+
import { RecordPicker } from './record-picker'
|
|
21
|
+
import { OptionLead } from './record-picker-option'
|
|
22
|
+
import type { ResolvedOption } from './use-options-resolver'
|
|
23
|
+
import { SEARCHABLE_SELECT_MAX_ROWS, filterSearchableOptions, windowOptions } from './searchable-select'
|
|
24
|
+
|
|
25
|
+
export interface SearchableSelectOption {
|
|
26
|
+
value: string | number
|
|
27
|
+
label: string
|
|
28
|
+
description?: string | null
|
|
29
|
+
color?: string
|
|
30
|
+
icon?: string
|
|
31
|
+
image?: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface SearchableSelectFieldProps {
|
|
35
|
+
options: readonly SearchableSelectOption[]
|
|
36
|
+
/** Current value (string | number); empty / nullish = nothing selected. */
|
|
37
|
+
value: unknown
|
|
38
|
+
onChange: (value: string) => void
|
|
39
|
+
id?: string
|
|
40
|
+
/** Accessible name (the field label). */
|
|
41
|
+
ariaLabel?: string
|
|
42
|
+
placeholder?: string
|
|
43
|
+
/** Required fields cannot be cleared. */
|
|
44
|
+
required?: boolean
|
|
45
|
+
disabled?: boolean
|
|
46
|
+
invalid?: boolean
|
|
47
|
+
/** `cell` = compact variant for table / line-item cells. */
|
|
48
|
+
variant?: 'field' | 'cell'
|
|
49
|
+
/** Overrides the "Buscar..." search placeholder. */
|
|
50
|
+
searchPlaceholder?: string
|
|
51
|
+
/** Overrides the "Sin resultados" copy. */
|
|
52
|
+
emptyText?: string
|
|
53
|
+
maxRows?: number
|
|
54
|
+
triggerClassName?: string
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const toResolved = (o: SearchableSelectOption): ResolvedOption => ({
|
|
58
|
+
id: String(o.value),
|
|
59
|
+
value: String(o.value),
|
|
60
|
+
label: o.label,
|
|
61
|
+
name: o.label,
|
|
62
|
+
description: o.description ?? undefined,
|
|
63
|
+
color: o.color,
|
|
64
|
+
icon: o.icon,
|
|
65
|
+
image: o.image,
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
export function SearchableSelectField({
|
|
69
|
+
options,
|
|
70
|
+
value,
|
|
71
|
+
onChange,
|
|
72
|
+
id,
|
|
73
|
+
ariaLabel,
|
|
74
|
+
placeholder = 'Seleccionar...',
|
|
75
|
+
required = false,
|
|
76
|
+
disabled = false,
|
|
77
|
+
invalid = false,
|
|
78
|
+
variant = 'field',
|
|
79
|
+
searchPlaceholder = 'Buscar…',
|
|
80
|
+
emptyText = 'Sin resultados',
|
|
81
|
+
maxRows = SEARCHABLE_SELECT_MAX_ROWS,
|
|
82
|
+
triggerClassName,
|
|
83
|
+
}: SearchableSelectFieldProps) {
|
|
84
|
+
const [query, setQuery] = useState('')
|
|
85
|
+
const all = useMemo(() => options.map(toResolved), [options])
|
|
86
|
+
const valueKey = value != null && value !== '' ? String(value) : ''
|
|
87
|
+
const selected = valueKey ? (all.find((o) => String(o.id) === valueKey) ?? null) : null
|
|
88
|
+
|
|
89
|
+
const { rows, hidden } = useMemo(() => {
|
|
90
|
+
const matched = filterSearchableOptions(all, query)
|
|
91
|
+
return windowOptions(matched, maxRows, (o) => String(o.id) === valueKey)
|
|
92
|
+
}, [all, query, maxRows, valueKey])
|
|
93
|
+
|
|
94
|
+
return (
|
|
95
|
+
<RecordPicker<ResolvedOption>
|
|
96
|
+
slot="searchable-select"
|
|
97
|
+
id={id}
|
|
98
|
+
ariaLabel={ariaLabel}
|
|
99
|
+
items={rows}
|
|
100
|
+
getKey={(o) => String(o.id)}
|
|
101
|
+
getLabel={(o) => o.label}
|
|
102
|
+
getDescription={(o) => o.description}
|
|
103
|
+
// Plain text options get no lead (OptionLead would add an initials avatar).
|
|
104
|
+
renderLead={(o, where) => (o.image || o.icon || o.color ? <OptionLead option={o} size={where === 'option' ? 24 : 20} /> : null)}
|
|
105
|
+
value={valueKey || null}
|
|
106
|
+
selected={selected}
|
|
107
|
+
onSelect={(o) => onChange(String(o.id))}
|
|
108
|
+
onClear={!required && valueKey ? () => onChange('') : undefined}
|
|
109
|
+
query={query}
|
|
110
|
+
onQueryChange={setQuery}
|
|
111
|
+
onOpenChange={(o) => {
|
|
112
|
+
if (!o) setQuery('')
|
|
113
|
+
}}
|
|
114
|
+
placeholder={placeholder}
|
|
115
|
+
searchPlaceholder={searchPlaceholder}
|
|
116
|
+
emptyText={emptyText}
|
|
117
|
+
highlightQuery
|
|
118
|
+
disabled={disabled}
|
|
119
|
+
invalid={invalid}
|
|
120
|
+
variant={variant}
|
|
121
|
+
triggerClassName={triggerClassName}
|
|
122
|
+
listLabel={ariaLabel}
|
|
123
|
+
beforeList={
|
|
124
|
+
hidden > 0 ? (
|
|
125
|
+
<p className="px-3 py-1.5 text-xs text-muted-foreground" data-slot="searchable-select-more" role="status">
|
|
126
|
+
{`Mostrando ${rows.length} de ${rows.length + hidden} — escribe para filtrar`}
|
|
127
|
+
</p>
|
|
128
|
+
) : null
|
|
129
|
+
}
|
|
130
|
+
/>
|
|
131
|
+
)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export default SearchableSelectField
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Pure rules of the searchable select (combobox with a search box) used by the
|
|
2
|
+
// STATIC `select` / `multiselect` widgets. Kept free of React so the threshold
|
|
3
|
+
// and the matching are unit-testable and shared with the table filters.
|
|
4
|
+
import { matchesSearch, normalizeSearchText } from '@asteby/metacore-ui/lib'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Option count above which a static select becomes a searchable combobox when
|
|
8
|
+
* the field does not say otherwise. Mirrors the kernel constant
|
|
9
|
+
* `modelbase.SearchableSelectThreshold`. At or below it the flat select stays.
|
|
10
|
+
*/
|
|
11
|
+
export const SEARCHABLE_SELECT_THRESHOLD = 8
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Rows rendered at once in the list. Static lists are filtered client-side, so
|
|
15
|
+
* a long catalog (hundreds of rows) is windowed instead of painting every row:
|
|
16
|
+
* the match set is cut to this many (the selected option is always kept) and
|
|
17
|
+
* the list says how many more there are. Typing narrows it.
|
|
18
|
+
*/
|
|
19
|
+
export const SEARCHABLE_SELECT_MAX_ROWS = 100
|
|
20
|
+
|
|
21
|
+
export interface SearchableSelectConfig {
|
|
22
|
+
/** `true` forces the combobox, `false` the flat select, unset = by option count. */
|
|
23
|
+
searchable?: boolean | null
|
|
24
|
+
/** Per-field override of the threshold (`searchThreshold`). */
|
|
25
|
+
searchThreshold?: number | null
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Should a static select with `count` options render as a searchable combobox? */
|
|
29
|
+
export function isSearchableSelect(field: SearchableSelectConfig | undefined | null, count: number): boolean {
|
|
30
|
+
if (field?.searchable === true) return true
|
|
31
|
+
if (field?.searchable === false) return false
|
|
32
|
+
const t = field?.searchThreshold
|
|
33
|
+
const threshold = typeof t === 'number' && Number.isFinite(t) && t >= 0 ? t : SEARCHABLE_SELECT_THRESHOLD
|
|
34
|
+
return count > threshold
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface SearchableOptionLike {
|
|
38
|
+
value: unknown
|
|
39
|
+
label: string
|
|
40
|
+
description?: string | null
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Text an option is matched against: label, code (value) and description. */
|
|
44
|
+
export function optionHaystack(o: SearchableOptionLike): string {
|
|
45
|
+
return `${o.label ?? ''} ${o.value ?? ''} ${o.description ?? ''}`
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Filters options by `query` (case/accent insensitive, every token must hit the
|
|
50
|
+
* label, value or description) and ranks them: label or code starts with the
|
|
51
|
+
* query, then a word of the label starts with it, then any other hit. The
|
|
52
|
+
* original order is kept inside each rank. An empty query returns a copy of the
|
|
53
|
+
* list untouched.
|
|
54
|
+
*/
|
|
55
|
+
export function filterSearchableOptions<T extends SearchableOptionLike>(options: readonly T[], query: string): T[] {
|
|
56
|
+
const q = normalizeSearchText(query)
|
|
57
|
+
if (!q) return options.slice()
|
|
58
|
+
const first = q.split(' ')[0]!
|
|
59
|
+
const ranked: Array<{ o: T; rank: number; i: number }> = []
|
|
60
|
+
options.forEach((o, i) => {
|
|
61
|
+
if (!matchesSearch(optionHaystack(o), q)) return
|
|
62
|
+
const label = normalizeSearchText(o.label)
|
|
63
|
+
const code = normalizeSearchText(o.value)
|
|
64
|
+
let rank = 3
|
|
65
|
+
if (label.startsWith(q) || code.startsWith(q)) rank = 0
|
|
66
|
+
else if (label.split(/[^a-z0-9]+/).some((w) => w.startsWith(first))) rank = 1
|
|
67
|
+
else if (label.includes(q)) rank = 2
|
|
68
|
+
ranked.push({ o, rank, i })
|
|
69
|
+
})
|
|
70
|
+
ranked.sort((a, b) => a.rank - b.rank || a.i - b.i)
|
|
71
|
+
return ranked.map((r) => r.o)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Cuts a match list to `max` rows, always keeping the selected one(s) so the
|
|
76
|
+
* list never loses them. Returns the window and how many rows were hidden.
|
|
77
|
+
*/
|
|
78
|
+
export function windowOptions<T>(
|
|
79
|
+
rows: readonly T[],
|
|
80
|
+
max: number,
|
|
81
|
+
isSelected: (o: T) => boolean,
|
|
82
|
+
): { rows: T[]; hidden: number } {
|
|
83
|
+
if (rows.length <= max) return { rows: rows.slice(), hidden: 0 }
|
|
84
|
+
const head = rows.slice(0, max)
|
|
85
|
+
const missing = rows.slice(max).filter(isSelected)
|
|
86
|
+
return { rows: [...head, ...missing], hidden: rows.length - max - missing.length }
|
|
87
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -202,6 +202,16 @@ export interface TableMetadata {
|
|
|
202
202
|
titleKey?: string
|
|
203
203
|
title_key?: string
|
|
204
204
|
title: string
|
|
205
|
+
/**
|
|
206
|
+
* Backend-localized model nouns. `singular_label` ("cliente") feeds dialog
|
|
207
|
+
* verbs ("Editar cliente") and the create label; `plural_label` the list
|
|
208
|
+
* title; `new_label` ("Nuevo cliente") the create button; `gender` ("m"|"f"|"n")
|
|
209
|
+
* picks Nuevo/Nueva when the label is derived. Host i18n `models.<model>.*` wins.
|
|
210
|
+
*/
|
|
211
|
+
singular_label?: string
|
|
212
|
+
plural_label?: string
|
|
213
|
+
new_label?: string
|
|
214
|
+
gender?: 'm' | 'f' | 'n'
|
|
205
215
|
endpoint: string
|
|
206
216
|
columns: ColumnDefinition[]
|
|
207
217
|
actions: ActionDefinition[]
|
|
@@ -723,6 +733,8 @@ export interface OptionDef {
|
|
|
723
733
|
icon?: string
|
|
724
734
|
color?: string
|
|
725
735
|
image?: string
|
|
736
|
+
/** Secondary text; matched by the searchable select search box and shown under the label. */
|
|
737
|
+
description?: string
|
|
726
738
|
when?: OptionWhen
|
|
727
739
|
}
|
|
728
740
|
|
|
@@ -752,6 +764,16 @@ export interface ActionFieldDef {
|
|
|
752
764
|
*/
|
|
753
765
|
nullable?: boolean
|
|
754
766
|
options?: OptionDef[]
|
|
767
|
+
/**
|
|
768
|
+
* Searchable select: `true` always renders the combobox with a search box
|
|
769
|
+
* (filters while typing, accent/case-insensitive, by label, code and option
|
|
770
|
+
* `description`), `false` always the flat select, unset = combobox when the
|
|
771
|
+
* field has more than 8 options (`SEARCHABLE_SELECT_THRESHOLD`). The kernel
|
|
772
|
+
* serves it as `searchable` (FieldDef.Searchable). Static selects only.
|
|
773
|
+
*/
|
|
774
|
+
searchable?: boolean
|
|
775
|
+
/** Per-field override of the option count above which the select becomes searchable. */
|
|
776
|
+
searchThreshold?: number
|
|
755
777
|
defaultValue?: any
|
|
756
778
|
placeholder?: string
|
|
757
779
|
searchEndpoint?: string
|
|
@@ -9,7 +9,7 @@ import { createHostApiClient, type HostApiClient, type HostApiClientOptions } fr
|
|
|
9
9
|
*/
|
|
10
10
|
export function useHostApiClient(options?: HostApiClientOptions): HostApiClient {
|
|
11
11
|
const api = useHostApi()
|
|
12
|
-
const key =
|
|
12
|
+
const key = JSON.stringify([options?.defaultHeaders ?? null, options?.defaultTimeout ?? null])
|
|
13
13
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
14
14
|
return useMemo(() => createHostApiClient(api, options), [api, key])
|
|
15
15
|
}
|