import { useMemo, useState } from 'react' import { ApiError, declareParam, type ParamDeclaration } from '../lib/api' import { CollapseToggle, PopOutButton, sectionHeaderClassName, sectionHeaderLeftClassName, useSectionCollapsed } from './CollapsibleSection' import { HelpIcon } from './HelpIcon' const EMPTY_KIND: ParamDeclaration['kind'] = 'string' type ExtractionSource = 'regex' | 'json_field' /// A JSON *object* (not an array/scalar) parses cleanly and pretty-prints with braces — the same /// shape a JSON field path can be read from, so this is the "line looks like JSON" gate that /// unlocks the "JSON field" extraction option. function looksLikeJsonObject(text: string): boolean { const trimmed = text.trim() if (!trimmed.startsWith('{')) return false try { const parsed = JSON.parse(trimmed) return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) } catch { return false } } export function Params({ params, onDeclared }: { params: ParamDeclaration[]; onDeclared: () => void }) { const [name, setName] = useState('') const [regex, setRegex] = useState('') const [captureGroup, setCaptureGroup] = useState('') const [jsonFieldPath, setJsonFieldPath] = useState('') const [source, setSource] = useState('regex') const [kind, setKind] = useState(EMPTY_KIND) const [submitError, setSubmitError] = useState(null) const [submitting, setSubmitting] = useState(false) const [collapsed, setCollapsed] = useSectionCollapsed('params') // The message match regex doubles as a sample line here so a pasted JSON log line unlocks the // "JSON field" extraction option — regex-based params are unaffected either way. const detectedJson = useMemo(() => looksLikeJsonObject(regex), [regex]) const effectiveSource: ExtractionSource = detectedJson ? source : 'regex' async function handleSubmit(e: React.FormEvent) { e.preventDefault() setSubmitError(null) setSubmitting(true) try { await declareParam({ name, message_match_regex: regex, capture_group: effectiveSource === 'json_field' ? '' : captureGroup, json_field_path: effectiveSource === 'json_field' ? jsonFieldPath : null, kind, }) setName('') setRegex('') setCaptureGroup('') setJsonFieldPath('') setSource('regex') setKind(EMPTY_KIND) onDeclared() } catch (err) { setSubmitError(err instanceof ApiError ? err.message : 'Failed to declare param') } finally { setSubmitting(false) } } return (
Params
setCollapsed(!collapsed)} />
) }