@asteby/metacore-runtime-react 53.27.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/business/customer-picker.d.ts +10 -1
  3. package/dist/business/customer-picker.d.ts.map +1 -1
  4. package/dist/business/customer-picker.js +3 -2
  5. package/dist/dialogs/create-record-dialog.d.ts +1 -1
  6. package/dist/dialogs/create-record-dialog.d.ts.map +1 -1
  7. package/dist/dialogs/create-record-dialog.js +2 -2
  8. package/dist/dialogs/dynamic-record.d.ts +3 -1
  9. package/dist/dialogs/dynamic-record.d.ts.map +1 -1
  10. package/dist/dialogs/dynamic-record.js +35 -23
  11. package/dist/dialogs/types.d.ts +2 -0
  12. package/dist/dialogs/types.d.ts.map +1 -1
  13. package/dist/dynamic-crud-page.d.ts.map +1 -1
  14. package/dist/dynamic-crud-page.js +3 -0
  15. package/dist/dynamic-form.d.ts.map +1 -1
  16. package/dist/dynamic-form.js +6 -5
  17. package/dist/field-widget-registry.d.ts +6 -0
  18. package/dist/field-widget-registry.d.ts.map +1 -1
  19. package/dist/index.d.ts +3 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +2 -1
  22. package/dist/model-labels.d.ts +26 -0
  23. package/dist/model-labels.d.ts.map +1 -1
  24. package/dist/model-labels.js +22 -5
  25. package/dist/record-picker-dialog.d.ts +4 -1
  26. package/dist/record-picker-dialog.d.ts.map +1 -1
  27. package/dist/record-picker-dialog.js +2 -2
  28. package/dist/record-picker.d.ts +6 -0
  29. package/dist/record-picker.d.ts.map +1 -1
  30. package/dist/record-picker.js +4 -1
  31. package/dist/types.d.ts +10 -0
  32. package/dist/types.d.ts.map +1 -1
  33. package/package.json +3 -3
  34. package/src/__tests__/dynamic-record-texts.test.tsx +22 -0
  35. package/src/__tests__/field-widget-set-values.test.tsx +65 -0
  36. package/src/__tests__/model-labels.test.tsx +41 -1
  37. package/src/__tests__/record-picker-open-on-focus.test.tsx +49 -0
  38. package/src/business/customer-picker.tsx +13 -0
  39. package/src/dialogs/create-record-dialog.tsx +2 -0
  40. package/src/dialogs/dynamic-record.tsx +48 -26
  41. package/src/dialogs/types.ts +2 -0
  42. package/src/dynamic-crud-page.tsx +3 -0
  43. package/src/dynamic-form.tsx +9 -2
  44. package/src/field-widget-registry.tsx +6 -0
  45. package/src/index.ts +3 -1
  46. package/src/model-labels.ts +45 -5
  47. package/src/record-picker-dialog.tsx +5 -0
  48. package/src/record-picker.tsx +10 -0
  49. package/src/types.ts +10 -0
@@ -10,6 +10,7 @@
10
10
  // the image-url resolver and the org IANA timezone — are passed as props so the
11
11
  // SDK stays transport- and host-agnostic.
12
12
  import { emitRecordMutation } from '../record-mutation-events'
13
+ import { modelVerbTitle, resolveModelNoun } from '../model-labels'
13
14
  import { createContext, lazy, Suspense, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from 'react'
14
15
  import { useTranslation } from 'react-i18next'
15
16
  import type { ModelSchema } from './types'
@@ -286,6 +287,9 @@ interface ModalMetadata {
286
287
  titleKey?: string
287
288
  createTitle?: string
288
289
  editTitle?: string
290
+ /** Backend-localized singular noun ("cliente"): feeds "Crear/Editar/Eliminar {noun}". Host i18n `models.<model>.singular` wins. */
291
+ singular_label?: string
292
+ singularLabel?: string
289
293
  /**
290
294
  * Optional per-model dialog texts. When present they replace the generic
291
295
  * description / submit label of the mode; absent → the built-in texts.
@@ -334,13 +338,17 @@ interface ModalMetadata {
334
338
  messages?: { created?: string; updated?: string; deleted?: string }
335
339
  }
336
340
 
337
- type TFn = (key: string) => string
341
+ type TFn = (key: string, opts?: Record<string, unknown>) => string
338
342
 
339
343
  // localizedModelName resolves the (possibly addon-i18n) model name: prefer the
340
344
  // translated titleKey, fall back to the backend-provided raw title.
341
- function localizedModelName(meta: ModalMetadata, t: TFn): string {
342
- if (meta.titleKey && t(meta.titleKey) !== meta.titleKey) return t(meta.titleKey)
343
- return meta.title || ''
345
+ function localizedModelName(meta: ModalMetadata, t: TFn, model = ''): string {
346
+ return resolveModelNoun(t, {
347
+ model,
348
+ singularLabel: meta.singular_label ?? meta.singularLabel,
349
+ titleKey: meta.titleKey,
350
+ title: meta.title,
351
+ })
344
352
  }
345
353
 
346
354
  export interface DynamicRecordDialogProps {
@@ -642,9 +650,9 @@ function modeTexts(
642
650
 
643
651
  const MODE_CONFIG = {
644
652
  create: {
645
- getTitle: (meta: ModalMetadata, t: TFn) => {
646
- const name = localizedModelName(meta, t)
647
- return name ? `Crear ${name}` : (meta.createTitle || meta.title || 'Nuevo registro')
653
+ getTitle: (meta: ModalMetadata, t: TFn, model = '') => {
654
+ const name = localizedModelName(meta, t, model)
655
+ return name ? modelVerbTitle(t, 'create', name, `Crear ${name}`) : (meta.createTitle || meta.title || 'Nuevo registro')
648
656
  },
649
657
  description: 'Completa los campos para crear un nuevo registro.',
650
658
  submitLabel: 'Crear',
@@ -652,9 +660,9 @@ const MODE_CONFIG = {
652
660
  cancelLabel: 'Cancelar',
653
661
  },
654
662
  edit: {
655
- getTitle: (meta: ModalMetadata, t: TFn) => {
656
- const name = localizedModelName(meta, t)
657
- return name ? `Editar ${name}` : (meta.editTitle || meta.title || 'Editar registro')
663
+ getTitle: (meta: ModalMetadata, t: TFn, model = '') => {
664
+ const name = localizedModelName(meta, t, model)
665
+ return name ? modelVerbTitle(t, 'edit', name, `Editar ${name}`) : (meta.editTitle || meta.title || 'Editar registro')
658
666
  },
659
667
  description: 'Modifica los campos y guarda los cambios.',
660
668
  submitLabel: 'Guardar cambios',
@@ -662,7 +670,7 @@ const MODE_CONFIG = {
662
670
  cancelLabel: 'Cancelar',
663
671
  },
664
672
  view: {
665
- getTitle: (meta: ModalMetadata, t: TFn) => localizedModelName(meta, t) || meta.title || 'Ver registro',
673
+ getTitle: (meta: ModalMetadata, t: TFn, model = '') => localizedModelName(meta, t, model) || meta.title || 'Ver registro',
666
674
  description: 'Información detallada del registro.',
667
675
  submitLabel: '',
668
676
  submittingLabel: '',
@@ -1314,14 +1322,21 @@ export function DynamicRecordDialog({
1314
1322
  }
1315
1323
 
1316
1324
  const title = modalMeta
1317
- ? config.getTitle(modalMeta, t)
1325
+ ? config.getTitle(modalMeta, t, model)
1318
1326
  : mode === 'create'
1319
1327
  ? 'Nuevo registro'
1320
1328
  : mode === 'edit'
1321
1329
  ? 'Editar registro'
1322
1330
  : 'Ver registro'
1323
1331
 
1324
- const texts = modeTexts(modalMeta, mode, config)
1332
+ // Generic dialog texts go through the host's i18n (`dynamic.*`, es defaults) so an English host
1333
+ // gets English buttons without per-model metadata; per-model metadata texts still win.
1334
+ const texts = modeTexts(modalMeta, mode, {
1335
+ description: t(`dynamic.${mode}_description`, { defaultValue: config.description }),
1336
+ submitLabel: t(`dynamic.${mode}_submit`, { defaultValue: config.submitLabel }),
1337
+ })
1338
+ const submittingLabel = t(`dynamic.${mode}_submitting`, { defaultValue: config.submittingLabel })
1339
+ const cancelLabel = t(`dynamic.${mode}_cancel`, { defaultValue: config.cancelLabel })
1325
1340
 
1326
1341
  const visibleFields = filterVisibleFields(modalMeta?.fields, mode, formValues, attributeClasses)
1327
1342
 
@@ -1351,6 +1366,7 @@ export function DynamicRecordDialog({
1351
1366
  mode={mode}
1352
1367
  locked={isCreate && !!lockedFields?.includes(field.key)}
1353
1368
  error={fieldErrors[field.key]}
1369
+ setValues={patch => setFormValues((prev: Record<string, any>) => ({ ...prev, ...patch }))}
1354
1370
  onChange={val => {
1355
1371
  if (getDeriveFrom(field)) {
1356
1372
  if (val === '' || val == null) manualDerived.current.delete(field.key)
@@ -1580,11 +1596,11 @@ export function DynamicRecordDialog({
1580
1596
  on; the first step still shows Cancel. */}
1581
1597
  {isSteps && clampedStep > 0 ? (
1582
1598
  <Button variant="outline" onClick={goBackStep} disabled={saving || deleting}>
1583
- Anterior
1599
+ {t('dynamic.previous', { defaultValue: 'Anterior' })}
1584
1600
  </Button>
1585
1601
  ) : (
1586
1602
  <Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving || deleting}>
1587
- {config.cancelLabel}
1603
+ {cancelLabel}
1588
1604
  </Button>
1589
1605
  )}
1590
1606
  {isView && onDelete && (
@@ -1594,12 +1610,12 @@ export function DynamicRecordDialog({
1594
1610
  disabled={deleting || loading}
1595
1611
  >
1596
1612
  {deleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
1597
- {deleting ? 'Eliminando...' : 'Eliminar'}
1613
+ {deleting ? t('dynamic.deleting', { defaultValue: 'Eliminando...' }) : t('dynamic.delete_confirm', { defaultValue: 'Eliminar' })}
1598
1614
  </Button>
1599
1615
  )}
1600
1616
  {isView && onEdit && (
1601
1617
  <Button onClick={onEdit} disabled={deleting || loading}>
1602
- Editar
1618
+ {t('dynamic.edit', { defaultValue: 'Editar' })}
1603
1619
  </Button>
1604
1620
  )}
1605
1621
  {/* Non-final wizard step → "Siguiente" validates the step
@@ -1607,7 +1623,7 @@ export function DynamicRecordDialog({
1607
1623
  every non-wizard form) keeps the real submit button. */}
1608
1624
  {isEditable && isSteps && !isLastStep && (
1609
1625
  <Button type="button" onClick={goNextStep} disabled={saving || loading}>
1610
- Siguiente
1626
+ {t('dynamic.next', { defaultValue: 'Siguiente' })}
1611
1627
  </Button>
1612
1628
  )}
1613
1629
  {isEditable && (!isSteps || isLastStep) && (
@@ -1617,7 +1633,7 @@ export function DynamicRecordDialog({
1617
1633
  disabled={saving || loading}
1618
1634
  >
1619
1635
  {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
1620
- {saving ? config.submittingLabel : texts.submitLabel}
1636
+ {saving ? submittingLabel : texts.submitLabel}
1621
1637
  </Button>
1622
1638
  )}
1623
1639
  </div>
@@ -1647,6 +1663,8 @@ interface FieldRowProps {
1647
1663
  value: any
1648
1664
  mode: 'view' | 'edit' | 'create'
1649
1665
  onChange: (val: any) => void
1666
+ /** Patches several form values at once (forwarded to host field widgets). */
1667
+ setValues?: (patch: Record<string, any>) => void
1650
1668
  /** Localized validation error for this field, shown in red under the input. */
1651
1669
  error?: string
1652
1670
  /**
@@ -1658,7 +1676,7 @@ interface FieldRowProps {
1658
1676
  locked?: boolean
1659
1677
  }
1660
1678
 
1661
- function FieldRow({ field, record, value, mode, onChange, error, locked }: FieldRowProps) {
1679
+ function FieldRow({ field, record, value, mode, onChange, setValues, error, locked }: FieldRowProps) {
1662
1680
  // A `readonly` field is server/system-generated (e.g. the GitHub addon's
1663
1681
  // `number`/`github_url`, filled by the API after the outbound create). On
1664
1682
  // CREATE it is excluded from the form entirely (see `visibleFields`); on EDIT
@@ -1685,7 +1703,7 @@ function FieldRow({ field, record, value, mode, onChange, error, locked }: Field
1685
1703
  ) : isEditReadonly ? (
1686
1704
  <ReadonlyEditField field={field} value={value} />
1687
1705
  ) : (
1688
- <EditField field={field} value={value} onChange={onChange} record={record} invalid={!!error} error={error} labelId={labelId} />
1706
+ <EditField field={field} value={value} onChange={onChange} setValues={setValues} record={record} invalid={!!error} error={error} labelId={labelId} />
1689
1707
  )}
1690
1708
 
1691
1709
  {error && mode !== 'view' && (
@@ -2381,12 +2399,14 @@ function JsonObjectViewValue({ value }: { value: Record<string, unknown> }) {
2381
2399
  )
2382
2400
  }
2383
2401
 
2384
- export function EditField({ field, value, onChange, record, invalid, error, labelId }: {
2402
+ export function EditField({ field, value, onChange, setValues, record, invalid, error, labelId }: {
2385
2403
  field: FieldDef
2386
2404
  /** id de la etiqueta visible (FieldRow); el control de tres estados la referencia. */
2387
2405
  labelId?: string
2388
2406
  value: any
2389
2407
  onChange: (val: any) => void
2408
+ /** Patches several form values at once (forwarded to host field widgets). */
2409
+ setValues?: (patch: Record<string, any>) => void
2390
2410
  /** The full record being edited — supplies FK relation siblings + line-items. */
2391
2411
  record?: any
2392
2412
  /** When true, paint the control with a destructive border (Laravel-style). */
@@ -2413,6 +2433,7 @@ export function EditField({ field, value, onChange, record, invalid, error, labe
2413
2433
  field={field as unknown as ActionFieldDef}
2414
2434
  value={value}
2415
2435
  onChange={onChange}
2436
+ setValues={setValues}
2416
2437
  error={error}
2417
2438
  record={record}
2418
2439
  />
@@ -2616,7 +2637,7 @@ export function EditField({ field, value, onChange, record, invalid, error, labe
2616
2637
  return (
2617
2638
  <Select value={String(value ?? '')} onValueChange={onChange}>
2618
2639
  <SelectTrigger className={cn("w-full", invalidCls)} aria-invalid={invalid || undefined}>
2619
- <SelectValue placeholder="Seleccionar..." />
2640
+ <SelectValue placeholder={t('dynamic.select_placeholder', { defaultValue: 'Seleccionar...' })} />
2620
2641
  </SelectTrigger>
2621
2642
  <SelectContent>
2622
2643
  {field.options.map(opt => (
@@ -2674,7 +2695,7 @@ export function EditField({ field, value, onChange, record, invalid, error, labe
2674
2695
  <CalendarIcon className="mr-2 h-4 w-4" />
2675
2696
  {validDate
2676
2697
  ? format(validDate, 'PPP', { locale: es })
2677
- : "Seleccionar fecha"}
2698
+ : t('dynamic.select_date', { defaultValue: 'Seleccionar fecha' })}
2678
2699
  </Button>
2679
2700
  </PopoverTrigger>
2680
2701
  <PopoverContent className="w-auto p-0" align="start">
@@ -2901,6 +2922,7 @@ function extractArray(res: any): any[] {
2901
2922
  const searchCache = new Map<string, any[]>()
2902
2923
 
2903
2924
  function SearchField({ field, value, onChange }: { field: FieldDef; value: any; onChange: (val: any) => void }) {
2925
+ const { t } = useTranslation()
2904
2926
  const api = useApi()
2905
2927
  const [selectedLabel, setSelectedLabel] = useState('')
2906
2928
  const ep = field.searchEndpoint!
@@ -2947,14 +2969,14 @@ function SearchField({ field, value, onChange }: { field: FieldDef; value: any;
2947
2969
  selected={value ? { value, label: selectedLabel } : null}
2948
2970
  renderValue={() => (
2949
2971
  <span className={cn('min-w-0 flex-1 truncate', !selectedLabel && 'text-muted-foreground')}>
2950
- {selectedLabel || `Seleccionar ${what}...`}
2972
+ {selectedLabel || t('dynamic.select_what', { what, defaultValue: `Seleccionar ${what}...` })}
2951
2973
  </span>
2952
2974
  )}
2953
2975
  onSelect={(item) => {
2954
2976
  onChange(itemValue(item))
2955
2977
  setSelectedLabel(itemLabel(item))
2956
2978
  }}
2957
- searchPlaceholder={`Buscar ${what}...`}
2979
+ searchPlaceholder={t('dynamic.search_what', { what, defaultValue: `Buscar ${what}...` })}
2958
2980
  emptyText="Sin resultados."
2959
2981
  />
2960
2982
  )
@@ -113,6 +113,8 @@ export interface CreateRecordDialogProps extends RecordDialogProps {
113
113
  * Ignored outside create mode.
114
114
  */
115
115
  lockedFields?: string[]
116
+ /** Fields merged into the modal schema after load (see DynamicRecordDialog.ensureFields). */
117
+ ensureFields?: import('./dynamic-record').FieldDef[]
116
118
  /** Notification when a create or update succeeds. */
117
119
  onSaved?: () => void
118
120
  }
@@ -192,6 +192,9 @@ export function DynamicCRUDPage(props: DynamicCRUDPageProps) {
192
192
  model,
193
193
  title: metadata?.title,
194
194
  titleKey: metadata?.titleKey ?? metadata?.title_key,
195
+ singularLabel: metadata?.singular_label,
196
+ newLabelMeta: metadata?.new_label,
197
+ gender: metadata?.gender,
195
198
  titleOverride: titleOverride ?? ext?.title,
196
199
  newLabelOverride: newLabel ?? ext?.newLabel,
197
200
  newPrefix: strings.newPrefix,
@@ -241,6 +241,8 @@ export function DynamicForm({
241
241
  try { await onSubmit(data) } finally { setSubmitting(false) }
242
242
  }
243
243
 
244
+ const patchValues = (patch: Record<string, any>) => setValues((prev: Record<string, any>) => ({ ...prev, ...patch }))
245
+
244
246
  // Renders one group's fields into the responsive 2-column grid: scalar
245
247
  // header fields flow through it; line-items grids (and textareas) span full
246
248
  // width so the row table / memo gets room. Shared by every layout mode.
@@ -256,6 +258,7 @@ export function DynamicForm({
256
258
  error={errors[field.key]}
257
259
  initialValues={initialValues}
258
260
  onFieldMeta={onFieldMeta}
261
+ setValues={patchValues}
259
262
  />
260
263
  ))}
261
264
  </div>
@@ -376,6 +379,8 @@ interface FieldRendererProps {
376
379
  onFieldMeta?: (key: string, meta: { width?: number; height?: number }) => void
377
380
  /** id único (useId) de la etiqueta visible; el control de tres estados la referencia. */
378
381
  labelId?: string
382
+ /** Patches several form values at once (forwarded to host field widgets). */
383
+ setValues?: (patch: Record<string, any>) => void
379
384
  }
380
385
 
381
386
  interface FieldRowProps extends FieldRendererProps {
@@ -386,7 +391,7 @@ interface FieldRowProps extends FieldRendererProps {
386
391
  // component so a STATIC enum select whose options are all gated out by a sibling
387
392
  // value (`when`) can hide the ENTIRE row (label included) and run its reset
388
393
  // effect with valid hook ordering.
389
- function FieldRow({ field, value, onChange, values, error, initialValues, onFieldMeta }: FieldRowProps) {
394
+ function FieldRow({ field, value, onChange, values, error, initialValues, onFieldMeta, setValues }: FieldRowProps) {
390
395
  // Único por instancia: dos formularios montados con el mismo campo no chocan.
391
396
  const labelId = `${useId()}-label`
392
397
  const isStaticSelect =
@@ -427,6 +432,7 @@ function FieldRow({ field, value, onChange, values, error, initialValues, onFiel
427
432
  error={error}
428
433
  onFieldMeta={onFieldMeta}
429
434
  labelId={labelId}
435
+ setValues={setValues}
430
436
  />
431
437
  {error && <span className="text-red-500 text-sm" role="alert">{error}</span>}
432
438
  </div>
@@ -470,13 +476,14 @@ function FieldRenderer({
470
476
  error,
471
477
  onFieldMeta,
472
478
  labelId,
479
+ setValues,
473
480
  }: FieldRendererProps & { effectiveOptions?: import('./types').OptionDef[]; error?: string }) {
474
481
  // Host-registered widget (`widget: "<name>"`) wins over every built-in and
475
482
  // type-based branch. Unregistered names fall through untouched.
476
483
  useFieldWidgetRegistryVersion()
477
484
  const HostWidget = getFieldWidget(field.widget)
478
485
  if (HostWidget) {
479
- return <HostWidget field={field} value={value} onChange={onChange} error={error} record={values} />
486
+ return <HostWidget field={field} value={value} onChange={onChange} error={error} record={values} setValues={setValues} />
480
487
  }
481
488
  // Repeatable line-items group → render the row grid. Its value is an array
482
489
  // of row objects rather than a scalar.
@@ -37,6 +37,12 @@ export interface FieldWidgetProps {
37
37
  * record dialog (`EditField`) it is the loaded/edited record.
38
38
  */
39
39
  record?: Record<string, any>
40
+ /**
41
+ * Merge several sibling fields into the form at once. For widgets that fill
42
+ * the form from an external source (a scanned document, a lookup) instead of
43
+ * editing their own value. Absent where the host form cannot patch siblings.
44
+ */
45
+ setValues?: (patch: Record<string, any>) => void
40
46
  }
41
47
 
42
48
  export type FieldWidgetComponent = React.ComponentType<FieldWidgetProps>
package/src/index.ts CHANGED
@@ -586,6 +586,8 @@ export { DynamicRecordDialog, ViewValue } from './dialogs/dynamic-record'
586
586
  export { normalizeRefFieldsForSubmit } from './dialogs/normalize-submit'
587
587
  export type { DynamicRecordDialogProps, FieldDef, FieldOption, GetImageUrl } from './dialogs/dynamic-record'
588
588
  export { CreateRecordDialog } from './dialogs/create-record-dialog'
589
+ export { useInfiniteScrollSentinel, dedupeById } from './use-infinite-scroll'
590
+ export type { UseInfiniteScrollOptions, InfiniteScrollRefs } from './use-infinite-scroll'
589
591
  export { EntitySelect } from './entity-select'
590
592
  export type { EntitySelectProps, EntitySelectOption } from './entity-select'
591
593
  // RecordPicker — the ONE "pick a related record" control (search, single /
@@ -912,5 +914,5 @@ export type { BatchLog as BulkImageBatchLog } from './bulk-image-import'
912
914
  export * from './attention'
913
915
  export * from './view-system'
914
916
 
915
- export { useModelLabels, resolveModelLabels, defaultSingular } from './model-labels'
917
+ export { useModelLabels, resolveModelLabels, resolveModelNoun, modelVerbTitle, defaultSingular } from './model-labels'
916
918
  export type { ModelLabels, ModelLabelInput, ModelLabelT } from './model-labels'
@@ -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
- `${tryKey(t, 'common.new') ?? input.newPrefix ?? 'New'} ${singular}`
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')
@@ -273,6 +273,12 @@ export interface RecordPickerProps<T> {
273
273
  variant?: RecordPickerVariant
274
274
  /** Input mode: the typed text IS the value (never shows a selected display). */
275
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
276
282
  icon?: LucideIcon
277
283
  id?: string
278
284
  ariaLabel?: string
@@ -377,6 +383,7 @@ export function RecordPicker<T>(props: RecordPickerProps<T>) {
377
383
  className,
378
384
  triggerClassName,
379
385
  triggerProps,
386
+ openOnFocus = false,
380
387
  inputRef,
381
388
  minListWidth = '14rem',
382
389
  maxListWidth,
@@ -807,6 +814,9 @@ export function RecordPicker<T>(props: RecordPickerProps<T>) {
807
814
  setQuery(e.target.value)
808
815
  setOpen(true)
809
816
  }}
817
+ onFocus={() => {
818
+ if (openOnFocus) setOpen(true)
819
+ }}
810
820
  onBlur={() => close()}
811
821
  onKeyDown={onKeyDown}
812
822
  {...triggerProps}
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[]