[as] feat: 행정지원 페이지 useSearchParamsState 적용
This commit is contained in:
@@ -1,10 +1,12 @@
|
||||
export { getCookie, removeCookie, setCookie } from "./cookie";
|
||||
export { dayjs } from "./dayjs";
|
||||
export { getListHref, withListQs } from "./list-return-href";
|
||||
export { matchQueryStatus } from "./match-query-status";
|
||||
export { queryClient } from "./query-client";
|
||||
export { useAlertStore } from "./use-alert-store";
|
||||
export { useDataTable } from "./use-data-table";
|
||||
export { useMenuStore } from "./use-menu-store";
|
||||
export { useMutationWrapper } from "./use-mutation-wrapper";
|
||||
export { useSearchParamsState } from "./use-search-params-state";
|
||||
export { getDefaultFileKey, useTus } from "./use-tus";
|
||||
export { useUserStore } from "./use-user-store";
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* 목록 조회 조건을 sessionStorage에 저장하고, 목록 복귀 시 복원하기 위한 헬퍼.
|
||||
*
|
||||
* - 목록 → 상세: 현재 목록 쿼리를 `list-qs-{listPath}` 키로 저장
|
||||
* - 상세 → 수정·저장 후 이동: storage를 건드리지 않음 (같은 탭에서 유지)
|
||||
* - 목록/삭제 후 이동: storage에서 읽어 `/listPath?bizNm=...` 로 복원
|
||||
*/
|
||||
|
||||
function toListSlug(listPath: string) {
|
||||
return listPath.replace(/^\/+|\/+$/g, "").replaceAll("/", "-");
|
||||
}
|
||||
|
||||
function storageKey(listPath: string) {
|
||||
return `list-qs-${toListSlug(listPath)}`;
|
||||
}
|
||||
|
||||
/** 상세/수정 href에서 목록 slug를 추출한다. */
|
||||
function inferListPath(href: string) {
|
||||
const path = href.split("?")[0] ?? "";
|
||||
const segments = path.split("/").filter(Boolean);
|
||||
return segments[0] ?? "";
|
||||
}
|
||||
|
||||
function isOnListPage(slug: string) {
|
||||
if (typeof window === "undefined" || !slug) return false;
|
||||
const { pathname } = window.location;
|
||||
return pathname === `/${slug}` || pathname === `/${slug}/`;
|
||||
}
|
||||
|
||||
/** 목록에 있을 때 현재 쿼리를 저장하고, href는 그대로 반환한다. */
|
||||
export function withListQs(href: string) {
|
||||
if (typeof window === "undefined") return href;
|
||||
|
||||
const slug = inferListPath(href);
|
||||
if (!isOnListPage(slug)) return href;
|
||||
|
||||
const search = window.location.search.replace(/^\?/, "");
|
||||
if (search) sessionStorage.setItem(storageKey(slug), search);
|
||||
else sessionStorage.removeItem(storageKey(slug));
|
||||
|
||||
return href;
|
||||
}
|
||||
|
||||
/** sessionStorage에 저장된 목록 쿼리로 href를 만든다. */
|
||||
export function getListHref(listPath: string) {
|
||||
if (typeof window === "undefined") return listPath;
|
||||
|
||||
const listQs = sessionStorage.getItem(storageKey(listPath));
|
||||
return listQs ? `${listPath}?${listQs}` : listPath;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo, useRef } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
|
||||
/**
|
||||
* 조회 조건을 URL searchParams와 동기화하는 훅.
|
||||
*
|
||||
* - URL이 단일 소스 오브 트루스(SSOT)이며, 새로고침·뒤로가기 시에도 조건이 유지된다.
|
||||
* - 기본값과 동일한 값은 URL에서 제거해 쿼리스트링을 깨끗하게 유지한다.
|
||||
* - `window.history.replaceState` 기반 shallow 갱신으로 서버 라운드트립 없이 동작한다.
|
||||
* - 숫자 기본값이 주어진 키는 자동으로 `Number` 파싱한다.
|
||||
*
|
||||
* @example
|
||||
* const { params, setParams, resetParams } = useSearchParamsState({
|
||||
* keyword: "",
|
||||
* page: 0,
|
||||
* size: 10,
|
||||
* });
|
||||
*/
|
||||
export function useSearchParamsState<T extends Record<string, ParamValue>>(
|
||||
defaults: T,
|
||||
): UseSearchParamsStateReturn<T> {
|
||||
const searchParams = useSearchParams();
|
||||
const defaultsRef = useRef(defaults);
|
||||
|
||||
const params = useMemo(
|
||||
() => parseParams(searchParams, defaultsRef.current),
|
||||
[searchParams],
|
||||
);
|
||||
|
||||
const setParams = useCallback((partial: Partial<T>) => {
|
||||
const next = new URLSearchParams(window.location.search);
|
||||
for (const [key, value] of Object.entries(partial)) {
|
||||
if (value === undefined || value === defaultsRef.current[key]) {
|
||||
next.delete(key);
|
||||
} else {
|
||||
next.set(key, String(value));
|
||||
}
|
||||
}
|
||||
replaceUrl(next);
|
||||
}, []);
|
||||
|
||||
const resetParams = useCallback(() => {
|
||||
const next = new URLSearchParams(window.location.search);
|
||||
for (const key of Object.keys(defaultsRef.current)) {
|
||||
next.delete(key);
|
||||
}
|
||||
replaceUrl(next);
|
||||
}, []);
|
||||
|
||||
return { params, setParams, resetParams };
|
||||
}
|
||||
|
||||
function parseParams<T extends Record<string, ParamValue>>(
|
||||
searchParams: ReturnType<typeof useSearchParams>,
|
||||
defaults: T,
|
||||
): T {
|
||||
const result = { ...defaults };
|
||||
|
||||
for (const key of Object.keys(defaults) as (keyof T)[]) {
|
||||
const raw = searchParams?.get(key as string) ?? null;
|
||||
if (raw === null) continue;
|
||||
|
||||
if (typeof defaults[key] === "number") {
|
||||
const parsed = Number(raw);
|
||||
if (!Number.isNaN(parsed)) result[key] = parsed as T[keyof T];
|
||||
} else {
|
||||
result[key] = raw as T[keyof T];
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function replaceUrl(searchParams: URLSearchParams) {
|
||||
const qs = searchParams.toString();
|
||||
const url = qs
|
||||
? `${window.location.pathname}?${qs}`
|
||||
: window.location.pathname;
|
||||
window.history.replaceState(null, "", url);
|
||||
}
|
||||
|
||||
type ParamValue = string | number | null;
|
||||
|
||||
interface UseSearchParamsStateReturn<T> {
|
||||
params: T;
|
||||
setParams: (partial: Partial<T>) => void;
|
||||
resetParams: () => void;
|
||||
}
|
||||
Reference in New Issue
Block a user