)
}
// The UI for building the query string, which includes two kinds of settings:
// 1. Custom query params defined by the service, stored in
// `this.state.queryParams`
// 2. The standard badge options which apply to all badges, stored in
// `this.state.badgeOptions`
export default function QueryStringBuilder({
exampleParams,
initialStyle = 'flat',
onChange,
}) {
const [queryParams, setQueryParams] = useState(() => {
// For each of the custom query params defined in `exampleParams`,
// create empty values in `queryParams`.
const result = {}
Object.entries(exampleParams).forEach(([name, value]) => {
// Custom query params are either string or boolean. Inspect the example
// value to infer which one, and set empty values accordingly.
// Throughout the component, these two types are supported in the same
// manner: by inspecting this value type.
const isStringParam = typeof value === 'string'
result[name] = isStringParam ? '' : true
})
return result
})
// For each of the standard badge options, create empty values in
// `badgeOptions`. When `initialStyle` has been provided, use it.
const [badgeOptions, setBadgeOptions] = useState(() =>
supportedBadgeOptions.reduce((accum, { name }) => {
if (name === 'style') {
accum[name] = initialStyle
} else {
accum[name] = ''
}
return accum
}, {})
)
function handleServiceQueryParamChange(event) {
const { name, type } = event.target
const value =
type === 'checkbox' ? event.target.checked : event.target.value
setQueryParams({ ...queryParams, [name]: value })
}
function handleBadgeOptionChange(event) {
const { name, value } = event.target
setBadgeOptions({ ...badgeOptions, [name]: value })
}
useEffect(() => {
if (onChange) {
const { queryString, isComplete } = getQueryString({
queryParams,
badgeOptions,
})
onChange({ queryString, isComplete })
}
}, [onChange, queryParams, badgeOptions])
const hasQueryParams = Boolean(Object.keys(queryParams).length)
let stringParamCount = 0
return (
<>
{hasQueryParams && (