@asteby/metacore-runtime-react 53.20.1 → 53.21.1
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 +14 -0
- package/dist/attention/apply-nav-badges.d.ts +10 -0
- package/dist/attention/apply-nav-badges.d.ts.map +1 -0
- package/dist/attention/apply-nav-badges.js +35 -0
- package/dist/attention/index.d.ts +4 -0
- package/dist/attention/index.d.ts.map +1 -0
- package/dist/attention/index.js +3 -0
- package/dist/attention/use-document-attention.d.ts +10 -0
- package/dist/attention/use-document-attention.d.ts.map +1 -0
- package/dist/attention/use-document-attention.js +66 -0
- package/dist/attention/use-nav-badges.d.ts +42 -0
- package/dist/attention/use-nav-badges.d.ts.map +1 -0
- package/dist/attention/use-nav-badges.js +54 -0
- package/dist/genui/index.d.ts +2 -0
- package/dist/genui/index.d.ts.map +1 -0
- package/dist/genui/index.js +1 -0
- package/dist/genui/settings-block.d.ts +31 -0
- package/dist/genui/settings-block.d.ts.map +1 -0
- package/dist/genui/settings-block.js +100 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/setup/addon-config-surface.d.ts +14 -1
- package/dist/setup/addon-config-surface.d.ts.map +1 -1
- package/dist/setup/addon-config-surface.js +116 -6
- package/dist/setup/messages.d.ts.map +1 -1
- package/dist/setup/messages.js +50 -0
- package/dist/setup/secret-field-model.d.ts +47 -0
- package/dist/setup/secret-field-model.d.ts.map +1 -0
- package/dist/setup/secret-field-model.js +95 -0
- package/dist/view-system/card-spec.d.ts +24 -0
- package/dist/view-system/card-spec.d.ts.map +1 -0
- package/dist/view-system/card-spec.js +40 -0
- package/dist/view-system/cards-view.d.ts +17 -0
- package/dist/view-system/cards-view.d.ts.map +1 -0
- package/dist/view-system/cards-view.js +37 -0
- package/dist/view-system/index.d.ts +10 -0
- package/dist/view-system/index.d.ts.map +1 -0
- package/dist/view-system/index.js +9 -0
- package/dist/view-system/model-view.d.ts +31 -0
- package/dist/view-system/model-view.d.ts.map +1 -0
- package/dist/view-system/model-view.js +50 -0
- package/dist/view-system/saved-views.d.ts +22 -0
- package/dist/view-system/saved-views.d.ts.map +1 -0
- package/dist/view-system/saved-views.js +53 -0
- package/dist/view-system/types.d.ts +63 -0
- package/dist/view-system/types.d.ts.map +1 -0
- package/dist/view-system/types.js +1 -0
- package/dist/view-system/use-view-mode.d.ts +26 -0
- package/dist/view-system/use-view-mode.d.ts.map +1 -0
- package/dist/view-system/use-view-mode.js +60 -0
- package/dist/view-system/view-state.d.ts +19 -0
- package/dist/view-system/view-state.d.ts.map +1 -0
- package/dist/view-system/view-state.js +66 -0
- package/dist/view-system/view-switcher.d.ts +14 -0
- package/dist/view-system/view-switcher.d.ts.map +1 -0
- package/dist/view-system/view-switcher.js +26 -0
- package/dist/view-system/view-toolbar.d.ts +19 -0
- package/dist/view-system/view-toolbar.d.ts.map +1 -0
- package/dist/view-system/view-toolbar.js +33 -0
- package/package.json +14 -5
- package/src/__tests__/addon-config-surface.test.tsx +67 -1
- package/src/__tests__/attention-view-system.test.tsx +128 -0
- package/src/__tests__/dynamic-table-bulk-delete-reasons.test.tsx +6 -1
- package/src/__tests__/genui-settings-block.test.tsx +73 -0
- package/src/attention/apply-nav-badges.ts +42 -0
- package/src/attention/index.ts +11 -0
- package/src/attention/use-document-attention.ts +62 -0
- package/src/attention/use-nav-badges.ts +94 -0
- package/src/genui/index.ts +1 -0
- package/src/genui/settings-block.tsx +123 -0
- package/src/index.ts +2 -0
- package/src/setup/addon-config-surface.tsx +303 -16
- package/src/setup/messages.ts +50 -0
- package/src/setup/secret-field-model.test.ts +67 -0
- package/src/setup/secret-field-model.ts +104 -0
- package/src/view-system/card-spec.tsx +78 -0
- package/src/view-system/cards-view.tsx +61 -0
- package/src/view-system/index.ts +9 -0
- package/src/view-system/model-view.tsx +105 -0
- package/src/view-system/saved-views.ts +66 -0
- package/src/view-system/types.ts +63 -0
- package/src/view-system/use-view-mode.ts +79 -0
- package/src/view-system/view-state.ts +61 -0
- package/src/view-system/view-switcher.tsx +53 -0
- package/src/view-system/view-toolbar.tsx +119 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Pure helpers for connector secret fields (no React, no i18n): the minimum
|
|
2
|
+
// length a field declares, a CSPRNG generator that honours it, and a strength
|
|
3
|
+
// grade. Provider-agnostic on purpose: they read only how the field itself is
|
|
4
|
+
// declared (`validation` hint on a credential), so any addon benefits.
|
|
5
|
+
|
|
6
|
+
/** What these helpers need from a credential definition. */
|
|
7
|
+
export interface SecretFieldLike {
|
|
8
|
+
key: string
|
|
9
|
+
validation?: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Length used by "Generar" when the field declares no minimum. */
|
|
13
|
+
export const DEFAULT_GENERATED_LENGTH = 32
|
|
14
|
+
/** Hard ceiling so a bad hint never produces an absurd secret. */
|
|
15
|
+
const MAX_GENERATED_LENGTH = 128
|
|
16
|
+
|
|
17
|
+
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Minimum length the manifest declares for a credential, from its `validation`
|
|
21
|
+
* hint. Understands `min_length:32` / `minlength=32` / `min:32` and the regex
|
|
22
|
+
* form `^.{32,}$`. Returns 0 when nothing is declared.
|
|
23
|
+
*/
|
|
24
|
+
export function secretMinLength(field: SecretFieldLike): number {
|
|
25
|
+
const v = (field.validation ?? '').trim()
|
|
26
|
+
if (!v) return 0
|
|
27
|
+
const named = /^(?:min_?length|min)\s*[:=]\s*(\d{1,4})$/i.exec(v)
|
|
28
|
+
if (named) return Number(named[1])
|
|
29
|
+
const rx = /^\^?\(?(?:\.|\\S|\[[^\]]+\])\{(\d{1,4}),(?:\d{0,4})\}\)?\$?$/.exec(v)
|
|
30
|
+
if (rx) return Number(rx[1])
|
|
31
|
+
return 0
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Length "Generar" produces: the declared minimum (never below the default). */
|
|
35
|
+
export function generatedLength(field: SecretFieldLike): number {
|
|
36
|
+
return Math.min(MAX_GENERATED_LENGTH, Math.max(DEFAULT_GENERATED_LENGTH, secretMinLength(field)))
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type RandomSource = Pick<Crypto, 'getRandomValues'>
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Random secret of `length` chars over [A-Za-z0-9] using crypto.getRandomValues.
|
|
43
|
+
* Rejection sampling keeps every character equally likely (no modulo bias).
|
|
44
|
+
* Throws when no CSPRNG exists: a weak fallback is never acceptable here.
|
|
45
|
+
*/
|
|
46
|
+
export function generateSecret(length: number, source?: RandomSource): string {
|
|
47
|
+
const rng = source ?? (typeof globalThis !== 'undefined' ? globalThis.crypto : undefined)
|
|
48
|
+
if (!rng?.getRandomValues) throw new Error('crypto.getRandomValues unavailable')
|
|
49
|
+
const n = Math.max(1, Math.min(MAX_GENERATED_LENGTH, Math.floor(length)))
|
|
50
|
+
const limit = 256 - (256 % ALPHABET.length)
|
|
51
|
+
let out = ''
|
|
52
|
+
while (out.length < n) {
|
|
53
|
+
const buf = new Uint8Array(n * 2)
|
|
54
|
+
rng.getRandomValues(buf)
|
|
55
|
+
for (const b of buf) {
|
|
56
|
+
if (b < limit && out.length < n) out += ALPHABET[b % ALPHABET.length]
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return out
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type SecretStrength = 'empty' | 'weak' | 'fair' | 'strong'
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Coarse grade for the strength bar: length against the declared minimum
|
|
66
|
+
* (or 16/32 when none), plus character variety and repetition.
|
|
67
|
+
*/
|
|
68
|
+
export function secretStrength(value: string, min = 0): SecretStrength {
|
|
69
|
+
if (!value) return 'empty'
|
|
70
|
+
const unique = new Set(value).size
|
|
71
|
+
const classes = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/].filter((r) => r.test(value)).length
|
|
72
|
+
const floor = Math.max(min, 16)
|
|
73
|
+
if (value.length < floor || unique < 6) return 'weak'
|
|
74
|
+
if (value.length >= Math.max(min, 32) && classes >= 2 && unique >= 12) return 'strong'
|
|
75
|
+
return 'fair'
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Keys of non-empty secret values shorter than the minimum their field declares. */
|
|
79
|
+
export function tooShortSecrets(
|
|
80
|
+
fields: (SecretFieldLike & { secret?: boolean; type?: string })[],
|
|
81
|
+
values: Record<string, string>,
|
|
82
|
+
): { key: string; min: number }[] {
|
|
83
|
+
const out: { key: string; min: number }[] = []
|
|
84
|
+
for (const f of fields) {
|
|
85
|
+
if (!f.secret && f.type !== 'secret') continue
|
|
86
|
+
const min = secretMinLength(f)
|
|
87
|
+
const v = values[f.key] ?? ''
|
|
88
|
+
if (min > 0 && v !== '' && v.length < min) out.push({ key: f.key, min })
|
|
89
|
+
}
|
|
90
|
+
return out
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Splits a long help sentence into a short lead and the technical remainder
|
|
95
|
+
* (shown under a collapsible "Cómo se usa"). Splits at the first `;`, `.` or
|
|
96
|
+
* line break; short texts are returned whole.
|
|
97
|
+
*/
|
|
98
|
+
export function splitHelp(text: string, maxLead = 90): { lead: string; detail: string } {
|
|
99
|
+
const t = text.trim()
|
|
100
|
+
if (t.length <= maxLead) return { lead: t, detail: '' }
|
|
101
|
+
const m = /^(.+?)(?:[;.]\s+|\n+)(.+)$/s.exec(t)
|
|
102
|
+
if (!m || m[1].length > 160) return { lead: t, detail: '' }
|
|
103
|
+
return { lead: m[1].replace(/[;.]$/, '').trim(), detail: m[2].trim() }
|
|
104
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { BADGE_TONE_CLASS, type Severity } from '@asteby/metacore-ui/layout'
|
|
2
|
+
import { cn } from '@asteby/metacore-ui/lib'
|
|
3
|
+
import type { CardFieldSpec, CardSpec } from './types'
|
|
4
|
+
|
|
5
|
+
export interface ResolvedCard {
|
|
6
|
+
title: string
|
|
7
|
+
subtitle?: string
|
|
8
|
+
badge?: { text: string; tone: Severity }
|
|
9
|
+
chips: string[]
|
|
10
|
+
meta: { label?: string; value: string }[]
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function fmt(v: unknown, f: CardFieldSpec['format'] = 'text', locale?: string): string {
|
|
14
|
+
if (v == null || v === '') return ''
|
|
15
|
+
try {
|
|
16
|
+
if (f === 'number') return new Intl.NumberFormat(locale).format(Number(v))
|
|
17
|
+
if (f === 'percent') return `${new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(Number(v))}%`
|
|
18
|
+
if (f === 'currency') return new Intl.NumberFormat(locale, { style: 'currency', currency: 'MXN' }).format(Number(v))
|
|
19
|
+
if (f === 'date') return new Date(String(v)).toLocaleDateString(locale)
|
|
20
|
+
if (f === 'datetime') return new Date(String(v)).toLocaleString(locale)
|
|
21
|
+
} catch {
|
|
22
|
+
/* fall through */
|
|
23
|
+
}
|
|
24
|
+
return String(v)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Pure: row + manifest CardSpec -> display model. Missing fields are skipped, never throw. */
|
|
28
|
+
export function resolveCard(spec: CardSpec, row: Record<string, unknown>, locale?: string): ResolvedCard {
|
|
29
|
+
const bv = spec.badge ? row[spec.badge.field] : undefined
|
|
30
|
+
const key = bv == null ? '' : String(bv)
|
|
31
|
+
return {
|
|
32
|
+
title: fmt(row[spec.title]) || '—',
|
|
33
|
+
subtitle: spec.subtitle ? fmt(row[spec.subtitle]) || undefined : undefined,
|
|
34
|
+
badge: spec.badge && key ? { text: spec.badge.labels?.[key] ?? key, tone: spec.badge.tones?.[key] ?? 'info' } : undefined,
|
|
35
|
+
chips: (spec.chips ?? []).map((f) => fmt(row[f])).filter(Boolean),
|
|
36
|
+
meta: (spec.meta ?? []).map((m) => ({ label: m.label, value: fmt(row[m.field], m.format, locale) })).filter((m) => m.value),
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function ConfigurableCard({ spec, row, onClick, locale }: { spec: CardSpec; row: Record<string, unknown>; onClick?: () => void; locale?: string }) {
|
|
41
|
+
const c = resolveCard(spec, row, locale)
|
|
42
|
+
const Tag = onClick ? 'button' : 'div'
|
|
43
|
+
return (
|
|
44
|
+
<Tag
|
|
45
|
+
{...(onClick ? { type: 'button' as const, onClick } : {})}
|
|
46
|
+
className={cn('flex w-full flex-col gap-2 rounded-xl border bg-card p-4 text-start', onClick && 'transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring')}
|
|
47
|
+
>
|
|
48
|
+
<div className='flex items-start justify-between gap-2'>
|
|
49
|
+
<span className='line-clamp-2 font-medium'>{c.title}</span>
|
|
50
|
+
{c.badge && (
|
|
51
|
+
<span data-tone={c.badge.tone} className={cn('shrink-0 rounded-full px-2 text-xs font-semibold leading-5 ring-1 ring-inset', BADGE_TONE_CLASS[c.badge.tone].replace(/motion-safe:animate-pulse/, ''))}>
|
|
52
|
+
{c.badge.text}
|
|
53
|
+
</span>
|
|
54
|
+
)}
|
|
55
|
+
</div>
|
|
56
|
+
{c.subtitle && <span className='line-clamp-2 text-sm text-muted-foreground'>{c.subtitle}</span>}
|
|
57
|
+
{c.chips.length > 0 && (
|
|
58
|
+
<div className='flex flex-wrap gap-1'>
|
|
59
|
+
{c.chips.map((x, i) => (
|
|
60
|
+
<span key={i} className='rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground'>
|
|
61
|
+
{x}
|
|
62
|
+
</span>
|
|
63
|
+
))}
|
|
64
|
+
</div>
|
|
65
|
+
)}
|
|
66
|
+
{c.meta.length > 0 && (
|
|
67
|
+
<dl className='mt-auto grid grid-cols-2 gap-x-3 gap-y-1 text-xs text-muted-foreground'>
|
|
68
|
+
{c.meta.map((m, i) => (
|
|
69
|
+
<div key={i} className='min-w-0'>
|
|
70
|
+
{m.label && <dt className='sr-only'>{m.label}</dt>}
|
|
71
|
+
<dd className='truncate'>{m.value}</dd>
|
|
72
|
+
</div>
|
|
73
|
+
))}
|
|
74
|
+
</dl>
|
|
75
|
+
)}
|
|
76
|
+
</Tag>
|
|
77
|
+
)
|
|
78
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { useEffect, useState } from 'react'
|
|
2
|
+
import { useQuery } from '@tanstack/react-query'
|
|
3
|
+
import { useTranslation } from 'react-i18next'
|
|
4
|
+
import { Button } from '@asteby/metacore-ui/primitives'
|
|
5
|
+
import { useApi } from '../api-context'
|
|
6
|
+
import { ConfigurableCard } from './card-spec'
|
|
7
|
+
import type { CardSpec } from './types'
|
|
8
|
+
|
|
9
|
+
export interface CardsViewProps {
|
|
10
|
+
model: string
|
|
11
|
+
endpoint?: string
|
|
12
|
+
card: CardSpec
|
|
13
|
+
/** Server params from `viewStateToParams` — the SAME filters the table uses. */
|
|
14
|
+
params: Record<string, string>
|
|
15
|
+
pageSize?: number
|
|
16
|
+
onOpen?: (row: Record<string, unknown>) => void
|
|
17
|
+
/** Reports the filtered total so the shell can render "7,358 hallazgos". */
|
|
18
|
+
onTotal?: (total: number) => void
|
|
19
|
+
/** Bump to refetch (e.g. realtime tick). */
|
|
20
|
+
refreshTrigger?: unknown
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Card grid over the same list endpoint DynamicTable uses; "load more" pagination. */
|
|
24
|
+
export function CardsView({ model, endpoint, card, params, pageSize = 24, onOpen, onTotal, refreshTrigger }: CardsViewProps) {
|
|
25
|
+
const api = useApi()
|
|
26
|
+
const { t, i18n } = useTranslation()
|
|
27
|
+
const [pages, setPages] = useState(1)
|
|
28
|
+
const key = JSON.stringify(params)
|
|
29
|
+
useEffect(() => setPages(1), [key])
|
|
30
|
+
const q = useQuery({
|
|
31
|
+
queryKey: ['view-cards', model, endpoint, key, pages, refreshTrigger],
|
|
32
|
+
queryFn: async () => {
|
|
33
|
+
const res = await api.get(endpoint ?? `/data/${model}`, { params: { ...params, page: 1, per_page: pageSize * pages } })
|
|
34
|
+
const b = res.data
|
|
35
|
+
const rows = (Array.isArray(b?.data) ? b.data : Array.isArray(b) ? b : []) as Record<string, unknown>[]
|
|
36
|
+
return { rows, total: Number(b?.meta?.total ?? rows.length) }
|
|
37
|
+
},
|
|
38
|
+
placeholderData: (prev) => prev,
|
|
39
|
+
})
|
|
40
|
+
useEffect(() => {
|
|
41
|
+
if (q.data) onTotal?.(q.data.total)
|
|
42
|
+
}, [q.data, onTotal])
|
|
43
|
+
if (q.isLoading) return <div className='p-6 text-sm text-muted-foreground'>{t('common.loading', { defaultValue: 'Cargando…' })}</div>
|
|
44
|
+
if (q.isError) return <div role='alert' className='p-6 text-sm text-destructive'>{t('views.error', { defaultValue: 'No se pudo cargar la lista' })}</div>
|
|
45
|
+
const rows = q.data?.rows ?? []
|
|
46
|
+
if (rows.length === 0) return <div className='p-6 text-sm text-muted-foreground'>{t('views.empty', { defaultValue: 'Sin resultados' })}</div>
|
|
47
|
+
return (
|
|
48
|
+
<div className='flex flex-col gap-4'>
|
|
49
|
+
<div className='grid gap-3 sm:grid-cols-2 xl:grid-cols-3'>
|
|
50
|
+
{rows.map((r, i) => (
|
|
51
|
+
<ConfigurableCard key={String(r.id ?? i)} spec={card} row={r} locale={i18n.language} onClick={onOpen ? () => onOpen(r) : undefined} />
|
|
52
|
+
))}
|
|
53
|
+
</div>
|
|
54
|
+
{rows.length < (q.data?.total ?? 0) && (
|
|
55
|
+
<Button variant='outline' className='self-center' onClick={() => setPages((p) => p + 1)}>
|
|
56
|
+
{t('views.load_more', { defaultValue: 'Cargar más' })}
|
|
57
|
+
</Button>
|
|
58
|
+
)}
|
|
59
|
+
</div>
|
|
60
|
+
)
|
|
61
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export * from './types'
|
|
2
|
+
export { parseViewState, serializeViewState, viewStateToParams, isViewStateEmpty, EMPTY_VIEW_STATE } from './view-state'
|
|
3
|
+
export { useViewMode, resolveViewMode, viewPrefKey, DEFAULT_MODES, type UseViewModeOptions } from './use-view-mode'
|
|
4
|
+
export { ViewSwitcher, type ViewSwitcherProps } from './view-switcher'
|
|
5
|
+
export { ViewToolbar, type ViewToolbarProps } from './view-toolbar'
|
|
6
|
+
export { useSavedViews, localSavedViewsAdapter, upsertSavedView, removeSavedView, MAX_SAVED_VIEWS, type SavedViewsAdapter } from './saved-views'
|
|
7
|
+
export { ConfigurableCard, resolveCard, type ResolvedCard } from './card-spec'
|
|
8
|
+
export { CardsView, type CardsViewProps } from './cards-view'
|
|
9
|
+
export { ModelView, type ModelViewProps, type ModelViewRendererProps } from './model-view'
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { useCallback, useEffect, useState, type ComponentType } from 'react'
|
|
2
|
+
import { DynamicTable, type DynamicTableProps } from '../dynamic-table'
|
|
3
|
+
import { CardsView } from './cards-view'
|
|
4
|
+
import { parseViewState, serializeViewState, viewStateToParams } from './view-state'
|
|
5
|
+
import { DEFAULT_MODES, useViewMode } from './use-view-mode'
|
|
6
|
+
import { useSavedViews, type SavedViewsAdapter } from './saved-views'
|
|
7
|
+
import { ViewSwitcher } from './view-switcher'
|
|
8
|
+
import { ViewToolbar } from './view-toolbar'
|
|
9
|
+
import type { CardSpec, QuickFilterDef, SortSpec, ViewModeDef, ViewState } from './types'
|
|
10
|
+
|
|
11
|
+
export interface ModelViewRendererProps {
|
|
12
|
+
model: string
|
|
13
|
+
/** Server params for the active filters — identical across modes. */
|
|
14
|
+
params: Record<string, string>
|
|
15
|
+
state: ViewState
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface ModelViewProps extends DynamicTableProps {
|
|
19
|
+
/** Modes declared by the module's manifest; default Tarjetas | Datos. A host adds `map` here. */
|
|
20
|
+
modes?: ViewModeDef[]
|
|
21
|
+
card?: CardSpec
|
|
22
|
+
quickFilters?: QuickFilterDef[]
|
|
23
|
+
/** Plural noun for the counter. */
|
|
24
|
+
noun?: string
|
|
25
|
+
sort?: SortSpec
|
|
26
|
+
userId?: string
|
|
27
|
+
savedViewsAdapter?: SavedViewsAdapter
|
|
28
|
+
/** Extra mode renderers keyed by mode key (e.g. `map`, supplied by the maps work). */
|
|
29
|
+
renderers?: Record<string, ComponentType<ModelViewRendererProps>>
|
|
30
|
+
onOpenRecord?: (row: Record<string, unknown>) => void
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function currentSearch() {
|
|
34
|
+
return typeof window === 'undefined' ? '' : window.location.search
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The generic list surface: ViewSwitcher + ViewToolbar over ONE ViewState that
|
|
39
|
+
* lives in the URL, so cards / table / map show the same filtered data.
|
|
40
|
+
* Table mode is DynamicTable (it adopts the same `search`/`f_*` URL params).
|
|
41
|
+
*/
|
|
42
|
+
export function ModelView({ modes, card, quickFilters, noun, sort, userId, savedViewsAdapter, renderers, onOpenRecord, ...table }: ModelViewProps) {
|
|
43
|
+
const { model } = table
|
|
44
|
+
const effModes = (modes ?? DEFAULT_MODES).filter((m) => m.key !== 'cards' || card)
|
|
45
|
+
const [state, setState] = useState<ViewState>(() => parseViewState(currentSearch()))
|
|
46
|
+
const [total, setTotal] = useState<number | undefined>()
|
|
47
|
+
const urlView = typeof window === 'undefined' ? undefined : new URLSearchParams(currentSearch()).get('view') ?? undefined
|
|
48
|
+
const [mode, setMode] = useViewMode(model, effModes, {
|
|
49
|
+
userId,
|
|
50
|
+
urlView,
|
|
51
|
+
defaultKey: effModes[0]?.key,
|
|
52
|
+
onUrlChange: (v) => {
|
|
53
|
+
const p = new URLSearchParams(currentSearch())
|
|
54
|
+
p.set('view', v)
|
|
55
|
+
window.history.replaceState(null, '', `${window.location.pathname}?${p}`)
|
|
56
|
+
},
|
|
57
|
+
})
|
|
58
|
+
const saved = useSavedViews(model, { userId, adapter: savedViewsAdapter })
|
|
59
|
+
|
|
60
|
+
const apply = useCallback((next: ViewState) => {
|
|
61
|
+
setState(next)
|
|
62
|
+
if (typeof window !== 'undefined') {
|
|
63
|
+
const s = serializeViewState(next, currentSearch())
|
|
64
|
+
window.history.replaceState(null, '', `${window.location.pathname}${s}`)
|
|
65
|
+
}
|
|
66
|
+
}, [])
|
|
67
|
+
useEffect(() => {
|
|
68
|
+
const on = () => setState(parseViewState(currentSearch()))
|
|
69
|
+
window.addEventListener('popstate', on)
|
|
70
|
+
return () => window.removeEventListener('popstate', on)
|
|
71
|
+
}, [])
|
|
72
|
+
|
|
73
|
+
const params = viewStateToParams(state, quickFilters)
|
|
74
|
+
const Extra = renderers?.[mode]
|
|
75
|
+
return (
|
|
76
|
+
<div className='flex h-full min-h-0 flex-col gap-3'>
|
|
77
|
+
<div className='flex flex-wrap items-start justify-between gap-2'>
|
|
78
|
+
{mode !== 'table' && (
|
|
79
|
+
<div className='min-w-0 flex-1'>
|
|
80
|
+
<ViewToolbar
|
|
81
|
+
state={state}
|
|
82
|
+
onChange={apply}
|
|
83
|
+
quickFilters={quickFilters}
|
|
84
|
+
total={total}
|
|
85
|
+
noun={noun}
|
|
86
|
+
sort={sort}
|
|
87
|
+
savedViews={saved.views}
|
|
88
|
+
onSaveView={(name) => saved.save({ name, state, mode })}
|
|
89
|
+
onApplySavedView={(v) => apply(v.state)}
|
|
90
|
+
onRemoveSavedView={saved.remove}
|
|
91
|
+
/>
|
|
92
|
+
</div>
|
|
93
|
+
)}
|
|
94
|
+
<ViewSwitcher modes={effModes} active={mode} onChange={setMode} className='ms-auto' />
|
|
95
|
+
</div>
|
|
96
|
+
{mode === 'cards' && card ? (
|
|
97
|
+
<CardsView model={model} endpoint={table.endpoint} card={card} params={params} onOpen={onOpenRecord} onTotal={setTotal} refreshTrigger={table.refreshTrigger} />
|
|
98
|
+
) : Extra ? (
|
|
99
|
+
<Extra model={model} params={params} state={state} />
|
|
100
|
+
) : (
|
|
101
|
+
<DynamicTable {...table} enableUrlSync={table.enableUrlSync ?? true} />
|
|
102
|
+
)}
|
|
103
|
+
</div>
|
|
104
|
+
)
|
|
105
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { useCallback, useEffect, useMemo, useState } from 'react'
|
|
2
|
+
import type { SavedView } from './types'
|
|
3
|
+
|
|
4
|
+
/** Pluggable persistence; default is per-user localStorage. A host can back it by the server so views follow the user across devices. */
|
|
5
|
+
export interface SavedViewsAdapter {
|
|
6
|
+
load(model: string): Promise<SavedView[]> | SavedView[]
|
|
7
|
+
save(model: string, views: SavedView[]): Promise<void> | void
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export const MAX_SAVED_VIEWS = 20
|
|
11
|
+
|
|
12
|
+
export function localSavedViewsAdapter(userId?: string): SavedViewsAdapter {
|
|
13
|
+
const key = (m: string) => `mc:saved-views:${userId ?? 'anon'}:${m}`
|
|
14
|
+
return {
|
|
15
|
+
load(model) {
|
|
16
|
+
try {
|
|
17
|
+
const raw = localStorage.getItem(key(model))
|
|
18
|
+
const v = raw ? JSON.parse(raw) : []
|
|
19
|
+
return Array.isArray(v) ? v : []
|
|
20
|
+
} catch {
|
|
21
|
+
return []
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
save(model, views) {
|
|
25
|
+
try {
|
|
26
|
+
localStorage.setItem(key(model), JSON.stringify(views))
|
|
27
|
+
} catch {
|
|
28
|
+
/* ignore */
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Pure: add (or rename-replace by name) a view, bounded. */
|
|
35
|
+
export function upsertSavedView(list: SavedView[], v: SavedView): SavedView[] {
|
|
36
|
+
const rest = list.filter((x) => x.id !== v.id && x.name !== v.name)
|
|
37
|
+
return [...rest, v].slice(-MAX_SAVED_VIEWS)
|
|
38
|
+
}
|
|
39
|
+
export function removeSavedView(list: SavedView[], id: string): SavedView[] {
|
|
40
|
+
return list.filter((x) => x.id !== id)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function useSavedViews(model: string, opts: { userId?: string; adapter?: SavedViewsAdapter } = {}) {
|
|
44
|
+
const adapter = useMemo(() => opts.adapter ?? localSavedViewsAdapter(opts.userId), [opts.adapter, opts.userId])
|
|
45
|
+
const [views, setViews] = useState<SavedView[]>([])
|
|
46
|
+
useEffect(() => {
|
|
47
|
+
let live = true
|
|
48
|
+
Promise.resolve(adapter.load(model)).then((v) => live && setViews(v))
|
|
49
|
+
return () => {
|
|
50
|
+
live = false
|
|
51
|
+
}
|
|
52
|
+
}, [adapter, model])
|
|
53
|
+
const commit = useCallback(
|
|
54
|
+
(next: SavedView[]) => {
|
|
55
|
+
setViews(next)
|
|
56
|
+
void adapter.save(model, next)
|
|
57
|
+
},
|
|
58
|
+
[adapter, model],
|
|
59
|
+
)
|
|
60
|
+
return {
|
|
61
|
+
views,
|
|
62
|
+
save: (v: Omit<SavedView, 'id'> & { id?: string }) =>
|
|
63
|
+
commit(upsertSavedView(views, { ...v, id: v.id ?? `v_${Date.now().toString(36)}` })),
|
|
64
|
+
remove: (id: string) => commit(removeSavedView(views, id)),
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { Severity } from '@asteby/metacore-ui/layout'
|
|
2
|
+
|
|
3
|
+
/** `cards` and `table` are built in; `map` (and anything else) is a host/addon renderer. */
|
|
4
|
+
export type ViewModeKey = 'cards' | 'table' | 'map' | (string & {})
|
|
5
|
+
|
|
6
|
+
export interface ViewModeDef {
|
|
7
|
+
key: ViewModeKey
|
|
8
|
+
/** Label override from the manifest (e.g. "Hallazgos", "Pedidos"). Absent -> default i18n label. */
|
|
9
|
+
label?: string
|
|
10
|
+
/** Lucide icon name override. */
|
|
11
|
+
icon?: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface CardFieldSpec {
|
|
15
|
+
field: string
|
|
16
|
+
/** i18n key or literal shown before the value in meta rows. */
|
|
17
|
+
label?: string
|
|
18
|
+
format?: 'text' | 'date' | 'datetime' | 'number' | 'currency' | 'percent'
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Manifest-declared card: no per-addon code. */
|
|
22
|
+
export interface CardSpec {
|
|
23
|
+
title: string
|
|
24
|
+
subtitle?: string
|
|
25
|
+
/** Priority/severity badge: value -> tone, optional value -> label. */
|
|
26
|
+
badge?: { field: string; tones?: Record<string, Severity>; labels?: Record<string, string> }
|
|
27
|
+
/** Fields rendered as small chips (status, territory...). */
|
|
28
|
+
chips?: string[]
|
|
29
|
+
/** Secondary metadata rows. */
|
|
30
|
+
meta?: CardFieldSpec[]
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface QuickFilterDef {
|
|
34
|
+
key: string
|
|
35
|
+
/** Label (already translated or an i18n key). */
|
|
36
|
+
label: string
|
|
37
|
+
/** Column -> filter value (same shape as DynamicTable `defaultFilters`, e.g. { status: 'EQ:human_review' }). Empty = "Todos". */
|
|
38
|
+
params: Record<string, string>
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface SortSpec {
|
|
42
|
+
field: string
|
|
43
|
+
dir: 'asc' | 'desc'
|
|
44
|
+
/** Human label for the counter ("prioridad"). */
|
|
45
|
+
label?: string
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The one filter state shared by EVERY mode (cards, table, map). */
|
|
49
|
+
export interface ViewState {
|
|
50
|
+
search: string
|
|
51
|
+
/** Active quick-filter key; '' = none/"Todos". */
|
|
52
|
+
quick: string
|
|
53
|
+
/** Extra column filters (`f_<col>` on the wire). */
|
|
54
|
+
filters: Record<string, string>
|
|
55
|
+
sort?: { field: string; dir: 'asc' | 'desc' }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface SavedView {
|
|
59
|
+
id: string
|
|
60
|
+
name: string
|
|
61
|
+
state: ViewState
|
|
62
|
+
mode?: ViewModeKey
|
|
63
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { useCallback, useState } from 'react'
|
|
2
|
+
import type { ViewModeDef, ViewModeKey } from './types'
|
|
3
|
+
|
|
4
|
+
export const DEFAULT_MODES: ViewModeDef[] = [{ key: 'cards' }, { key: 'table' }]
|
|
5
|
+
|
|
6
|
+
/** Legacy `?view=` values: list -> table. */
|
|
7
|
+
function normalize(v: string | undefined): string | undefined {
|
|
8
|
+
if (!v) return undefined
|
|
9
|
+
return v === 'list' ? 'table' : v
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Pure precedence: URL `?view=` > preference for (model, scope) > preference for
|
|
14
|
+
* model > default > first mode. Only keys present in `modes` are accepted.
|
|
15
|
+
*/
|
|
16
|
+
export function resolveViewMode(
|
|
17
|
+
modes: ViewModeDef[],
|
|
18
|
+
o: { urlView?: string; scoped?: string; model?: string; defaultKey?: string },
|
|
19
|
+
): ViewModeKey {
|
|
20
|
+
const keys = new Set(modes.map((m) => m.key as string))
|
|
21
|
+
for (const c of [o.urlView, o.scoped, o.model, o.defaultKey]) {
|
|
22
|
+
const n = normalize(c)
|
|
23
|
+
if (n && keys.has(n)) return n
|
|
24
|
+
}
|
|
25
|
+
return modes[0]?.key ?? 'table'
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function read(key: string): string | undefined {
|
|
29
|
+
try {
|
|
30
|
+
return localStorage.getItem(key) ?? undefined
|
|
31
|
+
} catch {
|
|
32
|
+
return undefined
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function write(key: string, v: string) {
|
|
36
|
+
try {
|
|
37
|
+
localStorage.setItem(key, v)
|
|
38
|
+
} catch {
|
|
39
|
+
/* storage blocked: preference just doesn't persist */
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface UseViewModeOptions {
|
|
44
|
+
/** Per-user namespace so two users on one browser keep their own choice. */
|
|
45
|
+
userId?: string
|
|
46
|
+
/** Optional finer scope (e.g. a menu entry / segment). */
|
|
47
|
+
scope?: string
|
|
48
|
+
urlView?: string
|
|
49
|
+
defaultKey?: ViewModeKey
|
|
50
|
+
/** Called on change so the host can mirror it into `?view=`. */
|
|
51
|
+
onUrlChange?: (view: string) => void
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function viewPrefKey(userId: string | undefined, model: string, scope?: string) {
|
|
55
|
+
return `mc:view:${userId ?? 'anon'}:${model}${scope ? `:${scope}` : ''}`
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Active mode + setter that persists the preference (localStorage, try/catch). */
|
|
59
|
+
export function useViewMode(model: string, modes: ViewModeDef[] = DEFAULT_MODES, opts: UseViewModeOptions = {}) {
|
|
60
|
+
const { userId, scope, urlView, defaultKey, onUrlChange } = opts
|
|
61
|
+
const [rev, setRev] = useState(0)
|
|
62
|
+
void rev
|
|
63
|
+
const active = resolveViewMode(modes, {
|
|
64
|
+
urlView,
|
|
65
|
+
scoped: scope ? read(viewPrefKey(userId, model, scope)) : undefined,
|
|
66
|
+
model: read(viewPrefKey(userId, model)),
|
|
67
|
+
defaultKey,
|
|
68
|
+
})
|
|
69
|
+
const setMode = useCallback(
|
|
70
|
+
(key: ViewModeKey) => {
|
|
71
|
+
write(viewPrefKey(userId, model), key)
|
|
72
|
+
if (scope) write(viewPrefKey(userId, model, scope), key)
|
|
73
|
+
onUrlChange?.(key)
|
|
74
|
+
setRev((r) => r + 1)
|
|
75
|
+
},
|
|
76
|
+
[userId, model, scope, onUrlChange],
|
|
77
|
+
)
|
|
78
|
+
return [active, setMode] as const
|
|
79
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { QuickFilterDef, ViewState } from './types'
|
|
2
|
+
|
|
3
|
+
export const EMPTY_VIEW_STATE: ViewState = { search: '', quick: '', filters: {} }
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* URL <-> ViewState. Same param names DynamicTable already reads/writes
|
|
7
|
+
* (`search`, `f_<col>`, `sortBy`, `order`) plus `q` for the quick filter, so
|
|
8
|
+
* the URL is the single source of truth and the table adopts the shell's
|
|
9
|
+
* filters (and vice versa) with no extra wiring.
|
|
10
|
+
*/
|
|
11
|
+
export function parseViewState(search: string): ViewState {
|
|
12
|
+
const p = new URLSearchParams(search.startsWith('?') ? search.slice(1) : search)
|
|
13
|
+
const filters: Record<string, string> = {}
|
|
14
|
+
p.forEach((v, k) => {
|
|
15
|
+
if (k.startsWith('f_') && k.length > 2) filters[k.slice(2)] = v
|
|
16
|
+
})
|
|
17
|
+
const sortBy = p.get('sortBy')
|
|
18
|
+
return {
|
|
19
|
+
search: p.get('search') ?? '',
|
|
20
|
+
quick: p.get('q') ?? '',
|
|
21
|
+
filters,
|
|
22
|
+
sort: sortBy ? { field: sortBy, dir: p.get('order') === 'desc' ? 'desc' : 'asc' } : undefined,
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Writes the ViewState onto an existing search string, leaving unrelated params (view, page...) alone. */
|
|
27
|
+
export function serializeViewState(state: ViewState, base = ''): string {
|
|
28
|
+
const p = new URLSearchParams(base.startsWith('?') ? base.slice(1) : base)
|
|
29
|
+
for (const k of [...p.keys()]) if (k.startsWith('f_') || k === 'search' || k === 'q' || k === 'sortBy' || k === 'order') p.delete(k)
|
|
30
|
+
if (state.search) p.set('search', state.search)
|
|
31
|
+
if (state.quick) p.set('q', state.quick)
|
|
32
|
+
for (const [k, v] of Object.entries(state.filters)) if (v) p.set(`f_${k}`, v)
|
|
33
|
+
if (state.sort) {
|
|
34
|
+
p.set('sortBy', state.sort.field)
|
|
35
|
+
p.set('order', state.sort.dir)
|
|
36
|
+
}
|
|
37
|
+
const s = p.toString()
|
|
38
|
+
return s ? `?${s}` : ''
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The effective server params for a state: quick-filter columns + explicit
|
|
43
|
+
* filters (explicit wins) as `f_<col>`, `search`, sort. Used by cards/map; the
|
|
44
|
+
* table gets the same via the URL.
|
|
45
|
+
*/
|
|
46
|
+
export function viewStateToParams(state: ViewState, quickDefs: QuickFilterDef[] = []): Record<string, string> {
|
|
47
|
+
const out: Record<string, string> = {}
|
|
48
|
+
const quick = quickDefs.find((q) => q.key === state.quick)
|
|
49
|
+
for (const [k, v] of Object.entries(quick?.params ?? {})) out[`f_${k}`] = v
|
|
50
|
+
for (const [k, v] of Object.entries(state.filters)) if (v) out[`f_${k}`] = v
|
|
51
|
+
if (state.search) out.search = state.search
|
|
52
|
+
if (state.sort) {
|
|
53
|
+
out.sortBy = state.sort.field
|
|
54
|
+
out.order = state.sort.dir
|
|
55
|
+
}
|
|
56
|
+
return out
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function isViewStateEmpty(s: ViewState): boolean {
|
|
60
|
+
return !s.search && !s.quick && Object.keys(s.filters).length === 0
|
|
61
|
+
}
|