Files
saas_frontend/src/lib/tablePageSize.ts
T

58 lines
1.5 KiB
TypeScript
Raw Normal View History

export const DEFAULT_TABLE_PAGE_SIZE_OPTIONS = [5, 10, 20, 50] as const;
export const SHARED_ADMIN_TABLE_PAGE_SIZE_STORAGE_KEY =
"admin-table-page-size";
type ResolveTablePageSizeArgs = {
storageKey?: string;
pageSizeOptions?: readonly number[];
defaultPageSize: number;
};
function isValidPageSize(pageSize: number, pageSizeOptions?: readonly number[]) {
if (!Number.isFinite(pageSize) || pageSize <= 0) return false;
if (!pageSizeOptions || pageSizeOptions.length === 0) return true;
return pageSizeOptions.includes(pageSize);
}
export function resolveStoredTablePageSize({
storageKey,
pageSizeOptions,
defaultPageSize,
}: ResolveTablePageSizeArgs) {
if (!isValidPageSize(defaultPageSize, pageSizeOptions)) {
return pageSizeOptions?.[0] ?? 10;
}
if (typeof window === "undefined" || !storageKey) {
return defaultPageSize;
}
try {
const rawValue = window.localStorage.getItem(storageKey);
if (!rawValue) return defaultPageSize;
const parsedValue = Number(rawValue);
return isValidPageSize(parsedValue, pageSizeOptions)
? parsedValue
: defaultPageSize;
} catch {
return defaultPageSize;
}
}
export function persistTablePageSize(
storageKey: string | undefined,
pageSize: number,
pageSizeOptions?: readonly number[]
) {
if (typeof window === "undefined" || !storageKey) return;
if (!isValidPageSize(pageSize, pageSizeOptions)) return;
try {
window.localStorage.setItem(storageKey, String(pageSize));
} catch {
// Ignore storage failures so pagination keeps working normally.
}
}