Merge branch 'feat/restore-hub-view-hide-aoi-non-geo' into 'main'

feat(editor): restore 3-col HubView + hide AOI on non-geo dicts

See merge request 2-6/2-6-4/terravault/ordinis!89
This commit is contained in:
Александр Зимин
2026-05-11 17:49:44 +00:00
2 changed files with 198 additions and 176 deletions
@@ -1,63 +1,99 @@
/** /**
* DictionaryHubView — Связи tab per redesign/screens/04-editor-links.png. * Hub view (View B из design handoff) — focused dictionary в центре + соседи
* по обе стороны.
* *
* <p>2-column split: * Layout:
* <ul> * ┌──────────────┬─────────────────┬──────────────┐
* <li><b>→ ССЫЛАЕТСЯ НА (N)</b>: outgoing FK — каждая row показывает * │ → ссылается │ <current> │ ← N использ. │
* target_dict (link) + record_count + required/optional chip + source_field * │ (outgoing) │ (focused) │ (refBy) │
* (mono right).</li> * └──────────────┴─────────────────┴──────────────┘
* <li><b>← ССЫЛАЮТСЯ НА НАС (M)</b>: incoming FK — source_dict (link) +
* activeRecordsInSourceDict + onClose policy chip ("критично" для BLOCK).
* Footer warning если total dependents > N — указывает что удаление
* записи в этом dict сложно.</li>
* </ul>
* *
* <p>Replaces старый 3-col hub view с central dict card — center больше не * Outgoing FK derived from schemaJson properties[*].x-references
* нужен (всё info уже в InfoPanel слева). * (format: "dict.field"). Incoming refBy via useDictionaryDependents.
*
* Click на neighbor card → navigate к его Hub view (recursion fine).
*/ */
import { useMemo } from 'react' import { useMemo } from 'react'
import { Link } from '@tanstack/react-router' import { Link } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { useDictionaries, useDictionaryDependents } from '@/api/queries' import { Badge } from '@/ui'
import type { import { useDictionaryDependents, useDictionaries } from '@/api/queries'
DictionaryDefinition, import type { DictionaryDetail, DictionaryDefinition, JsonSchema } from '@/api/client'
DictionaryDetail,
JsonSchema,
SchemaDependent,
} from '@/api/client'
import { cn } from '@/lib/utils'
type OutgoingFkRow = { const SCOPE_STRIP: Record<string, string> = {
/** Target dict name. */ PUBLIC: 'bg-emerald-500',
target: string INTERNAL: 'bg-amber-500',
/** Source field name in current schema. */ RESTRICTED: 'bg-rose-500',
sourceField: string
/** Target field name (usually .id или .code). */
targetField: string
/** Required в JSON schema. */
required: boolean
} }
/** Walk schema properties → build outgoing FK rows. */ /**
const extractOutgoingFk = (schema: JsonSchema | undefined): OutgoingFkRow[] => { * Walk schemaJson properties — собираем targets из x-references.
* Format: "targetDict.targetField" → возвращаем уникальные targetDict names.
*/
const extractOutgoingFk = (schema: JsonSchema | undefined): string[] => {
if (!schema?.properties) return [] if (!schema?.properties) return []
const required = new Set(schema.required ?? []) const targets = new Set<string>()
const rows: OutgoingFkRow[] = [] for (const prop of Object.values(schema.properties)) {
for (const [field, prop] of Object.entries(schema.properties)) {
const ref = prop['x-references'] const ref = prop['x-references']
if (typeof ref === 'string' && ref.length > 0) { if (typeof ref === 'string' && ref.length > 0) {
const [target, targetField] = ref.split('.') const [target] = ref.split('.')
if (target) { if (target) targets.add(target)
rows.push({
target,
sourceField: field,
targetField: targetField ?? 'id',
required: required.has(field),
})
}
} }
} }
return rows.sort((a, b) => a.target.localeCompare(b.target)) return Array.from(targets).sort()
}
const NeighborCard = ({
dict,
side,
}: {
dict: DictionaryDefinition
side: 'left' | 'right'
}) => (
<Link
to="/dictionaries/$name"
params={{ name: dict.name }}
search={{ tab: 'relations' }}
className={`group block bg-white border border-line rounded-lg p-3 transition hover:shadow-hover hover:border-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40 ${
side === 'left' ? 'text-right' : 'text-left'
}`}
>
<div className={`flex items-baseline gap-2 ${side === 'left' ? 'justify-end' : ''}`}>
<span
className={`inline-block size-1.5 rounded-full shrink-0 ${
SCOPE_STRIP[dict.scope] ?? 'bg-ink/40'
}`}
aria-hidden="true"
/>
<h4 className="font-sans text-[14px] font-semibold text-accent truncate group-hover:underline">
{dict.displayName ?? dict.name}
</h4>
</div>
<div className="mt-0.5 font-mono text-[10px] text-mute truncate">
{dict.name}
</div>
</Link>
)
const SectionLabel = ({
side,
count,
}: {
side: 'left' | 'right'
count: number
}) => {
const { t } = useTranslation()
return (
<div
className={`text-cap text-mute mb-2 ${
side === 'left' ? 'text-right' : 'text-left'
}`}
>
{side === 'left'
? t('hub.outgoing', { count, defaultValue: '→ ссылается ({{count}})' })
: t('hub.incoming', { count, defaultValue: '← {{count}} использ.' })}
</div>
)
} }
export function DictionaryHubView({ detail }: { detail: DictionaryDetail }) { export function DictionaryHubView({ detail }: { detail: DictionaryDetail }) {
@@ -65,146 +101,113 @@ export function DictionaryHubView({ detail }: { detail: DictionaryDetail }) {
const { data: allDicts } = useDictionaries() const { data: allDicts } = useDictionaries()
const { data: refByRaw } = useDictionaryDependents(detail.name) const { data: refByRaw } = useDictionaryDependents(detail.name)
const outgoing = useMemo(() => extractOutgoingFk(detail.schemaJson), [detail.schemaJson]) // Outgoing FK targets — names derived из schemaJson.
const incoming: SchemaDependent[] = useMemo(() => refByRaw ?? [], [refByRaw]) const outgoingNames = useMemo(
() => extractOutgoingFk(detail.schemaJson),
// Resolve target dict definitions для record count badge. [detail.schemaJson],
const dictByName = useMemo(() => {
if (!allDicts) return new Map<string, DictionaryDefinition>()
return new Map(allDicts.map((d) => [d.name, d]))
}, [allDicts])
// Aggregate total incoming deps count для warning footer.
const totalIncomingDeps = useMemo(
() => incoming.reduce((sum, d) => sum + d.activeRecordsInSourceDict, 0),
[incoming],
) )
const HEAVY_THRESHOLD = 100
// Resolve names → DictionaryDefinition (для card rendering).
// Filter недоступные / unknown names (защита от устаревших schema refs).
const outgoingDicts = useMemo(() => {
if (!allDicts) return []
const byName = new Map(allDicts.map((d) => [d.name, d]))
return outgoingNames
.map((name) => byName.get(name))
.filter((d): d is DictionaryDefinition => Boolean(d))
}, [allDicts, outgoingNames])
// refBy: уникальные source dicts (те что ссылаются на нас) → resolve в definitions.
const incomingDicts = useMemo(() => {
if (!allDicts || !refByRaw) return []
const byName = new Map(allDicts.map((d) => [d.name, d]))
const seen = new Set<string>()
const out: DictionaryDefinition[] = []
for (const dep of refByRaw) {
if (seen.has(dep.sourceDict)) continue
seen.add(dep.sourceDict)
const def = byName.get(dep.sourceDict)
if (def) out.push(def)
}
return out
}, [allDicts, refByRaw])
return ( return (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <section
{/* Outgoing → */} aria-label={t('hub.heading', { defaultValue: 'Связи справочника' })}
<section className="rounded-lg border border-line bg-surface overflow-hidden"> className="grid grid-cols-1 md:grid-cols-[1fr_minmax(280px,_360px)_1fr] gap-4 md:gap-6 items-start py-2"
<header className="px-4 py-2.5 border-b border-line-2"> >
<div className="text-cap text-mute tracking-[0.16em] uppercase"> {/* Left rail: outgoing FK */}
{t('hub.outgoing', { defaultValue: 'ссылается на' })} <div className="md:order-1 order-2 space-y-2">
<span className="text-mono text-ink ml-1">({outgoing.length})</span> <SectionLabel side="left" count={outgoingDicts.length} />
</div> {outgoingDicts.length === 0 ? (
</header> <div className="text-cell text-mute/70 text-right italic">
{outgoing.length === 0 ? ( {t('hub.noOutgoing', { defaultValue: 'нет исходящих ссылок' })}
<div className="px-4 py-8 text-center text-body text-mute">
{t('hub.empty.outgoing', {
defaultValue: 'Нет исходящих FK',
})}
</div> </div>
) : ( ) : (
<ul> <div className="space-y-2">
{outgoing.map((row) => { {outgoingDicts.map((d) => (
const target = dictByName.get(row.target) <NeighborCard key={d.id} dict={d} side="left" />
return ( ))}
<li </div>
key={`${row.target}.${row.sourceField}`}
className="border-b border-line-2 last:border-b-0"
>
<Link
to="/dictionaries/$name"
params={{ name: row.target }}
className="flex items-center gap-3 px-4 py-2.5 hover:bg-surface-2/50 transition-colors"
>
<span className="text-mono text-body text-accent font-medium truncate flex-1 min-w-0">
{row.target}
</span>
{target?.recordCount !== undefined && (
<span className="text-mono text-cell text-mute tabular-nums shrink-0">
{target.recordCount}
</span>
)}
<span
className={cn(
'text-cap font-semibold tracking-wider px-1.5 py-0.5 rounded-sm shrink-0',
row.required
? 'bg-accent-bg text-accent'
: 'bg-surface-2 text-mute',
)}
>
{row.required ? 'required' : 'optional'}
</span>
<span className="text-mono text-cell text-ink-2 shrink-0 min-w-[80px] text-right">
{row.sourceField}
</span>
</Link>
</li>
)
})}
</ul>
)} )}
</section> </div>
{/* Incoming ← */} {/* Center: focused dict (large card) */}
<section className="rounded-lg border border-line bg-surface overflow-hidden flex flex-col"> <div className="md:order-2 order-1 relative">
<header className="px-4 py-2.5 border-b border-line-2"> <div
<div className="text-cap text-mute tracking-[0.16em] uppercase"> className="relative bg-white rounded-xl p-5 border-2 border-accent"
{t('hub.incoming', { defaultValue: 'ссылаются на нас' })} style={{ boxShadow: '0 18px 36px -22px rgba(20,30,140,.5)' }}
<span className="text-mono text-ink ml-1">({incoming.length})</span> >
<div className="flex items-start gap-2 mb-2 flex-wrap">
<Badge variant="info">{detail.scope}</Badge>
{detail.approvalRequired && (
<Badge variant="warning">
{t('dict.list.approval', { defaultValue: 'approval' })}
</Badge>
)}
<span className="text-mono ml-auto text-mute">
v{detail.schemaVersion}
</span>
</div> </div>
</header> <h2 className="text-title-xl font-sans text-accent leading-tight">
{incoming.length === 0 ? ( {detail.displayName ?? detail.name}
<div className="px-4 py-8 text-center text-body text-mute"> </h2>
{t('hub.empty.incoming', { <div className="text-mono text-mute mt-0.5">
defaultValue: 'Никто не ссылается', {detail.name}
})} </div>
{detail.description && (
<p className="text-[13px] text-ink mt-3 leading-relaxed">
{detail.description}
</p>
)}
<div className="text-cap mt-4 pt-3 border-t border-line flex items-center justify-between text-mute">
<span>{detail.bundle}</span>
<span>{detail.supportedLocales.join(', ')}</span>
{typeof detail.recordCount === 'number' && (
<span>
{t('dict.list.recordCount', { count: detail.recordCount })}
</span>
)}
</div>
</div>
</div>
{/* Right rail: refBy */}
<div className="md:order-3 order-3 space-y-2">
<SectionLabel side="right" count={incomingDicts.length} />
{incomingDicts.length === 0 ? (
<div className="text-cell text-mute/70 italic">
{t('hub.noIncoming', { defaultValue: 'никто не ссылается' })}
</div> </div>
) : ( ) : (
<> <div className="space-y-2">
<ul className="flex-1"> {incomingDicts.map((d) => (
{incoming.map((dep) => ( <NeighborCard key={d.id} dict={d} side="right" />
<li ))}
key={`${dep.sourceDict}.${dep.sourceField}`} </div>
className="border-b border-line-2 last:border-b-0"
>
<Link
to="/dictionaries/$name"
params={{ name: dep.sourceDict }}
className="flex items-center gap-3 px-4 py-2.5 hover:bg-surface-2/50 transition-colors"
>
<span className="text-mono text-body text-accent font-medium truncate flex-1 min-w-0">
{dep.sourceDict}
</span>
{dep.activeRecordsInSourceDict > 0 && (
<span className="text-mono text-cell text-mute tabular-nums shrink-0">
{dep.activeRecordsInSourceDict}
</span>
)}
{dep.onClose === 'BLOCK' && (
<span className="text-cap font-semibold tracking-wider px-1.5 py-0.5 rounded-sm bg-pink-bg text-pink shrink-0">
{t('hub.critical', { defaultValue: 'критично' })}
</span>
)}
{dep.onClose === 'CASCADE' && (
<span className="text-cap font-semibold tracking-wider px-1.5 py-0.5 rounded-sm bg-warn-bg text-warn shrink-0">
CASCADE
</span>
)}
<span className="text-mono text-cell text-ink-2 shrink-0 min-w-[80px] text-right">
.{dep.sourceField}
</span>
</Link>
</li>
))}
</ul>
{/* Footer warning если в this dict много incoming refs — удаление
* записи будет сложным (cascade chain или blockers). */}
{totalIncomingDeps > HEAVY_THRESHOLD && (
<div className="px-4 py-2.5 border-t border-line-2 bg-warn-bg/30 text-cell text-ink-2">
{t('hub.heavyDeps', {
count: totalIncomingDeps,
defaultValue: `Удаление записи в этом справочнике сложно — ${totalIncomingDeps} ссылок`,
})}
</div>
)}
</>
)} )}
</section> </div>
</div> </section>
) )
} }
@@ -577,6 +577,21 @@ function DictionaryDetail() {
const totalRecords = recordsResult.data?.length ?? 0 const totalRecords = recordsResult.data?.length ?? 0
const scope = detailQuery.data?.scope const scope = detailQuery.data?.scope
// Geo capability detection — для скрытия AOI button на non-geo dicts.
// Эвристика по schema properties: property name matches geom/location/
// bbox/polygon/coordinates, OR format=geojson. Не идеально (false negatives
// если backend хранит geometry separately в записи без schema mention),
// но в practice все geo-dicts имеют geometry property в schemaJson.
const hasGeoRecords = useMemo(() => {
const props = detailQuery.data?.schemaJson?.properties
if (!props) return false
for (const [key, p] of Object.entries(props)) {
if (/geom|location|bbox|polygon|coordinates|geo/i.test(key)) return true
if (p.format === 'geojson' || p.format === 'wkt') return true
}
return false
}, [detailQuery.data?.schemaJson])
return ( return (
<div className="space-y-6"> <div className="space-y-6">
{scope && ( {scope && (
@@ -601,7 +616,11 @@ function DictionaryDetail() {
actions={{ actions={{
onTimeTravel: () => setTimeTravelOpen((v) => !v), onTimeTravel: () => setTimeTravelOpen((v) => !v),
timeTravelActive: Boolean(timeTravelAt), timeTravelActive: Boolean(timeTravelAt),
onAoi: () => setAoiOpen(true), // AOI button показываем только если у этого dict есть geo data —
// хотя бы одна record имеет geometryWkt. На non-geo dicts кнопка
// лишняя. Per user feedback: "aoi там где нет полей гео лишний".
// Edge case: если active aoi уже set → показываем чтобы юзер мог clear.
onAoi: hasGeoRecords || aoi ? () => setAoiOpen(true) : undefined,
aoiActive: Boolean(aoi), aoiActive: Boolean(aoi),
// Открываем ExportModal вместо immediate triggera — пользователь // Открываем ExportModal вместо immediate triggera — пользователь
// выбирает формат/scope/columns/encoding/delimiter. // выбирает формат/scope/columns/encoding/delimiter.