forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

data-table.tsx845 lines, 41.3 KiBHistoryRawDownload
1import { For, Show, createEffect, createSignal, on, onCleanup } from "solid-js";
2import type { JSX, ParentProps } from "solid-js";
3import {
4 type Column,
5 type ColumnDef,
6 type ColumnFiltersState,
7 type PaginationState,
8 type SortingState,
9 type Updater,
10 createSolidTable,
11 flexRender,
12 getCoreRowModel,
13 getFilteredRowModel,
14 getPaginationRowModel,
15 getSortedRowModel,
16} from "@tanstack/solid-table";
17import { Illustration } from "@/components/ui/illustration";
18import type { IllustrationName } from "@/lib/illustrations";
19import { Button } from "@/components/ui/button";
20import { DataTableSearch } from "@/components/ui/data-table-search";
21import { DataTableViewMenu, type ViewMenuColumn } from "@/components/ui/data-table-view-menu";
22import { TablePagination } from "@/components/ui/table-pagination";
23import { IconArrowDown, IconArrowUp, IconChevronsUpDown } from "@/components/ui/icons";
24import { InfoTip } from "@/components/ui/info-tip";
25import { cn } from "@/lib/cn";
26import { createMediaQuery } from "@/lib/create-media-query";
27import { COMPACT_SCREEN_QUERY, createResponsivePageSize } from "@/lib/create-page-size";
28import { createScrollRestore } from "@/lib/scroll-restore";
29import { createTablePreferences } from "@/lib/table-preferences";
30import { createUrlPageIndex, createUrlParam, createUrlString, decodeSort, encodeSort, listParamKeys } from "@/lib/url-state";
31import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
32import { useT } from "@/stores/preferences-context";
33
34declare module "@tanstack/solid-table" {
35 interface ColumnMeta<TData, TValue> {
36 headerClass?: string;
37 cellClass?: string;
38 label?: string;
39 /** Header + cell horizontal alignment. Applied to both so they never drift apart. */
40 align?: "left" | "center" | "right";
41 /** Freeze this column to the left edge on horizontal scroll. */
42 stickyLeft?: boolean;
43 /** Vertical divider on the given edge — separates frozen label from metric columns. */
44 divider?: "left" | "right";
45 /** Leave this column out of the phone card layout (e.g. a column that only matters on a wide table). */
46 hideInCards?: boolean;
47 /**
48 * A note that explains this column (what fills it, a limit behind it).
49 * Renders a circled "i" after the header label that shows the text on
50 * hover, focus and tap — instead of a line kept on screen above the table.
51 */
52 headerInfo?: string;
53 }
54}
55
56export type DataTableProps<TData, TValue = unknown> = {
57 columns: ColumnDef<TData, TValue>[];
58 data: TData[];
59 empty?: JSX.Element;
60 /** Scene shown above `empty`; defaults to a generic empty / no-results one. */
61 emptyIllustration?: IllustrationName;
62 class?: string;
63 tableClass?: string;
64 enableColumnVisibility?: boolean;
65 enablePagination?: boolean;
66 enableSorting?: boolean;
67 filters?: JSX.Element;
68 filterColumn?: string;
69 filterPlaceholder?: string;
70 /** On-focus hint under the search box naming the fields it matches. */
71 filterHint?: string;
72 title?: string;
73 description?: string;
74 actions?: JSX.Element;
75 manualPagination?: {
76 pageIndex: number;
77 /** The size the caller actually fetched — pass a `createResponsivePageSize` accessor's value. */
78 pageSize: number;
79 total: number;
80 onPageChange: (pageIndex: number) => void;
81 };
82 /**
83 * Fetch-as-you-scroll: `data` holds the rows loaded so far and the table
84 * asks for the next page (`onLoadMore`) as the reader nears its end. Pair
85 * with `createInfiniteList` (lib/infinite-list); search must reach the
86 * server through `onSearchInput`, and sorting is off (the backend takes no
87 * sort parameter, so a header sort would order the loaded rows alone).
88 */
89 infinite?: {
90 hasMore: boolean;
91 loading: boolean;
92 total: number;
93 onLoadMore: () => void;
94 };
95 /**
96 * Below the `sm` breakpoint rows render as cards (first column as the
97 * title, actions top-right, the rest as label/value pairs) instead of a
98 * table that scrolls sideways. "scroll" keeps the table on phones too.
99 */
100 mobileLayout?: "cards" | "scroll";
101 onRowClick?: (row: TData) => void;
102 /** Reports the rows on the rendered page after paging, search, or sorting changes. */
103 onPageRowsChange?: (rows: TData[]) => void;
104 onSearchInput?: (value: string) => void;
105 /** Rows per page on a wide screen; client tables use fewer on phones. */
106 pageSize?: number;
107 searchPredicate?: (row: TData, query: string) => boolean;
108 searchValue?: string;
109 /**
110 * When set, column widths / visibility / row density persist to localStorage.
111 * Without a key the same controls remain available for the current mount.
112 */
113 storageKey?: string;
114 /** Split the title/toolbar and table into the same inner surfaces as detail pages. */
115 surfaceSections?: boolean;
116 /**
117 * Keep search, page and sort in the URL (`?q=`, `?page=`, `?sort=`) so Back
118 * and a reload restore them. A string prefixes the keys (`?roster.q=`) for
119 * a page with more than one list. Needs a router; only the search the table
120 * owns (`searchPredicate` / `filterColumn`) is stored — a caller passing
121 * `searchValue` / `onSearchInput` keeps its own.
122 */
123 urlState?: boolean | string;
124 /** Back to the top of the list whenever this changes — pass the caller's own filters. */
125 pageResetKey?: unknown;
126 /**
127 * The caller's own filters narrow the list. An empty result then offers
128 * `onClearFilters` instead of the "nothing here yet" message.
129 */
130 filtersActive?: boolean;
131 onClearFilters?: () => void;
132};
133
134const resolveUpdater = <T,>(updater: Updater<T>, old: T): T =>
135 typeof updater === "function" ? (updater as (value: T) => T)(old) : updater;
136
137const alignClass = { left: "text-left", center: "text-center", right: "text-right" } as const;
138
139/** Start fetching the next server page this far before the list's end comes into view. */
140const REVEAL_MARGIN_PX = 600;
141
142export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, TValue>) {
143 const t = useT();
144 const paginationEnabled = props.enablePagination ?? true;
145 const prefs = createTablePreferences(props.storageKey);
146 // Read once: a table either keeps its state in the URL or it does not.
147 const urlKeys = props.urlState
148 ? listParamKeys(typeof props.urlState === "string" ? props.urlState : undefined)
149 : null;
150 const [sorting, setSortingState] = urlKeys
151 ? createUrlParam<SortingState>(urlKeys.sort, { parse: decodeSort, serialize: encodeSort })
152 : createSignal<SortingState>([]);
153 const [otherColumnFilters, setOtherColumnFilters] = createSignal<ColumnFiltersState>([]);
154 const clientPageSize = createResponsivePageSize(props.pageSize ?? 10);
155 const [clientPageIndex, setClientPageIndex] = urlKeys && !props.manualPagination && !props.infinite
156 ? createUrlPageIndex(urlKeys.page)
157 : createSignal(0);
158 const pagination = (): PaginationState => ({ pageIndex: clientPageIndex(), pageSize: clientPageSize() });
159 createEffect(on(clientPageSize, () => setClientPageIndex(0), { defer: true }));
160 createEffect(on(() => props.pageResetKey, () => setClientPageIndex(0), { defer: true }));
161 // The search box's text when the table owns it — the `searchPredicate`
162 // query, or the `filterColumn` filter value.
163 const [search, setSearch] = urlKeys && props.searchValue === undefined && !props.onSearchInput
164 ? createUrlString(urlKeys.q)
165 : createSignal("");
166 const searchValue = () => props.searchValue ?? search();
167 // The filterColumn filter is the search signal; any other column filter
168 // stays local.
169 const columnFilters = (): ColumnFiltersState => {
170 const column = props.filterColumn;
171 const query = search();
172 if (!column || props.searchPredicate || props.onSearchInput || !query) return otherColumnFilters();
173 return [...otherColumnFilters().filter((filter) => filter.id !== column), { id: column, value: query }];
174 };
175 const setColumnFilters = (next: ColumnFiltersState) => {
176 const column = props.filterColumn;
177 if (!column || props.searchPredicate || props.onSearchInput) {
178 setOtherColumnFilters(next);
179 return;
180 }
181 const own = next.find((filter) => filter.id === column);
182 setSearch(typeof own?.value === "string" ? own.value : "");
183 setOtherColumnFilters(next.filter((filter) => filter.id !== column));
184 setClientPageIndex(0);
185 };
186 // A new sort order is a new list: start again from its top.
187 const setSorting = (next: SortingState) => {
188 setSortingState(next);
189 setClientPageIndex(0);
190 };
191 // Sorting is client-side only, and the backend takes no sort parameter: on
192 // a server-paged table it would reorder the visible page alone while the
193 // header claimed the whole list. Off there unless a caller opts in.
194 const sortingEnabled = () => props.enableSorting ?? !(props.manualPagination || props.infinite);
195 const tableData = () => {
196 const query = searchValue().trim();
197 if (!query || !props.searchPredicate) return props.data;
198 return props.data.filter((row) => props.searchPredicate?.(row, query));
199 };
200 const table = createSolidTable({
201 defaultColumn: {
202 size: 120,
203 minSize: 72,
204 maxSize: 360,
205 },
206 get data() {
207 return tableData();
208 },
209 get columns() {
210 return props.columns;
211 },
212 enableSorting: sortingEnabled(),
213 getCoreRowModel: getCoreRowModel(),
214 getSortedRowModel: getSortedRowModel(),
215 getFilteredRowModel: getFilteredRowModel(),
216 ...(paginationEnabled && !props.manualPagination && !props.infinite ? { getPaginationRowModel: getPaginationRowModel() } : {}),
217 autoResetPageIndex: false,
218 onSortingChange: (updater) => setSorting(resolveUpdater(updater, sorting())),
219 onColumnFiltersChange: (updater) => setColumnFilters(resolveUpdater(updater, columnFilters())),
220 onColumnVisibilityChange: (updater) =>
221 prefs.setVisibility(resolveUpdater(updater, prefs.preferences().visibility)),
222 onPaginationChange: (updater) => setClientPageIndex(resolveUpdater(updater, pagination()).pageIndex),
223 state: {
224 get sorting() {
225 return sorting();
226 },
227 get columnFilters() {
228 return columnFilters();
229 },
230 get columnVisibility() {
231 return prefs.preferences().visibility;
232 },
233 get pagination(): PaginationState {
234 return props.manualPagination
235 ? { pageIndex: props.manualPagination.pageIndex, pageSize: props.manualPagination.pageSize }
236 : props.infinite ? { pageIndex: 0, pageSize: Number.MAX_SAFE_INTEGER } : pagination();
237 },
238 },
239 });
240 const hiddenLocked = (columnId: string) => columnId === "actions" || columnId === "update";
241 const stickyRightLocked = (columnId: string) =>
242 columnId === "actions" || (columnId === "update" && table.getColumn("actions") == null);
243 const isStickyLeft = (column: Column<TData, unknown>) => column.columnDef.meta?.stickyLeft === true;
244 // Headers stay centred; body cells read from the left edge. System columns
245 // (row actions, checkboxes) keep their controls centred under the header.
246 const isSystemColumnId = (columnId: string) => ["actions", "update", "select"].includes(columnId);
247 const alignOf = (column: Column<TData, unknown>) => isSystemColumnId(column.id) ? "center" as const : "left" as const;
248 // Cell renderers written for the old centred layout carry their own
249 // mx-auto / justify-center / text-center on their root; pull those to the
250 // start. Direct children only: deeper centring (avatar initials, icon
251 // buttons) is the widget's own layout, not the column's.
252 const leftCellClass = (column: Column<TData, unknown>) => isSystemColumnId(column.id)
253 ? undefined
254 : "[&>.mx-auto]:mx-0 [&>.justify-center]:justify-start [&>.text-center]:text-left";
255 const dividerClass = (column: Column<TData, unknown>) => {
256 const divider = column.columnDef.meta?.divider;
257 return divider === "left" ? "border-l border-border/70" : divider === "right" ? "border-r border-border/70" : undefined;
258 };
259 const actionColumnClass = (columnId: string) => stickyRightLocked(columnId) ? "table-action-cell h-[45px] w-[110px] min-w-[110px] max-w-[110px] px-2 py-0 text-center whitespace-nowrap" : undefined;
260 const stickyHeadClass = (column: Column<TData, unknown>) =>
261 isStickyLeft(column)
262 ? "table-sticky-head-left sticky left-0 z-30"
263 : stickyRightLocked(column.id)
264 ? "table-sticky-head-right sticky right-0 z-30"
265 : undefined;
266 const stickyCellClass = (column: Column<TData, unknown>) =>
267 isStickyLeft(column)
268 ? "table-sticky-left sticky left-0 z-10"
269 : stickyRightLocked(column.id)
270 ? "table-sticky-right sticky right-0 z-10"
271 : undefined;
272 const hideableColumns = () => table.getAllColumns().filter((column) => column.getCanHide() && !hiddenLocked(column.id));
273 const columnLabel = (column: Column<TData, unknown>) => {
274 const header = column.columnDef.header;
275 return column.columnDef.meta?.label ?? (typeof header === "string" ? header : column.id);
276 };
277 const viewMenuColumns = (): ViewMenuColumn[] =>
278 hideableColumns().map((column) => ({
279 id: column.id,
280 label: columnLabel(column),
281 visible: column.getIsVisible(),
282 toggle: (visible: boolean) => column.toggleVisibility(visible),
283 }));
284 const colSpan = () => Math.max(1, table.getVisibleLeafColumns().length);
285 const dataColumnsWidth = () =>
286 table.getVisibleLeafColumns().reduce(
287 (total, column) => total + (stickyRightLocked(column.id) ? 0 : column.getSize()),
288 0,
289 );
290 // The table scrolls sideways only once the frame is narrower than every
291 // column at its floor: a column that declares `minSize` may shrink to it,
292 // one that does not keeps its `size`. Sizing the table by `size` alone
293 // made a tablet scroll a table that fit, and slid the last data column
294 // under the sticky action column.
295 const minTableWidth = () =>
296 table.getVisibleLeafColumns().reduce(
297 (total, column) =>
298 total + (stickyRightLocked(column.id) ? 110 : Math.min(column.getSize(), column.columnDef.minSize ?? column.getSize())),
299 0,
300 );
301 const columnWidth = (column: Column<TData, unknown>) => {
302 if (stickyRightLocked(column.id)) return "110px";
303 const total = dataColumnsWidth();
304 if (total === 0) return `${column.getSize()}px`;
305 // A plain percentage: Chrome treats a calc() that mixes % and px on a
306 // table column as auto, which split every table into equal columns and
307 // ignored each column's size. The shares sum to 100% beside the fixed
308 // 110px action column; the fixed layout scales them into what is left.
309 return `${(column.getSize() / total) * 100}%`;
310 };
311 const compactScreen = createMediaQuery(COMPACT_SCREEN_QUERY);
312 const useCards = () => (props.mobileLayout ?? "cards") === "cards" && compactScreen();
313 // Cards print every visible column as a label/value pair, so a column picker
314 // there only hides lines; on phones it is one more control for nothing.
315 const showColumnMenu = () => (props.enableColumnVisibility ?? true) && hideableColumns().length > 0 && !useCards();
316 const showSearch = () => props.searchPredicate != null || props.filterColumn != null || props.onSearchInput != null;
317 const sectioned = () => props.surfaceSections !== false;
318 const showHeader = () => false;
319 const showToolbar = () => showSearch() || props.filters != null || showColumnMenu() || props.actions != null;
320 // Toolbar controls — search, filters, actions, "Sütunlar" — are one pill
321 // shape and one height on every page: touch-sized (h-10) below `sm` and on touch screens, h-8
322 // above. Page actions arrive as plain Buttons (size="sm" is 26px), so the
323 // slot sizes them rather than trusting each page to.
324 const TOOLBAR_ACTIONS =
325 "[&_button]:h-10 [&_button]:rounded-full [&_button]:px-3.5 [&_button]:text-[13px] sm:[&_button]:h-8 touch:[&_button]:h-10 [&_a]:h-10 [&_a]:rounded-full [&_a]:px-3.5 [&_a]:text-[13px] sm:[&_a]:h-8 touch:[&_a]:h-10";
326 const pageCount = () => props.manualPagination
327 ? Math.max(1, Math.ceil(props.manualPagination.total / props.manualPagination.pageSize))
328 : table.getPageCount();
329 const pageIndex = () => props.manualPagination?.pageIndex ?? clientPageIndex();
330 const pageSize = () => props.manualPagination?.pageSize ?? clientPageSize();
331 const totalRows = () => props.manualPagination?.total ?? props.infinite?.total ?? table.getFilteredRowModel().rows.length;
332 const setPageIndex = (next: number) => {
333 if (props.manualPagination) props.manualPagination.onPageChange(next);
334 else setClientPageIndex(next);
335 };
336 createEffect(() => {
337 if (props.manualPagination || props.infinite || !paginationEnabled) return;
338 const rows = table.getFilteredRowModel().rows.length;
339 if (rows === 0) return;
340 const last = Math.max(0, Math.ceil(rows / clientPageSize()) - 1);
341 if (clientPageIndex() > last) setClientPageIndex(last);
342 });
343 const visibleRows = () => table.getRowModel().rows;
344 createEffect(on(visibleRows, (rows) => props.onPageRowsChange?.(rows.map((row) => row.original))));
345 let sentinel: HTMLDivElement | undefined;
346 const observing = typeof IntersectionObserver !== "undefined";
347 const nearEnd = () => !!sentinel && sentinel.getBoundingClientRect().top < window.innerHeight + REVEAL_MARGIN_PX;
348 const loadMore = () => {
349 if (!nearEnd()) return;
350 const infinite = props.infinite;
351 if (infinite?.hasMore && !infinite.loading) infinite.onLoadMore();
352 };
353 createEffect(() => {
354 if (!props.infinite || !observing) return;
355 const node = sentinel;
356 if (!node) return;
357 const observer = new IntersectionObserver((entries) => {
358 if (entries.some((entry) => entry.isIntersecting)) loadMore();
359 }, { rootMargin: `0px 0px ${REVEAL_MARGIN_PX}px 0px` });
360 observer.observe(node);
361 onCleanup(() => observer.disconnect());
362 });
363 // Same for a fetched page: once it lands, a short page may leave the end
364 // in view, so ask for the next one straight away.
365 createEffect(on(() => props.infinite?.loading, (busy) => {
366 if (busy === false && observing) queueMicrotask(loadMore);
367 }, { defer: true }));
368 const scrollKey = typeof window === "undefined" || props.infinite || props.manualPagination
369 ? null
370 : `${window.location.pathname}:${props.storageKey ?? props.title ?? ""}:${urlKeys?.page ?? "page"}`;
371 createScrollRestore(scrollKey, () => visibleRows().length > 0);
372 const searchFieldValue = () => {
373 if (props.onSearchInput || props.searchPredicate || props.filterColumn) return searchValue();
374 return "";
375 };
376 const handleSearch = (value: string) => {
377 if (props.onSearchInput) props.onSearchInput(value);
378 else setSearch(value);
379 setPageIndex(0);
380 };
381 const isInteractiveTarget = (target: EventTarget | null, row: EventTarget | null) => {
382 if (!(target instanceof Element)) return false;
383 // Solid bubbles a portalled element's events through its owner, so a pick
384 // in a row's action menu (rendered in a portal) reaches the row too; it is
385 // not a click on the row.
386 if (row instanceof Node && !row.contains(target)) return true;
387 const interactive = target.closest("button,a,input,select,textarea,[role='button']");
388 return interactive != null && interactive !== row;
389 };
390 // A search or filter that matches nothing is not an empty list: say what
391 // was asked for and offer the way back, instead of "nothing here yet".
392 const activeQuery = () => searchFieldValue().trim();
393 const narrowed = () => activeQuery() !== "" || props.filtersActive === true;
394 const clearNarrowing = () => {
395 if (activeQuery()) handleSearch("");
396 if (props.filtersActive) props.onClearFilters?.();
397 };
398 const emptyContent = () => (
399 <Show
400 when={narrowed()}
401 fallback={
402 <div class="flex flex-col items-center gap-3">
403 <Illustration name={props.emptyIllustration ?? "empty"} class="h-20 w-32" />
404 <span>{props.empty ?? t("common.noResults")}</span>
405 </div>
406 }
407 >
408 <div class="flex flex-col items-center gap-3">
409 <Illustration name="no-results" class="h-20 w-32" />
410 <span class="max-w-full break-words">
411 {activeQuery() ? t("common.noMatchesFor", { query: activeQuery() }) : t("common.noFilterMatches")}
412 </span>
413 <Show when={activeQuery() || props.onClearFilters}>
414 <Button type="button" size="sm" variant="outline" onClick={clearNarrowing}>
415 {props.filtersActive && props.onClearFilters ? t("common.clearFilters") : t("common.clearSearch")}
416 </Button>
417 </Show>
418 </div>
419 </Show>
420 );
421 const headerLabel = (columnId: string) => {
422 const header = table.getFlatHeaders().find((candidate) => candidate.column.id === columnId);
423 return header ? flexRender(header.column.columnDef.header, header.getContext()) : columnId;
424 };
425 // Screen readers hear the order only through aria-sort on the header cell.
426 const ariaSort = (column: Column<TData, unknown>) => {
427 if (!sortingEnabled() || !column.getCanSort()) return undefined;
428 const sorted = column.getIsSorted();
429 return sorted === "asc" ? "ascending" : sorted === "desc" ? "descending" : "none";
430 };
431 // The info icon sits beside the label, never inside the sort button: a
432 // button in a button is invalid, and opening the note must not sort.
433 const headerInfoTip = (column: Column<TData, unknown>) => (
434 <Show when={column.columnDef.meta?.headerInfo}>
435 {(text) => <InfoTip text={text()} label={t("common.infoAbout", { item: columnLabel(column) })} />}
436 </Show>
437 );
438 const renderHeader = (header: ReturnType<typeof table.getHeaderGroups>[number]["headers"][number]) => {
439 const content = flexRender(header.column.columnDef.header, header.getContext());
440 if (!sortingEnabled() || !header.column.getCanSort()) {
441 return (
442 <Show when={header.column.columnDef.meta?.headerInfo} fallback={<span class="block truncate whitespace-nowrap text-center">{content}</span>}>
443 <span class="flex min-w-0 items-center justify-center gap-1 whitespace-nowrap">
444 <span class="min-w-0 truncate">{content}</span>
445 {headerInfoTip(header.column)}
446 </span>
447 </Show>
448 );
449 }
450 const sorted = () => header.column.getIsSorted();
451 const sortButton = () => (
452 <Button
453 type="button"
454 variant="ghost"
455 size="sm"
456 class={cn("mx-auto h-8 min-w-0 max-w-full justify-center px-2 text-center font-medium tracking-normal normal-case", sorted() && "text-foreground")}
457 onClick={() => header.column.toggleSorting(sorted() === "asc")}
458 >
459 <span class="truncate">{content}</span>
460 <Show
461 when={sorted() !== false}
462 fallback={
463 <IconChevronsUpDown class="h-3.5 w-3.5 opacity-0 transition-opacity group-hover/head:opacity-50 group-focus-within/head:opacity-50" />
464 }
465 >
466 <Show
467 when={sorted() === "asc"}
468 fallback={<IconArrowDown class="h-3.5 w-3.5" />}
469 >
470 <IconArrowUp class="h-3.5 w-3.5" />
471 </Show>
472 </Show>
473 </Button>
474 );
475 return (
476 <Show when={header.column.columnDef.meta?.headerInfo} fallback={sortButton()}>
477 <span class="flex min-w-0 items-center justify-center whitespace-nowrap">
478 {sortButton()}
479 {headerInfoTip(header.column)}
480 </span>
481 </Show>
482 );
483 };
484
485 return (
486 <div class={cn("space-y-3", props.class)}>
487 <Show when={showHeader()}>
488 <div class={cn("flex flex-wrap items-start justify-between gap-3", sectioned() && "rounded-xl border border-border-line bg-surface-base p-3 shadow-xs sm:p-4")}>
489 <div class="min-w-0">
490 <Show when={props.title}>
491 <h2 class="truncate text-lg font-semibold tracking-tight text-foreground">{props.title}</h2>
492 </Show>
493 <Show when={props.description}>
494 <p class="mt-1 text-sm text-muted-foreground">{props.description}</p>
495 </Show>
496 </div>
497 <Show when={props.actions}>
498 <div class={cn("flex min-w-0 flex-wrap items-center gap-2", TOOLBAR_ACTIONS)}>{props.actions}</div>
499 </Show>
500 </div>
501 </Show>
502 <Show when={showToolbar()}>
503 {/* One wrapping row, ordered by width. Phones: search and actions share
504 the first line, filters get a line of their own that scrolls
505 sideways instead of stacking one control per line. From `lg`:
506 search, filters, then actions pushed to the right edge. Controls
507 are touch-sized (h-10) below `sm` and compact (h-8) above it. */}
508 {/* Always a card when sectioned, even when "Sütunlar" is its only
509 control, so every list page's toolbar reads the same. */}
510 <div class={cn("flex flex-wrap items-center gap-2", sectioned() && "rounded-xl border border-border-line bg-surface-base p-3 shadow-xs")}>
511 <Show when={showSearch()}>
512 <DataTableSearch
513 class="order-1 w-auto min-w-40 flex-1 grow-[100] sm:max-w-xs"
514 value={searchFieldValue()}
515 onChange={handleSearch}
516 placeholder={props.filterPlaceholder ?? t("common.searchPlaceholder")}
517 hint={props.filterHint}
518 />
519 </Show>
520 <Show when={props.filters}>
521 <div class="order-3 -my-1 flex w-full items-center gap-2 overflow-x-auto py-1 [scrollbar-width:none] sm:my-0 sm:py-0 sm:flex-wrap sm:overflow-visible lg:order-2 lg:w-auto [&_button]:h-10 [&_button]:shrink-0 [&_button]:rounded-full [&_button]:px-3 [&_button]:text-[13px] [&_[data-filter-active]]:border-primary [&_[data-filter-active]]:text-primary-text [&_[data-slot=combobox-control]]:h-10 [&_[data-slot=combobox-control]]:rounded-full [&_[data-slot=combobox-control]]:text-[13px] sm:[&_[data-slot=combobox-control]]:h-8 touch:[&_[data-slot=combobox-control]]:h-10 sm:[&_button]:h-8 touch:[&_button]:h-10 [&_select]:h-10 [&_select]:rounded-full [&_select]:text-[13px] sm:[&_select]:h-8 touch:[&_select]:h-10 max-sm:[&>*]:flex-nowrap max-sm:[&>*]:shrink-0">{props.filters}</div>
522 </Show>
523 <Show when={props.actions || showColumnMenu()}>
524 {/* Beside the search the actions keep their own width (the search
525 out-grows them 100:1). A label too long to fit there wraps to
526 a line of its own, where the sole grower takes the full row and
527 the button stretches instead of hanging off the right edge. */}
528 <div class="order-2 ml-auto flex shrink-0 grow flex-wrap items-center justify-end gap-2 sm:grow-0 lg:order-3">
529 <Show when={props.actions}>
530 <div class={cn("flex min-w-0 flex-wrap items-center gap-2 max-sm:flex-1 max-sm:[&_button]:flex-1", TOOLBAR_ACTIONS)}>{props.actions}</div>
531 </Show>
532 <Show when={showColumnMenu()}>
533 <DataTableViewMenu columns={viewMenuColumns()} />
534 </Show>
535 </div>
536 </Show>
537 </div>
538 </Show>
539 <Show when={useCards()}>
540 <ul class="space-y-2" aria-label={props.title}>
541 <Show
542 when={visibleRows().length > 0}
543 fallback={<li class="rounded-lg border border-border-line bg-surface-base px-4 py-8 text-center text-sm text-muted-foreground">{emptyContent()}</li>}
544 >
545 <For each={visibleRows()}>
546 {(row, rowIndex) => {
547 const cells = () =>
548 row.getVisibleCells().filter((cell) => cell.column.id !== "select" && !cell.column.columnDef.meta?.hideInCards);
549 const action = () => cells().find((cell) => cell.column.id === "actions");
550 const body = () => cells().filter((cell) => cell.column.id !== "actions");
551 // A "-" line only makes a phone card taller: leave out fields
552 // with no value. Display columns draw themselves from
553 // row.original, so they have no value to test and always stay.
554 const details = () =>
555 body().slice(1).filter((cell) => cell.column.accessorFn == null || (cell.getValue() != null && cell.getValue() !== ""));
556 return (
557 <li>
558 <div
559 role={props.onRowClick ? "button" : undefined}
560 tabIndex={props.onRowClick ? 0 : undefined}
561 class={cn(
562 "rounded-lg border border-border-line bg-surface-base p-3 text-sm",
563 props.onRowClick && "cursor-pointer outline-hidden focus-visible:ring-2 focus-visible:ring-ring active:bg-primary/6",
564 )}
565 onClick={(event) => {
566 if (!props.onRowClick || isInteractiveTarget(event.target, event.currentTarget)) return;
567 props.onRowClick(row.original);
568 }}
569 onKeyDown={(event) => {
570 if (!props.onRowClick || isInteractiveTarget(event.target, event.currentTarget) || (event.key !== "Enter" && event.key !== " ")) return;
571 event.preventDefault();
572 props.onRowClick(row.original);
573 }}
574 >
575 <div class="flex items-start gap-2">
576 <div class="min-w-0 flex-1 font-medium">
577 <Show when={body()[0]}>{(first) => flexRender(first().column.columnDef.cell, first().getContext())}</Show>
578 </div>
579 {/* The row menu shrinks to its ⋮ glyph here — the word
580 beside it cost the title a third of the card width. */}
581 <Show when={action()}>{(cell) => <div class="-my-1 shrink-0 [&_[data-row-actions-label]]:hidden [&_[data-row-actions-trigger]]:h-10 [&_[data-row-actions-trigger]]:w-10 [&_[data-row-actions-trigger]]:min-w-0 [&_[data-row-actions-trigger]]:px-0">{flexRender(cell().column.columnDef.cell, cell().getContext())}</div>}</Show>
582 </div>
583 <Show when={details().length > 0}>
584 {/* Two fields per line, label over value: a label/value
585 row per field made every card as tall as its column
586 count. Cells are written for a centred table column,
587 so the card pulls their content back to the left, and
588 a status pill sized for that column's width shrinks
589 back to its own label. */}
590 <dl class="mt-2 grid grid-cols-2 gap-x-4 gap-y-2">
591 <For each={details()}>
592 {(cell) => (
593 <div class="min-w-0">
594 {/* A column note shows on the first card only: once
595 per list, like the table header it stands in for. */}
596 <dt class="flex min-w-0 items-center gap-1 text-[11px] leading-4 text-muted-foreground">
597 <span class="min-w-0 truncate">{headerLabel(cell.column.id)}</span>
598 <Show when={rowIndex() === 0}>{headerInfoTip(cell.column)}</Show>
599 </dt>
600 <dd class="mt-0.5 min-w-0 break-words text-[13px] leading-5 text-foreground text-left [&_*]:text-left [&_.items-center]:items-start [&_.justify-center]:justify-start [&_.justify-end]:justify-start [&_.mx-auto]:mx-0 [&_[data-slot=badge]]:w-auto [&_[data-slot=badge]]:min-w-0 [&_[data-slot=badge]]:max-w-full [&_[data-slot=badge]]:items-center!">
601 {flexRender(cell.column.columnDef.cell, cell.getContext())}
602 </dd>
603 </div>
604 )}
605 </For>
606 </dl>
607 </Show>
608 </div>
609 </li>
610 );
611 }}
612 </For>
613 </Show>
614 </ul>
615 </Show>
616 <Show when={!useCards()}>
617 {/* No inner padding: the header row sits flush on the card's top edge.
618 A padded frame left it floating inside the card, and the sticky
619 header then pinned below that padding while rows scrolled through
620 the gap above it. */}
621 <DataTableFrame class={sectioned() ? "shadow-xs" : undefined}>
622 <Table
623 class={cn("data-table table-fixed", props.tableClass)}
624 style={{ width: `max(100%, ${minTableWidth()}px)` }}
625 >
626 <colgroup>
627 <For each={table.getVisibleLeafColumns()}>
628 {(column) => <col style={{ width: columnWidth(column) }} />}
629 </For>
630 </colgroup>
631 <TableHeader>
632 <For each={table.getHeaderGroups()}>
633 {(headerGroup) => (
634 <TableRow class="hover:bg-transparent">
635 <For each={headerGroup.headers}>
636 {(header) => (
637 <TableHead
638 colSpan={header.colSpan}
639 class={cn(
640 "group/head relative overflow-hidden",
641 dividerClass(header.column),
642 stickyHeadClass(header.column),
643 header.column.columnDef.meta?.headerClass,
644 actionColumnClass(header.column.id),
645 )}
646 style={{ width: columnWidth(header.column) }}
647 aria-sort={ariaSort(header.column)}
648 >
649 <Show when={!header.isPlaceholder}>{renderHeader(header)}</Show>
650 </TableHead>
651 )}
652 </For>
653 </TableRow>
654 )}
655 </For>
656 </TableHeader>
657 <TableBody>
658 <Show
659 when={visibleRows().length > 0}
660 fallback={
661 <TableRow>
662 <TableCell colSpan={colSpan()} class="py-8 text-center text-muted-foreground">
663 {emptyContent()}
664 </TableCell>
665 </TableRow>
666 }
667 >
668 <For each={visibleRows()}>
669 {(row) => (
670 <TableRow
671 data-state={row.getIsSelected() ? "selected" : undefined}
672 role={props.onRowClick ? "button" : undefined}
673 tabIndex={props.onRowClick ? 0 : undefined}
674 class={cn(
675 "group/row",
676 props.onRowClick && "cursor-pointer outline-hidden focus-visible:bg-primary/6 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring active:bg-primary/8",
677 )}
678 onClick={(event) => {
679 if (!props.onRowClick || isInteractiveTarget(event.target, event.currentTarget)) return;
680 props.onRowClick(row.original);
681 }}
682 onKeyDown={(event) => {
683 if (!props.onRowClick || isInteractiveTarget(event.target, event.currentTarget) || (event.key !== "Enter" && event.key !== " ")) return;
684 event.preventDefault();
685 props.onRowClick(row.original);
686 }}
687 >
688 <For each={row.getVisibleCells()}>
689 {(cell) => {
690 const val = cell.getValue();
691 const isSystemColumn = ["actions", "update", "select"].includes(cell.column.id);
692 // A display column (no accessorFn/accessorKey) has no
693 // value to be empty — getValue() is always undefined —
694 // so it must render its own `cell`, or a column that
695 // draws itself from row.original silently shows "-".
696 const isDisplayColumn = cell.column.accessorFn == null;
697 const isEmpty =
698 !isSystemColumn && !isDisplayColumn && (val == null || val === "");
699
700 return (
701 <TableCell
702 class={cn(
703 leftCellClass(cell.column),
704 dividerClass(cell.column),
705 stickyCellClass(cell.column),
706 cell.column.columnDef.meta?.cellClass,
707 // After cellClass on purpose: values start at the
708 // left edge in every table, and a page-level
709 // text-center left over from an older layout
710 // must not pull one column into the middle.
711 alignClass[alignOf(cell.column)],
712 actionColumnClass(cell.column.id),
713 )}
714 style={{ width: columnWidth(cell.column) }}
715 // The tooltip is what the cell shows, and only when
716 // it is cut: the accessor value is a sort key (an
717 // epoch, minutes, an unrounded mark), not the text.
718 onMouseEnter={(event) => {
719 if (isSystemColumn) return;
720 const el = event.currentTarget;
721 const clipped = [el, ...el.querySelectorAll<HTMLElement>("*")].some((node) => node.scrollWidth > node.clientWidth + 1);
722 const text = el.textContent?.trim() ?? "";
723 if (clipped && text) el.title = text;
724 else el.removeAttribute("title");
725 }}
726 >
727 <Show when={!isEmpty} fallback={<span class="text-muted-foreground">—</span>}>
728 {flexRender(cell.column.columnDef.cell, cell.getContext())}
729 </Show>
730 </TableCell>
731 );
732 }}
733 </For>
734 </TableRow>
735 )}
736 </For>
737 </Show>
738 </TableBody>
739 </Table>
740 </DataTableFrame>
741 </Show>
742 <Show when={(props.manualPagination || paginationEnabled) && !props.infinite && totalRows() > 0}>
743 <TablePagination
744 pageIndex={pageIndex()}
745 pageCount={pageCount()}
746 pageSize={pageSize()}
747 total={totalRows()}
748 onPageChange={setPageIndex}
749 />
750 </Show>
751 <Show when={props.infinite && totalRows() > 0}>
752 {/* One block, so the parent's space-y gap is paid once: the sentinel
753 and the count as siblings put two gaps under the scroll hint. */}
754 <div class="-mt-1.5 flex flex-col gap-2">
755 <div ref={sentinel} aria-hidden="true" class="-mb-2 h-px" />
756 <p class="px-1 text-xs font-medium tabular-nums text-muted-foreground sm:text-[11px]" aria-live="polite">
757 {props.infinite?.loading
758 ? t("common.loadingMore")
759 : props.infinite?.hasMore
760 ? t("common.showingOf", { shown: props.data.length, total: totalRows() })
761 : t("common.rowCount", { total: totalRows() })}
762 </p>
763 <Show when={!observing && props.infinite?.hasMore && !props.infinite.loading}>
764 <Button type="button" variant="outline" size="sm" class="self-start" onClick={() => props.infinite?.onLoadMore()}>
765 {t("common.loadMore")}
766 </Button>
767 </Show>
768 </div>
769 </Show>
770 </div>
771 );
772}
773
774export function DataTableFrame(props: ParentProps<{ class?: string }>) {
775 const t = useT();
776 let frame: HTMLDivElement | undefined;
777 const [scrollable, setScrollable] = createSignal(false);
778 const checkOverflow = () => setScrollable(!!frame && frame.scrollWidth > frame.clientWidth + 2);
779 createEffect(() => {
780 queueMicrotask(checkOverflow);
781 if (typeof ResizeObserver === "undefined" || !frame) return;
782 const observer = new ResizeObserver(checkOverflow);
783 observer.observe(frame);
784 onCleanup(() => observer.disconnect());
785 });
786 // The hint sits under the frame, not floated inside it: pinned to the
787 // frame's bottom edge it covered the last row's action button.
788 return (
789 <div class="space-y-1">
790 <div ref={frame} class={cn("data-table-wrap relative", props.class)} data-scrollable={scrollable() ? "" : undefined}>
791 {props.children}
792 </div>
793 <Show when={scrollable()}>
794 <p class="flex justify-end text-[11px] font-medium text-muted-foreground" aria-hidden="true">
795 ↔ {t("common.scrollHint")}
796 </p>
797 </Show>
798 </div>
799 );
800}
801
802export function DataTableEmpty(props: ParentProps<{ class?: string }>) {
803 return (
804 <div class={cn("rounded-xl border border-dashed border-border-line bg-surface-overlay px-6 py-10 text-center text-sm leading-6 text-text-subtle", props.class)}>
805 {props.children}
806 </div>
807 );
808}
809
810export function DataTableSkeleton(props: { rows?: number; columns?: number }) {
811 const rows = () => Array.from({ length: props.rows ?? 6 });
812 const columns = () => Array.from({ length: props.columns ?? 5 });
813 return (
814 <DataTableFrame class="animate-pulse">
815 <table class="data-table">
816 <thead>
817 <tr>
818 <For each={columns()}>
819 {() => (
820 <th>
821 <div class="h-2.5 w-20 rounded-full bg-muted" />
822 </th>
823 )}
824 </For>
825 </tr>
826 </thead>
827 <tbody>
828 <For each={rows()}>
829 {() => (
830 <tr>
831 <For each={columns()}>
832 {() => (
833 <td>
834 <div class="h-3 w-full max-w-32 rounded-full bg-muted/80" />
835 </td>
836 )}
837 </For>
838 </tr>
839 )}
840 </For>
841 </tbody>
842 </table>
843 </DataTableFrame>
844 );
845}