Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | 79x 79x 79x 6x 79x 5x 79x 124x 124x 124x 124x 124x 124x 124x 124x 124x 124x 124x 124x 124x 124x 124x 124x 8x 474x 124x 73x 4x 4x 124x 73x 4x 4x 124x 124x 124x 124x | /**
* Everything a list table does against the server: the search box, the column
* filters, the sort, the page and the query that ties them into one request.
*
* A form table has none of this — its rows come from the form value — so the state
* lives in a hook and the component asks a single question: what rows should I show?
* The filters are returned as well as set, because a form table reuses them to narrow
* rows it already holds, and because a page must restart when one of them changes.
*/
import {useQuery} from '@tanstack/react-query';
import {useCallback, useMemo, useRef, useState} from 'react';
import type {Row} from './model.js';
/**
* The order a list is already read in, from the params the widget declares.
*
* A model's browse table names its default order in `listParams.orderBy`, and the
* header has to show it: the rows arrive ordered either way, so a table that drew
* the sort arrow nowhere would leave the reader unable to tell whether the order
* is theirs or the model's — and clicking a header would appear to do nothing
* until it flipped the column it was already sorted by.
*
* Both spellings the framework accepts are read: `{field, dir}` (what the browser
* sends) and `{column, order}` (what a knex-facing config may carry).
*/
export function sortFromParams(
listParams?: Record<string, unknown>,
): {field: string; dir: 1 | -1} | null {
const terms = listParams?.orderBy;
const term = (Array.isArray(terms) ? terms[0] : terms) as Record<string, unknown> | undefined;
if (!term || typeof term !== 'object') return null;
const field = (term.field ?? term.column) as string | undefined;
if (!field) return null;
const order = String(term.dir ?? term.order ?? 'ASC').toLowerCase();
return {field, dir: order === 'desc' || order === '-1' ? -1 : 1};
}
export interface ITableListOptions {
/** The handler that reads a page, e.g. `portal.bundle.find`. Empty when not a list. */
listAction: string;
/** Params the widget declares for its own list read. */
listParams?: Record<string, unknown>;
/** The result key holding the rows (default `items`). */
resultSet: string;
/** The params the report form submitted, when the widget runs as a report. */
reportParams?: Record<string, unknown>;
reportMode: boolean;
/** The label columns the read should project. */
labelFields: string[];
/** Master-detail keys the server narrows by, when the table is cascaded. */
cascadeFilter?: Record<string, unknown>;
pageSize: number;
handler: Record<
string,
(params: Record<string, unknown>, meta: Record<string, unknown>) => Promise<unknown>
>;
}
export function useTableList({
listAction,
listParams,
resultSet,
reportParams,
reportMode,
labelFields,
cascadeFilter,
pageSize,
handler,
}: ITableListOptions) {
const [searchInput, setSearchInput] = useState('');
const [committedSearch, setCommittedSearch] = useState('');
const [columnFilterInputs, setColumnFilterInputs] = useState<Record<string, string>>({});
const [committedFilters, setCommittedFilters] = useState<Record<string, string>>({});
// The model's own order, so the header starts out showing the sort the rows
// are already in (see `sortFromParams`).
const declaredSort = useMemo(() => sortFromParams(listParams), [listParams]);
const [sortField, setSortField] = useState<string | null>(declaredSort?.field ?? null);
const [sortOrder, setSortOrder] = useState<1 | -1>(declaredSort?.dir ?? 1);
const [first, setFirst] = useState(0);
const [listPageSize, setListPageSize] = useState(pageSize);
const filterDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const searchDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const isListMode = !!listAction;
const params = useMemo(() => {
const filterBy = Object.fromEntries(
Object.entries(committedFilters).filter(([, value]) => value !== ''),
);
return {
...(listParams ?? {}),
// Report params are merged before the filters so a filter takes precedence
...(reportParams ?? {}),
...(cascadeFilter ?? {}),
...(labelFields.length > 0 ? {labels: labelFields} : {}),
...(Object.keys(filterBy).length > 0 ? {filterBy} : {}),
...(committedSearch ? {search: committedSearch} : {}),
...(sortField
? {orderBy: [{field: sortField, dir: sortOrder === 1 ? 'ASC' : 'DESC'}]}
: {}),
paging: {
pageSize: listPageSize,
pageNumber: Math.floor(first / listPageSize) + 1,
/**
* Ask the server for the size of the whole result, not just the
* page. The paginator's arrows need it: without a total the
* widget only knows the rows it was handed, so every page looked
* like the last one and the forward arrows stayed disabled.
* A read that ignores the flag answers rows alone, which the
* paginator still handles by asking whether the page is full.
*/
count: true,
},
};
}, [
listParams,
reportParams,
cascadeFilter,
labelFields,
committedFilters,
committedSearch,
sortField,
sortOrder,
first,
listPageSize,
]);
type ListResult = Record<string, unknown>;
const {data, isFetching: loading} = useQuery<ListResult>({
queryKey: [listAction, params],
queryFn: () => handler[listAction](params, {}) as Promise<ListResult>,
// In report mode, wait until the user submits params
enabled: isListMode && (!reportMode || reportParams !== undefined),
staleTime: 0,
placeholderData: previousData => previousData,
});
const rows: Row[] = useMemo(() => {
if (!data) return [];
Eif (resultSet && Array.isArray((data as Record<string, unknown>)[resultSet])) {
return (data as Record<string, unknown>)[resultSet] as Row[];
}
return Array.isArray(data) ? (data as Row[]) : [];
}, [data, resultSet]);
/**
* How many rows the whole result holds, when the server reported it.
*
* `undefined` means the read answers a bare page — the generic `find`
* before it learned `paging.count`, or a realm's own projection. The page
* is then judged by whether it was full (`hasMore`), so the arrows still
* move rather than locking on the first page.
*/
const total: number | undefined = useMemo(() => {
if (!data) return undefined;
const pagination = (data as {pagination?: {recordsTotal?: number}}).pagination;
return typeof pagination?.recordsTotal === 'number' ? pagination.recordsTotal : undefined;
}, [data]);
/** Whether a further page exists — known exactly when `total` is. */
const hasMore =
total === undefined ? rows.length >= listPageSize : first + listPageSize < total;
const onSearchChange = useCallback((value: string) => {
setSearchInput(value);
if (searchDebounceRef.current) clearTimeout(searchDebounceRef.current);
searchDebounceRef.current = setTimeout(
() => {
setCommittedSearch(value);
setFirst(0);
},
value === '' ? 0 : 350,
);
}, []);
const onColumnFilterChange = useCallback((field: string, value: string) => {
setColumnFilterInputs(prev => ({...prev, [field]: value}));
if (filterDebounceRef.current) clearTimeout(filterDebounceRef.current);
filterDebounceRef.current = setTimeout(
() => {
setCommittedFilters(prev => {
const next = {...prev, [field]: value};
if (value === '') delete next[field];
return next;
});
setFirst(0);
},
value === '' ? 0 : 350,
);
}, []);
return {
isListMode,
rows,
total,
hasMore,
loading,
params,
searchInput,
onSearchChange,
columnFilterInputs,
committedFilters,
onColumnFilterChange,
sortField,
sortOrder,
onSortChange: (field: string | null, order: 1 | -1) => {
setSortField(field);
setSortOrder(order);
setFirst(0);
},
first,
setFirst,
/** Back to the first page — a new parent row, or a new report run. */
resetPage: () => setFirst(0),
pageSize: listPageSize,
setPageSize: setListPageSize,
};
}
|