refactor: Move trpc-dependent components from features to web [2] (#26420)
* fix * move event types components to web * update import paths * mv apps components * migrate form builder * fix * mv sso * fix * mv * update import paths * update import paths * mv * mv * mv * fix * update Booker * fix * fix * fix * fix * mv video * mv embed components to web * update import paths * mv calendar weekly view components * update import paths * fix * fixp * fix * fix * fix * fix: update FormBuilder imports to use @calcom/features/form-builder Co-Authored-By: [email protected] <[email protected]> * fix: update broken import paths after file migrations Co-Authored-By: [email protected] <[email protected]> * fix: correct import paths for platform atoms and moved components Co-Authored-By: [email protected] <[email protected]> * fix: apply CSS type fixes and add missing atoms exports Co-Authored-By: [email protected] <[email protected]> * fix: resolve type errors in test files after component migrations Co-Authored-By: [email protected] <[email protected]> * fix: resolve remaining type errors in test files Co-Authored-By: [email protected] <[email protected]> * fix * migrate * fix: resolve type errors in test and mock files - Add missing bookingForm, bookerFormErrorRef, instantConnectCooldownMs to Booker.test.tsx bookings prop - Add all required BookerEvent properties to event.mock.ts - Add vi import from vitest to all mock files - Fix date parameter types in packages/dayjs/__mocks__/index.ts - Add verificationCode and setVerificationCode to test-utils.tsx mock store - Remove children.type access in Section.tsx mock to fix type error - Fix lint issues: remove unused React imports, use import type where needed, add return types - Add biome-ignore comments for pre-existing lint warnings in test files Co-Authored-By: [email protected] <[email protected]> * migrate * migrate * migrate * update import paths * update import paths * update import paths * fix * migrate data table * migrate data table * fix * fix * fix * migrate insights components * migrate insights components * fix * mv * update import paths * fix * fix * fix * fix * fix * fix: resolve type errors in test mocks - Booker.test.tsx: Add all required UseFormReturn methods to bookingForm mock - event.mock.ts: Fix entity, subsetOfHosts, instantMeetingParameters, fieldTranslations, image types - dayjs/__mocks__/index.ts: Use Object.assign for proper typing of mock properties - Section.tsx: Change 'class' to 'className' in JSX with biome-ignore comment Co-Authored-By: [email protected] <[email protected]> * fix: add missing hasDataErrors and dataErrors to bookings.errors mock Co-Authored-By: [email protected] <[email protected]> * fix: add missing loadingStates properties to bookings mock Co-Authored-By: [email protected] <[email protected]> * fix: add missing slots properties (setTentativeSelectedTimeslots, tentativeSelectedTimeslots, slotReservationId) Co-Authored-By: [email protected] <[email protected]> * fix: update quickAvailabilityChecks to include utcEndIso and use valid status type Co-Authored-By: [email protected] <[email protected]> * fix: add missing bookerForm properties (formName, beforeVerifyEmail, formErrors) Co-Authored-By: [email protected] <[email protected]> * fix: add missing UseFormReturn properties to bookerForm.bookingForm mock Co-Authored-By: [email protected] <[email protected]> * fix: add hasFormErrors and formErrors to bookerForm.formErrors mock Co-Authored-By: [email protected] <[email protected]> * fix: add hasFormErrors and formErrors to bookerForm.errors mock Co-Authored-By: [email protected] <[email protected]> * fix: add missing isError property to mockEvent Co-Authored-By: [email protected] <[email protected]> * fix: use complete BookerEvent mock in Booker.test.tsx Co-Authored-By: [email protected] <[email protected]> * fix: use branded bookingFields type in event mock Co-Authored-By: [email protected] <[email protected]> * fix: add missing schedule mock properties (isError, isSuccess, isLoading, dataUpdatedAt) Co-Authored-By: [email protected] <[email protected]> * revert * fix * fix * fix * fix build * fix * fix * fix * fix: correct AddMembersWithSwitch test wrapper to use initial assignAllTeamMembers value - Fixed test wrapper to initialize useState with componentProps.assignAllTeamMembers instead of hardcoded false, allowing tests to properly test different states - Updated test expectations for ALL_TEAM_MEMBERS_ENABLED_AND_SEGMENT_NOT_APPLICABLE state to match actual component behavior (toggle should be present and checked) - Fixed 'should show Segment when toggled on' test to start with assignAllTeamMembers: false to properly test the flow of enabling it - Added explicit types to satisfy biome lint requirements Co-Authored-By: [email protected] <[email protected]> * fix: use JSX.Element instead of React.JSX.Element for type compatibility Co-Authored-By: [email protected] <[email protected]> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
3d73238c00
commit
404d46c991
390 files changed
+645
-667
No files matched your search
@@ -0,0 +1,546 @@
|
||||
"use client";
|
||||
|
||||
import type { Row } from "@tanstack/react-table";
|
||||
import { flexRender } from "@tanstack/react-table";
|
||||
import type { Table as ReactTableType, Header, HeaderGroup } from "@tanstack/react-table";
|
||||
import { useVirtualizer, type Virtualizer, type VirtualItem } from "@tanstack/react-virtual";
|
||||
import kebabCase from "lodash/kebabCase";
|
||||
import { useEffect, useState, memo, useMemo } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Command, CommandList, CommandItem } from "@calcom/ui/components/command";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { Popover, PopoverTrigger, PopoverContent } from "@calcom/ui/components/popover";
|
||||
import {
|
||||
TableNew,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@calcom/ui/components/table";
|
||||
|
||||
import { useColumnSizingVars } from "@calcom/features/data-table/hooks";
|
||||
import { useColumnResizing } from "@calcom/features/data-table/hooks/useColumnResizing";
|
||||
import type { SeparatorRow } from "@calcom/features/data-table/lib/separator";
|
||||
import { isSeparatorRow } from "@calcom/features/data-table/lib/separator";
|
||||
|
||||
export type DataTablePropsFromWrapper<TData> = {
|
||||
table: ReactTableType<TData>;
|
||||
tableContainerRef: React.RefObject<HTMLDivElement>;
|
||||
isPending?: boolean;
|
||||
variant?: "default" | "compact";
|
||||
testId?: string;
|
||||
bodyTestId?: string;
|
||||
children?: React.ReactNode;
|
||||
enableColumnResizing?: boolean;
|
||||
className?: string;
|
||||
containerClassName?: string;
|
||||
headerClassName?: string;
|
||||
rowClassName?: string | ((row: Row<TData>) => string);
|
||||
rowTestId?: string | ((row: Row<TData>) => string | undefined);
|
||||
rowDataAttributes?: (row: Row<TData>) => Record<string, string> | undefined;
|
||||
paginationMode?: "infinite" | "standard";
|
||||
hasWrapperContext?: boolean;
|
||||
hideSeparatorsOnSort?: boolean;
|
||||
hideSeparatorsOnFilter?: boolean;
|
||||
separatorClassName?: string;
|
||||
};
|
||||
|
||||
export type DataTableProps<TData> = DataTablePropsFromWrapper<TData> & {
|
||||
onRowMouseclick?: (row: Row<TData>) => void;
|
||||
onScroll?: (e: Pick<React.UIEvent<HTMLDivElement, UIEvent>, "target">) => void;
|
||||
tableOverlay?: React.ReactNode;
|
||||
enableColumnResizing?: boolean;
|
||||
};
|
||||
|
||||
export function DataTable<TData>({
|
||||
table,
|
||||
tableContainerRef,
|
||||
isPending,
|
||||
variant,
|
||||
onRowMouseclick,
|
||||
onScroll,
|
||||
children,
|
||||
enableColumnResizing,
|
||||
testId,
|
||||
bodyTestId,
|
||||
className,
|
||||
containerClassName,
|
||||
headerClassName,
|
||||
rowClassName,
|
||||
rowTestId,
|
||||
rowDataAttributes,
|
||||
paginationMode = "infinite",
|
||||
hasWrapperContext = false,
|
||||
hideSeparatorsOnSort = true,
|
||||
hideSeparatorsOnFilter = false,
|
||||
separatorClassName,
|
||||
...rest
|
||||
}: DataTableProps<TData> & React.ComponentPropsWithoutRef<"div">) {
|
||||
const { rows } = table.getRowModel();
|
||||
|
||||
const rowVirtualizer = useVirtualizer({
|
||||
count: rows.length,
|
||||
estimateSize: () => 100,
|
||||
getScrollElement: () => tableContainerRef.current,
|
||||
measureElement:
|
||||
typeof window !== "undefined" && navigator.userAgent.indexOf("Firefox") === -1
|
||||
? (element) => element?.getBoundingClientRect().height
|
||||
: undefined,
|
||||
overscan: 10,
|
||||
});
|
||||
|
||||
const virtualItemsCount = rowVirtualizer.getVirtualItems().length;
|
||||
|
||||
useEffect(() => {
|
||||
if (paginationMode === "infinite" && virtualItemsCount >= rows.length && tableContainerRef.current) {
|
||||
const target = tableContainerRef.current;
|
||||
// Right after the last row is rendered, tableContainer's scrollHeight is
|
||||
// temporarily larger than the actual height of the table, so we need to
|
||||
// wait for a short time before calling onScroll to ensure the scrollHeight
|
||||
// is correct.
|
||||
setTimeout(() => {
|
||||
onScroll?.({ target });
|
||||
}, 100);
|
||||
}
|
||||
}, [virtualItemsCount, rows.length, tableContainerRef.current, paginationMode, onScroll]);
|
||||
|
||||
const columnSizingVars = useColumnSizingVars({ table });
|
||||
|
||||
useColumnResizing({
|
||||
enabled: Boolean(enableColumnResizing),
|
||||
table,
|
||||
tableContainerRef,
|
||||
});
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
!hasWrapperContext ? "grid" : "bg-cal-muted grid rounded-xl px-0.5 pb-0.5",
|
||||
className
|
||||
)}
|
||||
style={{
|
||||
gridTemplateRows: "auto 1fr auto",
|
||||
gridTemplateAreas: "'header' 'body' 'footer'",
|
||||
...rest.style,
|
||||
}}
|
||||
data-testid={testId ?? "data-table"}>
|
||||
{/*
|
||||
Invalidate left & right properties for <= sm screen size,
|
||||
because we pin columns only for >= sm screen sizes.
|
||||
*/}
|
||||
<style jsx global>{`
|
||||
@media (max-width: 640px) {
|
||||
.data-table th,
|
||||
.data-table td {
|
||||
left: initial !important;
|
||||
right: initial !important;
|
||||
}
|
||||
}
|
||||
`}</style>
|
||||
<div
|
||||
ref={tableContainerRef}
|
||||
onScroll={onScroll}
|
||||
className={classNames(
|
||||
"relative overflow-auto",
|
||||
"scrollbar-thin relative rounded-md ",
|
||||
paginationMode === "infinite" && "h-[80dvh]", // Set a fixed height for the container
|
||||
containerClassName
|
||||
)}
|
||||
style={{ gridArea: "body" }}>
|
||||
<TableNew
|
||||
className={classNames(
|
||||
"data-table grid border-0",
|
||||
!hasWrapperContext && "bg-cal-muted rounded-xl px-0.5 pb-0.5"
|
||||
)}
|
||||
style={{
|
||||
...columnSizingVars,
|
||||
...(Boolean(enableColumnResizing) && { width: table.getTotalSize() }),
|
||||
}}>
|
||||
<TableHeader className={classNames("sticky top-0 z-10", headerClassName)}>
|
||||
{table.getHeaderGroups().map((headerGroup: HeaderGroup<TData>) => (
|
||||
<TableRow key={headerGroup.id} className="hover:bg-subtle flex w-full border-none">
|
||||
{headerGroup.headers.map((header: Header<TData, unknown>) => {
|
||||
const { column } = header;
|
||||
return (
|
||||
<TableHead
|
||||
key={header.id}
|
||||
style={{
|
||||
...(column.getIsPinned() === "left" && { left: `${column.getStart("left")}px` }),
|
||||
...(column.getIsPinned() === "right" && { right: `${column.getStart("right")}px` }),
|
||||
width: `var(--header-${kebabCase(header?.id)}-size)`,
|
||||
}}
|
||||
className={classNames(
|
||||
"relative flex shrink-0 items-center",
|
||||
"bg-cal-muted",
|
||||
column.getIsPinned() && "top-0 z-20 sm:sticky"
|
||||
)}>
|
||||
<TableHeadLabel header={header} />
|
||||
{Boolean(enableColumnResizing) && header.column.getCanResize() && (
|
||||
<div
|
||||
onMouseDown={header.getResizeHandler()}
|
||||
onTouchStart={header.getResizeHandler()}
|
||||
className={classNames(
|
||||
"group absolute right-0 top-0 h-full w-[5px] cursor-col-resize touch-none select-none opacity-0 hover:opacity-50",
|
||||
header.column.getIsResizing() && "opacity-75!"
|
||||
)}>
|
||||
<div className="bg-inverted mx-auto h-full w-px" />
|
||||
</div>
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
{/* When resizing any column we will render this special memoized version of our table body */}
|
||||
{table.getState().columnSizingInfo.isResizingColumn ? (
|
||||
<MemoizedTableBody
|
||||
table={table}
|
||||
rowVirtualizer={rowVirtualizer}
|
||||
rows={rows}
|
||||
testId={bodyTestId}
|
||||
variant={variant}
|
||||
isPending={isPending}
|
||||
onRowMouseclick={onRowMouseclick}
|
||||
paginationMode={paginationMode}
|
||||
rowClassName={rowClassName}
|
||||
rowTestId={rowTestId}
|
||||
rowDataAttributes={rowDataAttributes}
|
||||
hideSeparatorsOnSort={hideSeparatorsOnSort}
|
||||
hideSeparatorsOnFilter={hideSeparatorsOnFilter}
|
||||
separatorClassName={separatorClassName}
|
||||
tableContainerRef={tableContainerRef}
|
||||
/>
|
||||
) : (
|
||||
<DataTableBody
|
||||
table={table}
|
||||
rowVirtualizer={rowVirtualizer}
|
||||
rows={rows}
|
||||
testId={bodyTestId}
|
||||
variant={variant}
|
||||
isPending={isPending}
|
||||
onRowMouseclick={onRowMouseclick}
|
||||
paginationMode={paginationMode}
|
||||
rowClassName={rowClassName}
|
||||
rowTestId={rowTestId}
|
||||
rowDataAttributes={rowDataAttributes}
|
||||
hideSeparatorsOnSort={hideSeparatorsOnSort}
|
||||
hideSeparatorsOnFilter={hideSeparatorsOnFilter}
|
||||
separatorClassName={separatorClassName}
|
||||
tableContainerRef={tableContainerRef}
|
||||
/>
|
||||
)}
|
||||
</TableNew>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const MemoizedTableBody = memo(
|
||||
DataTableBody,
|
||||
(prev, next) =>
|
||||
prev.table.options.data === next.table.options.data &&
|
||||
prev.rowVirtualizer === next.rowVirtualizer &&
|
||||
prev.rows === next.rows &&
|
||||
prev.testId === next.testId &&
|
||||
prev.variant === next.variant &&
|
||||
prev.isPending === next.isPending &&
|
||||
prev.onRowMouseclick === next.onRowMouseclick &&
|
||||
prev.paginationMode === next.paginationMode &&
|
||||
prev.rowClassName === next.rowClassName &&
|
||||
prev.rowTestId === next.rowTestId &&
|
||||
prev.rowDataAttributes === next.rowDataAttributes &&
|
||||
prev.hideSeparatorsOnSort === next.hideSeparatorsOnSort &&
|
||||
prev.hideSeparatorsOnFilter === next.hideSeparatorsOnFilter &&
|
||||
prev.separatorClassName === next.separatorClassName &&
|
||||
prev.tableContainerRef === next.tableContainerRef
|
||||
) as typeof DataTableBody;
|
||||
|
||||
type DataTableBodyProps<TData> = {
|
||||
table: ReactTableType<TData>;
|
||||
rowVirtualizer: Virtualizer<HTMLDivElement, Element>;
|
||||
rows: Row<TData>[];
|
||||
testId?: string;
|
||||
variant?: "default" | "compact";
|
||||
isPending?: boolean;
|
||||
onRowMouseclick?: (row: Row<TData>) => void;
|
||||
paginationMode?: "infinite" | "standard";
|
||||
rowClassName?: string | ((row: Row<TData>) => string);
|
||||
rowTestId?: string | ((row: Row<TData>) => string | undefined);
|
||||
rowDataAttributes?: (row: Row<TData>) => Record<string, string> | undefined;
|
||||
hideSeparatorsOnSort?: boolean;
|
||||
hideSeparatorsOnFilter?: boolean;
|
||||
separatorClassName?: string;
|
||||
tableContainerRef: React.RefObject<HTMLDivElement>;
|
||||
};
|
||||
|
||||
type RowToRender<TData> = {
|
||||
row: Row<TData>;
|
||||
virtualItem?: VirtualItem;
|
||||
};
|
||||
|
||||
function SeparatorRowRenderer({ separator, className }: { separator: SeparatorRow; className?: string }) {
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
"bg-cal-muted text-emphasis w-full px-3 py-2 font-semibold",
|
||||
separator.className,
|
||||
className
|
||||
)}>
|
||||
{separator.label}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DataTableBody<TData>({
|
||||
table,
|
||||
rowVirtualizer: _rowVirtualizer,
|
||||
rows,
|
||||
testId,
|
||||
variant,
|
||||
isPending,
|
||||
onRowMouseclick,
|
||||
paginationMode,
|
||||
rowClassName,
|
||||
rowTestId,
|
||||
rowDataAttributes,
|
||||
hideSeparatorsOnSort = true,
|
||||
hideSeparatorsOnFilter = false,
|
||||
separatorClassName,
|
||||
tableContainerRef,
|
||||
}: DataTableBodyProps<TData> & { paginationMode?: "infinite" | "standard" }) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const hasActiveSorting = table.getState().sorting.length > 0;
|
||||
const hasActiveFilters = table.getState().columnFilters.length > 0;
|
||||
|
||||
const filteredRows = useMemo(() => {
|
||||
if ((hideSeparatorsOnSort && hasActiveSorting) || (hideSeparatorsOnFilter && hasActiveFilters)) {
|
||||
return rows.filter((row) => !isSeparatorRow(row.original));
|
||||
}
|
||||
return rows;
|
||||
}, [rows, hideSeparatorsOnSort, hideSeparatorsOnFilter, hasActiveSorting, hasActiveFilters]);
|
||||
|
||||
const filteredRowVirtualizer = useVirtualizer({
|
||||
count: filteredRows.length,
|
||||
estimateSize: () => 100,
|
||||
getScrollElement: () => tableContainerRef.current,
|
||||
measureElement:
|
||||
typeof window !== "undefined" && navigator.userAgent.indexOf("Firefox") === -1
|
||||
? (element) => element?.getBoundingClientRect().height
|
||||
: undefined,
|
||||
overscan: 10,
|
||||
});
|
||||
|
||||
const virtualItems = filteredRowVirtualizer.getVirtualItems();
|
||||
const tableHeight = paginationMode === "infinite" ? filteredRowVirtualizer.getTotalSize() : "auto";
|
||||
|
||||
const rowsToRender = useMemo<RowToRender<TData>[]>(() => {
|
||||
return paginationMode === "infinite"
|
||||
? virtualItems.map((virtualItem) => ({
|
||||
row: filteredRows[virtualItem.index] as Row<TData>,
|
||||
virtualItem,
|
||||
}))
|
||||
: filteredRows.map((row) => ({ row }));
|
||||
}, [paginationMode, virtualItems, filteredRows]);
|
||||
|
||||
if (!isPending && rowsToRender.length === 0) {
|
||||
return (
|
||||
<TableBody className="relative grid" data-testid={testId} style={{ height: tableHeight }}>
|
||||
<TableRow>
|
||||
<TableCell colSpan={table.getAllColumns().length} className="h-24 text-center">
|
||||
{t("no_results")}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<TableBody
|
||||
className="border-muted relative grid border-t"
|
||||
data-testid={testId}
|
||||
style={{ height: tableHeight }}>
|
||||
{rowsToRender.map(({ row, virtualItem }) => {
|
||||
const isSeparator = isSeparatorRow(row.original);
|
||||
|
||||
if (isSeparator) {
|
||||
return (
|
||||
<TableRow
|
||||
ref={virtualItem ? (node) => filteredRowVirtualizer.measureElement(node) : undefined}
|
||||
key={row.id}
|
||||
data-index={virtualItem?.index}
|
||||
style={{
|
||||
display: "flex",
|
||||
width: "100%",
|
||||
...(virtualItem && {
|
||||
position: "absolute",
|
||||
transform: `translateY(${virtualItem.start}px)`,
|
||||
}),
|
||||
}}
|
||||
className="hover:bg-subtle border-muted flex w-full border-b">
|
||||
<SeparatorRowRenderer separator={row.original as SeparatorRow} className={separatorClassName} />
|
||||
</TableRow>
|
||||
);
|
||||
}
|
||||
|
||||
const computedRowTestId = typeof rowTestId === "function" ? rowTestId(row) : rowTestId;
|
||||
const computedRowClassName = typeof rowClassName === "function" ? rowClassName(row) : rowClassName;
|
||||
const computedDataAttributes = rowDataAttributes?.(row);
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
ref={virtualItem ? (node) => filteredRowVirtualizer.measureElement(node) : undefined}
|
||||
key={row.id}
|
||||
data-testid={computedRowTestId}
|
||||
{...computedDataAttributes}
|
||||
data-index={virtualItem?.index} // needed for dynamic row height measurement
|
||||
data-state={row.getIsSelected() && "selected"}
|
||||
onClick={(e) => {
|
||||
if (!onRowMouseclick) return;
|
||||
const target = e.target as Node | null;
|
||||
const current = e.currentTarget as HTMLElement | null;
|
||||
// Only invoke the handler when the event target is inside the row element.
|
||||
if (!target || !current || !current.contains(target)) return;
|
||||
onRowMouseclick(row);
|
||||
}}
|
||||
style={{
|
||||
display: "flex",
|
||||
...(virtualItem && {
|
||||
position: "absolute",
|
||||
transform: `translateY(${virtualItem.start}px)`,
|
||||
width: "100%",
|
||||
}),
|
||||
}}
|
||||
className={classNames(onRowMouseclick && "hover:cursor-pointer", "group", computedRowClassName)}>
|
||||
{row.getVisibleCells().map((cell) => {
|
||||
const column = cell.column;
|
||||
return (
|
||||
<TableCell
|
||||
key={cell.id}
|
||||
data-testid={`data-table-td-${cell.column.id}`}
|
||||
style={{
|
||||
...(column.getIsPinned() === "left" && { left: `${column.getStart("left")}px` }),
|
||||
...(column.getIsPinned() === "right" && { right: `${column.getStart("right")}px` }),
|
||||
width: `var(--col-${kebabCase(cell.column.id)}-size)`,
|
||||
}}
|
||||
className={classNames(
|
||||
"bg-default group-hover:!bg-cal-muted group-data-[state=selected]:bg-subtle flex shrink-0 items-center overflow-hidden",
|
||||
variant === "compact" && "p-0",
|
||||
column.getIsPinned() &&
|
||||
"bg-default group-hover:!bg-cal-muted group-data-[state=selected]:bg-subtle sm:sticky"
|
||||
)}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
);
|
||||
})}
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
);
|
||||
}
|
||||
|
||||
const TableHeadLabel = <TData,>({ header }: { header: Header<TData, unknown> }) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { t } = useLocale();
|
||||
|
||||
const canHide = header.column.getCanHide();
|
||||
const canSort = header.column.getCanSort();
|
||||
|
||||
if (!canSort && !canHide) {
|
||||
if (typeof header.column.columnDef.header === "string") {
|
||||
return (
|
||||
<div className="truncate" title={header.column.columnDef.header}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
return header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext());
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className={classNames(
|
||||
"group mr-1 flex w-full items-center gap-2 rounded-md px-2 py-1",
|
||||
open && "bg-cal-muted"
|
||||
)}>
|
||||
<div
|
||||
className="text-default truncate text-sm leading-none"
|
||||
title={
|
||||
typeof header.column.columnDef.header === "string" ? header.column.columnDef.header : undefined
|
||||
}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</div>
|
||||
{header.column.getIsSorted() === "asc" && <Icon name="arrow-up" className="h-4 w-4 shrink-0" />}
|
||||
{header.column.getIsSorted() === "desc" && <Icon name="arrow-down" className="h-4 w-4 shrink-0" />}
|
||||
<div className="grow" />
|
||||
<Icon
|
||||
name="chevrons-up-down"
|
||||
className={classNames(
|
||||
"text-subtle h-4 w-4 shrink-0",
|
||||
!open && "opacity-0 group-hover:opacity-100"
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="start" className="w-32 p-0">
|
||||
<Command>
|
||||
<CommandList>
|
||||
{canSort && (
|
||||
<>
|
||||
<CommandItem
|
||||
className="flex cursor-pointer items-center gap-2 px-3 py-2"
|
||||
onSelect={() => {
|
||||
if (header.column.getIsSorted() === "asc") {
|
||||
header.column.clearSorting();
|
||||
} else {
|
||||
header.column.toggleSorting(false, true);
|
||||
}
|
||||
}}>
|
||||
<Icon name="arrow-up" className="h-4 w-4" />
|
||||
{t("asc")}
|
||||
<div className="flex-1" />
|
||||
{header.column.getIsSorted() === "asc" && <Icon name="check" className="h-4 w-4" />}
|
||||
</CommandItem>
|
||||
<CommandItem
|
||||
className="flex cursor-pointer items-center gap-2 px-3 py-2"
|
||||
onSelect={() => {
|
||||
if (header.column.getIsSorted() === "desc") {
|
||||
header.column.clearSorting();
|
||||
} else {
|
||||
header.column.toggleSorting(true, true);
|
||||
}
|
||||
}}>
|
||||
<Icon name="arrow-down" className="h-4 w-4" />
|
||||
{t("desc")}
|
||||
<div className="flex-1" />
|
||||
{header.column.getIsSorted() === "desc" && <Icon name="check" className="h-4 w-4" />}
|
||||
</CommandItem>
|
||||
</>
|
||||
)}
|
||||
{canHide && (
|
||||
<CommandItem
|
||||
className="flex cursor-pointer items-center gap-2 px-3 py-2"
|
||||
onSelect={() => {
|
||||
header.column.toggleVisibility(false);
|
||||
setOpen(false);
|
||||
}}>
|
||||
<Icon name="eye-off" className="h-4 w-4" />
|
||||
{t("hide")}
|
||||
</CommandItem>
|
||||
)}
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { type Table } from "@tanstack/react-table";
|
||||
|
||||
import { Pagination } from "@calcom/ui/components/pagination";
|
||||
|
||||
import { useDataTable } from "@calcom/features/data-table/hooks";
|
||||
|
||||
interface DataTablePaginationProps<TData> {
|
||||
table: Table<TData>;
|
||||
totalRowCount?: number;
|
||||
paginationMode?: "infinite" | "standard";
|
||||
}
|
||||
|
||||
export function DataTablePagination<TData>({
|
||||
table,
|
||||
totalRowCount,
|
||||
paginationMode = "infinite",
|
||||
}: DataTablePaginationProps<TData>) {
|
||||
const { pageIndex, pageSize, setPageIndex, setPageSize } = useDataTable();
|
||||
if (!totalRowCount) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (paginationMode === "infinite") {
|
||||
const loadedCount = table.getRowModel().rows.length;
|
||||
return (
|
||||
<p className="text-subtle text-sm tabular-nums">
|
||||
Loaded <span className="text-default font-medium">{loadedCount}</span> of{" "}
|
||||
<span className="text-default font-medium">{totalRowCount}</span>
|
||||
</p>
|
||||
);
|
||||
} else if (paginationMode === "standard") {
|
||||
return (
|
||||
<Pagination
|
||||
currentPage={pageIndex + 1}
|
||||
pageSize={pageSize}
|
||||
totalItems={totalRowCount}
|
||||
onPageSizeChange={(newSize) => setPageSize(newSize)}
|
||||
onPageChange={(page) => setPageIndex(page - 1)}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
"use client";
|
||||
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
import { forwardRef } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button, type ButtonProps } from "@calcom/ui/components/button";
|
||||
import { Icon, type IconName } from "@calcom/ui/components/icon";
|
||||
|
||||
export type ActionItem<TData> =
|
||||
| {
|
||||
type: "action";
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
icon?: IconName;
|
||||
needsXSelected?: number;
|
||||
}
|
||||
| {
|
||||
type: "render";
|
||||
render: (table: Table<TData>) => React.ReactNode;
|
||||
needsXSelected?: number;
|
||||
};
|
||||
|
||||
type ResponsiveButtonProps = {
|
||||
className?: string;
|
||||
icon: IconName;
|
||||
onClick?: () => void;
|
||||
children: string;
|
||||
} & ButtonProps;
|
||||
|
||||
const ResponsiveButton = forwardRef<HTMLButtonElement, ResponsiveButtonProps>(
|
||||
({ icon, onClick, children, ...rest }, ref) => {
|
||||
return (
|
||||
<Button ref={ref} onClick={onClick} title={children} {...rest}>
|
||||
<Icon name={icon} size={18} className="sm:hidden" />
|
||||
<Icon name={icon} size={16} className="mr-2 hidden shrink-0 sm:inline" />
|
||||
<span className="sr-only shrink-0 md:not-sr-only">{children}</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
ResponsiveButton.displayName = "ResponsiveButton";
|
||||
|
||||
const Root = forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement> & { showSelectionCount?: boolean }
|
||||
>(({ children, ...props }, ref) => {
|
||||
const { className, style, ...rest } = props;
|
||||
return createPortal(
|
||||
<div
|
||||
ref={ref}
|
||||
className={classNames(
|
||||
"bg-default text-emphasis shadow-outline-gray-rested border-subtle fixed left-0 right-0 flex items-center space-x-1 overflow-x-auto border px-2 py-2 sm:space-x-2 md:left-1/2 md:z-auto md:w-fit md:-translate-x-1/2 md:transform md:space-x-3 md:overflow-x-hidden md:rounded-lg md:px-4",
|
||||
className
|
||||
)}
|
||||
style={{ ...style }}
|
||||
{...rest}>
|
||||
{children}
|
||||
</div>,
|
||||
document.body
|
||||
);
|
||||
});
|
||||
|
||||
Root.displayName = "Root";
|
||||
|
||||
export const DataTableSelectionBar = {
|
||||
Root,
|
||||
Button: ResponsiveButton,
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
import {
|
||||
TableNew,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@calcom/ui/components/table";
|
||||
|
||||
interface DataTableSkeletonProps {
|
||||
columns: number;
|
||||
rows?: number;
|
||||
columnWidths?: number[];
|
||||
}
|
||||
|
||||
export function DataTableSkeleton({ columns, rows = 10, columnWidths = [] }: DataTableSkeletonProps) {
|
||||
return (
|
||||
<div
|
||||
className="grid h-[75dvh]"
|
||||
style={{ gridTemplateRows: "auto 1fr auto", gridTemplateAreas: "'header' 'body' 'footer'" }}>
|
||||
<div
|
||||
className="scrollbar-thin border-subtle relative h-full overflow-auto rounded-md border"
|
||||
style={{ gridArea: "body" }}>
|
||||
<TableNew>
|
||||
<TableHeader className="bg-subtle sticky top-0 z-10">
|
||||
<TableRow>
|
||||
{[...Array(columns)].map((_, index) => (
|
||||
<TableHead key={`skeleton-header-${index}`}>
|
||||
<div
|
||||
className="bg-subtle h-4 animate-pulse rounded-md"
|
||||
style={{ width: columnWidths[index] ? `${columnWidths[index]}px` : "200px" }}
|
||||
/>
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{[...Array(rows)].map((_, rowIndex) => (
|
||||
<TableRow key={`skeleton-row-${rowIndex}`}>
|
||||
{[...Array(columns)].map((_, colIndex) => (
|
||||
<TableCell key={`skeleton-cell-${rowIndex}-${colIndex}`}>
|
||||
<div
|
||||
className="bg-subtle h-6 animate-pulse rounded-md"
|
||||
style={{ width: columnWidths[colIndex] ? `${columnWidths[colIndex]}px` : "200px" }}
|
||||
/>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</TableNew>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
import { forwardRef, useEffect } from "react";
|
||||
import type { ComponentPropsWithoutRef } from "react";
|
||||
import { useState, type Ref, type ChangeEvent } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button, type ButtonProps } from "@calcom/ui/components/button";
|
||||
import { FilterSearchField } from "@calcom/ui/components/form";
|
||||
|
||||
import { useColumnFilters, useDataTable } from "@calcom/features/data-table/hooks";
|
||||
|
||||
interface DataTableToolbarProps extends ComponentPropsWithoutRef<"div"> {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
const Root = forwardRef<HTMLDivElement, DataTableToolbarProps>(function DataTableToolbar(
|
||||
{ children, className },
|
||||
ref
|
||||
) {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={classNames("grid w-full items-center gap-2 py-4", className)}
|
||||
style={{ gridArea: "header" }}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
interface SearchBarProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function SearchBarComponent({ className }: SearchBarProps, ref: Ref<HTMLInputElement>) {
|
||||
const { searchTerm, setSearchTerm } = useDataTable();
|
||||
const { t } = useLocale();
|
||||
const [localValue, setLocalValue] = useState(searchTerm);
|
||||
|
||||
useEffect(() => {
|
||||
setLocalValue(searchTerm);
|
||||
}, [searchTerm]);
|
||||
|
||||
const handleSearchChange = (event: ChangeEvent<HTMLInputElement>) => {
|
||||
const value = event.target.value;
|
||||
setLocalValue(value);
|
||||
setSearchTerm(value);
|
||||
};
|
||||
|
||||
return (
|
||||
<FilterSearchField
|
||||
ref={ref}
|
||||
className={classNames("max-w-48", className)}
|
||||
placeholder={t("search")}
|
||||
value={localValue}
|
||||
onChange={handleSearchChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const SearchBar = forwardRef(SearchBarComponent) as (
|
||||
props: SearchBarProps & { ref?: React.Ref<HTMLInputElement> }
|
||||
) => ReturnType<typeof SearchBarComponent>;
|
||||
|
||||
interface ClearFiltersButtonProps<TData> {
|
||||
table: Table<TData>;
|
||||
}
|
||||
|
||||
function ClearFiltersButtonComponent<TData>(
|
||||
{ table }: ClearFiltersButtonProps<TData>,
|
||||
ref: React.Ref<HTMLButtonElement>
|
||||
) {
|
||||
const { t } = useLocale();
|
||||
const columnFilters = useColumnFilters();
|
||||
const isFiltered = columnFilters.length > 0;
|
||||
if (!isFiltered) return null;
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
color="minimal"
|
||||
EndIcon="x"
|
||||
onClick={() => table.resetColumnFilters()}
|
||||
className="h-8 px-2 lg:px-3">
|
||||
{t("clear")}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
const ClearFiltersButton = forwardRef(ClearFiltersButtonComponent) as <TData>(
|
||||
props: ClearFiltersButtonProps<TData> & { ref?: React.Ref<HTMLButtonElement> }
|
||||
) => ReturnType<typeof ClearFiltersButtonComponent>;
|
||||
|
||||
function CTAComponent(
|
||||
{ children, onClick, color = "primary", ...rest }: ButtonProps,
|
||||
ref: React.Ref<HTMLButtonElement>
|
||||
) {
|
||||
return (
|
||||
<Button ref={ref} color={color} onClick={onClick} {...rest}>
|
||||
{children}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
const CTA = forwardRef(CTAComponent) as (
|
||||
props: ButtonProps & { ref?: React.Ref<HTMLButtonElement> }
|
||||
) => ReturnType<typeof CTAComponent>;
|
||||
|
||||
export const DataTableToolbar = { Root, SearchBar, ClearFiltersButton, CTA };
|
||||
@@ -0,0 +1,208 @@
|
||||
"use client";
|
||||
|
||||
import type { Row, VisibilityState } from "@tanstack/react-table";
|
||||
import { noop } from "lodash";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
import { useColumnFilters } from "@calcom/features/data-table/hooks/useColumnFilters";
|
||||
import { useDataTable } from "@calcom/features/data-table/hooks/useDataTable";
|
||||
import { useFetchMoreOnBottomReached } from "@calcom/features/data-table/hooks/useFetchMoreOnBottomReached";
|
||||
import type { DataTablePropsFromWrapper } from "./DataTable";
|
||||
import { DataTable } from "./DataTable";
|
||||
import { DataTablePagination } from "./DataTablePagination";
|
||||
|
||||
type BaseDataTableWrapperProps<TData> = Omit<
|
||||
DataTablePropsFromWrapper<TData>,
|
||||
"paginationMode" | "tableContainerRef"
|
||||
> & {
|
||||
totalRowCount?: number;
|
||||
ToolbarLeft?: React.ReactNode;
|
||||
ToolbarRight?: React.ReactNode;
|
||||
EmptyView?: React.ReactNode;
|
||||
LoaderView?: React.ReactNode;
|
||||
ErrorView?: React.ReactNode;
|
||||
hasError?: boolean;
|
||||
tableContainerRef?: React.RefObject<HTMLDivElement>;
|
||||
onRowMouseclick?: (row: Row<TData>) => void;
|
||||
rowTestId?: string | ((row: Row<TData>) => string | undefined);
|
||||
rowDataAttributes?: (row: Row<TData>) => Record<string, string> | undefined;
|
||||
};
|
||||
|
||||
type InfinitePaginationProps<TData> = BaseDataTableWrapperProps<TData> & {
|
||||
paginationMode: "infinite";
|
||||
hasNextPage: boolean;
|
||||
fetchNextPage: () => void;
|
||||
isFetching: boolean;
|
||||
};
|
||||
|
||||
type StandardPaginationProps<TData> = BaseDataTableWrapperProps<TData> & {
|
||||
paginationMode: "standard";
|
||||
hasNextPage?: never;
|
||||
fetchNextPage?: never;
|
||||
isFetching?: never;
|
||||
};
|
||||
|
||||
export type DataTableWrapperProps<TData> = InfinitePaginationProps<TData> | StandardPaginationProps<TData>;
|
||||
|
||||
export function DataTableWrapper<TData>({
|
||||
testId,
|
||||
bodyTestId,
|
||||
table,
|
||||
isPending,
|
||||
hasNextPage,
|
||||
fetchNextPage,
|
||||
isFetching,
|
||||
totalRowCount,
|
||||
variant,
|
||||
ToolbarLeft,
|
||||
ToolbarRight,
|
||||
EmptyView,
|
||||
LoaderView,
|
||||
ErrorView,
|
||||
hasError,
|
||||
className,
|
||||
containerClassName,
|
||||
headerClassName,
|
||||
rowClassName,
|
||||
rowTestId,
|
||||
rowDataAttributes,
|
||||
children,
|
||||
tableContainerRef: externalRef,
|
||||
paginationMode,
|
||||
onRowMouseclick,
|
||||
hideSeparatorsOnSort,
|
||||
hideSeparatorsOnFilter,
|
||||
separatorClassName,
|
||||
}: DataTableWrapperProps<TData>) {
|
||||
const internalRef = useRef<HTMLDivElement>(null);
|
||||
const tableContainerRef = externalRef || internalRef;
|
||||
const fetchMoreOnBottomReached = useFetchMoreOnBottomReached({
|
||||
tableContainerRef,
|
||||
hasNextPage: paginationMode === "infinite" ? hasNextPage : false,
|
||||
fetchNextPage: paginationMode === "infinite" ? fetchNextPage : noop,
|
||||
isFetching: paginationMode === "infinite" ? isFetching : false,
|
||||
enabled: paginationMode === "infinite",
|
||||
});
|
||||
const { sorting, setSorting, columnVisibility, setColumnVisibility } = useDataTable();
|
||||
const columnFilters = useColumnFilters();
|
||||
|
||||
useEffect(() => {
|
||||
const mergedColumnVisibility = {
|
||||
...table.initialState?.columnVisibility,
|
||||
...columnVisibility,
|
||||
} satisfies VisibilityState;
|
||||
|
||||
table.setState((prev) => ({
|
||||
...prev,
|
||||
sorting,
|
||||
columnFilters,
|
||||
columnVisibility: mergedColumnVisibility,
|
||||
}));
|
||||
table.setOptions((prev) => ({
|
||||
...prev,
|
||||
onSortingChange: setSorting,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
}));
|
||||
}, [table, sorting, columnFilters, columnVisibility, setSorting, setColumnVisibility]);
|
||||
|
||||
// Scroll to top when table data changes
|
||||
useScrollToTopOnDataChange({
|
||||
tableData: table.options.data,
|
||||
paginationMode,
|
||||
});
|
||||
|
||||
let view: "loader" | "empty" | "error" | "table" = "table";
|
||||
if (hasError && ErrorView) {
|
||||
view = "error";
|
||||
} else if (isPending && LoaderView) {
|
||||
view = "loader";
|
||||
} else if (table.getRowCount() === 0 && EmptyView) {
|
||||
view = "empty";
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{(ToolbarLeft || ToolbarRight || children) && (
|
||||
<div className="grid w-full items-center gap-2 pb-4">
|
||||
<div className="flex w-full flex-col gap-2">
|
||||
<div className="flex w-full flex-wrap justify-between gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">{ToolbarLeft}</div>
|
||||
<div className="flex flex-wrap items-center gap-2">{ToolbarRight}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
{view === "error" && ErrorView}
|
||||
{view === "loader" && LoaderView}
|
||||
{view === "empty" && EmptyView}
|
||||
{view === "table" && (
|
||||
<DataTable
|
||||
testId={testId}
|
||||
bodyTestId={bodyTestId}
|
||||
table={table}
|
||||
tableContainerRef={tableContainerRef}
|
||||
isPending={isPending}
|
||||
enableColumnResizing={true}
|
||||
variant={variant}
|
||||
className={className}
|
||||
containerClassName={containerClassName}
|
||||
headerClassName={headerClassName}
|
||||
rowClassName={rowClassName}
|
||||
rowTestId={rowTestId}
|
||||
rowDataAttributes={rowDataAttributes}
|
||||
paginationMode={paginationMode}
|
||||
onRowMouseclick={onRowMouseclick}
|
||||
hasWrapperContext={true}
|
||||
hideSeparatorsOnSort={hideSeparatorsOnSort}
|
||||
hideSeparatorsOnFilter={hideSeparatorsOnFilter}
|
||||
separatorClassName={separatorClassName}
|
||||
onScroll={
|
||||
paginationMode === "infinite"
|
||||
? (e: Pick<React.UIEvent<HTMLDivElement, UIEvent>, "target">) =>
|
||||
fetchMoreOnBottomReached(e.target as HTMLDivElement)
|
||||
: undefined
|
||||
}>
|
||||
<div style={{ gridArea: "footer" }} className="px-3 py-2">
|
||||
<DataTablePagination<TData>
|
||||
table={table}
|
||||
totalRowCount={totalRowCount}
|
||||
paginationMode={paginationMode}
|
||||
/>
|
||||
</div>
|
||||
</DataTable>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scrolls to top when table data changes (pagination, filters, etc.)
|
||||
* Only active for standard pagination mode where we show discrete pages
|
||||
*/
|
||||
function useScrollToTopOnDataChange<TData>({
|
||||
tableData,
|
||||
paginationMode,
|
||||
}: {
|
||||
tableData: TData[];
|
||||
paginationMode: "standard" | "infinite";
|
||||
}) {
|
||||
const previousDataRef = useRef(tableData);
|
||||
const isInitialMount = useRef(true);
|
||||
|
||||
useEffect(() => {
|
||||
// Skip on initial mount
|
||||
if (isInitialMount.current) {
|
||||
isInitialMount.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const hasDataChanged = previousDataRef.current !== tableData;
|
||||
previousDataRef.current = tableData;
|
||||
|
||||
if (paginationMode === "standard" && hasDataChanged) {
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
}, [tableData, paginationMode]);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
"use client";
|
||||
|
||||
import { type Table } from "@tanstack/react-table";
|
||||
|
||||
import { useDataTable, useFilterableColumns } from "@calcom/features/data-table/hooks";
|
||||
import { ColumnFilterType } from "@calcom/features/data-table/lib/types";
|
||||
import { DateRangeFilter } from "./DateRangeFilter";
|
||||
import { FilterPopover } from "./FilterPopover";
|
||||
|
||||
// Add the new ActiveFilters component
|
||||
interface ActiveFiltersProps<TData> {
|
||||
table: Table<TData>;
|
||||
columnIdsToHide?: string[];
|
||||
}
|
||||
|
||||
export function ActiveFilters<TData>({ table, columnIdsToHide }: ActiveFiltersProps<TData>) {
|
||||
const { activeFilters } = useDataTable();
|
||||
const filterableColumns = useFilterableColumns(table);
|
||||
|
||||
return (
|
||||
<>
|
||||
{activeFilters.map((filter) => {
|
||||
const column = filterableColumns.find((col) => col.id === filter.f);
|
||||
if (!column) {
|
||||
return null;
|
||||
}
|
||||
if (columnIdsToHide?.includes(column.id)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (column.type === ColumnFilterType.DATE_RANGE) {
|
||||
return (
|
||||
<DateRangeFilter
|
||||
key={column.id}
|
||||
column={column}
|
||||
options={column.dateRangeOptions}
|
||||
showColumnName
|
||||
showClearButton
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
return <FilterPopover key={column.id} column={column} />;
|
||||
}
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
"use client";
|
||||
|
||||
import { type Table } from "@tanstack/react-table";
|
||||
import startCase from "lodash/startCase";
|
||||
import { forwardRef, useState } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Command, CommandInput, CommandList, CommandEmpty, CommandItem } from "@calcom/ui/components/command";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { Popover, PopoverTrigger, PopoverContent } from "@calcom/ui/components/popover";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
import { useDataTable, useFilterableColumns } from "@calcom/features/data-table/hooks";
|
||||
|
||||
export interface AddFilterButtonProps<TData> {
|
||||
table: Table<TData>;
|
||||
variant?: "base" | "minimal";
|
||||
}
|
||||
|
||||
function AddFilterButtonComponent<TData>(
|
||||
{ table, variant = "base" }: AddFilterButtonProps<TData>,
|
||||
ref: React.Ref<HTMLButtonElement>
|
||||
) {
|
||||
const { t } = useLocale();
|
||||
const { activeFilters, addFilter, filterToOpen } = useDataTable();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const filterableColumns = useFilterableColumns(table);
|
||||
const availableColumns = filterableColumns.filter(
|
||||
(column) => !activeFilters?.some((filter) => filter.f === column.id)
|
||||
);
|
||||
|
||||
if (variant === "minimal" && availableColumns.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
{variant === "base" && (
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
ref={ref}
|
||||
color="secondary"
|
||||
data-testid="add-filter-button"
|
||||
StartIcon="list-filter"
|
||||
className="h-full">
|
||||
{t("filter")}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
)}
|
||||
{variant === "minimal" && (
|
||||
<Tooltip content={t("add_filter")}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button ref={ref} color="secondary" data-testid="add-filter-button" className="h-full">
|
||||
<span className="sr-only">{t("filter")}</span>
|
||||
<Icon name="plus" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
</Tooltip>
|
||||
)}
|
||||
<PopoverContent className="w-[200px] p-0" align="start">
|
||||
<Command>
|
||||
<CommandInput placeholder={t("search")} />
|
||||
<CommandList>
|
||||
<CommandEmpty>{t("no_columns_found")}</CommandEmpty>
|
||||
{availableColumns.map((column) => {
|
||||
const showHiddenIndicator =
|
||||
!table.getColumn(column.id)?.getIsVisible() &&
|
||||
table.initialState.columnVisibility?.[column.id] !== false;
|
||||
|
||||
return (
|
||||
<CommandItem
|
||||
key={column.id}
|
||||
onSelect={() => {
|
||||
if (filterToOpen) filterToOpen.current = column.id;
|
||||
addFilter(column.id);
|
||||
setOpen(false);
|
||||
}}
|
||||
className="flex items-center justify-between rounded-none px-4 py-2"
|
||||
data-testid={`add-filter-item-${column.id}`}>
|
||||
<span>{startCase(column.title)}</span>
|
||||
{showHiddenIndicator && <Icon name="eye-off" className="h-4 w-4 opacity-50" />}
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const AddFilterButton = forwardRef(AddFilterButtonComponent) as <TData>(
|
||||
props: AddFilterButtonProps<TData> & { ref?: React.Ref<HTMLButtonElement> }
|
||||
) => ReturnType<typeof AddFilterButtonComponent>;
|
||||
@@ -0,0 +1,170 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { buttonClasses } from "@calcom/ui/components/button";
|
||||
import {
|
||||
Command,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandItem,
|
||||
CommandSeparator,
|
||||
CommandGroup,
|
||||
} from "@calcom/ui/components/command";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
|
||||
import { useDataTable, useFilterValue } from "@calcom/features/data-table/hooks";
|
||||
import type {
|
||||
FacetedValue,
|
||||
FilterableColumn as _FilterableColumn,
|
||||
FilterValueSchema,
|
||||
} from "@calcom/features/data-table/lib/types";
|
||||
import type { FilterType } from "@calcom/types/data-table";
|
||||
|
||||
type FilterableColumn = Extract<
|
||||
_FilterableColumn,
|
||||
{ type: Extract<FilterType, "ms" | "ss"> }
|
||||
>;
|
||||
|
||||
type FilterableSelectColumn<T extends Extract<FilterType, "ms" | "ss">> =
|
||||
Extract<FilterableColumn, { type: T }>;
|
||||
|
||||
type FilterValue<T extends Extract<FilterType, "ms" | "ss">> = ReturnType<
|
||||
typeof useFilterValue<T, FilterValueSchema<T>>
|
||||
>;
|
||||
|
||||
export type BaseSelectFilterOptionsProps<
|
||||
T extends Extract<FilterType, "ms" | "ss">
|
||||
> = {
|
||||
column: FilterableSelectColumn<T>;
|
||||
filterValueSchema: FilterValueSchema<T>;
|
||||
isOptionSelected: (filterValue: FilterValue<T> | undefined, optionValue: string | number) => boolean;
|
||||
onOptionSelect: (
|
||||
column: FilterableSelectColumn<T>,
|
||||
currentFilterValue: FilterValue<T> | undefined,
|
||||
optionValue: string | number
|
||||
) => void;
|
||||
testIdPrefix: string;
|
||||
};
|
||||
|
||||
type SectionedOptions = {
|
||||
[section: string]: FacetedValue[];
|
||||
};
|
||||
|
||||
function getSectionedOptions(options: FacetedValue[]) {
|
||||
// First map and normalize the options
|
||||
const normalizedOptions = options
|
||||
.map((option) => {
|
||||
if (!option) return null;
|
||||
const {
|
||||
label: optionLabel,
|
||||
value: optionValue,
|
||||
section,
|
||||
} = typeof option === "string" ? { label: option, value: option, section: undefined } : option;
|
||||
return { label: optionLabel, value: optionValue, section };
|
||||
})
|
||||
.filter((option): option is NonNullable<typeof option> => option !== null);
|
||||
|
||||
// Group options by section
|
||||
const sectionedOptions: SectionedOptions = {};
|
||||
|
||||
let currentSection = "";
|
||||
normalizedOptions.forEach((option) => {
|
||||
const sectionKey = option.section ?? ""; // Use empty string for unsectioned items
|
||||
if (sectionKey && sectionKey !== currentSection) {
|
||||
currentSection = sectionKey;
|
||||
}
|
||||
if (!sectionedOptions[currentSection]) {
|
||||
sectionedOptions[currentSection] = [];
|
||||
}
|
||||
const { section: _, ...optionWithoutSection } = option;
|
||||
sectionedOptions[currentSection].push(optionWithoutSection);
|
||||
});
|
||||
|
||||
return sectionedOptions;
|
||||
}
|
||||
|
||||
export function BaseSelectFilterOptions<
|
||||
T extends Extract<FilterType, "ms" | "ss">
|
||||
>({
|
||||
column,
|
||||
filterValueSchema,
|
||||
isOptionSelected,
|
||||
onOptionSelect,
|
||||
testIdPrefix,
|
||||
}: BaseSelectFilterOptionsProps<T>) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const filterValue = useFilterValue(column.id, filterValueSchema);
|
||||
const { removeFilter } = useDataTable();
|
||||
|
||||
const options = useMemo(() => {
|
||||
const sectionedOptions = getSectionedOptions(column.options);
|
||||
|
||||
// Sort options within each section based on selection status
|
||||
Object.keys(sectionedOptions).forEach((section) => {
|
||||
sectionedOptions[section] = [
|
||||
...sectionedOptions[section].filter((option) => isOptionSelected(filterValue, option.value)),
|
||||
...sectionedOptions[section].filter((option) => !isOptionSelected(filterValue, option.value)),
|
||||
];
|
||||
});
|
||||
|
||||
// Flatten the sections back into an array with section information
|
||||
return Object.keys(sectionedOptions).flatMap((section) =>
|
||||
sectionedOptions[section].map((option, index) => ({
|
||||
section: section === "" || index > 0 ? undefined : section,
|
||||
...option,
|
||||
}))
|
||||
);
|
||||
}, [column.options, filterValue]);
|
||||
|
||||
return (
|
||||
<Command data-testid={`${testIdPrefix}-${column.id}`}>
|
||||
<CommandInput placeholder={t("search")} data-testid={`select-filter-options-search-${column.id}`} />
|
||||
<CommandList>
|
||||
<CommandEmpty>{t("no_options_available")}</CommandEmpty>
|
||||
{options.map((option, index) => {
|
||||
const { label: optionLabel, value: optionValue, section } = option;
|
||||
|
||||
return (
|
||||
<>
|
||||
{section && index !== 0 && <hr className="border-subtle my-1" />}
|
||||
{section && (
|
||||
<div className="text-subtle px-4 py-2 text-xs font-medium uppercase leading-none">
|
||||
{section}
|
||||
</div>
|
||||
)}
|
||||
<CommandItem
|
||||
key={optionValue}
|
||||
onSelect={() => onOptionSelect(column, filterValue, optionValue)}>
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle mr-2 flex h-4 w-4 items-center justify-center rounded-sm",
|
||||
isOptionSelected(filterValue, optionValue) ? "bg-primary-default" : "border opacity-50"
|
||||
)}>
|
||||
{isOptionSelected(filterValue, optionValue) && (
|
||||
<Icon name="check" className="text-primary-foreground h-4 w-4" />
|
||||
)}
|
||||
</div>
|
||||
{optionLabel}
|
||||
</CommandItem>
|
||||
</>
|
||||
);
|
||||
})}
|
||||
</CommandList>
|
||||
<CommandSeparator />
|
||||
<CommandGroup>
|
||||
<CommandItem
|
||||
onSelect={() => {
|
||||
removeFilter(column.id);
|
||||
}}
|
||||
className={classNames("w-full justify-center text-center", buttonClasses({ color: "secondary" }))}>
|
||||
{t("clear")}
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
</Command>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
import { useDataTable } from "@calcom/features/data-table/hooks/useDataTable";
|
||||
|
||||
export const ClearFiltersButton = ({ exclude }: { exclude?: string[] }) => {
|
||||
const { t } = useLocale();
|
||||
const { activeFilters, clearAll } = useDataTable();
|
||||
|
||||
if (!activeFilters?.length || (exclude && activeFilters.every((filter) => exclude.includes(filter.f)))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip content={t("clear_filters")}>
|
||||
<Button
|
||||
color="minimal"
|
||||
data-testid="clear-filters-button"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
StartIcon="x"
|
||||
onClick={() => clearAll(exclude)}>
|
||||
{t("clear")}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import { vi } from "vitest";
|
||||
import { useReactTable, getCoreRowModel, type Table, type Column } from "@tanstack/react-table";
|
||||
|
||||
import { ColumnVisibilityButton } from "./ColumnVisibilityButton";
|
||||
|
||||
let tableRef: Table<{ a: number; b: number; c: number }> | null = null;
|
||||
|
||||
const TestWrapper = () => {
|
||||
const data = useMemo(() => [{ a: 1, b: 2, c: 3 }], []);
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{ accessorKey: "a", header: "A" },
|
||||
{ accessorKey: "b", header: "B", enableHiding: true },
|
||||
{ accessorKey: "c", header: "C", enableHiding: true },
|
||||
],
|
||||
[]
|
||||
);
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
initialState: { columnVisibility: { b: false, c: false } },
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
tableRef = table;
|
||||
}, [table]);
|
||||
|
||||
return <ColumnVisibilityButton table={table} />;
|
||||
}
|
||||
|
||||
describe("ColumnVisibilityButton", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
tableRef = null;
|
||||
});
|
||||
|
||||
it("show_all_columns sets all columns visible", async () => {
|
||||
render(<TestWrapper />);
|
||||
|
||||
fireEvent.click(screen.getByText("display"));
|
||||
|
||||
const showAll = await screen.findByText("show_all_columns");
|
||||
fireEvent.click(showAll);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(tableRef).not.toBeNull();
|
||||
const allVisible = tableRef!.getAllLeafColumns().every((col: Column<{ a: number; b: number; c: number }, unknown>) => col.getIsVisible());
|
||||
expect(allVisible).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
"use client";
|
||||
|
||||
import { type Table } from "@tanstack/react-table";
|
||||
|
||||
import { forwardRef, useState } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { type ButtonProps, Button, buttonClasses } from "@calcom/ui/components/button";
|
||||
import {
|
||||
Command,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandSeparator,
|
||||
} from "@calcom/ui/components/command";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { Popover, PopoverTrigger, PopoverContent } from "@calcom/ui/components/popover";
|
||||
|
||||
export interface ColumnVisiblityProps<TData> {
|
||||
table: Table<TData>;
|
||||
}
|
||||
|
||||
function ColumnVisibilityButtonComponent<TData>(
|
||||
{
|
||||
children,
|
||||
color = "secondary",
|
||||
StartIcon = "sliders-vertical",
|
||||
table,
|
||||
...rest
|
||||
}: ColumnVisiblityProps<TData> & ButtonProps,
|
||||
ref: React.Ref<HTMLButtonElement>
|
||||
) {
|
||||
const { t } = useLocale();
|
||||
const allColumns = table.getAllLeafColumns();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button ref={ref} color={color} StartIcon={StartIcon} {...rest}>
|
||||
{children ? children : t("display")}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[200px] p-0" align="start">
|
||||
<Command>
|
||||
<CommandInput placeholder={t("search")} />
|
||||
<CommandList>
|
||||
<CommandEmpty>{t("no_columns_found")}</CommandEmpty>
|
||||
<CommandGroup heading={t("toggle_columns")}>
|
||||
{allColumns.map((column) => {
|
||||
const canHide = column.getCanHide();
|
||||
if (!column.columnDef.header || typeof column.columnDef.header !== "string" || !canHide)
|
||||
return null;
|
||||
const isVisible = column.getIsVisible();
|
||||
return (
|
||||
<CommandItem
|
||||
key={column.id}
|
||||
onSelect={() => {
|
||||
column.toggleVisibility(!isVisible);
|
||||
}}>
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle mr-2 flex h-4 w-4 items-center justify-center rounded-sm border",
|
||||
isVisible ? "text-emphasis" : "opacity-50 [&_svg]:invisible"
|
||||
)}>
|
||||
<Icon name="check" className={classNames("h-4 w-4", !isVisible && "invisible")} />
|
||||
</div>
|
||||
{column.columnDef.header}
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
<CommandSeparator className="mb-0" />
|
||||
<CommandGroup>
|
||||
<CommandItem
|
||||
onSelect={() => {
|
||||
table.toggleAllColumnsVisible(true);
|
||||
}}
|
||||
className={classNames(
|
||||
buttonClasses({ color: "secondary" }),
|
||||
"mt-0 w-full cursor-pointer justify-center text-center"
|
||||
)}>
|
||||
{t("show_all_columns")}
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
export const ColumnVisibilityButton = forwardRef(ColumnVisibilityButtonComponent) as <TData>(
|
||||
props: ColumnVisiblityProps<TData> & ButtonProps & { ref?: React.Ref<HTMLButtonElement> }
|
||||
) => ReturnType<typeof ColumnVisibilityButtonComponent>;
|
||||
@@ -0,0 +1,265 @@
|
||||
import { format } from "date-fns";
|
||||
import type { Dayjs } from "dayjs";
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { CURRENT_TIMEZONE } from "@calcom/lib/timezoneConstants";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button, buttonClasses } from "@calcom/ui/components/button";
|
||||
import {
|
||||
Command,
|
||||
CommandList,
|
||||
CommandItem,
|
||||
CommandGroup,
|
||||
CommandSeparator,
|
||||
} from "@calcom/ui/components/command";
|
||||
import { DateRangePicker } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@calcom/ui/components/popover";
|
||||
|
||||
import { useDataTable, useFilterValue } from "@calcom/features/data-table/hooks";
|
||||
import {
|
||||
CUSTOM_PRESET,
|
||||
CUSTOM_PRESET_VALUE,
|
||||
DEFAULT_PRESET,
|
||||
getDefaultStartDate,
|
||||
getDefaultEndDate,
|
||||
getDateRangeFromPreset,
|
||||
getCompatiblePresets,
|
||||
type PresetOption,
|
||||
} from "@calcom/features/data-table/lib/dateRange";
|
||||
import { preserveLocalTime } from "@calcom/features/data-table/lib/preserveLocalTime";
|
||||
import type { FilterableColumn, DateRangeFilterOptions } from "@calcom/features/data-table/lib/types";
|
||||
import { ZDateRangeFilterValue, ColumnFilterType } from "@calcom/features/data-table/lib/types";
|
||||
import type { FilterType } from "@calcom/types/data-table";
|
||||
import { useFilterPopoverOpen } from "./useFilterPopoverOpen";
|
||||
|
||||
type DateRangeFilterProps = {
|
||||
column: Extract<FilterableColumn, { type: Extract<FilterType, "dr"> }>;
|
||||
options?: DateRangeFilterOptions;
|
||||
showColumnName?: boolean;
|
||||
showClearButton?: boolean;
|
||||
};
|
||||
|
||||
export const DateRangeFilter = ({
|
||||
column,
|
||||
options,
|
||||
showColumnName = false,
|
||||
showClearButton = false,
|
||||
}: DateRangeFilterProps) => {
|
||||
const { open, onOpenChange } = useFilterPopoverOpen(column.id);
|
||||
const filterValue = useFilterValue(column.id, ZDateRangeFilterValue);
|
||||
const { updateFilter, removeFilter, timeZone: givenTimeZone } = useDataTable();
|
||||
const range = options?.range ?? "past";
|
||||
|
||||
const compatiblePresets = getCompatiblePresets(range);
|
||||
const showPresets = compatiblePresets.length > 1;
|
||||
const forceCustomOnly = range === "customOnly" || !showPresets;
|
||||
|
||||
const { t } = useLocale();
|
||||
const currentDate = dayjs();
|
||||
const [startDate, setStartDate] = useState<Dayjs | undefined>(
|
||||
filterValue?.data.startDate ? dayjs(filterValue.data.startDate) : undefined
|
||||
);
|
||||
const [endDate, setEndDate] = useState<Dayjs | undefined>(
|
||||
filterValue?.data.endDate ? dayjs(filterValue.data.endDate) : undefined
|
||||
);
|
||||
const [selectedPreset, setSelectedPreset] = useState<PresetOption>(
|
||||
forceCustomOnly
|
||||
? CUSTOM_PRESET
|
||||
: filterValue?.data.preset
|
||||
? compatiblePresets.find((o) => o.value === filterValue.data.preset) ?? DEFAULT_PRESET
|
||||
: DEFAULT_PRESET
|
||||
);
|
||||
|
||||
const convertTimestamp = useCallback(
|
||||
(timestamp: string) => {
|
||||
if (!options?.convertToTimeZone) {
|
||||
return timestamp;
|
||||
}
|
||||
if (!givenTimeZone || CURRENT_TIMEZONE === givenTimeZone) {
|
||||
return timestamp;
|
||||
}
|
||||
return preserveLocalTime(timestamp, CURRENT_TIMEZONE, givenTimeZone);
|
||||
},
|
||||
[options?.convertToTimeZone, givenTimeZone]
|
||||
);
|
||||
|
||||
const updateValues = useCallback(
|
||||
({ preset, startDate, endDate }: { preset: PresetOption; startDate?: Dayjs; endDate?: Dayjs }) => {
|
||||
setSelectedPreset(preset);
|
||||
setStartDate(startDate);
|
||||
setEndDate(endDate);
|
||||
|
||||
if (startDate && endDate) {
|
||||
updateFilter(column.id, {
|
||||
type: ColumnFilterType.DATE_RANGE,
|
||||
data: {
|
||||
startDate: convertTimestamp(startDate.toDate().toISOString()),
|
||||
endDate: convertTimestamp(endDate.toDate().toISOString()),
|
||||
preset: preset.value,
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
[column.id, updateFilter, convertTimestamp]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
// initially apply the default value
|
||||
// if the query param is not set yet
|
||||
if (!filterValue && !forceCustomOnly) {
|
||||
updateValues({
|
||||
preset: DEFAULT_PRESET,
|
||||
startDate: getDefaultStartDate(),
|
||||
endDate: getDefaultEndDate(),
|
||||
});
|
||||
}
|
||||
}, [filterValue, forceCustomOnly, updateValues]);
|
||||
|
||||
const updateDateRangeFromPreset = (val: string | null) => {
|
||||
if (val === CUSTOM_PRESET_VALUE) {
|
||||
updateValues({
|
||||
preset: CUSTOM_PRESET,
|
||||
startDate,
|
||||
endDate,
|
||||
});
|
||||
} else {
|
||||
const { preset, startDate, endDate } = getDateRangeFromPreset(val);
|
||||
updateValues({
|
||||
preset,
|
||||
startDate,
|
||||
endDate,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const updateDateRangeFromPicker = ({
|
||||
startDate,
|
||||
endDate,
|
||||
}: {
|
||||
startDate?: Date | undefined;
|
||||
endDate?: Date | undefined;
|
||||
}) => {
|
||||
// DateRangePicker returns the beginning of the day,
|
||||
// so we need to update `endDate` to the end of the day.
|
||||
updateValues({
|
||||
preset: CUSTOM_PRESET,
|
||||
startDate: startDate ? dayjs(startDate) : getDefaultStartDate(),
|
||||
endDate: endDate ? dayjs(endDate).add(1, "day").subtract(1, "millisecond") : undefined,
|
||||
});
|
||||
};
|
||||
|
||||
const isCustomPreset = selectedPreset.value === CUSTOM_PRESET_VALUE;
|
||||
|
||||
let customButtonLabel = t("date_range");
|
||||
if (startDate && endDate) {
|
||||
customButtonLabel = `${format(startDate.toDate(), "LLL dd, y")} - ${format(
|
||||
endDate.toDate(),
|
||||
"LLL dd, y"
|
||||
)}`;
|
||||
} else if (startDate) {
|
||||
customButtonLabel = `${format(startDate.toDate(), "LLL dd, y")} - ?`;
|
||||
}
|
||||
|
||||
const selectedValue = isCustomPreset
|
||||
? customButtonLabel
|
||||
: t(selectedPreset.labelKey, selectedPreset.i18nOptions);
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={onOpenChange}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
color="secondary"
|
||||
className="items-center capitalize"
|
||||
StartIcon="calendar-range"
|
||||
EndIcon="chevron-down"
|
||||
data-testid={`filter-popover-trigger-${column.id}`}>
|
||||
{showColumnName && (
|
||||
<>
|
||||
<span>{column.title}</span>
|
||||
<Badge variant="gray" className="ml-2">
|
||||
{selectedValue}
|
||||
</Badge>
|
||||
</>
|
||||
)}
|
||||
{!showColumnName && <span>{selectedValue}</span>}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="flex w-fit p-0" align="end">
|
||||
{isCustomPreset && (
|
||||
<div className="border-subtle border-r">
|
||||
<DateRangePicker
|
||||
dates={{
|
||||
startDate: startDate?.toDate(),
|
||||
endDate: endDate?.toDate(),
|
||||
}}
|
||||
data-testid="date-range-calendar"
|
||||
minDate={
|
||||
range === "past"
|
||||
? currentDate.subtract(2, "year").toDate()
|
||||
: range === "future"
|
||||
? currentDate.toDate()
|
||||
: null
|
||||
}
|
||||
maxDate={range === "past" ? currentDate.toDate() : undefined}
|
||||
disabled={false}
|
||||
onDatesChange={updateDateRangeFromPicker}
|
||||
withoutPopover={true}
|
||||
/>
|
||||
{forceCustomOnly && (
|
||||
<div className="border-subtle border-t px-2 py-3">
|
||||
<Button
|
||||
color="secondary"
|
||||
className="w-full justify-center"
|
||||
onClick={() => removeFilter(column.id)}>
|
||||
{t("clear")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{showPresets && (
|
||||
<Command className={classNames("w-40", isCustomPreset && "rounded-b-none")}>
|
||||
<CommandList>
|
||||
{compatiblePresets.map((option) => (
|
||||
<CommandItem
|
||||
key={option.value}
|
||||
data-testid={`date-range-options-${option.value}`}
|
||||
className={classNames(
|
||||
"cursor-pointer justify-between px-3 py-2 rounded-none",
|
||||
selectedPreset.value === option.value && "bg-emphasis"
|
||||
)}
|
||||
onSelect={() => {
|
||||
updateDateRangeFromPreset(option.value);
|
||||
}}>
|
||||
<span className="capitalize">{t(option.labelKey, option.i18nOptions)}</span>
|
||||
{selectedPreset.value === option.value && <Icon name="check" />}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandList>
|
||||
{showClearButton && (
|
||||
<>
|
||||
<CommandSeparator />
|
||||
<CommandGroup>
|
||||
<CommandItem
|
||||
onSelect={() => {
|
||||
removeFilter(column.id);
|
||||
}}
|
||||
className={classNames(
|
||||
"w-full justify-center text-center",
|
||||
buttonClasses({ color: "secondary" })
|
||||
)}>
|
||||
{t("clear")}
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
</>
|
||||
)}
|
||||
</Command>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
"use client";
|
||||
|
||||
import { type Table } from "@tanstack/react-table";
|
||||
|
||||
import { useDisplayedFilterCount } from "@calcom/features/data-table/hooks";
|
||||
import { ActiveFilters } from "./ActiveFilters";
|
||||
import { AddFilterButton } from "./AddFilterButton";
|
||||
|
||||
interface FilterBarProps<TData> {
|
||||
table: Table<TData>;
|
||||
columnIdsToHide?: string[];
|
||||
}
|
||||
|
||||
export function FilterBar<TData>({ table, columnIdsToHide }: FilterBarProps<TData>) {
|
||||
const displayedFilterCount = useDisplayedFilterCount({ columnIdsToHide });
|
||||
|
||||
return (
|
||||
<>
|
||||
{displayedFilterCount === 0 && <AddFilterButton table={table} />}
|
||||
<ActiveFilters table={table} columnIdsToHide={columnIdsToHide} />
|
||||
{displayedFilterCount > 0 && <AddFilterButton table={table} variant="minimal" />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import type { FilterableColumn } from "@calcom/features/data-table/lib/types";
|
||||
import { ColumnFilterType } from "@calcom/features/data-table/lib/types";
|
||||
import { MultiSelectFilterOptions } from "./MultiSelectFilterOptions";
|
||||
import { NumberFilterOptions } from "./NumberFilterOptions";
|
||||
import { SingleSelectFilterOptions } from "./SingleSelectFilterOptions";
|
||||
import { TextFilterOptions } from "./TextFilterOptions";
|
||||
|
||||
export type FilterOptionsProps = {
|
||||
column: FilterableColumn;
|
||||
};
|
||||
|
||||
export function FilterOptions({ column }: FilterOptionsProps) {
|
||||
if (column.type === ColumnFilterType.TEXT) {
|
||||
return <TextFilterOptions column={column} />;
|
||||
} else if (column.type === ColumnFilterType.MULTI_SELECT) {
|
||||
return <MultiSelectFilterOptions column={column} />;
|
||||
} else if (column.type === ColumnFilterType.SINGLE_SELECT) {
|
||||
return <SingleSelectFilterOptions column={column} />;
|
||||
} else if (column.type === ColumnFilterType.NUMBER) {
|
||||
return <NumberFilterOptions column={column} />;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
|
||||
import startCase from "lodash/startCase";
|
||||
|
||||
import type { FilterType } from "@calcom/types/data-table";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import type { IconName } from "@calcom/ui/components/icon";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@calcom/ui/components/popover";
|
||||
|
||||
import { useFilterValue } from "@calcom/features/data-table/hooks";
|
||||
import { type FilterableColumn, type FilterValue, ZFilterValue, ColumnFilterType } from "@calcom/features/data-table/lib/types";
|
||||
import {
|
||||
isSingleSelectFilterValue,
|
||||
isMultiSelectFilterValue,
|
||||
isTextFilterValue,
|
||||
isNumberFilterValue,
|
||||
} from "@calcom/features/data-table/lib/utils";
|
||||
import { FilterOptions } from "./FilterOptions";
|
||||
import { useFilterPopoverOpen } from "./useFilterPopoverOpen";
|
||||
import { numberFilterOperatorOptions, useTextFilterOperatorOptions } from "./utils";
|
||||
|
||||
const FILTER_ICONS: Record<FilterType, IconName> = {
|
||||
[ColumnFilterType.TEXT]: "file-text",
|
||||
[ColumnFilterType.NUMBER]: "binary",
|
||||
[ColumnFilterType.MULTI_SELECT]: "layers",
|
||||
[ColumnFilterType.SINGLE_SELECT]: "disc",
|
||||
[ColumnFilterType.DATE_RANGE]: "calendar-range",
|
||||
};
|
||||
|
||||
type FilterPopoverProps = {
|
||||
column: FilterableColumn;
|
||||
};
|
||||
|
||||
type SelectedLabelsProps = {
|
||||
column: FilterableColumn;
|
||||
filterValue?: FilterValue;
|
||||
};
|
||||
|
||||
function Operator({ children }: { children: React.ReactNode }) {
|
||||
return <span className="ml-2 text-sm lowercase opacity-75">{children}</span>;
|
||||
}
|
||||
|
||||
function AppliedTextFilterValue({ filterValue }: SelectedLabelsProps) {
|
||||
const textFilterOperatorOptions = useTextFilterOperatorOptions();
|
||||
if (!isTextFilterValue(filterValue)) return null;
|
||||
|
||||
const operator = filterValue.data.operator;
|
||||
const operatorOption = textFilterOperatorOptions.find((o) => o.value === operator);
|
||||
if (!operatorOption) return null;
|
||||
|
||||
if (!operatorOption.requiresOperand) {
|
||||
return <Operator>{operatorOption.label}</Operator>;
|
||||
}
|
||||
|
||||
const operand = filterValue.data.operand;
|
||||
return (
|
||||
<>
|
||||
<Operator>{operatorOption.label}</Operator>
|
||||
<Badge variant="gray" className="ml-2">
|
||||
{operand}
|
||||
</Badge>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AppliedNumberFilterValue({ filterValue }: SelectedLabelsProps) {
|
||||
if (!isNumberFilterValue(filterValue)) return null;
|
||||
|
||||
const operator = filterValue.data.operator;
|
||||
const operatorOption = numberFilterOperatorOptions.find((o) => o.value === operator);
|
||||
if (!operatorOption) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Operator>{operatorOption.label}</Operator>
|
||||
<Badge variant="gray" className="ml-2">
|
||||
{filterValue.data.operand}
|
||||
</Badge>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AppliedSelectFilterValue({ column, filterValue }: SelectedLabelsProps) {
|
||||
let text: string | undefined;
|
||||
let moreCount = 0;
|
||||
|
||||
if (isSingleSelectFilterValue(filterValue)) {
|
||||
const options = (column as FilterableColumn & { type: "ss" }).options;
|
||||
text = options.find((opt) => opt.value === filterValue.data)?.label;
|
||||
moreCount = 0;
|
||||
} else if (isMultiSelectFilterValue(filterValue)) {
|
||||
const options = (column as FilterableColumn & { type: "ms" }).options;
|
||||
text = options.find((opt) => opt.value === filterValue.data[0])?.label;
|
||||
moreCount = filterValue.data.length - 1;
|
||||
}
|
||||
|
||||
if (!text) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Badge variant="gray" className="ml-2">
|
||||
{text}
|
||||
</Badge>
|
||||
{moreCount > 0 && (
|
||||
<Badge variant="gray" className="ml-2">
|
||||
+{moreCount}
|
||||
</Badge>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AppliedFilterValue({
|
||||
column,
|
||||
filterValue,
|
||||
}: {
|
||||
column: FilterableColumn;
|
||||
filterValue?: FilterValue;
|
||||
}) {
|
||||
if (column.type === ColumnFilterType.TEXT) {
|
||||
return <AppliedTextFilterValue column={column} filterValue={filterValue} />;
|
||||
} else if (column.type === ColumnFilterType.NUMBER) {
|
||||
return <AppliedNumberFilterValue column={column} filterValue={filterValue} />;
|
||||
} else if (
|
||||
column.type === ColumnFilterType.SINGLE_SELECT ||
|
||||
column.type === ColumnFilterType.MULTI_SELECT
|
||||
) {
|
||||
return <AppliedSelectFilterValue column={column} filterValue={filterValue} />;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function FilterPopover({ column }: FilterPopoverProps) {
|
||||
const icon = column.icon || FILTER_ICONS[column.type];
|
||||
const filterValue = useFilterValue(column.id, ZFilterValue);
|
||||
const { open, onOpenChange } = useFilterPopoverOpen(column.id);
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={onOpenChange}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
color="secondary"
|
||||
className="h-[34px] items-center"
|
||||
StartIcon={icon}
|
||||
EndIcon="chevron-down"
|
||||
data-testid={`filter-popover-trigger-${column.id}`}>
|
||||
<span>{startCase(column.title)}</span>
|
||||
<AppliedFilterValue column={column} filterValue={filterValue} />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="p-0" align="start">
|
||||
<FilterOptions column={column} />
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
"use client";
|
||||
|
||||
import { useDataTable } from "@calcom/features/data-table/hooks";
|
||||
import type { FilterableColumn } from "@calcom/features/data-table/lib/types";
|
||||
import { ZMultiSelectFilterValue, ColumnFilterType } from "@calcom/features/data-table/lib/types";
|
||||
import type { FilterType } from "@calcom/types/data-table";
|
||||
import { BaseSelectFilterOptions } from "./BaseSelectFilterOptions";
|
||||
|
||||
export type MultiSelectFilterOptionsProps = {
|
||||
column: Extract<FilterableColumn, { type: Extract<FilterType, "ms"> }>;
|
||||
};
|
||||
|
||||
export function MultiSelectFilterOptions({ column }: MultiSelectFilterOptionsProps) {
|
||||
const { updateFilter } = useDataTable();
|
||||
|
||||
return (
|
||||
<BaseSelectFilterOptions<Extract<FilterType, "ms">>
|
||||
column={column}
|
||||
filterValueSchema={ZMultiSelectFilterValue}
|
||||
testIdPrefix="select-filter-options"
|
||||
isOptionSelected={(filterValue, optionValue) => {
|
||||
if (!filterValue?.data) return false;
|
||||
return filterValue.data.includes(optionValue);
|
||||
}}
|
||||
onOptionSelect={(column, filterValue, optionValue) => {
|
||||
const currentData = filterValue?.data ?? [];
|
||||
const newFilterValue = currentData.includes(optionValue)
|
||||
? currentData.filter((value) => value !== optionValue)
|
||||
: [...currentData, optionValue];
|
||||
updateFilter(column.id, { type: ColumnFilterType.MULTI_SELECT, data: newFilterValue });
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
"use client";
|
||||
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Form, Select, NumberInput } from "@calcom/ui/components/form";
|
||||
|
||||
import { useFilterValue, useDataTable } from "@calcom/features/data-table/hooks";
|
||||
import type { FilterableColumn } from "@calcom/features/data-table/lib/types";
|
||||
import { ZNumberFilterValue, ColumnFilterType } from "@calcom/features/data-table/lib/types";
|
||||
import type { FilterType } from "@calcom/types/data-table";
|
||||
import { numberFilterOperatorOptions } from "./utils";
|
||||
|
||||
export type NumberFilterOptionsProps = {
|
||||
column: Extract<FilterableColumn, { type: Extract<FilterType, "n"> }>;
|
||||
};
|
||||
|
||||
export function NumberFilterOptions({ column }: NumberFilterOptionsProps) {
|
||||
const { t } = useLocale();
|
||||
const filterValue = useFilterValue(column.id, ZNumberFilterValue);
|
||||
const { updateFilter, removeFilter } = useDataTable();
|
||||
|
||||
const form = useForm({
|
||||
defaultValues: {
|
||||
operatorOption: filterValue
|
||||
? numberFilterOperatorOptions.find((o) => o.value === filterValue.data.operator)
|
||||
: numberFilterOperatorOptions[0],
|
||||
operand: filterValue?.data.operand || "",
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="mx-3 my-2" data-testid={`number-filter-options-${column.id}`}>
|
||||
<Form
|
||||
form={form}
|
||||
handleSubmit={({ operatorOption, operand }) => {
|
||||
if (operatorOption) {
|
||||
updateFilter(column.id, {
|
||||
type: ColumnFilterType.NUMBER,
|
||||
data: {
|
||||
operator: operatorOption.value,
|
||||
operand: Number(operand),
|
||||
},
|
||||
});
|
||||
}
|
||||
}}>
|
||||
<div>
|
||||
<Controller
|
||||
name="operatorOption"
|
||||
control={form.control}
|
||||
render={({ field: { value } }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<Select
|
||||
data-testid={`number-filter-options-select-${column.id}`}
|
||||
className="basis-1/3"
|
||||
options={numberFilterOperatorOptions}
|
||||
value={value}
|
||||
isSearchable={false}
|
||||
onChange={(event) => {
|
||||
if (event) {
|
||||
form.setValue("operatorOption", { ...event }, { shouldDirty: true });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<NumberInput className="h-[38px] basis-2/3" {...form.register("operand")} />
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="bg-subtle -mx-3 my-2 h-px" role="separator" />
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<Button
|
||||
type="button"
|
||||
color="secondary"
|
||||
disabled={form.formState.isSubmitting}
|
||||
onClick={() => removeFilter(column.id)}>
|
||||
{t("clear")}
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
color="primary"
|
||||
loading={form.formState.isSubmitting}
|
||||
disabled={form.formState.isSubmitting}>
|
||||
{t("apply")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import type { FilterType } from "@calcom/types/data-table";
|
||||
|
||||
import { useDataTable } from "@calcom/features/data-table/hooks";
|
||||
import type { FilterableColumn } from "@calcom/features/data-table/lib/types";
|
||||
import { ZSingleSelectFilterValue, ColumnFilterType } from "@calcom/features/data-table/lib/types";
|
||||
import { BaseSelectFilterOptions } from "./BaseSelectFilterOptions";
|
||||
|
||||
export type SingleSelectFilterOptionsProps = {
|
||||
column: Extract<FilterableColumn, { type: Extract<FilterType, "ss"> }>;
|
||||
};
|
||||
|
||||
export function SingleSelectFilterOptions({ column }: SingleSelectFilterOptionsProps) {
|
||||
const { updateFilter } = useDataTable();
|
||||
|
||||
return (
|
||||
<BaseSelectFilterOptions<Extract<FilterType, "ss">>
|
||||
column={column}
|
||||
filterValueSchema={ZSingleSelectFilterValue}
|
||||
testIdPrefix="select-filter-options"
|
||||
isOptionSelected={(filterValue, optionValue) => filterValue?.data === optionValue}
|
||||
onOptionSelect={(column, filterValue, optionValue) => {
|
||||
updateFilter(column.id, { type: ColumnFilterType.SINGLE_SELECT, data: optionValue });
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
"use client";
|
||||
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Form, Select, Input } from "@calcom/ui/components/form";
|
||||
|
||||
import { useFilterValue, useDataTable } from "@calcom/features/data-table/hooks";
|
||||
import type { FilterableColumn } from "@calcom/features/data-table/lib/types";
|
||||
import { ZTextFilterValue, ColumnFilterType } from "@calcom/features/data-table/lib/types";
|
||||
import type { FilterType } from "@calcom/types/data-table";
|
||||
import { useTextFilterOperatorOptions } from "./utils";
|
||||
|
||||
export type TextFilterOptionsProps = {
|
||||
column: Extract<FilterableColumn, { type: Extract<FilterType, "t"> }>;
|
||||
};
|
||||
|
||||
export function TextFilterOptions({ column }: TextFilterOptionsProps) {
|
||||
const { t } = useLocale();
|
||||
const textFilterOperatorOptions = useTextFilterOperatorOptions(column.textOptions?.allowedOperators);
|
||||
const filterValue = useFilterValue(column.id, ZTextFilterValue);
|
||||
const { updateFilter, removeFilter } = useDataTable();
|
||||
|
||||
const form = useForm({
|
||||
defaultValues: {
|
||||
operatorOption: filterValue
|
||||
? textFilterOperatorOptions.find((o) => o.value === filterValue.data.operator)
|
||||
: textFilterOperatorOptions[0],
|
||||
operand: filterValue?.data.operand || "",
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="mx-3 my-2" data-testid={`text-filter-options-${column.id}`}>
|
||||
<Form
|
||||
form={form}
|
||||
handleSubmit={({ operatorOption, operand }) => {
|
||||
if (operatorOption) {
|
||||
updateFilter(column.id, {
|
||||
type: ColumnFilterType.TEXT,
|
||||
data: {
|
||||
operator: operatorOption.value,
|
||||
operand: operatorOption.requiresOperand ? operand : "",
|
||||
},
|
||||
});
|
||||
}
|
||||
}}>
|
||||
<div>
|
||||
<Controller
|
||||
name="operatorOption"
|
||||
control={form.control}
|
||||
render={({ field: { value } }) => (
|
||||
<>
|
||||
<Select
|
||||
data-testid={`text-filter-options-select-${column.id}`}
|
||||
options={textFilterOperatorOptions}
|
||||
value={value}
|
||||
isSearchable={false}
|
||||
onChange={(event) => {
|
||||
if (event) {
|
||||
form.setValue("operatorOption", { ...event }, { shouldDirty: true });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{value?.requiresOperand && (
|
||||
<Input
|
||||
className="mt-2"
|
||||
{...form.register("operand")}
|
||||
placeholder={column.textOptions?.placeholder}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="bg-subtle -mx-3 my-2 h-px" role="separator" />
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<Button
|
||||
type="button"
|
||||
color="secondary"
|
||||
disabled={form.formState.isSubmitting}
|
||||
onClick={() => removeFilter(column.id)}>
|
||||
{t("clear")}
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
color="primary"
|
||||
loading={form.formState.isSubmitting}
|
||||
disabled={form.formState.isSubmitting}>
|
||||
{t("apply")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { ActiveFilters } from "./ActiveFilters";
|
||||
import { AddFilterButton } from "./AddFilterButton";
|
||||
import { ClearFiltersButton } from "./ClearFiltersButton";
|
||||
import { ColumnVisibilityButton } from "./ColumnVisibilityButton";
|
||||
import { DateRangeFilter } from "./DateRangeFilter";
|
||||
import { FilterBar } from "./FilterBar";
|
||||
|
||||
// Update the export to include ActiveFilters
|
||||
export const DataTableFilters = {
|
||||
ColumnVisibilityButton,
|
||||
AddFilterButton,
|
||||
ActiveFilters,
|
||||
ClearFiltersButton,
|
||||
FilterBar,
|
||||
};
|
||||
|
||||
export { DateRangeFilter };
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { NumberFilterOperator, TextFilterOperator } from "@calcom/features/data-table/lib/types";
|
||||
|
||||
export type NumberFilterOperatorOption = {
|
||||
label: string;
|
||||
value: NumberFilterOperator;
|
||||
};
|
||||
|
||||
export type TextFilterOperatorOption = {
|
||||
label: string;
|
||||
value: TextFilterOperator;
|
||||
requiresOperand: boolean;
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
|
||||
import { useDataTable } from "@calcom/features/data-table/hooks";
|
||||
|
||||
export function useFilterPopoverOpen(columnId: string) {
|
||||
const { filterToOpen } = useDataTable();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
if (filterToOpen.current === columnId) {
|
||||
timeoutId = setTimeout(() => {
|
||||
setOpen(true);
|
||||
// Reset only if we still own the marker to avoid clobbering a newer selection.
|
||||
if (filterToOpen.current === columnId) {
|
||||
filterToOpen.current = undefined;
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
};
|
||||
}, [filterToOpen, columnId]);
|
||||
|
||||
const onOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
if (filterToOpen.current === columnId && !open) {
|
||||
filterToOpen.current = undefined;
|
||||
}
|
||||
setOpen(open);
|
||||
},
|
||||
[filterToOpen, columnId]
|
||||
);
|
||||
|
||||
return { open, onOpenChange };
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
import { type TextFilterOperator, textFilterOperators } from "@calcom/features/data-table/lib/types";
|
||||
import type { TextFilterOperatorOption, NumberFilterOperatorOption } from "./types";
|
||||
|
||||
export const numberFilterOperatorOptions: NumberFilterOperatorOption[] = [
|
||||
{ value: "eq", label: "=" },
|
||||
{ value: "neq", label: "≠" },
|
||||
{ value: "gt", label: ">" },
|
||||
{ value: "gte", label: "≥" },
|
||||
{ value: "lt", label: "<" },
|
||||
{ value: "lte", label: "≤" },
|
||||
];
|
||||
|
||||
export const useTextFilterOperatorOptions = (
|
||||
allowedOperators?: TextFilterOperator[]
|
||||
): TextFilterOperatorOption[] => {
|
||||
const { t } = useLocale();
|
||||
const operators = allowedOperators ?? textFilterOperators;
|
||||
const options = [
|
||||
{ value: "equals", label: t("filter_operator_is"), requiresOperand: true },
|
||||
{ value: "notEquals", label: t("filter_operator_is_not"), requiresOperand: true },
|
||||
{ value: "contains", label: t("filter_operator_contains"), requiresOperand: true },
|
||||
{ value: "notContains", label: t("filter_operator_does_not_contain"), requiresOperand: true },
|
||||
{ value: "startsWith", label: t("filter_operator_starts_with"), requiresOperand: true },
|
||||
{ value: "endsWith", label: t("filter_operator_ends_with"), requiresOperand: true },
|
||||
{ value: "isEmpty", label: t("filter_operator_is_empty"), requiresOperand: false },
|
||||
{ value: "isNotEmpty", label: t("filter_operator_not_empty"), requiresOperand: false },
|
||||
];
|
||||
return options.filter((opt): opt is TextFilterOperatorOption =>
|
||||
operators.includes(opt.value as TextFilterOperator)
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
export { DataTableToolbar } from "./DataTableToolbar";
|
||||
export { DataTableSelectionBar } from "./DataTableSelectionBar";
|
||||
export { DataTablePagination } from "./DataTablePagination";
|
||||
export * from "./filters";
|
||||
export { DataTable } from "./DataTable";
|
||||
export { DataTableSkeleton } from "./DataTableSkeleton";
|
||||
export { DataTableWrapper } from "./DataTableWrapper";
|
||||
export type { DataTableProps } from "./DataTable";
|
||||
export { DataTableSegment } from "./segment";
|
||||
@@ -0,0 +1,58 @@
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Dialog, ConfirmationDialogContent } from "@calcom/ui/components/dialog";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import { useDataTable } from "@calcom/features/data-table/hooks";
|
||||
import type { FilterSegmentOutput } from "@calcom/features/data-table/lib/types";
|
||||
|
||||
export function DeleteSegmentDialog({
|
||||
segment,
|
||||
onClose,
|
||||
}: {
|
||||
segment: FilterSegmentOutput;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
const { segmentId, setSegmentId } = useDataTable();
|
||||
|
||||
const { mutate: deleteSegment, isPending } = trpc.viewer.filterSegments.delete.useMutation({
|
||||
onSuccess: ({ id }) => {
|
||||
utils.viewer.filterSegments.list.invalidate();
|
||||
showToast(t("filter_segment_deleted"), "success");
|
||||
if (segmentId && segmentId.type === "user" && segmentId.id === id) {
|
||||
setSegmentId(null);
|
||||
}
|
||||
onClose();
|
||||
},
|
||||
onError: () => {
|
||||
showToast(t("error_deleting_filter_segment"), "error");
|
||||
},
|
||||
});
|
||||
|
||||
const handleDelete = () => {
|
||||
if (!segment) return;
|
||||
deleteSegment({ id: segment.id });
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
onClose();
|
||||
}
|
||||
}}>
|
||||
<ConfirmationDialogContent
|
||||
variety="danger"
|
||||
title={t("delete_segment")}
|
||||
confirmBtnText={t("delete")}
|
||||
cancelBtnText={t("cancel")}
|
||||
isPending={isPending}
|
||||
onConfirm={handleDelete}>
|
||||
<p className="mt-5">{t("delete_segment_confirmation")}</p>
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/components/dialog";
|
||||
import { Form, TextField } from "@calcom/ui/components/form";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import { useDataTable } from "@calcom/features/data-table/hooks";
|
||||
import type { CombinedFilterSegment } from "@calcom/features/data-table/lib/types";
|
||||
|
||||
type FormValues = {
|
||||
name: string;
|
||||
};
|
||||
|
||||
export function DuplicateSegmentDialog({
|
||||
segment,
|
||||
onClose,
|
||||
}: {
|
||||
segment: CombinedFilterSegment;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const form = useForm<FormValues>({
|
||||
defaultValues: {
|
||||
name: "",
|
||||
},
|
||||
});
|
||||
const { setSegmentId } = useDataTable();
|
||||
const utils = trpc.useUtils();
|
||||
const session = useSession();
|
||||
const isAdminOrOwner = checkAdminOrOwner(session.data?.user?.org?.role);
|
||||
|
||||
const { mutate: createSegment, isPending } = trpc.viewer.filterSegments.create.useMutation({
|
||||
onSuccess: ({ id }) => {
|
||||
utils.viewer.filterSegments.list.invalidate();
|
||||
showToast(t("filter_segment_duplicated"), "success");
|
||||
setSegmentId({ id, type: "user" });
|
||||
onClose();
|
||||
},
|
||||
onError: () => {
|
||||
showToast(t("error_duplicating_filter_segment"), "error");
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = (data: FormValues) => {
|
||||
if (!segment) {
|
||||
return;
|
||||
}
|
||||
if (segment.type === "user") {
|
||||
const { type: _type, id: _id, name: _name, team: _team, teamId, ...rest } = segment;
|
||||
if (segment.scope === "TEAM" && isAdminOrOwner) {
|
||||
createSegment({
|
||||
...rest,
|
||||
teamId: teamId ?? 0,
|
||||
scope: "TEAM",
|
||||
name: data.name,
|
||||
});
|
||||
} else {
|
||||
createSegment({
|
||||
...rest,
|
||||
scope: "USER",
|
||||
name: data.name,
|
||||
});
|
||||
}
|
||||
} else if (segment.type === "system") {
|
||||
const { type: _type, ...rest } = segment;
|
||||
createSegment({
|
||||
...rest,
|
||||
scope: "USER",
|
||||
name: data.name,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
onClose();
|
||||
}
|
||||
}}>
|
||||
<DialogContent>
|
||||
<DialogHeader title={t("duplicate_segment")} />
|
||||
<Form form={form} handleSubmit={handleSubmit}>
|
||||
<div className="stack-y-4">
|
||||
<TextField
|
||||
required
|
||||
data-testid="duplicate-segment-name"
|
||||
type="text"
|
||||
label={t("name")}
|
||||
{...form.register("name")}
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button color="minimal" onClick={onClose}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button type="submit" loading={isPending}>
|
||||
{t("duplicate")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</div>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useState, useMemo } from "react";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import {
|
||||
Dropdown,
|
||||
DropdownItem,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuLabel,
|
||||
} from "@calcom/ui/components/dropdown";
|
||||
import { Icon, type IconName } from "@calcom/ui/components/icon";
|
||||
|
||||
import { useDataTable } from "@calcom/features/data-table/hooks";
|
||||
import type {
|
||||
FilterSegmentOutput,
|
||||
CombinedFilterSegment,
|
||||
SystemFilterSegmentInternal,
|
||||
UserFilterSegment,
|
||||
} from "@calcom/features/data-table/lib/types";
|
||||
import { DeleteSegmentDialog } from "./DeleteSegmentDialog";
|
||||
import { DuplicateSegmentDialog } from "./DuplicateSegmentDialog";
|
||||
import { RenameSegmentDialog } from "./RenameSegmentDialog";
|
||||
|
||||
type SubmenuItem = {
|
||||
iconName: IconName;
|
||||
labelKey: string;
|
||||
onClick: (segment: CombinedFilterSegment) => void;
|
||||
isDestructive?: boolean;
|
||||
adminOnly: boolean;
|
||||
enabledForSystemSegment?: boolean;
|
||||
};
|
||||
|
||||
interface Props {
|
||||
shortLabel?: boolean;
|
||||
}
|
||||
|
||||
export function FilterSegmentSelect({ shortLabel }: Props = {}) {
|
||||
const { t } = useLocale();
|
||||
const session = useSession();
|
||||
const isAdminOrOwner = checkAdminOrOwner(session.data?.user?.org?.role);
|
||||
const { segments, selectedSegment, segmentId, setSegmentId, isSegmentEnabled } = useDataTable();
|
||||
const [segmentToRename, setSegmentToRename] = useState<FilterSegmentOutput | undefined>();
|
||||
const [segmentToDuplicate, setSegmentToDuplicate] = useState<CombinedFilterSegment | undefined>();
|
||||
const [segmentToDelete, setSegmentToDelete] = useState<FilterSegmentOutput | undefined>();
|
||||
|
||||
const submenuItems: SubmenuItem[] = [
|
||||
{
|
||||
iconName: "square-pen",
|
||||
labelKey: "rename",
|
||||
onClick: (segment) => {
|
||||
if (segment.type === "system") {
|
||||
setSegmentToRename(undefined);
|
||||
} else {
|
||||
const { type: _type, ...rest } = segment;
|
||||
setSegmentToRename(rest);
|
||||
}
|
||||
},
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
iconName: "copy",
|
||||
labelKey: "duplicate",
|
||||
onClick: (segment) => setSegmentToDuplicate(segment),
|
||||
adminOnly: false,
|
||||
enabledForSystemSegment: true,
|
||||
},
|
||||
{
|
||||
iconName: "trash-2",
|
||||
labelKey: "delete",
|
||||
onClick: (segment) => {
|
||||
if (segment.type === "system") {
|
||||
setSegmentToDelete(undefined);
|
||||
} else {
|
||||
const { type: _type, ...rest } = segment;
|
||||
setSegmentToDelete(rest);
|
||||
}
|
||||
},
|
||||
isDestructive: true,
|
||||
adminOnly: true,
|
||||
},
|
||||
];
|
||||
|
||||
const segmentGroups = useMemo(() => {
|
||||
const sortFn = (a: CombinedFilterSegment, b: CombinedFilterSegment) => a.name.localeCompare(b.name);
|
||||
|
||||
const systemSegments =
|
||||
segments?.filter((s): s is SystemFilterSegmentInternal => s.type === "system") || [];
|
||||
const personalSegments =
|
||||
segments?.filter((s): s is UserFilterSegment => s.type === "user" && !s.team) || [];
|
||||
const teamSegments =
|
||||
segments?.filter(
|
||||
(s): s is UserFilterSegment & { team: NonNullable<FilterSegmentOutput["team"]> } =>
|
||||
s.type === "user" && s.team !== null
|
||||
) || [];
|
||||
|
||||
const groups = [];
|
||||
|
||||
if (systemSegments.length > 0) {
|
||||
groups.push({
|
||||
label: t("default"),
|
||||
segments: systemSegments.sort(sortFn),
|
||||
isSystem: true,
|
||||
});
|
||||
}
|
||||
|
||||
// Personal segments
|
||||
if (personalSegments.length > 0) {
|
||||
groups.push({
|
||||
label: t("personal"),
|
||||
segments: personalSegments.sort(sortFn),
|
||||
isSystem: false,
|
||||
});
|
||||
}
|
||||
|
||||
// Team segments (existing grouping logic)
|
||||
const teamSegmentsByTeam = teamSegments.reduce<{
|
||||
[teamName: string]: UserFilterSegment[];
|
||||
}>((acc, segment) => {
|
||||
const teamName = segment.team!.name;
|
||||
if (!acc[teamName]) {
|
||||
acc[teamName] = [];
|
||||
}
|
||||
acc[teamName].push(segment);
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
groups.push(
|
||||
...Object.entries(teamSegmentsByTeam)
|
||||
.map(([teamName, segments]) => ({
|
||||
label: teamName,
|
||||
segments: segments.sort(sortFn),
|
||||
isSystem: false,
|
||||
}))
|
||||
.sort((a, b) => a.label.localeCompare(b.label))
|
||||
);
|
||||
|
||||
return groups;
|
||||
}, [segments, t]);
|
||||
|
||||
if (!isSegmentEnabled) {
|
||||
return (
|
||||
<Button color="secondary" StartIcon="list-filter" EndIcon="chevron-down" disabled>
|
||||
{t("segment")}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dropdown>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
color="secondary"
|
||||
StartIcon="list-filter"
|
||||
EndIcon="chevron-down"
|
||||
data-testid="filter-segment-select">
|
||||
{selectedSegment?.name || (shortLabel ? t("saved") : t("saved_filters"))}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuContent align="end" className="w-60" data-testid="filter-segment-select-content">
|
||||
{segmentGroups.length === 0 && <p className="text-subtle px-3 py-1">{t("no_segments")}</p>}
|
||||
|
||||
{segmentGroups.map((group, index) => (
|
||||
<div key={index}>
|
||||
{group.label && (
|
||||
<DropdownMenuLabel className={index === 0 ? "" : "mt-2"}>{group.label}</DropdownMenuLabel>
|
||||
)}
|
||||
{group.segments.map((segment) => {
|
||||
let items: SubmenuItem[] = [];
|
||||
if (segment.type === "system") {
|
||||
items = submenuItems.filter((item) => item.enabledForSystemSegment);
|
||||
} else if (segment.type === "user" && segment.scope === "USER") {
|
||||
items = submenuItems;
|
||||
} else if (segment.type === "user" && segment.scope === "TEAM") {
|
||||
items = submenuItems.filter(
|
||||
(item) =>
|
||||
// Team segments: show if not admin-only or if user is admin/owner
|
||||
isAdminOrOwner || !item.adminOnly
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownItemWithSubmenu
|
||||
key={segment.id}
|
||||
submenuItems={items}
|
||||
segment={segment}
|
||||
onSelect={() => {
|
||||
if (segmentId && segmentId.type === segment.type && segmentId.id === segment.id) {
|
||||
setSegmentId(null);
|
||||
} else {
|
||||
if (segment.type === "system") {
|
||||
setSegmentId({ id: segment.id, type: "system" });
|
||||
} else {
|
||||
setSegmentId({ id: segment.id, type: "user" });
|
||||
}
|
||||
}
|
||||
}}>
|
||||
{segmentId && segmentId.type === segment.type && segmentId.id === segment.id && (
|
||||
<Icon name="check" className="ml-3 h-4 w-4" />
|
||||
)}
|
||||
<span className="ml-3">{segment.name}</span>
|
||||
</DropdownItemWithSubmenu>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenuPortal>
|
||||
</Dropdown>
|
||||
|
||||
{segmentToRename && (
|
||||
<RenameSegmentDialog segment={segmentToRename} onClose={() => setSegmentToRename(undefined)} />
|
||||
)}
|
||||
|
||||
{segmentToDuplicate && (
|
||||
<DuplicateSegmentDialog
|
||||
segment={segmentToDuplicate}
|
||||
onClose={() => setSegmentToDuplicate(undefined)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{segmentToDelete && (
|
||||
<DeleteSegmentDialog segment={segmentToDelete} onClose={() => setSegmentToDelete(undefined)} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownItemWithSubmenu({
|
||||
onSelect,
|
||||
segment,
|
||||
submenuItems,
|
||||
children,
|
||||
}: {
|
||||
onSelect: () => void;
|
||||
segment: CombinedFilterSegment;
|
||||
submenuItems: SubmenuItem[];
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
className="cursor-pointer rounded-lg last-of-type:rounded-b-lg"
|
||||
onSelect={onSelect}>
|
||||
<div className="flex items-center">
|
||||
{children}
|
||||
<div className="grow" />
|
||||
<Dropdown open={isOpen} onOpenChange={setIsOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
StartIcon="ellipsis"
|
||||
variant="icon"
|
||||
color="minimal"
|
||||
className="rounded-full"
|
||||
data-testid="filter-segment-select-submenu-button"
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
setIsOpen((prev) => !prev);
|
||||
}}
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuContent
|
||||
align="start"
|
||||
side="right"
|
||||
sideOffset={8}
|
||||
data-testid="filter-segment-select-submenu-content">
|
||||
{submenuItems.map((item, index) => (
|
||||
<DropdownMenuItem key={index}>
|
||||
<DropdownItem
|
||||
color={item.isDestructive ? "destructive" : undefined}
|
||||
StartIcon={item.iconName}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
item.onClick(segment);
|
||||
setIsOpen(false);
|
||||
}}>
|
||||
{t(item.labelKey)}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenuPortal>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/components/dialog";
|
||||
import { Form, TextField } from "@calcom/ui/components/form";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import type { FilterSegmentOutput } from "@calcom/features/data-table/lib/types";
|
||||
|
||||
type FormValues = {
|
||||
name: string;
|
||||
};
|
||||
|
||||
export function RenameSegmentDialog({
|
||||
segment,
|
||||
onClose,
|
||||
}: {
|
||||
segment: FilterSegmentOutput;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const form = useForm<FormValues>({
|
||||
defaultValues: {
|
||||
name: segment.name,
|
||||
},
|
||||
});
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const { mutate: updateSegment, isPending } = trpc.viewer.filterSegments.update.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.viewer.filterSegments.list.invalidate();
|
||||
showToast(t("filter_segment_updated"), "success");
|
||||
onClose();
|
||||
},
|
||||
onError: () => {
|
||||
showToast(t("error_updating_filter_segment"), "error");
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = (data: FormValues) => {
|
||||
if (!segment) {
|
||||
return;
|
||||
}
|
||||
if (segment.scope === "TEAM") {
|
||||
updateSegment({
|
||||
...segment,
|
||||
scope: "TEAM",
|
||||
teamId: segment.teamId ?? 0,
|
||||
name: data.name,
|
||||
});
|
||||
return;
|
||||
}
|
||||
updateSegment({
|
||||
...segment,
|
||||
scope: "USER",
|
||||
name: data.name,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
onClose();
|
||||
}
|
||||
}}>
|
||||
<DialogContent>
|
||||
<DialogHeader title={t("rename_segment")} />
|
||||
<Form form={form} handleSubmit={handleSubmit}>
|
||||
<div className="stack-y-4">
|
||||
<TextField
|
||||
required
|
||||
data-testid="rename-segment-name"
|
||||
type="text"
|
||||
label={t("name")}
|
||||
{...form.register("name")}
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button type="submit" loading={isPending}>
|
||||
{t("save")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</div>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import posthog from "posthog-js";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { type FilterSegmentScope } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTrigger,
|
||||
} from "@calcom/ui/components/dialog";
|
||||
import { Form, Input, Label, Select, Switch } from "@calcom/ui/components/form";
|
||||
import { RadioGroup, RadioField } from "@calcom/ui/components/radio";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import { useDataTable } from "@calcom/features/data-table/hooks";
|
||||
|
||||
interface FormValues {
|
||||
name: string;
|
||||
scope: FilterSegmentScope;
|
||||
teamId?: number;
|
||||
}
|
||||
|
||||
export function SaveFilterSegmentButton() {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isTeamSegment, setIsTeamSegment] = useState(false);
|
||||
const [selectedTeamId, setSelectedTeamId] = useState<number>();
|
||||
const session = useSession();
|
||||
const isAdminOrOwner = checkAdminOrOwner(session.data?.user?.org?.role);
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
defaultValues: {
|
||||
name: "",
|
||||
scope: "USER",
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
tableIdentifier,
|
||||
activeFilters,
|
||||
sorting,
|
||||
columnVisibility,
|
||||
columnSizing,
|
||||
selectedSegment,
|
||||
canSaveSegment,
|
||||
isSegmentEnabled,
|
||||
setSegmentId,
|
||||
pageSize,
|
||||
searchTerm,
|
||||
} = useDataTable();
|
||||
|
||||
const [saveMode, setSaveMode] = useState<"create" | "update">(() =>
|
||||
selectedSegment && selectedSegment.type === "user" ? "update" : "create"
|
||||
);
|
||||
|
||||
// When the dialog is not open,
|
||||
// switch `saveMode` according to `selectedSegment`
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
return;
|
||||
}
|
||||
setSaveMode(selectedSegment && selectedSegment.type === "user" ? "update" : "create");
|
||||
}, [selectedSegment, isOpen]);
|
||||
|
||||
const { data: teams } = trpc.viewer.teams.list.useQuery();
|
||||
|
||||
const { mutate: createSegment } = trpc.viewer.filterSegments.create.useMutation({
|
||||
onSuccess: (segment) => {
|
||||
utils.viewer.filterSegments.list.invalidate();
|
||||
showToast(t("filter_segment_saved"), "success");
|
||||
setSegmentId({ id: segment.id, type: "user" }, { type: "user", ...segment });
|
||||
setIsOpen(false);
|
||||
},
|
||||
onError: () => {
|
||||
showToast(t("error_saving_filter_segment"), "error");
|
||||
},
|
||||
});
|
||||
|
||||
const { mutate: updateSegment } = trpc.viewer.filterSegments.update.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.viewer.filterSegments.list.invalidate();
|
||||
showToast(t("filter_segment_updated"), "success");
|
||||
setIsOpen(false);
|
||||
},
|
||||
onError: () => {
|
||||
showToast(t("error_updating_filter_segment"), "error");
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = (values: FormValues) => {
|
||||
if (isTeamSegment && !selectedTeamId) {
|
||||
showToast(t("please_select_team"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const segmentData = {
|
||||
tableIdentifier,
|
||||
activeFilters,
|
||||
sorting,
|
||||
columnVisibility,
|
||||
columnSizing,
|
||||
perPage: pageSize,
|
||||
searchTerm,
|
||||
};
|
||||
|
||||
if (saveMode === "update" && selectedSegment && selectedSegment.type === "user") {
|
||||
const scope = selectedSegment.scope;
|
||||
if (scope === "TEAM") {
|
||||
updateSegment({
|
||||
id: selectedSegment.id,
|
||||
scope,
|
||||
teamId: selectedSegment.teamId || 0,
|
||||
name: selectedSegment.name,
|
||||
...segmentData,
|
||||
});
|
||||
} else {
|
||||
updateSegment({
|
||||
id: selectedSegment.id,
|
||||
scope,
|
||||
name: selectedSegment.name,
|
||||
...segmentData,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (isTeamSegment) {
|
||||
createSegment({
|
||||
...segmentData,
|
||||
name: values.name,
|
||||
scope: "TEAM",
|
||||
teamId: selectedTeamId || 0,
|
||||
});
|
||||
} else {
|
||||
createSegment({
|
||||
...segmentData,
|
||||
name: values.name,
|
||||
scope: "USER",
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenChange = (open: boolean) => {
|
||||
if (!open) {
|
||||
// Reset form state when dialog closes
|
||||
setIsTeamSegment(false);
|
||||
setSelectedTeamId(undefined);
|
||||
setSaveMode(selectedSegment && selectedSegment.type === "user" ? "update" : "create");
|
||||
form.reset();
|
||||
}
|
||||
setIsOpen(open);
|
||||
};
|
||||
|
||||
if (!isSegmentEnabled) {
|
||||
return (
|
||||
<Button StartIcon="bookmark" color="secondary" disabled>
|
||||
{t("save")}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
StartIcon="bookmark"
|
||||
color="secondary"
|
||||
onClick={() => posthog.capture("insights_routing_save_filter_clicked")}
|
||||
disabled={!canSaveSegment}
|
||||
data-testid="save-filter-segment-button">
|
||||
{t("save")}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent data-testid="save-filter-segment-dialog">
|
||||
<DialogHeader title={t("save_segment")} />
|
||||
<Form form={form} handleSubmit={onSubmit}>
|
||||
{selectedSegment && selectedSegment.type === "user" ? (
|
||||
<div className="mb-4">
|
||||
<RadioGroup
|
||||
defaultValue="update"
|
||||
onValueChange={(value: string) => setSaveMode(value as "create" | "update")}
|
||||
className="stack-y-2">
|
||||
<RadioField
|
||||
id="update_segment"
|
||||
label={t("override_segment", { name: selectedSegment.name })}
|
||||
value="update"
|
||||
/>
|
||||
<RadioField id="create_segment" label={t("create_new_segment")} value="create" />
|
||||
</RadioGroup>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div>
|
||||
{saveMode === "create" && (
|
||||
<div>
|
||||
<Label>{t("name")}</Label>
|
||||
<Input {...form.register("name")} data-testid="save-filter-segment-name" required />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isAdminOrOwner && saveMode === "create" && (
|
||||
<>
|
||||
<div className="-ml-2 mt-4">
|
||||
<Switch
|
||||
id="teamSegment"
|
||||
label={t("save_for_team")}
|
||||
checked={isTeamSegment}
|
||||
onCheckedChange={setIsTeamSegment}
|
||||
labelOnLeading
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isTeamSegment && teams && teams.length > 0 && (
|
||||
<div className="mt-1.5">
|
||||
<Select<{ value: string; label: string }>
|
||||
options={teams.map((team) => ({
|
||||
value: team.id.toString(),
|
||||
label: team.name,
|
||||
}))}
|
||||
onChange={(option) => setSelectedTeamId(parseInt(option?.value || "0"))}
|
||||
placeholder={t("select_team")}
|
||||
data-testid="save-filter-segment-team-select"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" color="minimal" onClick={() => setIsOpen(false)}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button type="submit">{t("save")}</Button>
|
||||
</DialogFooter>
|
||||
</div>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { FilterSegmentSelect } from "./FilterSegmentSelect";
|
||||
import { SaveFilterSegmentButton } from "./SaveFilterSegmentButton";
|
||||
|
||||
export const DataTableSegment = {
|
||||
SaveButton: SaveFilterSegmentButton,
|
||||
Select: FilterSegmentSelect,
|
||||
};
|
||||
Reference in new issue
Block a user