34 lines
1.8 KiB
TypeScript
34 lines
1.8 KiB
TypeScript
"use client"
|
|
|
|
import { useMemo } from "react"
|
|
import { useSearchParams } from "next/navigation"
|
|
import { readUptimeUrl, patchUptimeUrl, type UptimeTab, type ProbeStatusFilter, type UrlSetter } from "@/lib/data-filters/uptime-url-state"
|
|
|
|
export function useUptimeUrlState() {
|
|
const raw = useSearchParams().toString()
|
|
const state = useMemo(() => readUptimeUrl(new URLSearchParams(raw)), [raw])
|
|
function write(changes: Record<string, string | null>, replace = false) {
|
|
const href = patchUptimeUrl(new URLSearchParams(window.location.search), changes) + window.location.hash
|
|
if (href === window.location.pathname + window.location.search + window.location.hash) return
|
|
if (replace) window.history.replaceState(null, "", href)
|
|
else window.history.pushState(null, "", href)
|
|
}
|
|
const setStatusFilter: UrlSetter<ProbeStatusFilter> = value => {
|
|
const current = readUptimeUrl(new URLSearchParams(window.location.search)).status
|
|
const next = typeof value === "function" ? value(current) : value
|
|
write({ status: next === "all" ? null : next })
|
|
}
|
|
const setServerFilter: UrlSetter<string[]> = value => {
|
|
const current = readUptimeUrl(new URLSearchParams(window.location.search)).servers
|
|
const next = typeof value === "function" ? value(current) : value
|
|
write({ servers: next.length ? JSON.stringify(next) : null })
|
|
}
|
|
return {
|
|
tab: state.tab, search: state.search, statusFilter: state.status, serverFilter: state.servers, error: state.error,
|
|
setTab: (tab: UptimeTab) => write({ tab: tab === "probes" ? null : tab }),
|
|
setSearch: (q: string) => write({ q }, true), setStatusFilter, setServerFilter,
|
|
resetFilters: () => write({ q: null, status: null, servers: null }),
|
|
resetUrl: () => write({ tab: null, q: null, status: null, servers: null }),
|
|
}
|
|
}
|