fix: separate Filter Segment implementation from DataTableProvider (#20587)
* fix: separate Filter Segment implementation from DataTableProvider * disable components * early return * fix type error * add missing export
This commit is contained in:
1 parent
70eff63529
commit
5935cf7f1b
14 files changed
+123
-68
No files matched your search
@@ -0,0 +1,178 @@
|
||||
"use client";
|
||||
|
||||
import type { Header, Table, ColumnSizingState } from "@tanstack/react-table";
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import debounce from "lodash/debounce";
|
||||
import { useCallback, useEffect, useRef, useMemo } from "react";
|
||||
|
||||
import { useDebouncedWidth, useDataTable } from ".";
|
||||
|
||||
type UseColumnResizingProps<TData> = {
|
||||
enabled: boolean;
|
||||
table: Table<TData>;
|
||||
tableContainerRef: React.RefObject<HTMLDivElement>;
|
||||
};
|
||||
|
||||
function getAdjustedColumnSizing<TData>({
|
||||
headers,
|
||||
containerWidth,
|
||||
initialColumnSizing,
|
||||
currentColumnSizing,
|
||||
resizedColumns,
|
||||
}: {
|
||||
headers: Header<TData, unknown>[];
|
||||
containerWidth: number;
|
||||
initialColumnSizing: ColumnSizingState;
|
||||
currentColumnSizing: ColumnSizingState;
|
||||
resizedColumns: Set<string>;
|
||||
}) {
|
||||
// Return early if any column has auto width
|
||||
const hasAutoWidthColumn = headers.some((header) => header.column.columnDef.meta?.autoWidth);
|
||||
if (hasAutoWidthColumn) {
|
||||
return currentColumnSizing;
|
||||
}
|
||||
|
||||
const getColumnSize = (header: Header<TData, unknown>) => {
|
||||
const id = header.id;
|
||||
if (!initialColumnSizing[id]) {
|
||||
initialColumnSizing[id] = header.getSize();
|
||||
}
|
||||
if (resizedColumns.has(id)) {
|
||||
return currentColumnSizing[id] ?? initialColumnSizing[id];
|
||||
}
|
||||
return initialColumnSizing[id];
|
||||
};
|
||||
|
||||
const isAdjustable = (header: Header<TData, unknown>) =>
|
||||
header.column.columnDef.enableResizing !== false && !resizedColumns.has(header.id);
|
||||
|
||||
// Calculate how many columns can be adjusted
|
||||
const numberOfAdjustableColumns = headers.filter(isAdjustable).length;
|
||||
|
||||
// Calculate widths and required adjustments
|
||||
const totalColumnsWidth = headers.reduce((total, header) => total + getColumnSize(header), 0);
|
||||
const widthToFill = Math.max(0, containerWidth - totalColumnsWidth);
|
||||
const widthPerAdjustableColumn =
|
||||
numberOfAdjustableColumns === 0 ? 0 : Math.floor(widthToFill / numberOfAdjustableColumns);
|
||||
|
||||
// Handle any leftover width (due to rounding)
|
||||
const leftoverWidth = widthToFill - widthPerAdjustableColumn * numberOfAdjustableColumns;
|
||||
|
||||
// Build the new column sizing object
|
||||
const newColumnSizing = headers.reduce((acc, header, index) => {
|
||||
const baseWidth = getColumnSize(header);
|
||||
const adjustmentWidth = isAdjustable(header) ? widthPerAdjustableColumn : 0;
|
||||
const isLastColumn = index === headers.length - 1;
|
||||
const extraWidth = isLastColumn ? leftoverWidth : 0;
|
||||
|
||||
acc[header.id] = baseWidth + adjustmentWidth + extraWidth;
|
||||
return acc;
|
||||
}, {} as ColumnSizingState);
|
||||
|
||||
return newColumnSizing;
|
||||
}
|
||||
|
||||
function getPartialColumnSizing(columnSizing: ColumnSizingState, columnsToExtract: Set<string>) {
|
||||
return Object.keys(columnSizing).reduce((acc, key) => {
|
||||
if (columnsToExtract.has(key)) {
|
||||
acc[key] = columnSizing[key];
|
||||
}
|
||||
return acc;
|
||||
}, {} as ColumnSizingState);
|
||||
}
|
||||
|
||||
export function useColumnResizing<TData>({
|
||||
enabled,
|
||||
table,
|
||||
tableContainerRef,
|
||||
}: UseColumnResizingProps<TData>) {
|
||||
const initialized = useRef(false);
|
||||
const columnSizing = useRef<ColumnSizingState>({});
|
||||
const initialColumnSizing = useRef<ColumnSizingState>({});
|
||||
const resizedColumns = useRef<Set<string>>(new Set());
|
||||
const { columnSizing: loadedColumnSizing, setColumnSizing: setColumnSizingToContext } = useDataTable();
|
||||
|
||||
const debouncedSaveColumnSizing = useMemo(
|
||||
() => debounce(setColumnSizingToContext, 1000),
|
||||
[setColumnSizingToContext]
|
||||
);
|
||||
|
||||
const adjustColumnSizing = useCallback(
|
||||
(updater: ColumnSizingState | ((old: ColumnSizingState) => ColumnSizingState)) => {
|
||||
table.setState((oldTableState) => {
|
||||
let newColumnSizing = typeof updater === "function" ? updater(oldTableState.columnSizing) : updater;
|
||||
newColumnSizing = getAdjustedColumnSizing({
|
||||
headers: table.getFlatHeaders(),
|
||||
containerWidth: tableContainerRef.current?.clientWidth || 0,
|
||||
initialColumnSizing: initialColumnSizing.current,
|
||||
currentColumnSizing: newColumnSizing,
|
||||
resizedColumns: resizedColumns.current,
|
||||
});
|
||||
debouncedSaveColumnSizing(getPartialColumnSizing(newColumnSizing, resizedColumns.current));
|
||||
columnSizing.current = newColumnSizing;
|
||||
|
||||
return {
|
||||
...oldTableState,
|
||||
columnSizing: newColumnSizing,
|
||||
};
|
||||
});
|
||||
},
|
||||
[table, tableContainerRef, debouncedSaveColumnSizing]
|
||||
);
|
||||
|
||||
const onColumnSizingChange = useCallback(
|
||||
(updater: ColumnSizingState | ((old: ColumnSizingState) => ColumnSizingState)) => {
|
||||
const isResizingColumn = table.getState().columnSizingInfo.isResizingColumn;
|
||||
if (isResizingColumn) {
|
||||
resizedColumns.current.add(isResizingColumn);
|
||||
}
|
||||
adjustColumnSizing(updater);
|
||||
},
|
||||
[table, adjustColumnSizing]
|
||||
);
|
||||
|
||||
const debouncedContainerWidth = useDebouncedWidth(tableContainerRef);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !initialized.current) return;
|
||||
const newColumnSizing = getAdjustedColumnSizing({
|
||||
headers: table.getFlatHeaders(),
|
||||
containerWidth: debouncedContainerWidth,
|
||||
initialColumnSizing: initialColumnSizing.current,
|
||||
currentColumnSizing: columnSizing.current,
|
||||
resizedColumns: resizedColumns.current,
|
||||
});
|
||||
|
||||
columnSizing.current = newColumnSizing;
|
||||
table.setState((old) => ({
|
||||
...old,
|
||||
columnSizing: newColumnSizing,
|
||||
}));
|
||||
}, [debouncedContainerWidth, table.getFlatHeaders().length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
|
||||
// loadedColumnSizing is a partial object of explicitly resized columns.
|
||||
// combine loaded sizes and the default sizes from TanStack Table
|
||||
initialColumnSizing.current = table.getFlatHeaders().reduce((acc, header) => {
|
||||
acc[header.id] = loadedColumnSizing[header.id] || header.getSize();
|
||||
return acc;
|
||||
}, {} as ColumnSizingState);
|
||||
|
||||
columnSizing.current = loadedColumnSizing;
|
||||
resizedColumns.current = new Set(Object.keys(loadedColumnSizing));
|
||||
|
||||
table.setState((old) => ({
|
||||
...old,
|
||||
columnSizing: loadedColumnSizing,
|
||||
}));
|
||||
table.setOptions((prev) => ({
|
||||
...prev,
|
||||
columnResizeMode: "onChange",
|
||||
onColumnSizingChange,
|
||||
}));
|
||||
|
||||
initialized.current = true;
|
||||
}, [enabled, table, onColumnSizingChange]);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { isEqual } from "lodash";
|
||||
import { useCallback, useMemo, useEffect } from "react";
|
||||
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
import { ZSegmentStorage, type UseSegments } from "../lib/types";
|
||||
|
||||
export const useSegments: UseSegments = ({
|
||||
tableIdentifier,
|
||||
activeFilters,
|
||||
sorting,
|
||||
columnVisibility,
|
||||
columnSizing,
|
||||
pageSize,
|
||||
searchTerm,
|
||||
defaultPageSize,
|
||||
segmentId,
|
||||
setSegmentId,
|
||||
setActiveFilters,
|
||||
setSorting,
|
||||
setColumnVisibility,
|
||||
setColumnSizing,
|
||||
setPageSize,
|
||||
setPageIndex,
|
||||
setSearchTerm,
|
||||
}) => {
|
||||
const { data: segments, isFetching: isFetchingSegments } = trpc.viewer.filterSegments.list.useQuery({
|
||||
tableIdentifier,
|
||||
});
|
||||
const selectedSegment = useMemo(
|
||||
() => segments?.find((segment) => segment.id === segmentId),
|
||||
[segments, segmentId]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (segments && segmentId > 0 && !isFetchingSegments) {
|
||||
const segment = segments.find((segment) => segment.id === segmentId);
|
||||
if (!segment) {
|
||||
// If segmentId is invalid (or not found), clear the segmentId from the query params,
|
||||
// but we still keep all the other states like activeFilters, etc.
|
||||
// This is useful when someone shares a URL that is inaccessible to someone else.
|
||||
setSegmentId(null);
|
||||
}
|
||||
}
|
||||
}, [segments, segmentId, setSegmentId, isFetchingSegments]);
|
||||
|
||||
useEffect(() => {
|
||||
// this hook doesn't include segmentId in the dependency array
|
||||
// because we want to only run this once, when the component mounts
|
||||
if (segmentId === -1) {
|
||||
const segments = getSegmentsFromLocalStorage();
|
||||
if (segments[tableIdentifier]) {
|
||||
setSegmentId(segments[tableIdentifier].segmentId);
|
||||
}
|
||||
}
|
||||
}, [tableIdentifier, setSegmentId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedSegment) {
|
||||
// segment is selected, so we apply the filters, sorting, etc. from the segment
|
||||
setActiveFilters(selectedSegment.activeFilters);
|
||||
setSorting(selectedSegment.sorting);
|
||||
setColumnVisibility(selectedSegment.columnVisibility);
|
||||
setColumnSizing(selectedSegment.columnSizing);
|
||||
setPageSize(selectedSegment.perPage);
|
||||
setSearchTerm(selectedSegment.searchTerm);
|
||||
setPageIndex(0);
|
||||
}
|
||||
}, [
|
||||
selectedSegment,
|
||||
setActiveFilters,
|
||||
setSorting,
|
||||
setColumnVisibility,
|
||||
setColumnSizing,
|
||||
setPageSize,
|
||||
setPageIndex,
|
||||
setSearchTerm,
|
||||
]);
|
||||
|
||||
const canSaveSegment = useMemo(() => {
|
||||
if (!selectedSegment) {
|
||||
// if no segment is selected, we can save the segment if there are any active filters, sorting, etc.
|
||||
return (
|
||||
activeFilters.length > 0 ||
|
||||
sorting.length > 0 ||
|
||||
Object.keys(columnVisibility).length > 0 ||
|
||||
Object.keys(columnSizing).length > 0 ||
|
||||
pageSize !== defaultPageSize ||
|
||||
searchTerm?.length > 0
|
||||
);
|
||||
} else {
|
||||
// if a segment is selected, we can save the segment if the active filters, sorting, etc. are different from the segment
|
||||
return (
|
||||
!isEqual(activeFilters, selectedSegment.activeFilters) ||
|
||||
!isEqual(sorting, selectedSegment.sorting) ||
|
||||
!isEqual(columnVisibility, selectedSegment.columnVisibility) ||
|
||||
!isEqual(columnSizing, selectedSegment.columnSizing) ||
|
||||
!isEqual(pageSize, selectedSegment.perPage) ||
|
||||
!isEqual(searchTerm, selectedSegment.searchTerm)
|
||||
);
|
||||
}
|
||||
}, [
|
||||
selectedSegment,
|
||||
activeFilters,
|
||||
sorting,
|
||||
columnVisibility,
|
||||
columnSizing,
|
||||
pageSize,
|
||||
searchTerm,
|
||||
defaultPageSize,
|
||||
]);
|
||||
|
||||
const setAndPersistSegmentId = useCallback(
|
||||
(segmentId: number | null) => {
|
||||
setSegmentId(segmentId);
|
||||
saveSegmentToLocalStorage({ tableIdentifier, segmentId });
|
||||
},
|
||||
[tableIdentifier, setSegmentId]
|
||||
);
|
||||
|
||||
return {
|
||||
segments: segments ?? [],
|
||||
selectedSegment,
|
||||
canSaveSegment,
|
||||
setAndPersistSegmentId,
|
||||
isSegmentEnabled: true,
|
||||
};
|
||||
};
|
||||
|
||||
const LOCAL_STORAGE_KEY = "data-table:segments";
|
||||
|
||||
function getSegmentsFromLocalStorage() {
|
||||
try {
|
||||
return ZSegmentStorage.parse(JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY) ?? "{}"));
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function saveSegmentToLocalStorage({
|
||||
tableIdentifier,
|
||||
segmentId,
|
||||
}: {
|
||||
tableIdentifier: string;
|
||||
segmentId: number | null;
|
||||
}) {
|
||||
const segments = getSegmentsFromLocalStorage();
|
||||
if (segmentId) {
|
||||
segments[tableIdentifier] = { segmentId };
|
||||
} else {
|
||||
delete segments[tableIdentifier];
|
||||
}
|
||||
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(segments));
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { noop } from "lodash";
|
||||
|
||||
import { type UseSegments } from "../lib/types";
|
||||
|
||||
export const useSegmentsNoop: UseSegments = ({}) => {
|
||||
return {
|
||||
segments: [],
|
||||
selectedSegment: undefined,
|
||||
canSaveSegment: false,
|
||||
setAndPersistSegmentId: noop,
|
||||
isSegmentEnabled: false,
|
||||
};
|
||||
};
|
||||
Reference in new issue
Block a user