fix(ui): сохранять фильтры серверов в адресе страницы
This commit is contained in:
1 parent
b64e6834a9
commit
dfb993e1a3
7 files changed
+256
-10
No files matched your search
@@ -0,0 +1,47 @@
|
||||
"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 }) },
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user