import {useState} from 'react'; import {distSummary, label} from './np-batch.ts'; import type {Dist} from './np-batch.ts'; export function DistInput({value, onChange, kind, options = [], disabledOptions = [], unit}: { value: Dist; onChange: (value: Dist) => void; kind: 'number' | 'enum'; options?: string[]; disabledOptions?: string[]; unit?: string; }) { const [json, setJson] = useState(null), [error, setError] = useState(''), [open, setOpen] = useState(false); const summary = {distSummary(value, unit)}; if (kind === 'enum') { const values = typeof value === 'string' ? [value] : typeof value === 'object' && value.dist === 'fixed' ? [value.value] : typeof value === 'object' && value.dist === 'choice' ? value.values : []; const weights = typeof value === 'object' && value.dist === 'choice' ? value.weights : undefined; const commit = (next: (string | number)[], nextWeights: number[]) => {if (next.length) onChange(next.length === 1 ? {dist: 'fixed', value: String(next[0])} : {dist: 'choice', values: next, weights: nextWeights});}; return
{options.map(option => { const index = values.indexOf(option), disabled = disabledOptions.includes(option); return
{index >= 0 && }{disabled && 生成器还不支持}
; })}
{summary}
; } const dist = typeof value === 'object' ? value : {dist: 'fixed' as const, value}; // 数值分布默认只显示一行摘要,点“改”才展开编辑框,避免堆砌文本框 if (!open) return
{distSummary(value, unit)}
; const numeric = (title: string, n: number | string | undefined, change: (n: number | undefined) => void, optional = false) => ; const defaults: Record = {fixed: 1, uniform: {dist: 'uniform', lo: 0, hi: 1}, normal: {dist: 'normal', mean: 1, sd: .2}, lognormal: {dist: 'lognormal', median: 1, sigma: .2}, choice: {dist: 'choice', values: [1, 2]}}; return
{dist.dist === 'fixed' && numeric('数值', dist.value, n => onChange(n ?? 0))} {dist.dist === 'uniform' && <>{numeric('下限', dist.lo, n => onChange({...dist, lo: n ?? 0}))}{numeric('上限', dist.hi, n => onChange({...dist, hi: n ?? 0}))}} {dist.dist === 'normal' && <>{numeric('均值', dist.mean, n => onChange({...dist, mean: n ?? 0}))}{numeric('标准差', dist.sd, n => onChange({...dist, sd: n ?? 0}))}} {dist.dist === 'lognormal' && <>{numeric('中位数', dist.median, n => onChange({...dist, median: n ?? 0}))}{numeric('sigma', dist.sigma, n => onChange({...dist, sigma: n ?? 0}))}} {(dist.dist === 'normal' || dist.dist === 'lognormal') && <>{numeric('下限(可空)', dist.lo, n => onChange({...dist, lo: n}), true)}{numeric('上限(可空)', dist.hi, n => onChange({...dist, hi: n}), true)}} {dist.dist === 'choice' &&
{dist.values.map((v, i) =>
{numeric(`选项 ${i + 1}`, v, n => onChange({...dist, values: dist.values.map((x, j) => i === j ? n ?? 0 : x)}))}{numeric(`权重 ${i + 1}`, dist.weights?.[i] ?? 1, n => onChange({...dist, weights: dist.values.map((_, j) => j === i ? n ?? 0 : dist.weights?.[j] ?? 1)}))}
)}
}
{summary}{dist.dist === 'mixture' &&