parent
198e2400e7
commit
8ae2785aaa
@ -0,0 +1,65 @@
|
|||||||
|
/** Persist list pagination across detail → back navigation. */
|
||||||
|
|
||||||
|
export function parsePositiveInt(v: unknown, fallback: number): number {
|
||||||
|
const n = typeof v === 'string' ? Number(v) : typeof v === 'number' ? v : NaN
|
||||||
|
return Number.isInteger(n) && n > 0 ? n : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ListPageState = {
|
||||||
|
page: number
|
||||||
|
perPage: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listPageStateKey(scope: string, slug: string): string {
|
||||||
|
return `cxxfds.list.${scope}.${slug}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveListPageState(key: string, state: ListPageState): void {
|
||||||
|
if (!key || typeof sessionStorage === 'undefined') return
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(key, JSON.stringify({ page: state.page, perPage: state.perPage }))
|
||||||
|
} catch {
|
||||||
|
/* ignore quota / private mode */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadListPageState(key: string): ListPageState | null {
|
||||||
|
if (!key || typeof sessionStorage === 'undefined') return null
|
||||||
|
try {
|
||||||
|
const raw = sessionStorage.getItem(key)
|
||||||
|
if (!raw) return null
|
||||||
|
const o = JSON.parse(raw) as { page?: unknown; perPage?: unknown }
|
||||||
|
return {
|
||||||
|
page: parsePositiveInt(o.page, 1),
|
||||||
|
perPage: parsePositiveInt(o.perPage, 15),
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listPageStateToQuery(
|
||||||
|
state: ListPageState,
|
||||||
|
defaultPerPage = 15,
|
||||||
|
): Record<string, string> {
|
||||||
|
const q: Record<string, string> = {}
|
||||||
|
if (state.page > 1) q.page = String(state.page)
|
||||||
|
if (state.perPage !== defaultPerPage) q.per_page = String(state.perPage)
|
||||||
|
return q
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Prefer URL query, then sessionStorage, then defaults. */
|
||||||
|
export function resolveListPageState(
|
||||||
|
key: string,
|
||||||
|
query: Record<string, unknown> | { page?: unknown; per_page?: unknown },
|
||||||
|
defaults: ListPageState = { page: 1, perPage: 15 },
|
||||||
|
): ListPageState {
|
||||||
|
const qPage = parsePositiveInt(query.page, 0)
|
||||||
|
const qPer = parsePositiveInt(query.per_page, 0)
|
||||||
|
if (qPage > 0) {
|
||||||
|
return { page: qPage, perPage: qPer > 0 ? qPer : defaults.perPage }
|
||||||
|
}
|
||||||
|
const stored = loadListPageState(key)
|
||||||
|
if (stored) return stored
|
||||||
|
return { ...defaults }
|
||||||
|
}
|
||||||
Loading…
Reference in new issue