const CUSTOM_PAGE_SIZE_STORAGE_KEY = "cowa:custom-records-per-page-options:v1" function normalizePageSizeOptions(values: number[]) { return Array.from( new Set(values.filter((value) => Number.isInteger(value) && value > 0)) ).sort((a, b) => a - b) } function normalizeCustomPageSizeCache(value: unknown) { if (!Array.isArray(value)) return [] return normalizePageSizeOptions(value.map((item) => Number(item))) } export function resolvePageSizeWithinOptions( pageSize: number | undefined, availableOptions: number[], fallbackPageSize: number ) { const normalizedOptions = normalizePageSizeOptions(availableOptions) if ( typeof pageSize === "number" && Number.isInteger(pageSize) && pageSize > 0 && normalizedOptions.includes(pageSize) ) { return pageSize } if ( Number.isInteger(fallbackPageSize) && fallbackPageSize > 0 && normalizedOptions.includes(fallbackPageSize) ) { return fallbackPageSize } return normalizedOptions[0] ?? fallbackPageSize } export function getPersistedPageSizeOptions(defaultOptions: number[]) { const normalizedDefaultOptions = normalizePageSizeOptions(defaultOptions) if (typeof window === "undefined") { return normalizedDefaultOptions } try { const rawValue = window.localStorage.getItem(CUSTOM_PAGE_SIZE_STORAGE_KEY) if (!rawValue) { return normalizedDefaultOptions } const parsedValue = JSON.parse(rawValue) as | { state?: { customPageSizeCache?: unknown } } | number[] | null const customPageSizeCache = Array.isArray(parsedValue) ? normalizeCustomPageSizeCache(parsedValue) : normalizeCustomPageSizeCache(parsedValue?.state?.customPageSizeCache) return normalizePageSizeOptions([ ...normalizedDefaultOptions, ...customPageSizeCache, ]) } catch { return normalizedDefaultOptions } }