Files
MikrotikManager/hooks/use-server-url-state.ts
T

48 lines
2.2 KiB
TypeScript

"use client"
import { useEffect, useMemo, useState } from "react"
import { useSearchParams } from "next/navigation"
import type { FilterQuery } from "@/components/reui/filters/filters-types"
import { encodeServerQuery, patchServerUrl, readServerUrl, validateServerQuery, type ServerTypeFilter } from "@/lib/data-filters/server-url-state"
export function useServerUrlState() {
const params = useSearchParams()
const raw = params.toString()
const state = useMemo(() => readServerUrl(new URLSearchParams(raw)), [raw])
const filterKey = params.get("filters")
const [draft, setDraft] = useState<{ key: string | null; query: FilterQuery; error: string | null } | null>(null)
useEffect(() => {
const reset = () => setDraft(null)
window.addEventListener("popstate", reset)
return () => window.removeEventListener("popstate", reset)
}, [])
function write(changes: Record<string, string | null>, replace = false) {
const href = patchServerUrl(new URLSearchParams(window.location.search), changes)
if (href === window.location.pathname + window.location.search) return
if (replace) window.history.replaceState(null, "", href)
else window.history.pushState(null, "", href)
}
function setFilters(query: FilterQuery) {
if (validateServerQuery(query) === "draft") { setDraft({ key: filterKey, query, error: null }); return }
try {
const encoded = encodeServerQuery(query)
setDraft(null)
write({ filters: encoded })
} catch (error) {
setDraft({ key: filterKey, query, error: error instanceof Error ? error.message : "Некорректный фильтр." })
}
}
const currentDraft = draft?.key === filterKey ? draft : null
return {
search: state.search,
typeFilter: state.type,
filters: currentDraft?.query ?? state.query,
error: state.error ?? currentDraft?.error ?? null,
hasFilters: params.has("q") || params.has("type") || params.has("filters") || currentDraft !== null,
setSearch: (value: string) => write({ q: value }, true),
setTypeFilter: (value: ServerTypeFilter) => write({ type: value === "all" ? null : value }),
setFilters,
reset: () => { setDraft(null); write({ q: null, type: null, filters: null }) },
}
}