@asteby/metacore-runtime-react 53.20.0 → 53.21.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 (89) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/attention/apply-nav-badges.d.ts +10 -0
  3. package/dist/attention/apply-nav-badges.d.ts.map +1 -0
  4. package/dist/attention/apply-nav-badges.js +35 -0
  5. package/dist/attention/index.d.ts +4 -0
  6. package/dist/attention/index.d.ts.map +1 -0
  7. package/dist/attention/index.js +3 -0
  8. package/dist/attention/use-document-attention.d.ts +10 -0
  9. package/dist/attention/use-document-attention.d.ts.map +1 -0
  10. package/dist/attention/use-document-attention.js +66 -0
  11. package/dist/attention/use-nav-badges.d.ts +42 -0
  12. package/dist/attention/use-nav-badges.d.ts.map +1 -0
  13. package/dist/attention/use-nav-badges.js +54 -0
  14. package/dist/dynamic-columns.js +1 -1
  15. package/dist/dynamic-table.js +3 -3
  16. package/dist/genui/index.d.ts +2 -0
  17. package/dist/genui/index.d.ts.map +1 -0
  18. package/dist/genui/index.js +1 -0
  19. package/dist/genui/settings-block.d.ts +31 -0
  20. package/dist/genui/settings-block.d.ts.map +1 -0
  21. package/dist/genui/settings-block.js +100 -0
  22. package/dist/index.d.ts +2 -0
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2 -0
  25. package/dist/setup/addon-config-surface.d.ts +14 -1
  26. package/dist/setup/addon-config-surface.d.ts.map +1 -1
  27. package/dist/setup/addon-config-surface.js +109 -6
  28. package/dist/setup/messages.d.ts.map +1 -1
  29. package/dist/setup/messages.js +50 -0
  30. package/dist/setup/secret-field-model.d.ts +47 -0
  31. package/dist/setup/secret-field-model.d.ts.map +1 -0
  32. package/dist/setup/secret-field-model.js +95 -0
  33. package/dist/view-system/card-spec.d.ts +24 -0
  34. package/dist/view-system/card-spec.d.ts.map +1 -0
  35. package/dist/view-system/card-spec.js +40 -0
  36. package/dist/view-system/cards-view.d.ts +17 -0
  37. package/dist/view-system/cards-view.d.ts.map +1 -0
  38. package/dist/view-system/cards-view.js +37 -0
  39. package/dist/view-system/index.d.ts +10 -0
  40. package/dist/view-system/index.d.ts.map +1 -0
  41. package/dist/view-system/index.js +9 -0
  42. package/dist/view-system/model-view.d.ts +31 -0
  43. package/dist/view-system/model-view.d.ts.map +1 -0
  44. package/dist/view-system/model-view.js +50 -0
  45. package/dist/view-system/saved-views.d.ts +22 -0
  46. package/dist/view-system/saved-views.d.ts.map +1 -0
  47. package/dist/view-system/saved-views.js +53 -0
  48. package/dist/view-system/types.d.ts +63 -0
  49. package/dist/view-system/types.d.ts.map +1 -0
  50. package/dist/view-system/types.js +1 -0
  51. package/dist/view-system/use-view-mode.d.ts +26 -0
  52. package/dist/view-system/use-view-mode.d.ts.map +1 -0
  53. package/dist/view-system/use-view-mode.js +60 -0
  54. package/dist/view-system/view-state.d.ts +19 -0
  55. package/dist/view-system/view-state.d.ts.map +1 -0
  56. package/dist/view-system/view-state.js +66 -0
  57. package/dist/view-system/view-switcher.d.ts +14 -0
  58. package/dist/view-system/view-switcher.d.ts.map +1 -0
  59. package/dist/view-system/view-switcher.js +26 -0
  60. package/dist/view-system/view-toolbar.d.ts +19 -0
  61. package/dist/view-system/view-toolbar.d.ts.map +1 -0
  62. package/dist/view-system/view-toolbar.js +33 -0
  63. package/package.json +14 -5
  64. package/src/__tests__/addon-config-surface.test.tsx +67 -1
  65. package/src/__tests__/attention-view-system.test.tsx +128 -0
  66. package/src/__tests__/genui-settings-block.test.tsx +73 -0
  67. package/src/attention/apply-nav-badges.ts +42 -0
  68. package/src/attention/index.ts +11 -0
  69. package/src/attention/use-document-attention.ts +62 -0
  70. package/src/attention/use-nav-badges.ts +94 -0
  71. package/src/dynamic-columns.tsx +1 -1
  72. package/src/dynamic-table.tsx +3 -3
  73. package/src/genui/index.ts +1 -0
  74. package/src/genui/settings-block.tsx +123 -0
  75. package/src/index.ts +2 -0
  76. package/src/setup/addon-config-surface.tsx +297 -16
  77. package/src/setup/messages.ts +50 -0
  78. package/src/setup/secret-field-model.test.ts +67 -0
  79. package/src/setup/secret-field-model.ts +104 -0
  80. package/src/view-system/card-spec.tsx +78 -0
  81. package/src/view-system/cards-view.tsx +61 -0
  82. package/src/view-system/index.ts +9 -0
  83. package/src/view-system/model-view.tsx +105 -0
  84. package/src/view-system/saved-views.ts +66 -0
  85. package/src/view-system/types.ts +63 -0
  86. package/src/view-system/use-view-mode.ts +79 -0
  87. package/src/view-system/view-state.ts +61 -0
  88. package/src/view-system/view-switcher.tsx +53 -0
  89. package/src/view-system/view-toolbar.tsx +119 -0
@@ -4,7 +4,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
4
4
  import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
5
5
 
6
6
  vi.mock('react-i18next', () => {
7
- const dict: Record<string, string> = { 'pay.public_key': 'Llave pública', 'pay.token': 'Token', 'pay.serie_a': 'Serie A', 'pay.serie_b': 'Serie B', 'pay.settings.policy': 'Política de guía', 'pay.settings.policy_manual': 'A mano' }
7
+ const dict: Record<string, string> = { 'pay.public_key': 'Llave pública', 'pay.token': 'Token', 'pay.help': 'Secreto aleatorio; la tienda lo manda como Bearer a /submit_review y /list_reviews y cosas más largas todavía', 'pay.serie_a': 'Serie A', 'pay.serie_b': 'Serie B', 'pay.settings.policy': 'Política de guía', 'pay.settings.policy_manual': 'A mano' }
8
8
  const t = (k: string, o?: { defaultValue?: string }) => dict[k] ?? o?.defaultValue ?? k
9
9
  return { useTranslation: () => ({ t, i18n: { language: 'es', exists: (k: string) => k in dict } }) }
10
10
  })
@@ -389,3 +389,69 @@ describe('host-generated (auto) credentials', () => {
389
389
  expect(screen.getByText('Conectada automáticamente')).toBeTruthy()
390
390
  })
391
391
  })
392
+
393
+ describe('secret field tools (generate / validate / discard)', () => {
394
+ const secretConnector: ConnectorEntry = {
395
+ addon_key: 'pay',
396
+ provider: 'rev',
397
+ connected: false,
398
+ credentials: [
399
+ { key: 'api_key', type: 'secret', required: true, label: 'pay.token', validation: 'min_length:40', description: 'pay.help' },
400
+ ],
401
+ }
402
+ const input = () => document.querySelector('input[name="cfg_api_key"]') as HTMLInputElement
403
+
404
+ it('Generar fills a CSPRNG value of at least the declared minimum and Guardar sends it', async () => {
405
+ const { calls } = setup({ connector: secretConnector })
406
+ await screen.findByText('Generar')
407
+ fireEvent.click(screen.getByText('Generar'))
408
+ const v = input().value
409
+ expect(v.length).toBeGreaterThanOrEqual(40)
410
+ expect(v).toMatch(/^[A-Za-z0-9]+$/)
411
+ expect(screen.getByText(/Clave generada/)).toBeTruthy()
412
+ fireEvent.click(screen.getByTestId('config-save'))
413
+ await waitFor(() => expect(calls.find((c) => c.m === 'POST' && c.url === '/integrations/rev')?.body).toEqual({ api_key: v }))
414
+ })
415
+
416
+ it('a too-short secret shows a live error and blocks saving', async () => {
417
+ const { calls } = setup({ connector: secretConnector })
418
+ await screen.findByText('Generar')
419
+ fireEvent.focus(input())
420
+ fireEvent.change(input(), { target: { value: 'abc' } })
421
+ expect(screen.getByText('Mínimo 40 caracteres (llevas 3).')).toBeTruthy()
422
+ fireEvent.click(screen.getByTestId('config-save'))
423
+ await Promise.resolve()
424
+ expect(calls.some((c) => c.m === 'POST' && c.url === '/integrations/rev')).toBe(false)
425
+ })
426
+
427
+ it('splits technical help under «Cómo se usa»', async () => {
428
+ setup({ connector: secretConnector })
429
+ expect(await screen.findByText('Cómo se usa')).toBeTruthy()
430
+ })
431
+
432
+ it('asks before discarding unsaved changes', async () => {
433
+ const { onOpenChange } = setup({ connector: secretConnector })
434
+ await screen.findByText('Generar')
435
+ fireEvent.click(screen.getByText('Generar'))
436
+ fireEvent.click(screen.getByText('Cancelar'))
437
+ expect(onOpenChange).not.toHaveBeenCalled()
438
+ expect(screen.getByText('¿Descartar los cambios sin guardar?')).toBeTruthy()
439
+ fireEvent.click(screen.getByText('Seguir editando'))
440
+ expect(screen.queryByText('¿Descartar los cambios sin guardar?')).toBeNull()
441
+ fireEvent.click(screen.getByText('Cancelar'))
442
+ fireEvent.click(screen.getByText('Descartar'))
443
+ expect(onOpenChange).toHaveBeenCalledWith(false)
444
+ })
445
+
446
+ it('Rotar on a stored secret confirms first, then fills a new value', async () => {
447
+ setup(
448
+ { connector: { ...secretConnector, connected: true } },
449
+ { 'GET /integrations/rev/values': { data: { values: {}, secrets_set: ['api_key'] } } },
450
+ )
451
+ fireEvent.click(await screen.findByText('Rotar'))
452
+ expect(screen.getByText('¿Rotar esta clave?')).toBeTruthy()
453
+ expect(input().value).toBe('')
454
+ fireEvent.click(screen.getByText('Sí, rotar'))
455
+ expect(input().value.length).toBeGreaterThanOrEqual(40)
456
+ })
457
+ })
@@ -0,0 +1,128 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { renderToStaticMarkup } from 'react-dom/server'
3
+ import { applyNavBadges, parseNavCounts } from '../attention'
4
+ import {
5
+ ConfigurableCard,
6
+ parseViewState,
7
+ removeSavedView,
8
+ resolveCard,
9
+ resolveViewMode,
10
+ serializeViewState,
11
+ upsertSavedView,
12
+ viewStateToParams,
13
+ ViewSwitcher,
14
+ } from '../view-system'
15
+
16
+ describe('parseNavCounts', () => {
17
+ it('drops zero/invalid rows and defaults unknown tone to info', () => {
18
+ const m = parseNavCounts([
19
+ { id: 'a', count: 3, tone: 'urgent', href: '/m/a' },
20
+ { id: 'b', count: 0, tone: 'info' },
21
+ { id: 'c', count: 2, tone: 'weird' },
22
+ null,
23
+ ])
24
+ expect([...m.keys()]).toEqual(['a', 'c'])
25
+ expect(m.get('c')!.tone).toBe('info')
26
+ })
27
+ })
28
+
29
+ describe('applyNavBadges', () => {
30
+ const badges = new Map([
31
+ ['x', { id: 'x', count: 5, tone: 'attention' as const }],
32
+ ['y', { id: 'y', count: 2, tone: 'critical' as const }],
33
+ ])
34
+ it('sums folders deduplicating by id and takes max tone', () => {
35
+ const groups = [
36
+ {
37
+ title: 'g',
38
+ items: [
39
+ {
40
+ title: 'f',
41
+ url: '/f',
42
+ items: [
43
+ { title: 'l1', url: '/1', badgeId: 'x' },
44
+ { title: 'l2', url: '/2', badgeId: 'x' },
45
+ { title: 'l3', url: '/3', badgeId: 'y' },
46
+ ],
47
+ },
48
+ ],
49
+ },
50
+ ]
51
+ const out = applyNavBadges(groups as any, badges)
52
+ const folder = out[0].items[0] as any
53
+ expect(folder.badge).toEqual({ count: 7, tone: 'critical' })
54
+ expect(folder.items[0].badge.count).toBe(5)
55
+ expect((groups[0].items[0] as any).badge).toBeUndefined()
56
+ })
57
+ })
58
+
59
+ describe('view state', () => {
60
+ it('roundtrips through the URL keeping unrelated params', () => {
61
+ const s = parseViewState('?view=cards&search=agua&q=review&f_status=EQ%3Aopen&sortBy=priority&order=desc')
62
+ expect(s).toEqual({ search: 'agua', quick: 'review', filters: { status: 'EQ:open' }, sort: { field: 'priority', dir: 'desc' } })
63
+ const back = serializeViewState({ ...s, search: '' }, '?view=cards&page=2')
64
+ expect(back).toContain('view=cards')
65
+ expect(back).toContain('page=2')
66
+ expect(back).not.toContain('search')
67
+ expect(back).toContain('f_status=EQ%3Aopen')
68
+ })
69
+ it('same params for every mode; explicit filter beats quick', () => {
70
+ const p = viewStateToParams(
71
+ { search: 'x', quick: 'r', filters: { status: 'EQ:b' } },
72
+ [{ key: 'r', label: 'Por revisar', params: { status: 'EQ:a', severity: 'EQ:high' } }],
73
+ )
74
+ expect(p).toEqual({ f_status: 'EQ:b', f_severity: 'EQ:high', search: 'x' })
75
+ })
76
+ })
77
+
78
+ describe('view mode', () => {
79
+ const modes = [{ key: 'cards' }, { key: 'table' }, { key: 'map' }]
80
+ it('precedence url > scoped > model > default; list->table', () => {
81
+ expect(resolveViewMode(modes, { urlView: 'map', scoped: 'table' })).toBe('map')
82
+ expect(resolveViewMode(modes, { urlView: 'list' })).toBe('table')
83
+ expect(resolveViewMode(modes, { scoped: 'table', model: 'map' })).toBe('table')
84
+ expect(resolveViewMode(modes, { urlView: 'nope', model: 'nope', defaultKey: 'table' })).toBe('table')
85
+ expect(resolveViewMode(modes, {})).toBe('cards')
86
+ })
87
+ })
88
+
89
+ describe('ViewSwitcher', () => {
90
+ it('defaults to Tarjetas | Datos, module overrides cards label, hides with one mode', () => {
91
+ const h = renderToStaticMarkup(<ViewSwitcher modes={[{ key: 'cards', label: 'Hallazgos' }, { key: 'table' }]} active='cards' onChange={() => {}} />)
92
+ expect(h).toContain('Hallazgos')
93
+ expect(h).toContain('Datos')
94
+ expect(h).toContain('aria-pressed="true"')
95
+ expect(renderToStaticMarkup(<ViewSwitcher modes={[{ key: 'table' }]} active='table' onChange={() => {}} />)).toBe('')
96
+ expect(renderToStaticMarkup(<ViewSwitcher modes={[{ key: 'cards' }, { key: 'table' }, { key: 'map' }]} active='map' onChange={() => {}} />)).toContain('Mapa')
97
+ })
98
+ })
99
+
100
+ describe('saved views', () => {
101
+ it('upserts by name and removes by id', () => {
102
+ const st = { search: '', quick: '', filters: {} }
103
+ let l = upsertSavedView([], { id: '1', name: 'A', state: st })
104
+ l = upsertSavedView(l, { id: '2', name: 'A', state: { ...st, search: 'z' } })
105
+ expect(l).toHaveLength(1)
106
+ expect(l[0].state.search).toBe('z')
107
+ expect(removeSavedView(l, '2')).toEqual([])
108
+ })
109
+ })
110
+
111
+ describe('manifest-configurable card', () => {
112
+ const spec = {
113
+ title: 'title',
114
+ subtitle: 'summary',
115
+ badge: { field: 'priority', tones: { high: 'urgent' as const }, labels: { high: 'Alta' } },
116
+ chips: ['territory'],
117
+ meta: [{ field: 'seen_at', format: 'date' as const }, { field: 'missing' }],
118
+ }
119
+ const row = { title: 'Fuga', summary: 'Calle 5', priority: 'high', territory: 'Norte', seen_at: '2026-11-01' }
120
+ it('resolves without code per addon and skips missing fields', () => {
121
+ const c = resolveCard(spec, row, 'es')
122
+ expect(c.title).toBe('Fuga')
123
+ expect(c.badge).toEqual({ text: 'Alta', tone: 'urgent' })
124
+ expect(c.chips).toEqual(['Norte'])
125
+ expect(c.meta).toHaveLength(1)
126
+ expect(renderToStaticMarkup(<ConfigurableCard spec={spec} row={row} />)).toContain('Alta')
127
+ })
128
+ })
@@ -0,0 +1,73 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, describe, expect, it, vi } from 'vitest'
3
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
4
+
5
+ vi.mock('react-i18next', () => {
6
+ const t = (k: string, o?: { defaultValue?: string }) => (k.includes(' ') ? k : (o?.defaultValue ?? k))
7
+ return { useTranslation: () => ({ t, i18n: { language: 'es', exists: () => false } }) }
8
+ })
9
+
10
+ import { GenUI } from '@asteby/metacore-genui'
11
+ import { ApiProvider } from '../api-context'
12
+ import { coerceSettings, registerGenUISettingsBlock, settingsToFields } from '../genui'
13
+
14
+ let undo: (() => void) | undefined
15
+ afterEach(() => {
16
+ cleanup()
17
+ undo?.()
18
+ undo = undefined
19
+ })
20
+
21
+ const defs = [
22
+ { key: 'max_lines', label: 'Líneas máximas', type: 'integer', default_value: 5 },
23
+ { key: 'note', label: 'Nota', type: 'string' },
24
+ { key: 'strict', label: 'Estricto', type: 'boolean' },
25
+ { key: 'token', label: 'Token', type: 'string', write_only: true },
26
+ { key: 'branch_only', label: 'Por sucursal', type: 'string', scope: 'branch' },
27
+ ]
28
+
29
+ describe('settingsToFields / coerceSettings (FromSettings)', () => {
30
+ it('drops secrets and branch-scoped keys and types numbers', () => {
31
+ const f = settingsToFields(defs)
32
+ expect(f.map((x) => `${x.key}:${x.type}`)).toEqual(['max_lines:number', 'note:text', 'strict:boolean'])
33
+ expect(settingsToFields(defs, ['strict', 'max_lines']).map((x) => x.key)).toEqual(['strict', 'max_lines'])
34
+ })
35
+
36
+ it('sends integers as integers and drops empty numbers', () => {
37
+ expect(coerceSettings({ max_lines: '7', note: 'x', strict: true }, defs)).toEqual({ max_lines: 7, note: 'x', strict: true })
38
+ expect(coerceSettings({ max_lines: '' , note: 'x' }, defs)).toEqual({ note: 'x' })
39
+ })
40
+ })
41
+
42
+ describe('genui settings block (pilot)', () => {
43
+ it('loads the definitions, edits and saves through PUT /addons/:key/settings with typed integers', async () => {
44
+ undo = registerGenUISettingsBlock()
45
+ const puts: Array<{ url: string; body: unknown }> = []
46
+ const client = {
47
+ get: vi.fn(async () => ({ data: { data: { max_lines: 5, note: 'hola', strict: false }, definitions: defs } })),
48
+ post: vi.fn(),
49
+ put: vi.fn(async (url: string, body: unknown) => (puts.push({ url, body }), { data: { success: true } })),
50
+ delete: vi.fn(),
51
+ }
52
+ render(
53
+ <ApiProvider client={client as never}>
54
+ <GenUI spec={{ version: 'genui/v2', blocks: [{ type: 'settings', addon: 'inventory', scope: 'org' }] }} />
55
+ </ApiProvider>,
56
+ )
57
+ const lines = await screen.findByRole('spinbutton')
58
+ expect(screen.queryByText(/Token/)).toBeNull()
59
+ expect(screen.getByText(/Líneas máximas/)).toBeTruthy()
60
+ fireEvent.change(lines, { target: { value: '9' } })
61
+ fireEvent.click(screen.getByRole('button', { name: 'Guardar' }))
62
+ await waitFor(() => expect(puts).toHaveLength(1))
63
+ expect(puts[0]!.url).toBe('/addons/inventory/settings')
64
+ expect((puts[0]!.body as Record<string, unknown>).max_lines).toBe(9)
65
+ expect((puts[0]!.body as Record<string, unknown>).note).toBe('hola')
66
+ expect(await screen.findByText('Guardado.')).toBeTruthy()
67
+ })
68
+
69
+ it('without a registered renderer the block shows its fallback text', () => {
70
+ render(<GenUI spec={{ version: 'genui/v2', blocks: [{ type: 'settings', addon: 'inventory', scope: 'org', fallback: 'Abre Ajustes' }] }} />)
71
+ expect(screen.getByText('Abre Ajustes')).toBeTruthy()
72
+ })
73
+ })
@@ -0,0 +1,42 @@
1
+ import {
2
+ aggregateBadges,
3
+ maxSeverity,
4
+ type NavBadgeValue,
5
+ type NavGroupData,
6
+ type NavItem,
7
+ } from '@asteby/metacore-ui/layout'
8
+
9
+ type Leaf = { badgeId?: string }
10
+
11
+ function collect(item: NavItem, badges: ReadonlyMap<string, NavBadgeValue>, seen: Map<string, NavBadgeValue>) {
12
+ const id = (item as Leaf).badgeId
13
+ if (id) {
14
+ const b = badges.get(id)
15
+ if (b && b.count > 0) seen.set(id, b)
16
+ }
17
+ if ('items' in item) for (const c of item.items) collect(c, badges, seen)
18
+ }
19
+
20
+ /**
21
+ * Pure: returns nav groups with `badge` filled from the counters, matched by
22
+ * `badgeId`. A folder shows the SUM of its leaves deduplicated by id (two
23
+ * entries pointing at the same counter count once) with the most severe tone.
24
+ * Items without a match keep their own `badge`. Never mutates the input.
25
+ */
26
+ export function applyNavBadges(groups: NavGroupData[], badges: ReadonlyMap<string, NavBadgeValue>): NavGroupData[] {
27
+ const walk = (item: NavItem): NavItem => {
28
+ if ('items' in item) {
29
+ const items = item.items.map(walk)
30
+ const seen = new Map<string, NavBadgeValue>()
31
+ for (const c of items) collect(c, badges, seen)
32
+ const { count, tone } = aggregateBadges(seen.values())
33
+ return { ...item, items, badge: count > 0 ? { count, tone } : item.badge }
34
+ }
35
+ const id = (item as Leaf).badgeId
36
+ const b = id ? badges.get(id) : undefined
37
+ return b && b.count > 0 ? { ...item, badge: b } : item
38
+ }
39
+ return groups.map((g) => ({ ...g, items: g.items.map(walk) }))
40
+ }
41
+
42
+ export { maxSeverity }
@@ -0,0 +1,11 @@
1
+ export { applyNavBadges } from './apply-nav-badges'
2
+ export {
3
+ useNavBadges,
4
+ parseNavCounts,
5
+ NAV_BADGES_QUERY_KEY,
6
+ type NavCountDTO,
7
+ type AttentionBadge,
8
+ type UseNavBadgesOptions,
9
+ type UseNavBadgesResult,
10
+ } from './use-nav-badges'
11
+ export { useDocumentAttention } from './use-document-attention'
@@ -0,0 +1,62 @@
1
+ import { useEffect } from 'react'
2
+ import { formatTabTitle, stripTabTitleCount, type Severity } from '@asteby/metacore-ui/layout'
3
+
4
+ const TONE_COLOR: Record<Severity, string> = { info: '#0ea5e9', attention: '#f59e0b', urgent: '#f97316', critical: '#dc2626' }
5
+
6
+ /**
7
+ * Stamps the aggregate counter on the browser tab: "(99+) Title" plus a toned
8
+ * dot over the favicon. Idempotent, restores on unmount/zero, SSR-safe and
9
+ * best-effort for the favicon (canvas/CORS failures are swallowed).
10
+ */
11
+ export function useDocumentAttention(count: number, tone: Severity, opts: { favicon?: boolean } = {}) {
12
+ const { favicon = true } = opts
13
+ useEffect(() => {
14
+ if (typeof document === 'undefined') return
15
+ const base = stripTabTitleCount(document.title)
16
+ document.title = formatTabTitle(base, count)
17
+ return () => {
18
+ document.title = stripTabTitleCount(document.title)
19
+ }
20
+ }, [count])
21
+
22
+ useEffect(() => {
23
+ if (!favicon || typeof document === 'undefined') return
24
+ const link = document.querySelector<HTMLLinkElement>("link[rel~='icon']")
25
+ if (!link) return
26
+ const original = link.dataset.mcOriginalHref ?? link.href
27
+ link.dataset.mcOriginalHref = original
28
+ if (count <= 0) {
29
+ link.href = original
30
+ return
31
+ }
32
+ let cancelled = false
33
+ try {
34
+ const img = new Image()
35
+ img.crossOrigin = 'anonymous'
36
+ img.onload = () => {
37
+ if (cancelled) return
38
+ try {
39
+ const c = document.createElement('canvas')
40
+ c.width = c.height = 32
41
+ const ctx = c.getContext('2d')
42
+ if (!ctx) return
43
+ ctx.drawImage(img, 0, 0, 32, 32)
44
+ ctx.fillStyle = TONE_COLOR[tone]
45
+ ctx.beginPath()
46
+ ctx.arc(24, 8, 8, 0, Math.PI * 2)
47
+ ctx.fill()
48
+ link.href = c.toDataURL('image/png')
49
+ } catch {
50
+ /* tainted canvas: keep the original icon */
51
+ }
52
+ }
53
+ img.src = original
54
+ } catch {
55
+ /* ignore */
56
+ }
57
+ return () => {
58
+ cancelled = true
59
+ link.href = original
60
+ }
61
+ }, [count, tone, favicon])
62
+ }
@@ -0,0 +1,94 @@
1
+ import { useMemo } from 'react'
2
+ import { useQuery, useQueryClient } from '@tanstack/react-query'
3
+ import { useTranslation } from 'react-i18next'
4
+ import { aggregateBadges, isSeverity, type NavBadgeValue, type Severity } from '@asteby/metacore-ui/layout'
5
+ import { useApi } from '../api-context'
6
+ import { useRealtimeInvalidate } from '../realtime-context'
7
+
8
+ /** Wire shape of one counter served by kernel `navcounts` (GET /nav/counts). */
9
+ export interface NavCountDTO {
10
+ id: string
11
+ count: number
12
+ tone: string
13
+ label?: string
14
+ href?: string
15
+ refresh_on?: string[]
16
+ }
17
+
18
+ export interface AttentionBadge extends NavBadgeValue {
19
+ id: string
20
+ /** Deep link to the list filtered by the same predicate the count used. */
21
+ href?: string
22
+ }
23
+
24
+ export const NAV_BADGES_QUERY_KEY = ['nav-badges'] as const
25
+
26
+ /** Pure: DTO list -> map by id, dropping zero/invalid rows, unknown tone -> info. */
27
+ export function parseNavCounts(rows: unknown, translate: (k: string, count: number) => string = (k) => k): Map<string, AttentionBadge> {
28
+ const out = new Map<string, AttentionBadge>()
29
+ if (!Array.isArray(rows)) return out
30
+ for (const r of rows as NavCountDTO[]) {
31
+ if (!r || typeof r.id !== 'string' || typeof r.count !== 'number' || r.count <= 0) continue
32
+ const tone: Severity = isSeverity(r.tone) ? r.tone : 'info'
33
+ out.set(r.id, { id: r.id, count: r.count, tone, label: r.label ? translate(r.label, r.count) : undefined, href: r.href })
34
+ }
35
+ return out
36
+ }
37
+
38
+ export interface UseNavBadgesOptions {
39
+ /** Default '/nav/counts'. */
40
+ endpoint?: string
41
+ /** Default 60s. No interval polling: freshness comes from realtime events. */
42
+ staleTimeMs?: number
43
+ enabled?: boolean
44
+ /** Data-event models that should refresh the counters (the union of each counter's refresh_on). */
45
+ refreshModels?: string[]
46
+ }
47
+
48
+ export interface UseNavBadgesResult {
49
+ badges: ReadonlyMap<string, AttentionBadge>
50
+ /** Sum over all counters (what the tab title / bell show). */
51
+ count: number
52
+ /** Most severe tone across counters. */
53
+ tone: Severity
54
+ isLoading: boolean
55
+ refetch: () => void
56
+ }
57
+
58
+ /**
59
+ * One batched request for every attention counter the user may see. Reuses the
60
+ * realtime backbone (data events -> debounced invalidate) instead of polling.
61
+ */
62
+ export function useNavBadges(opts: UseNavBadgesOptions = {}): UseNavBadgesResult {
63
+ const { endpoint = '/nav/counts', staleTimeMs = 60_000, enabled = true, refreshModels } = opts
64
+ const api = useApi()
65
+ const qc = useQueryClient()
66
+ const { t } = useTranslation()
67
+ const q = useQuery({
68
+ queryKey: [...NAV_BADGES_QUERY_KEY, endpoint],
69
+ enabled,
70
+ staleTime: staleTimeMs,
71
+ refetchOnWindowFocus: true,
72
+ queryFn: async () => {
73
+ const res = await api.get(endpoint)
74
+ const body = res.data
75
+ return (body && typeof body === 'object' && 'data' in body ? body.data : body) as NavCountDTO[]
76
+ },
77
+ })
78
+ useRealtimeInvalidate({
79
+ models: refreshModels ?? [],
80
+ match: (key) => key[0] === NAV_BADGES_QUERY_KEY[0],
81
+ })
82
+ const badges = useMemo(
83
+ () => parseNavCounts(q.data, (k, count) => t(k, { count, defaultValue: k })),
84
+ [q.data, t],
85
+ )
86
+ const agg = useMemo(() => aggregateBadges(badges.values()), [badges])
87
+ return {
88
+ badges,
89
+ count: agg.count,
90
+ tone: agg.tone,
91
+ isLoading: q.isLoading,
92
+ refetch: () => void qc.invalidateQueries({ queryKey: NAV_BADGES_QUERY_KEY }),
93
+ }
94
+ }
@@ -880,7 +880,7 @@ const AvatarCell: React.FC<{
880
880
  <AvatarImage
881
881
  src={avatarSrc ? getImageUrl(avatarSrc) : ''}
882
882
  alt={name}
883
- className="object-cover"
883
+ className={shape === 'circle' ? 'object-cover' : 'object-contain p-0.5'}
884
884
  />
885
885
  <AvatarFallback
886
886
  className={`text-[10px] font-bold ${radius} ${brand ? '' : 'bg-primary/5 text-primary'}`}
@@ -1708,7 +1708,7 @@ export function DynamicTable({
1708
1708
  key={header.id}
1709
1709
  colSpan={header.colSpan}
1710
1710
  style={header.column.columnDef.size ? { width: header.column.columnDef.size } : undefined}
1711
- className={cn('bg-card border-b h-10', isActionsColumn && 'sticky right-0 z-20 bg-card shadow-[-2px_0_5px_-2px_rgba(0,0,0,0.1)]')}
1711
+ className={cn('bg-card border-b h-10', isActionsColumn && 'sticky right-0 z-20 bg-card [background:linear-gradient(var(--card),var(--card)),var(--background)] shadow-[-2px_0_5px_-2px_rgba(0,0,0,0.1)]')}
1712
1712
  >
1713
1713
  {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
1714
1714
  </TableHead>
@@ -1757,7 +1757,7 @@ export function DynamicTable({
1757
1757
  <TableCell
1758
1758
  key={cell.id}
1759
1759
  style={cell.column.columnDef.size ? { width: cell.column.columnDef.size } : undefined}
1760
- className={cn('py-2', isActionsColumn && 'sticky right-0 bg-card shadow-[-2px_0_5px_-2px_rgba(0,0,0,0.1)]')}
1760
+ className={cn('py-2', isActionsColumn && 'sticky right-0 bg-card [background:linear-gradient(var(--card),var(--card)),var(--background)] shadow-[-2px_0_5px_-2px_rgba(0,0,0,0.1)]')}
1761
1761
  onClick={(isActionsColumn || isSelectColumn) ? (e: MouseEvent) => e.stopPropagation() : undefined}
1762
1762
  >
1763
1763
  {flexRender(cell.column.columnDef.cell, cell.getContext())}
@@ -1797,7 +1797,7 @@ export function DynamicTable({
1797
1797
  <TableCell
1798
1798
  key={cell.id}
1799
1799
  style={cell.column.columnDef.size ? { width: cell.column.columnDef.size } : undefined}
1800
- className={cn('py-2', isActionsColumn && 'sticky right-0 bg-card shadow-[-2px_0_5px_-2px_rgba(0,0,0,0.1)]')}
1800
+ className={cn('py-2', isActionsColumn && 'sticky right-0 bg-card [background:linear-gradient(var(--card),var(--card)),var(--background)] shadow-[-2px_0_5px_-2px_rgba(0,0,0,0.1)]')}
1801
1801
  onClick={(isActionsColumn || isSelectColumn) ? (e: MouseEvent) => e.stopPropagation() : undefined}
1802
1802
  >
1803
1803
  {flexRender(cell.column.columnDef.cell, cell.getContext())}
@@ -0,0 +1 @@
1
+ export { SettingsBlock, coerceSettings, registerGenUISettingsBlock, settingsToFields, type SettingDefLike } from './settings-block'
@@ -0,0 +1,123 @@
1
+ // genui/v2 `settings` block (ADR 0001 del SDK, PR 7 "piloto"): the general,
2
+ // non-secret settings of an installed addon drawn from a reference
3
+ // `{type:"settings", addon, scope:"org"}`, never inline. It reads and writes
4
+ // through the same endpoints the installed-addons dialog uses
5
+ // (GET/PUT /addons/:key/settings) and renders with DynamicForm, so it is a
6
+ // drop-in replacement for the hand-written settings form there.
7
+ //
8
+ // Scope of the pilot: org scope only; `write_only` (secret) settings are never
9
+ // drawn here (they are never served; the connector/credentials area keeps
10
+ // them); `scope: branch` falls back to its `fallback` text. AddonConfigSurface
11
+ // is NOT touched by this module: wiring it behind a flag happens once the
12
+ // config-modal redesign lands.
13
+ import * as React from 'react'
14
+ import { useTranslation } from 'react-i18next'
15
+ import { registerGenUIBlockRenderer, type GenUIBlockRendererProps } from '@asteby/metacore-genui'
16
+ import { useApi } from '../api-context'
17
+ import { DynamicForm } from '../dynamic-form'
18
+ import type { ActionFieldDef } from '../types'
19
+
20
+ export interface SettingDefLike {
21
+ key: string
22
+ label?: string
23
+ type?: string
24
+ default_value?: unknown
25
+ options?: Array<{ value: unknown; label: string }>
26
+ write_only?: boolean
27
+ scope?: string
28
+ visible_when?: unknown
29
+ visibleWhen?: unknown
30
+ }
31
+
32
+ const humanize = (k: string) => k.replace(/[_.-]+/g, ' ').replace(/^\w/, (c) => c.toUpperCase())
33
+
34
+ /**
35
+ * `FromSettings`: projects an addon's setting definitions to form fields.
36
+ * Secrets (`write_only`) and branch-scoped keys are excluded; `keys` narrows to
37
+ * a subset (in the given order). `integer` and `number` become a typed number
38
+ * field (the value is coerced on submit by `coerceSettings`).
39
+ */
40
+ export function settingsToFields(defs: SettingDefLike[], keys?: string[], label: (d: SettingDefLike) => string = (d) => d.label || humanize(d.key)): ActionFieldDef[] {
41
+ const usable = defs.filter((d) => !d.write_only && (d.scope ?? 'org') === 'org')
42
+ const picked = keys?.length ? keys.map((k) => usable.find((d) => d.key === k)).filter((d): d is SettingDefLike => !!d) : usable
43
+ return picked.map((d) => {
44
+ const options = d.options?.map((o) => ({ value: String(o.value), label: o.label }))
45
+ const type = options?.length ? 'select' : d.type === 'integer' || d.type === 'number' ? 'number' : d.type === 'boolean' ? 'boolean' : d.type === 'textarea' ? 'textarea' : 'text'
46
+ const field: ActionFieldDef & { visibleWhen?: unknown } = { key: d.key, label: label(d), type, options, defaultValue: d.default_value }
47
+ const vw = d.visible_when ?? d.visibleWhen
48
+ if (vw) field.visibleWhen = vw
49
+ return field
50
+ })
51
+ }
52
+
53
+ /** Typed payload: integers go as integers, numbers as numbers (the legacy form sent text). */
54
+ export function coerceSettings(values: Record<string, unknown>, defs: SettingDefLike[]): Record<string, unknown> {
55
+ const out: Record<string, unknown> = { ...values }
56
+ for (const d of defs) {
57
+ if (!Object.hasOwn(out, d.key)) continue
58
+ const v = out[d.key]
59
+ if (d.type === 'integer' || d.type === 'number') {
60
+ if (v === '' || v === null || v === undefined) delete out[d.key]
61
+ else {
62
+ const n = Number(v)
63
+ out[d.key] = d.type === 'integer' ? Math.trunc(n) : n
64
+ }
65
+ }
66
+ }
67
+ return out
68
+ }
69
+
70
+ /** The `settings` block renderer. */
71
+ export function SettingsBlock({ block, text }: GenUIBlockRendererProps) {
72
+ const api = useApi()
73
+ const { t } = useTranslation()
74
+ const addon = String(block.addon)
75
+ const [state, setState] = React.useState<{ values: Record<string, unknown>; defs: SettingDefLike[] } | 'loading' | 'error'>('loading')
76
+ const [msg, setMsg] = React.useState<{ ok: boolean; text: string } | null>(null)
77
+
78
+ React.useEffect(() => {
79
+ let alive = true
80
+ setState('loading')
81
+ api
82
+ .get(`/addons/${addon}/settings`)
83
+ .then((res) => alive && setState({ values: res.data?.data ?? {}, defs: res.data?.definitions ?? [] }))
84
+ .catch(() => alive && setState('error'))
85
+ return () => {
86
+ alive = false
87
+ }
88
+ }, [api, addon])
89
+
90
+ if (block.scope === 'branch') return block.fallback ? <p className="m-0 text-sm text-muted-foreground">{block.fallback}</p> : null
91
+ if (state === 'loading') return <div aria-busy="true" role="status" aria-label={t('metacore.genui.loading', { defaultValue: 'Cargando ajustes…' })} className="h-24" />
92
+ if (state === 'error') return <p role="alert" className="m-0 text-sm text-destructive">{t('metacore.genui.settings_error', { defaultValue: 'No se pudieron cargar los ajustes.' })}</p>
93
+
94
+ const fields = settingsToFields(state.defs, block.keys, (d) => (d.label ? t(d.label, { defaultValue: humanize(d.key) }) : humanize(d.key)))
95
+ if (fields.length === 0) return null
96
+ const initial = Object.fromEntries(fields.map((f) => [f.key, state.values[f.key] ?? f.defaultValue]))
97
+ return (
98
+ <div data-genui-block="settings" className="flex flex-col gap-2">
99
+ {block.title ? <p className="m-0 text-sm font-semibold">{text(block.title)}</p> : null}
100
+ <DynamicForm
101
+ fields={fields}
102
+ initialValues={initial}
103
+ submitLabel={t('metacore.genui.save', { defaultValue: 'Guardar' })}
104
+ onSubmit={async (values) => {
105
+ setMsg(null)
106
+ try {
107
+ await api.put(`/addons/${addon}/settings`, coerceSettings(values, state.defs))
108
+ setMsg({ ok: true, text: t('metacore.genui.saved', { defaultValue: 'Guardado.' }) })
109
+ } catch (e) {
110
+ const m = (e as { response?: { data?: { message?: string } } })?.response?.data?.message
111
+ setMsg({ ok: false, text: m || t('metacore.genui.settings_save_error', { defaultValue: 'No se pudo guardar.' }) })
112
+ }
113
+ }}
114
+ />
115
+ {msg ? <p role={msg.ok ? 'status' : 'alert'} className={msg.ok ? 'm-0 text-sm text-muted-foreground' : 'm-0 text-sm text-destructive'}>{msg.text}</p> : null}
116
+ </div>
117
+ )
118
+ }
119
+
120
+ /** Registers the `settings` block (pilot). Returns a function that restores the previous renderer. */
121
+ export function registerGenUISettingsBlock(): () => void {
122
+ return registerGenUIBlockRenderer('settings', SettingsBlock)
123
+ }