import { useEffect, useId, useState } from 'react' import CountsFieldTree from '@/components/counts/CountsFieldTree' import DateTimeField from '@/components/common/DateTimeField' import FormField from '@/components/common/FormField' import { Button } from '@/components/ui/button' import { isCountsState, normaliseCountsParams } from '@/lib/counts' import { countsSummaryFields } from '@/lib/countsState' import { fetchTagByName } from '@/lib/tags' import { inputClass } from '@/lib/utils' import { useLocale } from '@/lib/useLocale' import { useUITranslation } from '@/lib/useUITranslation' import type { ReactNode } from 'react' import type { CountsResource } from '@/lib/counts' const CountsControls = ( { resource, applied, open, setOpen, execute, displayJSON, reorder, actions }: { resource: CountsResource applied: URLSearchParams open: boolean setOpen: (open: boolean) => void execute: (params: URLSearchParams) => void displayJSON: (enabled: boolean) => void reorder: (value: string) => void actions?: ReactNode }, ) => { const { label, message } = useUITranslation ('counts') const locale = useLocale () const id = useId () const [draft, setDraft] = useState (() => new URLSearchParams (applied)) const order = applied.get ('order') const nestedJSON = applied.get ('nested_json') useEffect (() => { setDraft (previous => { const next = new URLSearchParams (previous) for (const [key, value] of Object.entries ({ order, nested_json: nestedJSON })) { if (value == null) next.delete (key) else next.set (key, value) } return next }) }, [order, nestedJSON]) const [error, setError] = useState (false) const [pending, setPending] = useState (false) const mode = draft.get ('mode') ?? 'summary' const state = isCountsState (draft) const axes = (state && resource === 'posts') ? ['tags', 'month', 'user'] : ['month', 'user'] const update = (key: string, value: string) => { setDraft (previous => { const next = new URLSearchParams (previous) if (['mode', 'axis', 'basis'].includes (key)) next.delete ('sort') if (key === 'axis' || key === 'basis') next.delete ('summary_columns') if (key === 'basis' && value === 'history' && next.get ('axis') === 'tags') next.set ('axis', 'month') if (value || ['columns', 'children', 'summary_columns'].includes (key)) next.set (key, value) else next.delete (key) return next }) } const submit = async () => { setError (false) setPending (true) try { const next = new URLSearchParams (draft) for (const key of resource === 'posts' ? ['tag'] : ['resource_id']) { const value = next.get (key)?.trim () ?? '' if (value && !/^[1-9][0-9]*$/.test (value)) { if (state && next.get ('kind') === 'external') throw new Error () const tag = await fetchTagByName (value, locale) if (tag == null) throw new Error () next.set (key, String (tag.id)) } } next.delete ('page') execute (normaliseCountsParams (resource, next)) } catch { setError (true) } finally { setPending (false) } } return (
) } export default CountsControls