mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-18 15:33:12 +09:00
Persist table sort/filter state in the URL
Tables such as Hosts, Instances, Users, Roles, etc. now write their sort order, column filters and pagination into the URL query string, so reload, link-sharing and browser back/forward restore the same view (closes #927). Every parameter is namespaced with the table name so the URL is self-describing and two tables can share a page without colliding, e.g. ?user.sort=name&user.name=bob&user.admin=true or ?instance.name=foo. Adds two reusable hooks, exported from @clusterio/web_ui so plugins can use them too: - useTableQueryState: makes an antd Table controlled and round-trips its sort/filter/pagination through the URL via useSearchParams. The pure serialisation helpers live in util/tableQuery.ts and are unit tested. - useColumnSearch: a column-header text-search filter (matching the Users table style), persisted through the same filter mechanism. Applied to Hosts, Roles, Plugins, the instance list (standalone and on the host detail page), Users (main table and the online-players list on the instance detail page), instance saves, the per-instance user stats, the mod packs and stored mods tables, and the subspace_storage storage page. The storage page's resource search moves from a standalone box into the Resource column header, keeping its regex matching. The bundled user filter persists as separate readable params (user.name, user.admin, ...) via a per-column FilterCodec rather than one JSON blob. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
9e727f9a13
commit
49eb594e5b
19 files changed
+639
-78
No files matched your search
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* Pure helpers for storing antd Table state (sort / filters / pagination) in
|
||||
* the URL query string. Kept free of React and antd runtime imports so the
|
||||
* serialisation can be unit tested in isolation.
|
||||
*
|
||||
* Every parameter is namespaced with the table's name so the URL is
|
||||
* self-describing and two tables could coexist on one page without colliding:
|
||||
* <ns>.sort column key the table is sorted by
|
||||
* <ns>.order "ascend" | "descend"
|
||||
* <ns>.page 1-based page number
|
||||
* <ns>.pageSize rows per page
|
||||
* <ns>.<column> filter value for that column (e.g. user.name, user.admin)
|
||||
*
|
||||
* `prefix` below is the namespace with its trailing dot, e.g. "user.".
|
||||
* Multi-value filters use a repeated parameter (`user.roles=1&user.roles=2`)
|
||||
* so URLSearchParams handles all encoding/decoding exactly once.
|
||||
*/
|
||||
|
||||
export type SortOrder = "ascend" | "descend";
|
||||
|
||||
export interface TableSortState {
|
||||
/** Column key the table is sorted by, or undefined for no/default sort. */
|
||||
columnKey?: string;
|
||||
/** Sort direction, or undefined when unsorted. */
|
||||
order?: SortOrder;
|
||||
}
|
||||
|
||||
export interface TablePageState {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
/** A single filter value as produced by antd (React.Key is string | number | bigint). */
|
||||
export type FilterValue = string | number | bigint | boolean;
|
||||
|
||||
/**
|
||||
* Maps a single column's antd filter value to/from one or more query
|
||||
* parameters. Lets a column that bundles several controls (e.g. the user
|
||||
* filter) persist as separate readable params instead of one opaque blob.
|
||||
* `prefix` is the table namespace with its trailing dot, e.g. "user.".
|
||||
*/
|
||||
export interface FilterCodec {
|
||||
/** Read this column's `filteredValue` from the query, or null when inactive. */
|
||||
decode(params: URLSearchParams, prefix: string): string[] | null;
|
||||
/** Write this column's antd filter value into `params` (mutating). */
|
||||
encode(params: URLSearchParams, value: ReadonlyArray<FilterValue> | null, prefix: string): void;
|
||||
}
|
||||
|
||||
/** Suffixes reserved for table-level state; any other `<prefix><x>` is a column filter. */
|
||||
const RESERVED_SUFFIXES = new Set(["sort", "order", "page", "pageSize"]);
|
||||
|
||||
/** Parse an order parameter, returning undefined for anything unexpected. */
|
||||
export function parseOrder(value: string | null): SortOrder | undefined {
|
||||
return value === "ascend" || value === "descend" ? value : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the sort state from the query, falling back to the supplied defaults
|
||||
* when no (valid) sort parameter is present.
|
||||
*/
|
||||
export function parseSort(
|
||||
params: URLSearchParams,
|
||||
prefix: string,
|
||||
defaultKey?: string,
|
||||
defaultOrder: SortOrder = "ascend",
|
||||
): TableSortState {
|
||||
const columnKey = params.get(`${prefix}sort`);
|
||||
if (!columnKey) {
|
||||
return { columnKey: defaultKey, order: defaultKey ? defaultOrder : undefined };
|
||||
}
|
||||
return { columnKey, order: parseOrder(params.get(`${prefix}order`)) ?? defaultOrder };
|
||||
}
|
||||
|
||||
/** Read pagination state from the query, tolerating missing/garbage values. */
|
||||
export function parsePagination(
|
||||
params: URLSearchParams,
|
||||
prefix: string,
|
||||
defaultPageSize: number,
|
||||
defaultPage = 1,
|
||||
): TablePageState {
|
||||
const page = Number.parseInt(params.get(`${prefix}page`) ?? "", 10);
|
||||
const pageSize = Number.parseInt(params.get(`${prefix}pageSize`) ?? "", 10);
|
||||
return {
|
||||
page: Number.isInteger(page) && page >= 1 ? page : defaultPage,
|
||||
pageSize: Number.isInteger(pageSize) && pageSize >= 1 ? pageSize : defaultPageSize,
|
||||
};
|
||||
}
|
||||
|
||||
/** Collect every namespaced column-filter parameter into a map of column key -> values. */
|
||||
export function parseFilters(params: URLSearchParams, prefix: string): Record<string, string[]> {
|
||||
const filters: Record<string, string[]> = {};
|
||||
for (const key of params.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
const column = key.slice(prefix.length);
|
||||
if (!RESERVED_SUFFIXES.has(column) && !(column in filters)) {
|
||||
filters[column] = params.getAll(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
return filters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the sort state into `params` (mutating it). The parameters are omitted
|
||||
* when the sort matches the table default or is cleared, keeping default URLs
|
||||
* clean.
|
||||
*/
|
||||
export function applySort(
|
||||
params: URLSearchParams,
|
||||
prefix: string,
|
||||
sort: TableSortState,
|
||||
defaultKey?: string,
|
||||
defaultOrder: SortOrder = "ascend",
|
||||
): void {
|
||||
const { columnKey, order } = sort;
|
||||
const isDefault = columnKey === defaultKey && (order ?? defaultOrder) === defaultOrder;
|
||||
if (!columnKey || !order || isDefault) {
|
||||
params.delete(`${prefix}sort`);
|
||||
params.delete(`${prefix}order`);
|
||||
return;
|
||||
}
|
||||
params.set(`${prefix}sort`, columnKey);
|
||||
params.set(`${prefix}order`, order);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the filter state into `params` (mutating it). `filters` is the object
|
||||
* antd hands to onChange: every filterable column key mapped to its current
|
||||
* value array, or null when inactive.
|
||||
*/
|
||||
export function applyFilters(
|
||||
params: URLSearchParams,
|
||||
prefix: string,
|
||||
filters: Record<string, ReadonlyArray<FilterValue> | null>,
|
||||
): void {
|
||||
for (const [key, values] of Object.entries(filters)) {
|
||||
const param = prefix + key;
|
||||
params.delete(param);
|
||||
if (values) {
|
||||
for (const value of values) {
|
||||
params.append(param, String(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write pagination into `params` (mutating it). Defaults (page 1 / default
|
||||
* page size) are omitted to keep URLs clean.
|
||||
*/
|
||||
export function applyPagination(
|
||||
params: URLSearchParams,
|
||||
prefix: string,
|
||||
page: number,
|
||||
pageSize: number,
|
||||
defaultPageSize: number,
|
||||
): void {
|
||||
if (page > 1) {
|
||||
params.set(`${prefix}page`, String(page));
|
||||
} else {
|
||||
params.delete(`${prefix}page`);
|
||||
}
|
||||
if (pageSize !== defaultPageSize) {
|
||||
params.set(`${prefix}pageSize`, String(pageSize));
|
||||
} else {
|
||||
params.delete(`${prefix}pageSize`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import type { TablePaginationConfig } from "antd";
|
||||
import type { ColumnType, FilterValue, SorterResult } from "antd/es/table/interface";
|
||||
|
||||
import {
|
||||
applyFilters, applyPagination, applySort,
|
||||
parseFilters, parsePagination, parseSort,
|
||||
type FilterCodec, type SortOrder,
|
||||
} from "./tableQuery";
|
||||
|
||||
export interface TableQueryStateOptions {
|
||||
/** Table name used to namespace every query parameter, e.g. "user" -> `user.sort`, `user.name`. */
|
||||
namespace: string;
|
||||
/** Column key sorted by default (no `sort` param present). Omit for no default sort. */
|
||||
defaultSortKey?: string;
|
||||
/** Direction of the default sort. Default "ascend". */
|
||||
defaultSortOrder?: SortOrder;
|
||||
/** Pass an object to persist pagination; omit/false for `pagination={false}` tables. */
|
||||
pagination?: false | { defaultPageSize?: number };
|
||||
/** Per-column-key codecs to persist a bundled filter value as separate readable params. */
|
||||
filterCodecs?: Record<string, FilterCodec>;
|
||||
}
|
||||
|
||||
export interface TableQueryState<T> {
|
||||
/** Spread onto `<Table onChange={...}>` to persist sort/filter/pagination (pushes history). */
|
||||
onChange: (
|
||||
pagination: TablePaginationConfig,
|
||||
filters: Record<string, FilterValue | null>,
|
||||
sorter: SorterResult<T> | SorterResult<T>[],
|
||||
) => void;
|
||||
/** Wrap each column to inject controlled `sortOrder`/`filteredValue` from the URL. */
|
||||
applyColumn: (column: ColumnType<T>) => ColumnType<T>;
|
||||
/** Controlled pagination ({@link current}/{@link pageSize}), or `false` when disabled. */
|
||||
pagination: false | TablePaginationConfig;
|
||||
/** The active column filters parsed from the URL, keyed by column key. */
|
||||
filters: Record<string, string[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist an antd Table's sort, column filters and pagination into the URL
|
||||
* query string, so reload, link-sharing and browser back/forward restore the
|
||||
* same view (clusterio issue #927).
|
||||
*/
|
||||
export default function useTableQueryState<T>(options: TableQueryStateOptions): TableQueryState<T> {
|
||||
const { defaultSortKey, defaultSortOrder = "ascend" } = options;
|
||||
const prefix = `${options.namespace}.`;
|
||||
const codecs = options.filterCodecs ?? {};
|
||||
const paginationOptions = options.pagination && typeof options.pagination === "object"
|
||||
? options.pagination
|
||||
: undefined;
|
||||
const paginationEnabled = paginationOptions !== undefined;
|
||||
const defaultPageSize = paginationOptions?.defaultPageSize ?? 10;
|
||||
|
||||
const [params, setParams] = useSearchParams();
|
||||
|
||||
const sort = parseSort(params, prefix, defaultSortKey, defaultSortOrder);
|
||||
const filters = parseFilters(params, prefix);
|
||||
const page = paginationEnabled ? parsePagination(params, prefix, defaultPageSize) : undefined;
|
||||
|
||||
return {
|
||||
onChange(pagination, tableFilters, sorter) {
|
||||
const single = Array.isArray(sorter) ? sorter[0] : sorter;
|
||||
const order = single && single.order ? single.order : undefined;
|
||||
const columnKey = order ? String(single.columnKey ?? single.field ?? "") : undefined;
|
||||
|
||||
const next = new URLSearchParams(params);
|
||||
applySort(next, prefix, { columnKey, order }, defaultSortKey, defaultSortOrder);
|
||||
const plainFilters: Record<string, FilterValue | null> = {};
|
||||
for (const [key, values] of Object.entries(tableFilters)) {
|
||||
const codec = codecs[key];
|
||||
if (codec) {
|
||||
codec.encode(next, values, prefix);
|
||||
} else {
|
||||
plainFilters[key] = values;
|
||||
}
|
||||
}
|
||||
applyFilters(next, prefix, plainFilters);
|
||||
if (paginationEnabled) {
|
||||
applyPagination(
|
||||
next, prefix, pagination.current ?? 1, pagination.pageSize ?? defaultPageSize, defaultPageSize
|
||||
);
|
||||
}
|
||||
setParams(next);
|
||||
},
|
||||
|
||||
applyColumn(column) {
|
||||
const key = String(column.key ?? column.dataIndex ?? "");
|
||||
const next: ColumnType<T> = { ...column };
|
||||
if (column.sorter) {
|
||||
next.sortOrder = key === sort.columnKey ? (sort.order ?? null) : null;
|
||||
}
|
||||
if (column.filters || column.onFilter || column.filterDropdown) {
|
||||
const codec = codecs[key];
|
||||
next.filteredValue = codec ? codec.decode(params, prefix) : (filters[key] ?? null);
|
||||
}
|
||||
return next;
|
||||
},
|
||||
|
||||
pagination: paginationEnabled && page
|
||||
? { current: page.page, pageSize: page.pageSize }
|
||||
: false,
|
||||
|
||||
filters,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user