import { useEffect, useId, useMemo, useState } from 'react' import type { QAPeriodKind } from './qaPeriodInput' import { periodInputOptions, validPeriodInput } from './qaPeriodInput' import { qaWeek } from './qaWeeks' import './qaPeriodInput.css' export interface QAPeriodInputProps { kind: QAPeriodKind label: string ariaLabel: string value: string max: string onChange: (value: string) => void disabled?: boolean } export function QAPeriodInput(p: QAPeriodInputProps) { const id = useId(), [text, setText] = useState(p.value), [error, setError] = useState('') useEffect(() => { setText(p.value) setError('') }, [p.value, p.kind]) const options = useMemo(() => { const values = periodInputOptions(p.kind, p.max) if (validPeriodInput(p.kind, p.value, p.max) && !values.includes(p.value)) values.push(p.value) return values }, [p.kind, p.max, p.value]) const apply = () => { if (text === p.value) return if (!validPeriodInput(p.kind, text, p.max)) { setError( `请输入有效的${p.kind === 'month' ? 'YYYY-MM月份' : 'YYYY-Www自然周'},最早2000年、不晚于${p.max};仍显示${p.value}的结果` ) return } setError('') p.onChange(text) } return (
{ setText(e.target.value) setError('') }} onBlur={apply} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault() apply() } if (e.key === 'Escape') { setText(p.value) setError('') } }} />
{error || (text !== p.value ? '尚未应用,按回车或移开输入框确认' : p.kind === 'week' ? qaWeek(Number(p.value.slice(0, 4)), Number(p.value.slice(6))).label : '可下拉选择,也可直接输入')}
) }