import { useEffect, useMemo, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from 'react'
import { ArrowLeft, ListChecks, X } from 'lucide-react'
import clsx from 'clsx'
import { StatusBadge, isComposing } from '../components/ui'
import {
EVIDENCE_STATE, docForeign, graphDoc, integrityFailures, locatable, reasonOf, sealVerdict, segmentState, sourceOf,
type SealStatus,
} from '../lib/evidence'
import { formatNumber, NONE, shortId } from '../lib/format'
import { EVIDENCE_TEXT } from '../lib/terms'
import { segmentKey, useEvidence } from '../store/evidence'
import type {
EvidenceDocData, EvidenceInput, EvidenceSeal, EvidenceSegment, EvidenceStep, EvidenceUnit, EvidenceViolation,
} from '../types'
/**
* 证据面板:点开报告里的一个片段,看它从哪来。
*
* 本期(数字层)展示:片段和它所在的句子;指标步骤——名称、值、口径与版本、原式、
* 代入式(每个输入是「值 ← 路径」的小标签)、复算结果;封存状态。没有证据的片段说清
* 为什么(裸数字、引用解析不了),另有一份违规清单:列表序号、代码块标签里的数字
* 在正文里画不了线,只能在清单里找到。
*
* 数据两层来源:文档自己记着的出处(doc.catalog,打开就有),和证据接口的证据链
* (原式、代入式、输入、封存,点开才取)。接口取不到(老后端、没有运行 id 的预览)
* 就只显示第一层,并照实说缺了什么。
*
* 只信封存链:正文是按成果上的 _evidence.doc_artifact 取的(成果可以改写、工件表可以
* 事后插行),接口是从封存范围内的事件找的文档。两边不是同一份时,接口的封存状态和
* 证据链说的是另一份报告——不能挂到正文上画成绿的,要醒目地说正文不是封存的那一份。
*
* 三种摆法:side 从右侧弹出(宽屏),drawer 从底部抽出(窄屏),inline 在 360px 的
* 画布右栏里直接栏内展开。都不是模态的:开着面板照样能在正文里走。
*/
export type PanelMode = 'side' | 'drawer' | 'inline'
export type PanelView = { kind: 'seg'; id: string } | { kind: 'violations' }
export function EvidencePanel({ id, mode, doc, artifact, runId, view, onClose, onLocate, onViolations }: {
id: string
mode: PanelMode
doc: EvidenceDocData
/** 正文这份文档的工件 id:和证据接口报的封存文档比对,不是同一份就不信接口给的链 */
artifact?: string
runId?: string
view: PanelView
onClose: () => void
/** 跳到正文里的某个片段(违规清单里的「定位」) */
onLocate: (segId: string) => void
onViolations: () => void
}) {
const titleId = `${id}-title`
const found = useMemo(() => (view.kind === 'seg' ? findSeg(doc, view.id) : null), [doc, view])
const state = found ? segmentState(found.seg) : null
const meta = state ? EVIDENCE_STATE[state] : null
const onKeyDown = (e: ReactKeyboardEvent) => {
if (e.key !== 'Escape' || isComposing(e) || e.defaultPrevented) return
e.preventDefault()
// 画布上在 window 上听 Esc 的(收起检查器之类)不该跟着动
e.stopPropagation()
onClose()
}
const title = view.kind === 'violations' ? EVIDENCE_TEXT.violations : found?.seg.text ?? EVIDENCE_TEXT.panelTitle
const frame = mode === 'side'
? 'ev-panel-side fixed bottom-0 right-0 top-0 z-40 flex flex-col border-l bg-panel shadow-elev-3'
: mode === 'drawer'
? 'ev-panel-rise fixed bottom-0 left-0 right-0 z-40 flex flex-col rounded-t-lg border-t bg-panel shadow-elev-3'
: 'ev-panel-rise my-2 flex flex-col rounded-lg border bg-panel'
return (
{mode === 'inline' && (
)}
{meta && (
{meta.glyph && {meta.glyph}}{meta.label}
)}
{title}
{mode !== 'inline' && (
)}
{view.kind === 'violations'
?
: found
?
:
{NONE}
}
)
}
function findSeg(doc: EvidenceDocData, id: string): { seg: EvidenceSegment; unit: EvidenceUnit } | null {
for (const block of doc.blocks ?? []) {
for (const unit of block.units ?? []) {
const seg = (unit.segments ?? []).find((s) => s.id === id)
if (seg) return { seg, unit }
}
}
return null
}
/** 面板里的一节:小标题 + 内容 */
function Part({ title, children, ...rest }: { title: string; children: ReactNode } & Record<`data-${string}`, string>) {
return (
)
}
/** 值怎么写:数带千分位、不丢小数;拿不到写「—」 */
function valueText(v: unknown): string {
if (v == null || v === '') return NONE
if (typeof v === 'number') return Number.isFinite(v) ? v.toLocaleString('en-US', { maximumFractionDigits: 20 }) : String(v)
if (typeof v === 'boolean') return v ? '是' : '否'
if (typeof v === 'object') return JSON.stringify(v)
return String(v)
}
function SegmentBody({ doc, artifact, runId, seg, unit, onViolations }: {
doc: EvidenceDocData; artifact?: string; runId?: string; seg: EvidenceSegment; unit: EvidenceUnit
onViolations: () => void
}) {
const report = doc.node_id || undefined
const key = runId ? segmentKey(runId, seg.id, report) : ''
const slot = useEvidence((s) => (key ? s.segments[key] : undefined))
const graph = useEvidence((s) => (runId ? s.graphs[runId] : undefined))
const loadSegment = useEvidence((s) => s.loadSegment)
const loadGraph = useEvidence((s) => s.loadGraph)
useEffect(() => {
if (runId) void loadSegment(runId, seg.id, report)
}, [runId, seg.id, report, loadSegment])
const answered = slot?.status === 'ok' ? slot.data : undefined
// 接口答的是另一份报告(封存的那份不是正文这份):它的链和封存状态一概不用
const foreign = docForeign(answered, { artifact, node: report, seg })
const detail = foreign ? undefined : answered
// 片段接口没给封存状态(或者取不到)时,退回整次运行的证据图
const needGraph = !!runId && !foreign && (slot?.status === 'error' || (slot?.status === 'ok' && !answered?.seal))
useEffect(() => {
if (needGraph && runId) void loadGraph(runId)
}, [needGraph, runId, loadGraph])
const graphData = needGraph && graph?.status === 'ok' ? graph.data : undefined
// 证据图兜底时也得先认出正文这份文档在不在封存的报告里
const inGraph = graphDoc(graphData, artifact)
const docIssue: 'foreign' | 'tampered' | null = foreign || inGraph === 'foreign' ? 'foreign'
: inGraph === 'tampered' ? 'tampered' : null
const state = segmentState(seg)
const cite = seg.cite
const entry = cite?.alias ? doc.catalog?.[cite.alias] : undefined
const chain: EvidenceStep[] = Array.isArray(detail?.chain) ? detail.chain : []
const metricStep = chain.find((s) => s.step === 'metric')
const inputStep = chain.find((s) => s.step === 'run_input')
const isMetric = cite?.kind === 'metric' || entry?.kind === 'metric' || !!metricStep
const isInput = cite?.kind === 'input' || entry?.kind === 'input' || !!inputStep
const violations = (doc.violations ?? []).filter((v) => v.segment === seg.id)
const seal: EvidenceSeal | undefined = docIssue ? undefined : detail?.seal ?? graphData?.seal
const reason = reasonOf(seg) || detail?.note || ''
const verdict = sealVerdict(seal, {
foreign: !!docIssue,
pending: !!runId && !seal && (slot?.status === 'loading' || graph?.status === 'loading'),
noRun: !runId,
docOnly: state !== 'deterministic',
viaGraph: slot?.status === 'error',
})
const chainFailed = !runId ? EVIDENCE_TEXT.noRun
: docIssue ? EVIDENCE_TEXT.chainForeign
: slot?.status === 'error' ? EVIDENCE_TEXT.chainMissing : ''
return (
<>
{docIssue && (
// 正文不是封存的那一份:比「有出处」三个字重要得多,放在最前面
)}
{state === 'none' && (
{reason}
{/* 违规的原话多半是「引用 … 解析不了:<原因>」,和上面那句重复的不再列;裸数字那条说的是怎么改,留着 */}
{violations.filter((v) => v.message && !(reason && v.message.includes(reason))).map((v, i) => (
{v.message}
))}
{seg.ref && [[{seg.ref}]]
}
)}
{isMetric && (
)}
{isInput && !isMetric && (
{inputStep?.field ?? entry?.locator?.field ?? cite?.locator?.field ?? cite?.ref} ={' '}
{valueText(inputStep?.value ?? entry?.value ?? cite?.value)}
)}
{state === 'deterministic' && !isMetric && !isInput && (
{sourceOf(seg, doc) || detail?.note}
)}
{!!doc.violations?.length && (
)}
>
)
}
/** 所在的句子:点开的那一段描底,句子里的数字加粗 */
function Sentence({ unit, active }: { unit: EvidenceUnit; active: string }) {
return (
{(unit.segments ?? []).filter((s) => s.kind !== 'structural').map((s) => {
const state = segmentState(s)
const on = s.id === active
const number = s.kind === 'number' || s.kind === 'value'
return (
{s.text}
)
})}
)
}
/** 指标步骤:名称、值、口径与版本、原式、代入式(输入标签)、复算 */
function MetricPart({ step, entry, chain, runId, seal, pending, failed, resolved }: {
step?: EvidenceStep
entry?: Record
chain: EvidenceStep[]
runId?: string
/** 封存状态:逐项复核里「在不在封存范围内」只在封存完好时单独报 */
seal?: EvidenceSeal
pending: boolean
/** 证据链为什么没有:没有运行 id、接口取不到、接口答的是另一份报告 */
failed: string
/** 片段的引用解析成功了(有出处);解析不了的也画这一节,好说清缺的是哪个指标 */
resolved: boolean
}) {
const name = step?.name ?? entry?.name ?? step?.metric ?? entry?.locator?.metric ?? NONE
const value = step?.value !== undefined ? step.value : entry?.value
const rendered = step?.rendered ?? entry?.rendered
const caliber = step?.caliber ?? entry?.caliber
const version = step?.version ?? entry?.version
const artifact = step?.artifact ?? entry?.artifact
const inputs: EvidenceInput[] = step?.inputs?.length
? step.inputs
: chain.filter((s) => s.step === 'input').map((s) => s as EvidenceInput)
// 口径卡里 rendered 为「—」有两种:value 为 null 是缺输入,不为 null 是有值但按格式显示不出来
const dash = rendered === NONE || entry?.rendered === NONE
const missing = entry?.status === 'missing_input' || (value == null && (dash || !resolved))
const unshowable = !missing && dash && value != null
return (
{name}
{resolved && rendered && {rendered}}
{(caliber || version || artifact) && (
{(caliber || version) && 口径卡「{caliber || NONE}」{version}}
{artifact && 工件 {shortId(artifact)}}
)}
{missing && {EVIDENCE_TEXT.missingValue}
}
{unshowable && (
{EVIDENCE_TEXT.unshowable(valueText(value))}
)}
{step ? (
- {EVIDENCE_TEXT.expression}
{step.expression || NONE}
- {EVIDENCE_TEXT.substituted}
-
{step.substituted || NONE}
{!!inputs.length && (
{inputs.map((inp, i) => )}
)}
- {EVIDENCE_TEXT.recompute}
-
{step.recompute_ok == null ? EVIDENCE_TEXT.recomputeNone
: step.recompute_ok ? EVIDENCE_TEXT.recomputeOk : EVIDENCE_TEXT.recomputeBad}
) : resolved && (
{pending ? EVIDENCE_TEXT.chainPending : failed || (runId ? EVIDENCE_TEXT.chainMissing : EVIDENCE_TEXT.noRun)}
)}
)
}
/**
* 证据接口逐项复核的结果:eid 能重算、工件哈希复验、重新渲染一致、在封存范围内。
* 全过的时候不说(正常态安静);哪一项明确没过就用失败色写出来——这时候这件证据
* 不能信,比「有出处」三个字重要得多。「不在封存范围内」只在封存完好时报:没封存、
* 封存核对失败时后端把每一步都记成 sealed=false,那由封存那一行说,不能说成「事后补进来的」
*/
function Integrity({ step, seal }: { step?: EvidenceStep; seal?: EvidenceSeal }) {
const bad = integrityFailures(step, seal)
if (!bad.length) return null
return EVIDENCE_TEXT.integrity[k])} />
}
function IntegrityList({ code, items }: { code: string; items: string[] }) {
return (
)
}
/** 「45,678.5 ← vars.kpi.gmv」:值从哪条路径取的。缺的写「—」、标成提醒色 */
function InputChip({ input }: { input: EvidenceInput }) {
const missing = input.status === 'missing' || input.value == null
const from = [input.node_id && `来自节点 ${input.node_id}`, input.via && `(${input.via})`, input.role && ` · ${input.role}`]
.filter(Boolean).join('')
return (
{valueText(input.value)} ← {input.path ?? NONE}{missing ? '(缺)' : ''}
)
}
/**
* 封存状态:StatusBadge 的剪影 + 一句话。说什么由 lib/evidence 的 sealVerdict 定(顺序、
* 正文不是封存那份时的失败态都在那里);没有证据的片段封存的只是报告文档本身,
* 不能说成「这个数已封存」
*/
function SealLine({ status, label }: { status: SealStatus; label: string }) {
return (
{label}
)
}
const CODE_LABEL: Record = {
uncited_number: '裸数字',
unresolved_ref: '引用解析不了',
}
/** 违规清单:报告撰写节点核对出来的全部问题,画得出线的能定位,画不出的说清在哪 */
function ViolationList({ doc, onLocate }: { doc: EvidenceDocData; onLocate: (segId: string) => void }) {
const list: EvidenceViolation[] = doc.violations ?? []
if (!list.length) return {EVIDENCE_TEXT.allCited(docNumbers(doc))}
return (
<>
{EVIDENCE_TEXT.violationsHint}
>
)
}
const docNumbers = (doc: EvidenceDocData): number => doc.stats?.numbers ?? 0