Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: add linear-like filter component

Brad Barbin124f4b330b29
diff --git a/apps/carbon/app/components/Layout/Topbar/CreateMenu.tsx b/apps/carbon/app/components/Layout/Topbar/CreateMenu.tsx
index 70a14a789a..e9aef0d887 100644
--- a/apps/carbon/app/components/Layout/Topbar/CreateMenu.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/CreateMenu.tsx
@@ -1,12 +1,13 @@
import {
- Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuIcon,
DropdownMenuItem,
DropdownMenuTrigger,
+ IconButton,
} from "@carbon/react";
import { Link } from "@remix-run/react";
+import { MdAdd } from "react-icons/md";
import useCreate from "./useCreate";
const CreateMenu = () => {
@@ -17,7 +18,12 @@ const CreateMenu = () => {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button>Create</Button>
+ <IconButton
+ aria-label="Create"
+ icon={<MdAdd />}
+ variant="secondary"
+ className={"!border-dashed border-border"}
+ />
</DropdownMenuTrigger>
<DropdownMenuContent align="center" className="w-48">
{createLinks.map((link) => (
diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsx
index facefc90cf..a6d6fba067 100644
--- a/apps/carbon/app/components/Table/Table.tsx
+++ b/apps/carbon/app/components/Table/Table.tsx
@@ -40,6 +40,7 @@ import {
usePagination,
useSort,
} from "./components";
+import type { ColumnFilter } from "./components/Filter/types";
import type { TableAction } from "./types";
import { getAccessorKey, updateNestedProperty } from "./utils";
@@ -52,9 +53,11 @@ interface TableProps<T extends object> {
defaultColumnPinning?: ColumnPinningState;
defaultColumnVisibility?: Record<string, boolean>;
editableComponents?: Record<string, EditableTableCellComponent<T>>;
+ label?: string;
+ newPath?: string;
+ newPermission?: boolean;
withColumnOrdering?: boolean;
withInlineEditing?: boolean;
- withFilters?: boolean;
withPagination?: boolean;
withSelectableRows?: boolean;
withSimpleSorting?: boolean;
@@ -67,13 +70,15 @@ const Table = <T extends object>({
columns,
actions = [],
count = 0,
- editableComponents,
defaultColumnOrder,
defaultColumnPinning = {
left: ["Select"],
},
defaultColumnVisibility,
- withFilters = false,
+ editableComponents,
+ label,
+ newPath,
+ newPermission,
withInlineEditing = false,
withColumnOrdering = false,
withPagination = true,
@@ -413,31 +418,51 @@ const Table = <T extends object>({
setColumnOrder(table.getAllLeafColumns().map((column) => column.id));
});
+ const filters = useMemo(
+ () =>
+ columns.reduce<ColumnFilter[]>((acc, column) => {
+ if (
+ column.meta?.filter &&
+ column.header &&
+ typeof column.header === "string"
+ ) {
+ const filter: ColumnFilter = {
+ accessorKey: getAccessorKey(column) ?? "",
+ header: column.header,
+ pluralHeader: column.meta.pluralHeader,
+ filter: column.meta.filter,
+ };
+ return [...acc, filter];
+ }
+ return acc;
+ }, []),
+ [columns]
+ );
+
const rows = table.getRowModel().rows;
return (
<VStack spacing={0} className="h-full">
- {(withColumnOrdering ||
- withFilters ||
- withSelectableRows ||
- withInlineEditing) && (
- <TableHeader
- actions={actions}
- columnAccessors={columnAccessors}
- columnOrder={columnOrder}
- columns={table.getAllLeafColumns()}
- editMode={editMode}
- selectedRows={selectedRows}
- setColumnOrder={setColumnOrder}
- setEditMode={setEditMode}
- pagination={pagination}
- withInlineEditing={withInlineEditing}
- withColumnOrdering={withColumnOrdering}
- withFilters={withFilters}
- withPagination={withPagination}
- withSelectableRows={withSelectableRows}
- />
- )}
+ <TableHeader
+ actions={actions}
+ columnAccessors={columnAccessors}
+ columnOrder={columnOrder}
+ columns={table.getAllLeafColumns()}
+ editMode={editMode}
+ filters={filters}
+ label={label}
+ newPath={newPath}
+ newPermission={newPermission}
+ selectedRows={selectedRows}
+ setColumnOrder={setColumnOrder}
+ setEditMode={setEditMode}
+ pagination={pagination}
+ withInlineEditing={withInlineEditing}
+ withColumnOrdering={withColumnOrdering}
+ withPagination={withPagination}
+ withSelectableRows={withSelectableRows}
+ />
+
<div
className="w-full h-full bg-card overflow-scroll"
style={{ contain: "strict" }}
diff --git a/apps/carbon/app/components/Table/components/Filter/ActiveFilters.tsx b/apps/carbon/app/components/Table/components/Filter/ActiveFilters.tsx
new file mode 100644
index 0000000000..57d7503be9
--- /dev/null
+++ b/apps/carbon/app/components/Table/components/Filter/ActiveFilters.tsx
@@ -0,0 +1,189 @@
+import {
+ Button,
+ Checkbox,
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ HStack,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ reactNodeToString,
+ useMount,
+} from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import { useEffect, useState } from "react";
+import { MdClose } from "react-icons/md";
+import Filter from "./Filter";
+import type { ColumnFilter } from "./types";
+import { useFilters } from "./useFilters";
+
+type ActiveFiltersProps = {
+ filters: ColumnFilter[];
+};
+
+const ActiveFilters = ({ filters }: ActiveFiltersProps) => {
+ const { urlFiltersParams } = useFilters();
+ return (
+ <HStack spacing={2}>
+ {urlFiltersParams.map((f) => {
+ const [key, operator, value] = f.split(":");
+ const columnFilter = filters.find((f) => f.accessorKey === key);
+ if (!columnFilter) return null;
+
+ return (
+ <ActiveFilter
+ key={key}
+ filter={columnFilter}
+ operator={operator}
+ value={value}
+ />
+ );
+ })}
+ {urlFiltersParams.length > 0 && (
+ <Filter filters={filters} trigger="icon" />
+ )}
+ </HStack>
+ );
+};
+
+type ActiveFilterProps = {
+ filter: ColumnFilter;
+ operator: string;
+ value: string;
+};
+
+const ActiveFilter = ({ filter, operator, value }: ActiveFilterProps) => {
+ const { hasFilter, removeKey, toggleFilter } = useFilters();
+
+ const [open, setOpen] = useState(false);
+ const [input, setInput] = useState("");
+ const [loading, setLoading] = useState(false);
+ const [options, setOptions] = useState(
+ filter.filter.type === "static" ? filter.filter.options : []
+ );
+ useEffect(() => {
+ if (!open) {
+ setInput("");
+ }
+ }, [open]);
+
+ const fetcher = useFetcher<PostgrestResponse<{ id: string; name: string }>>();
+
+ useMount(() => {
+ if (filter.filter.type === "fetcher") {
+ setLoading(true);
+ fetcher.load(filter.filter.endpoint);
+ }
+ });
+
+ useEffect(() => {
+ if (
+ filter.filter.type === "fetcher" &&
+ fetcher.data !== null &&
+ typeof fetcher.data === "object" &&
+ "data" in fetcher.data
+ ) {
+ setOptions(
+ filter.filter.transform
+ ? // @ts-expect-error
+ filter.filter.transform(fetcher.data.data)
+ : fetcher.data.data?.map((d) => ({ label: d.name, value: d.id })) ??
+ []
+ );
+
+ setLoading(false);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fetcher.data, filter.filter.type]);
+
+ const makeLabel = (v: string) => {
+ const [, ...others] = v.split(",");
+ if (others && others.length > 0) {
+ return `${1 + others.length} ${
+ filter.pluralHeader ? filter.pluralHeader : filter.header + "s"
+ }`;
+ } else {
+ const node = options.find((o) => o.value === v)?.label ?? "";
+ return typeof node === "string" ? node : reactNodeToString(node);
+ }
+ };
+
+ return (
+ <HStack spacing={0}>
+ <Button className="rounded-r-none" size="sm" variant="secondary">
+ {filter.header}
+ </Button>
+ <Button className="rounded-none border-l-0" size="sm" variant="secondary">
+ {operator === "eq" ? "is" : "is any of"}
+ </Button>
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ className="rounded-none"
+ role="combobox"
+ variant="secondary"
+ onClick={() => {
+ setOpen(true);
+ }}
+ size="sm"
+ >
+ {makeLabel(value)}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ className="min-w-[200px] w-[--radix-popover-trigger-width] p-0"
+ sticky="always"
+ >
+ <Command>
+ <CommandInput
+ value={input}
+ onValueChange={setInput}
+ placeholder="Search..."
+ className="h-9"
+ />
+ <CommandEmpty>
+ {loading ? "Loading..." : "No options found."}
+ </CommandEmpty>
+ <CommandGroup>
+ {options.map((option) => {
+ const isChecked = hasFilter(filter.accessorKey, option.value);
+ return (
+ <CommandItem
+ value={option.value}
+ key={option.value}
+ onSelect={() => {
+ setOpen(false);
+ toggleFilter(filter.accessorKey, option.value);
+ }}
+ >
+ <HStack spacing={2}>
+ <Checkbox id={option.value} isChecked={isChecked} />
+ <label htmlFor={option.value}>{option.label}</label>
+ </HStack>
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ <Button
+ aria-label="Remove filter"
+ className="rounded-l-none border-l-0 px-1 w-6"
+ size="sm"
+ variant="secondary"
+ onClick={() => {
+ removeKey(filter.accessorKey);
+ }}
+ >
+ <MdClose />
+ </Button>
+ </HStack>
+ );
+};
+
+export default ActiveFilters;
diff --git a/apps/carbon/app/components/Table/components/Filter/Filter.tsx b/apps/carbon/app/components/Table/components/Filter/Filter.tsx
index b82408589b..b249f9d58a 100644
--- a/apps/carbon/app/components/Table/components/Filter/Filter.tsx
+++ b/apps/carbon/app/components/Table/components/Filter/Filter.tsx
@@ -1,91 +1,205 @@
import {
Button,
+ Checkbox,
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ HStack,
Popover,
PopoverContent,
- PopoverFooter,
- PopoverHeader,
PopoverTrigger,
- VStack,
} from "@carbon/react";
-import { BsFilter, BsPlus } from "react-icons/bs";
-import { useUrlParams } from "~/hooks";
-import FilterRow from "./FilterRow";
+import { useFetcher } from "@remix-run/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import type { ComponentPropsWithoutRef } from "react";
+import { forwardRef, useCallback, useEffect, useMemo, useState } from "react";
+import { BsFilter } from "react-icons/bs";
+import { IoMdAdd } from "react-icons/io";
+import { MdClose } from "react-icons/md";
+import type { ColumnFilter, Option } from "./types";
+import { useFilters } from "./useFilters";
-type FilterProps = {
- columnAccessors: Record<string, string>;
+export type FilterProps = Omit<
+ ComponentPropsWithoutRef<"button">,
+ "onChange"
+> & {
+ filters: ColumnFilter[];
+ trigger?: "button" | "icon";
};
-const Filter = ({ columnAccessors }: FilterProps) => {
- const [params, setParams] = useUrlParams();
- const filters = params.getAll("filter");
+const Filter = forwardRef<HTMLButtonElement, FilterProps>(
+ ({ filters, trigger = "button", ...props }, ref) => {
+ const { clearFilters, hasFilter, hasFilters, hasFilterKey, toggleFilter } =
+ useFilters();
- const addFilter = () => {
- const defaultFilter = `${Object.keys(columnAccessors)[0]}:contains:`;
- setParams({ filter: filters.concat(defaultFilter) });
- };
+ const [open, setOpen] = useState(false);
+ const [input, setInput] = useState("");
+ const [loading, setLoading] = useState(false);
+ const [activeFilter, setActiveFilter] = useState<ColumnFilter | null>(null);
+ const [activeOptions, setActiveOptions] = useState<Option[]>([]);
- const removeFilter = (filterIndex: number) => {
- setParams({
- filter: filters.filter((_, index) => index !== filterIndex),
- });
- };
+ // reset the state when the filter
+ useEffect(() => {
+ if (!open) {
+ setInput("");
+ setActiveOptions([]);
+ setActiveFilter(null);
+ }
+ }, [open]);
- const updateFilter = (filterIndex: number, newFilter: string) => {
- setParams({
- filter: filters.map((filter, index) =>
- index === filterIndex ? newFilter : filter
- ),
- });
- };
+ const fetcher =
+ useFetcher<PostgrestResponse<{ id: string; name: string }>>();
- return (
- <Popover>
- <PopoverTrigger asChild>
+ useEffect(() => {
+ if (
+ activeFilter?.filter.type === "fetcher" &&
+ fetcher.data !== null &&
+ typeof fetcher.data === "object" &&
+ "data" in fetcher.data
+ ) {
+ setActiveOptions(
+ activeFilter.filter.transform
+ ? // @ts-expect-error
+ activeFilter.filter.transform(fetcher.data.data)
+ : fetcher.data.data?.map((d) => ({ label: d.name, value: d.id })) ??
+ []
+ );
+
+ setLoading(false);
+ }
+ }, [fetcher.data, activeFilter]);
+
+ const columnFilters = useMemo(
+ () => filters.map((f) => ({ value: f.accessorKey, label: f.header })),
+ [filters]
+ );
+
+ const updateActiveOptions = useCallback(
+ (value: string) => {
+ const accessorKey = value.split(":")?.[1] ?? "";
+
+ const filter = filters.find(
+ (f) => f.accessorKey.toLowerCase() === accessorKey.toLowerCase()
+ );
+
+ if (!filter)
+ throw new Error(`Filter not found for accessorKey: ${accessorKey}`);
+
+ setInput("");
+ setActiveFilter(filter ?? null);
+
+ if (filter?.filter.type === "static") {
+ setActiveOptions(filter.filter.options);
+ } else if (filter?.filter.type === "fetcher") {
+ setLoading(true);
+ fetcher.load(filter.filter.endpoint);
+ }
+ },
+ [fetcher, filters]
+ );
+
+ return hasFilters && !open && trigger !== "icon" ? (
+ <HStack>
<Button
- variant={filters.length === 0 ? "ghost" : "primary"}
- leftIcon={<BsFilter />}
+ rightIcon={<MdClose />}
+ ref={ref}
+ variant="secondary"
+ onClick={clearFilters}
+ className={"!border-dashed border-border"}
+ {...props}
>
- {filters.length === 0 ? "Filter" : "Filtered"}
+ Clear Filters
</Button>
- </PopoverTrigger>
- <PopoverContent className="w-[520px]">
- {filters.length === 0 && (
- <PopoverHeader>
- <p className="text-sm">No filters applied to this view</p>
- <p className="text-xs text-muted-foreground">
- Add a column below to sort the view
- </p>
- </PopoverHeader>
- )}
-
- {filters.length > 0 && (
- <VStack>
- {filters.reduce<JSX.Element[]>((acc, filter, index) => {
- const [column, operator, searchValue] = filter.split(":");
- if (!column || !operator) return acc;
- acc.push(
- <FilterRow
- key={`filter-${column}-${[index]}`}
- column={column}
- columnAccessors={columnAccessors}
- operator={operator}
- searchValue={searchValue}
- onRemove={() => removeFilter(index)}
- onUpdate={(newFilter) => updateFilter(index, newFilter)}
- />
- );
- return acc;
- }, [])}
- </VStack>
- )}
- <PopoverFooter>
- <Button variant="secondary" leftIcon={<BsPlus />} onClick={addFilter}>
- Add Filter
- </Button>
- </PopoverFooter>
- </PopoverContent>
- </Popover>
- );
-};
+ </HStack>
+ ) : (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ {trigger === "icon" ? (
+ <Button
+ aria-label="Remove filter"
+ className="px-1 w-6"
+ variant="secondary"
+ size="sm"
+ onClick={() => {
+ setOpen(true);
+ }}
+ >
+ <IoMdAdd />
+ </Button>
+ ) : (
+ <Button
+ rightIcon={<BsFilter />}
+ role="combobox"
+ ref={ref}
+ variant="secondary"
+ onClick={() => {
+ setOpen(true);
+ }}
+ className={"!border-dashed border-border"}
+ {...props}
+ >
+ Filter
+ </Button>
+ )}
+ </PopoverTrigger>
+ <PopoverContent className="min-w-[200px] w-[--radix-popover-trigger-width] p-0">
+ <Command>
+ <CommandInput
+ value={input}
+ onValueChange={setInput}
+ placeholder="Search..."
+ className="h-9"
+ />
+ <CommandEmpty>
+ {loading ? "Loading..." : "No available filters."}
+ </CommandEmpty>
+ {activeFilter === null ? (
+ <CommandGroup>
+ {columnFilters
+ .filter((column) => !hasFilterKey(column.value))
+ .map((option) => (
+ <CommandItem
+ key={option.value}
+ value={`${option.label}:${option.value}`}
+ onSelect={updateActiveOptions}
+ >
+ {option.label}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ ) : (
+ <CommandGroup>
+ {activeOptions.map((option) => {
+ const isChecked = hasFilter(
+ activeFilter.accessorKey,
+ option.value
+ );
+ return (
+ <CommandItem
+ value={option.value}
+ key={option.value}
+ onSelect={() => {
+ setInput("");
+ toggleFilter(activeFilter.accessorKey, option.value);
+ }}
+ >
+ <HStack spacing={2}>
+ <Checkbox id={option.value} isChecked={isChecked} />
+ <label htmlFor={option.value}>{option.label}</label>
+ </HStack>
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ )}
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+ }
+);
+Filter.displayName = "Filter";
export default Filter;
diff --git a/apps/carbon/app/components/Table/components/Filter/index.ts b/apps/carbon/app/components/Table/components/Filter/index.ts
index 0cea50296e..49a78086f9 100644
--- a/apps/carbon/app/components/Table/components/Filter/index.ts
+++ b/apps/carbon/app/components/Table/components/Filter/index.ts
@@ -1,3 +1,4 @@
+import ActiveFilters from "./ActiveFilters";
import Filter from "./Filter";
-export default Filter;
+export { ActiveFilters, Filter };
diff --git a/apps/carbon/app/components/Table/components/Filter/types.ts b/apps/carbon/app/components/Table/components/Filter/types.ts
new file mode 100644
index 0000000000..141cd43035
--- /dev/null
+++ b/apps/carbon/app/components/Table/components/Filter/types.ts
@@ -0,0 +1,26 @@
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import type { ReactNode } from "react";
+
+export type ColumnFilter = {
+ accessorKey: string;
+ header: string;
+ pluralHeader?: string;
+ filter: ColumnFilterData;
+};
+
+export type Option = {
+ label: string | ReactNode;
+ value: string;
+ helper?: string;
+};
+
+export type ColumnFilterData =
+ | {
+ type: "static";
+ options: Option[];
+ }
+ | {
+ type: "fetcher";
+ endpoint: string;
+ transform?: (result: PostgrestResponse<unknown>) => Option[];
+ };
diff --git a/apps/carbon/app/components/Table/components/Filter/useFilters.tsx b/apps/carbon/app/components/Table/components/Filter/useFilters.tsx
new file mode 100644
index 0000000000..0f21426376
--- /dev/null
+++ b/apps/carbon/app/components/Table/components/Filter/useFilters.tsx
@@ -0,0 +1,121 @@
+import { useUrlParams } from "~/hooks";
+
+export function useFilters() {
+ const [params, setParams] = useUrlParams();
+ const urlFiltersParams = params.getAll("filter");
+ const hasFilter = (searchKey: string, searchValue: string) => {
+ return urlFiltersParams.some((filter) => {
+ const [key, operator, value] = filter.split(":");
+ if (key && operator && value) {
+ switch (operator) {
+ case "eq":
+ return key === searchKey && value === searchValue;
+ case "in":
+ const values = value.split(",");
+ return key === searchKey && values.some((v) => v === searchValue);
+ default:
+ return false;
+ }
+ }
+ return false;
+ });
+ };
+
+ const hasFilterKey = (searchKey: string) => {
+ return urlFiltersParams.some((filter) => {
+ const [key] = filter.split(":");
+ return key === searchKey;
+ });
+ };
+
+ const getFilterKeyIndex = (key: string) => {
+ return urlFiltersParams.findIndex((f) => {
+ let accessorKey = f.split(":")?.[0];
+ return key === accessorKey;
+ });
+ };
+
+ const addFilter = (newKey: string, newValue: string) => {
+ if (hasFilterKey(newKey)) {
+ const filterIndex = getFilterKeyIndex(newKey);
+ const filter = urlFiltersParams[filterIndex];
+ const [key, operator, value] = filter.split(":");
+
+ let newFilter = "";
+ if (operator === "in") {
+ newFilter = `${filter},${newValue}`;
+ } else {
+ newFilter = `${key}:in:${value},${newValue}`;
+ }
+
+ setParams({
+ filter: urlFiltersParams.map((f, index) =>
+ index === filterIndex ? newFilter : f
+ ),
+ });
+ } else {
+ setParams({
+ filter: urlFiltersParams.concat(`${newKey}:eq:${newValue}`),
+ });
+ }
+ };
+
+ const removeFilter = (oldKey: string, oldValue: string) => {
+ const filterIndex = getFilterKeyIndex(oldKey);
+ const filter = urlFiltersParams[filterIndex];
+ const [key, operator, value] = filter.split(":");
+ if (operator === "in") {
+ const values = value.split(",").filter((v) => v !== oldValue);
+ if (values.length === 1) {
+ setParams({
+ filter: urlFiltersParams.map((f, index) =>
+ index === filterIndex ? `${key}:eq:${values[0]}` : f
+ ),
+ });
+ } else {
+ setParams({
+ filter: urlFiltersParams.map((f, index) =>
+ index === filterIndex ? `${key}:in:${values.join(",")}` : f
+ ),
+ });
+ }
+ } else {
+ setParams({
+ filter: urlFiltersParams.filter((_, index) => index !== filterIndex),
+ });
+ }
+ };
+
+ const removeKey = (key: string) => {
+ setParams({
+ filter: urlFiltersParams.filter((f) => {
+ const [filterKey] = f.split(":");
+ return filterKey !== key;
+ }),
+ });
+ };
+
+ const toggleFilter = (key: string, value: string) => {
+ if (hasFilter(key, value)) {
+ removeFilter(key, value);
+ } else {
+ addFilter(key, value);
+ }
+ };
+
+ const clearFilters = () => {
+ setParams({ filter: undefined });
+ };
+
+ const hasFilters = urlFiltersParams.length > 0;
+
+ return {
+ clearFilters,
+ hasFilter,
+ hasFilters,
+ hasFilterKey,
+ removeKey,
+ toggleFilter,
+ urlFiltersParams,
+ };
+}
diff --git a/apps/carbon/app/components/Table/components/Sort/Sort.tsx b/apps/carbon/app/components/Table/components/Sort/Sort.tsx
index 9565255b90..97c80c4926 100644
--- a/apps/carbon/app/components/Table/components/Sort/Sort.tsx
+++ b/apps/carbon/app/components/Table/components/Sort/Sort.tsx
@@ -15,7 +15,7 @@ import {
Switch,
} from "@carbon/react";
import { Reorder } from "framer-motion";
-import { BsChevronDown, BsListUl } from "react-icons/bs";
+import { BsChevronDown, BsSortUp } from "react-icons/bs";
import { IoMdClose } from "react-icons/io";
import { MdOutlineDragIndicator } from "react-icons/md";
import { useSort } from "./useSort";
@@ -37,12 +37,11 @@ const Sort = ({ columnAccessors }: SortProps) => {
return (
<Popover>
<PopoverTrigger asChild>
- <Button
+ <IconButton
+ aria-label="Sort"
variant={hasNoSorts ? "ghost" : "primary"}
- leftIcon={<BsListUl />}
- >
- {hasNoSorts ? "Sort" : "Sorted"}
- </Button>
+ icon={<BsSortUp />}
+ />
</PopoverTrigger>
<PopoverContent className="w-[420px]">
{hasNoSorts && (
@@ -114,7 +113,7 @@ const Sort = ({ columnAccessors }: SortProps) => {
key={columnAccessor}
onClick={() => toggleSortBy(columnAccessor)}
>
- <DropdownMenuIcon icon={<BsListUl />} />
+ <DropdownMenuIcon icon={<BsSortUp />} />
{columnAccessors[columnAccessor]}
</DropdownMenuItem>
);
diff --git a/apps/carbon/app/components/Table/components/TableHeader.tsx b/apps/carbon/app/components/Table/components/TableHeader.tsx
index 9365a8ecd3..5bc37f45d5 100644
--- a/apps/carbon/app/components/Table/components/TableHeader.tsx
+++ b/apps/carbon/app/components/Table/components/TableHeader.tsx
@@ -2,10 +2,14 @@ import { Button, HStack } from "@carbon/react";
import type { Column, ColumnOrderState } from "@tanstack/react-table";
import { BsFillCheckCircleFill } from "react-icons/bs";
import { MdOutlineEditNote } from "react-icons/md";
+import New from "~/components/New";
+import { DebouncedInput } from "~/components/Search";
+import { useUrlParams } from "~/hooks";
import type { TableAction } from "../types";
import Actions from "./Actions";
import Columns from "./Columns";
-import Filter from "./Filter";
+import { ActiveFilters, Filter } from "./Filter";
+import type { ColumnFilter } from "./Filter/types";
import type { PaginationProps } from "./Pagination";
import { PaginationButtons } from "./Pagination";
import Sort from "./Sort";
@@ -16,12 +20,15 @@ type HeaderProps<T> = {
columnOrder: ColumnOrderState;
columns: Column<T, unknown>[];
editMode: boolean;
+ filters: ColumnFilter[];
+ label?: string;
+ newPath?: string;
+ newPermission?: boolean;
pagination: PaginationProps;
selectedRows: T[];
setColumnOrder: (newOrder: ColumnOrderState) => void;
setEditMode: (editMode: boolean) => void;
withColumnOrdering: boolean;
- withFilters: boolean;
withInlineEditing: boolean;
withPagination: boolean;
withSelectableRows: boolean;
@@ -33,59 +40,75 @@ const TableHeader = <T extends object>({
columnOrder,
columns,
editMode,
+ filters,
+ label,
+ newPath,
+ newPermission,
pagination,
selectedRows,
setColumnOrder,
setEditMode,
withColumnOrdering,
- withFilters,
withInlineEditing,
withPagination,
withSelectableRows,
}: HeaderProps<T>) => {
- return (
- <HStack className="px-4 py-1.5 justify-between bg-background border-b border-border w-full">
- <HStack>
- {withSelectableRows && actions.length > 0 && (
- <Actions actions={actions} selectedRows={selectedRows} />
- )}
- {withInlineEditing &&
- (editMode ? (
- <Button
- leftIcon={<BsFillCheckCircleFill />}
- onClick={() => setEditMode(false)}
- >
- Finish Editing
- </Button>
- ) : (
- <Button
- leftIcon={<MdOutlineEditNote />}
- variant="ghost"
- onClick={() => setEditMode(true)}
- >
- Edit
- </Button>
- ))}
- </HStack>
- <HStack>
- {withFilters && (
- <>
- <Filter columnAccessors={columnAccessors} />
- <Sort columnAccessors={columnAccessors} />
- </>
- )}
+ const [params] = useUrlParams();
+ const currentFilters = params.getAll("filter");
- {withColumnOrdering && (
- <Columns
- columnOrder={columnOrder}
- columns={columns}
- setColumnOrder={setColumnOrder}
- withSelectableRows={withSelectableRows}
- />
- )}
- {withPagination && <PaginationButtons {...pagination} condensed />}
+ return (
+ <>
+ <HStack className="px-2 py-1.5 justify-between bg-background border-b border-border w-full">
+ <HStack>
+ <DebouncedInput param="search" size="sm" placeholder="Search" />
+ {!!filters?.length && <Filter filters={filters} />}
+ </HStack>
+ <HStack>
+ {withSelectableRows && actions.length > 0 && (
+ // TODO: move this to a draggable bar like Linear
+ <Actions actions={actions} selectedRows={selectedRows} />
+ )}
+ {withInlineEditing &&
+ (editMode ? (
+ <Button
+ leftIcon={<BsFillCheckCircleFill />}
+ onClick={() => setEditMode(false)}
+ >
+ Finish Editing
+ </Button>
+ ) : (
+ <Button
+ leftIcon={<MdOutlineEditNote />}
+ variant="ghost"
+ onClick={() => setEditMode(true)}
+ >
+ Edit
+ </Button>
+ ))}
+ <Sort columnAccessors={columnAccessors} />
+ {withColumnOrdering && (
+ <Columns
+ columnOrder={columnOrder}
+ columns={columns}
+ setColumnOrder={setColumnOrder}
+ withSelectableRows={withSelectableRows}
+ />
+ )}
+ {withPagination &&
+ (pagination.canNextPage || pagination.canPreviousPage) && (
+ <PaginationButtons {...pagination} condensed />
+ )}
+ {!!newPath && !!newPermission && <New to={newPath} label={label} />}
+ </HStack>
</HStack>
- </HStack>
+ {currentFilters.length > 0 && (
+ <HStack className="flex-wrap px-2 py-1.5 justify-between bg-background border-b border-border w-full">
+ <HStack className="flex-wrap">
+ <ActiveFilters filters={filters} />
+ </HStack>
+ </HStack>
+ )}
+ </>
);
};
diff --git a/apps/carbon/app/components/Table/components/index.ts b/apps/carbon/app/components/Table/components/index.ts
index ef990dded6..b12b3d4978 100644
--- a/apps/carbon/app/components/Table/components/index.ts
+++ b/apps/carbon/app/components/Table/components/index.ts
@@ -1,10 +1,9 @@
-import { Td, Th, Tr, spring } from "./Animations";
import Cell from "./Cell";
-import TableHeader from "./TableHeader";
import IndeterminateCheckbox from "./IndeterminateCheckbox";
import { Pagination, usePagination } from "./Pagination";
import Row from "./Row";
import { useSort } from "./Sort";
+import TableHeader from "./TableHeader";
export {
Cell,
@@ -12,10 +11,6 @@ export {
Pagination,
Row,
TableHeader,
- Tr,
- Td,
- Th,
- spring,
usePagination,
useSort,
};
diff --git a/apps/carbon/app/components/Table/types.ts b/apps/carbon/app/components/Table/types.ts
index 473bbe3da2..85d7123a44 100644
--- a/apps/carbon/app/components/Table/types.ts
+++ b/apps/carbon/app/components/Table/types.ts
@@ -1,3 +1,13 @@
+import "@tanstack/react-table";
+import type { ColumnFilterData } from "./components/Filter/types";
+
+declare module "@tanstack/react-table" {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ interface ColumnMeta<TData extends unknown, TValue> {
+ filter?: ColumnFilterData;
+ pluralHeader?: string;
+ }
+}
export interface TableAction<T> {
label: string;
onClick: (rows: T[]) => void;
diff --git a/apps/carbon/app/components/TableOld/Table.tsx b/apps/carbon/app/components/TableOld/Table.tsx
new file mode 100644
index 0000000000..facefc90cf
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/Table.tsx
@@ -0,0 +1,733 @@
+import {
+ ActionMenu,
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuTrigger,
+ Menu,
+ Table as TableBase,
+ Tbody,
+ Th,
+ Thead,
+ Tr,
+ VStack,
+ cn,
+ useEscape,
+ useMount,
+} from "@carbon/react";
+import { clip } from "@carbon/utils";
+import type {
+ ColumnDef,
+ ColumnOrderState,
+ ColumnPinningState,
+ RowSelectionState,
+} from "@tanstack/react-table";
+import {
+ flexRender,
+ getCoreRowModel,
+ useReactTable,
+} from "@tanstack/react-table";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { FaSort, FaSortDown, FaSortUp } from "react-icons/fa";
+import type {
+ EditableTableCellComponent,
+ Position,
+} from "~/components/Editable";
+import {
+ IndeterminateCheckbox,
+ Pagination,
+ Row,
+ TableHeader,
+ usePagination,
+ useSort,
+} from "./components";
+import type { TableAction } from "./types";
+import { getAccessorKey, updateNestedProperty } from "./utils";
+
+interface TableProps<T extends object> {
+ columns: ColumnDef<T>[];
+ data: T[];
+ actions?: TableAction<T>[];
+ count?: number;
+ defaultColumnOrder?: string[];
+ defaultColumnPinning?: ColumnPinningState;
+ defaultColumnVisibility?: Record<string, boolean>;
+ editableComponents?: Record<string, EditableTableCellComponent<T>>;
+ withColumnOrdering?: boolean;
+ withInlineEditing?: boolean;
+ withFilters?: boolean;
+ withPagination?: boolean;
+ withSelectableRows?: boolean;
+ withSimpleSorting?: boolean;
+ onSelectedRowsChange?: (selectedRows: T[]) => void;
+ renderContextMenu?: (row: T) => JSX.Element | null;
+}
+
+const Table = <T extends object>({
+ data,
+ columns,
+ actions = [],
+ count = 0,
+ editableComponents,
+ defaultColumnOrder,
+ defaultColumnPinning = {
+ left: ["Select"],
+ },
+ defaultColumnVisibility,
+ withFilters = false,
+ withInlineEditing = false,
+ withColumnOrdering = false,
+ withPagination = true,
+ withSelectableRows = false,
+ withSimpleSorting = true,
+ onSelectedRowsChange,
+ renderContextMenu,
+}: TableProps<T>) => {
+ const tableContainerRef = useRef<HTMLDivElement>(null);
+
+ /* Data for Optimistic Updates */
+ const [internalData, setInternalData] = useState<T[]>(data);
+ useEffect(() => {
+ setInternalData(data);
+ }, [data]);
+
+ /* Seletable Rows */
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
+
+ /* Pagination */
+ const pagination = usePagination(count, setRowSelection);
+
+ /* Column Visibility */
+ const [columnVisibility, setColumnVisibility] = useState(
+ defaultColumnVisibility ?? {}
+ );
+
+ /* Column Ordering */
+ const [columnOrder, setColumnOrder] = useState<ColumnOrderState>(
+ defaultColumnOrder ?? []
+ );
+ const [columnPinning, setColumnPinning] = useState<ColumnPinningState>(
+ withColumnOrdering ? defaultColumnPinning : {}
+ );
+
+ /* Sorting */
+ const { isSorted, toggleSortBy } = useSort();
+
+ const columnAccessors = useMemo(
+ () =>
+ columns.reduce<Record<string, string>>((acc, column) => {
+ const accessorKey: string | undefined = getAccessorKey(column);
+ if (accessorKey?.includes("_"))
+ throw new Error(
+ `Invalid accessorKey ${accessorKey}. Cannot contain '_'`
+ );
+ if (accessorKey && column.header && typeof column.header === "string") {
+ return {
+ ...acc,
+ [accessorKey]: column.header,
+ };
+ }
+ return acc;
+ }, {}),
+ [columns]
+ );
+
+ const internalColumns = useMemo(() => {
+ let result: ColumnDef<T>[] = [];
+ if (withSelectableRows) {
+ result.push(...getRowSelectionColumn<T>());
+ }
+ result.push(...columns);
+ if (renderContextMenu) {
+ result.push(...getActionColumn<T>(renderContextMenu));
+ }
+ return result;
+ }, [columns, renderContextMenu, withSelectableRows]);
+
+ const table = useReactTable({
+ data: internalData,
+ columns: internalColumns,
+ state: {
+ columnVisibility,
+ columnOrder,
+ columnPinning,
+ rowSelection,
+ },
+ onColumnVisibilityChange: setColumnVisibility,
+ onColumnOrderChange: setColumnOrder,
+ onColumnPinningChange: setColumnPinning,
+ onRowSelectionChange: setRowSelection,
+ getCoreRowModel: getCoreRowModel(),
+ meta: {
+ // These are not part of the standard API, but are accessible via table.options.meta
+ editableComponents,
+ updateData: (rowIndex, updates) => {
+ setInternalData((previousData) =>
+ previousData.map((row, index) => {
+ if (index === rowIndex) {
+ let newRow = { ...row };
+ Object.entries(updates).forEach(([columnId, value]) => {
+ if (columnId.includes("_") && !(columnId in newRow)) {
+ updateNestedProperty(newRow, columnId, value);
+ return newRow;
+ } else {
+ return {
+ ...newRow,
+ [columnId]: value,
+ };
+ }
+ });
+ return newRow;
+ }
+ return row;
+ })
+ );
+ },
+ },
+ });
+
+ const selectedRows = withSelectableRows
+ ? table.getSelectedRowModel().flatRows.map((row) => row.original)
+ : [];
+
+ useEffect(() => {
+ if (typeof onSelectedRowsChange === "function") {
+ onSelectedRowsChange(selectedRows);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [rowSelection, onSelectedRowsChange]);
+
+ const [editMode, setEditMode] = useState(false);
+ const [isEditing, setIsEditing] = useState(false);
+ const [selectedCell, setSelectedCell] = useState<Position>(null);
+
+ const focusOnSelectedCell = useCallback(() => {
+ if (selectedCell == null) return;
+ const cell = tableContainerRef.current?.querySelector(
+ `[data-row="${selectedCell.row}"][data-column="${selectedCell.column}"]`
+ ) as HTMLDivElement;
+ if (cell) cell.focus();
+ }, [selectedCell, tableContainerRef]);
+
+ useEscape(() => {
+ setIsEditing(false);
+ focusOnSelectedCell();
+ });
+
+ const onSelectedCellChange = useCallback(
+ (position: Position) => {
+ if (
+ selectedCell == null ||
+ position == null ||
+ selectedCell.row !== position?.row ||
+ selectedCell.column !== position.column
+ )
+ setSelectedCell(position);
+ },
+ [selectedCell]
+ );
+
+ const isColumnEditable = useCallback(
+ (selectedColumn: number) => {
+ if (!withInlineEditing) return false;
+
+ const tableColumns = [
+ ...table.getLeftVisibleLeafColumns(),
+ ...table.getCenterVisibleLeafColumns(),
+ ];
+
+ const column =
+ tableColumns[withSelectableRows ? selectedColumn + 1 : selectedColumn];
+ if (!column) return false;
+
+ const accessorKey = getAccessorKey(column.columnDef);
+ return (
+ accessorKey && editableComponents && accessorKey in editableComponents
+ );
+ },
+ [table, editableComponents, withInlineEditing, withSelectableRows]
+ );
+
+ const onCellClick = useCallback(
+ (row: number, column: number) => {
+ // ignore row select checkbox column
+ if (
+ selectedCell?.row === row &&
+ selectedCell?.column === column &&
+ isColumnEditable(column)
+ ) {
+ setIsEditing(true);
+ return;
+ }
+ // ignore row select checkbox column
+ if (column === -1) return;
+ setIsEditing(false);
+ onSelectedCellChange({ row, column });
+ },
+ [selectedCell, isColumnEditable, onSelectedCellChange]
+ );
+
+ const onCellUpdate = useCallback(
+ (rowIndex: number) => (updates: Record<string, unknown>) =>
+ table.options.meta?.updateData
+ ? table.options.meta?.updateData(rowIndex, updates)
+ : undefined,
+ [table]
+ );
+
+ const onKeyDown = useCallback(
+ (event: React.KeyboardEvent<HTMLDivElement>) => {
+ if (!selectedCell) return;
+
+ const { code, shiftKey } = event;
+
+ const commandCodes: {
+ [key: string]: [number, number];
+ } = {
+ Tab: [0, 1],
+ Enter: [1, 0],
+ };
+
+ const navigationCodes: {
+ [key: string]: [number, number];
+ } = {
+ ArrowRight: [0, 1],
+ ArrowLeft: [0, -1],
+ ArrowDown: [1, 0],
+ ArrowUp: [-1, 0],
+ };
+
+ const lastRow = table.getRowModel().rows.length - 1;
+ const lastColumn =
+ table.getVisibleLeafColumns().length - 1 - (withSelectableRows ? 1 : 0);
+
+ const navigate = (
+ delta: [number, number],
+ tabWrap = false
+ ): [number, number] => {
+ const x0 = selectedCell?.column || 0;
+ const y0 = selectedCell?.row || 0;
+
+ let x1 = x0 + delta[1];
+ let y1 = y0 + delta[0];
+
+ if (tabWrap) {
+ if (delta[1] > 0) {
+ // wrap to the next row if we're on the last column
+ if (x1 > lastColumn) {
+ x1 = 0;
+ y1 += 1;
+ }
+ // don't wrap to the next row if we're on the last row
+ if (y1 > lastRow) {
+ x1 = x0;
+ y1 = y0;
+ }
+ } else {
+ // reverse tab wrap
+ if (x1 < 0) {
+ x1 = lastColumn;
+ y1 -= 1;
+ }
+
+ if (y1 < 0) {
+ x1 = x0;
+ y1 = y0;
+ }
+ }
+ } else {
+ x1 = clip(x1, 0, lastColumn);
+ }
+
+ y1 = clip(y1, 0, lastRow);
+
+ return [x1, y1];
+ };
+
+ if (code in commandCodes) {
+ event.preventDefault();
+
+ if (
+ !isEditing &&
+ code === "Enter" &&
+ !shiftKey &&
+ isColumnEditable(selectedCell.column)
+ ) {
+ setIsEditing(true);
+ return;
+ }
+
+ let direction = commandCodes[code];
+ if (shiftKey) direction = [-direction[0], -direction[1]];
+ const [x1, y1] = navigate(direction, code === "Tab");
+ setSelectedCell({
+ row: y1,
+ column: x1,
+ });
+ if (isEditing) {
+ setIsEditing(false);
+ }
+ } else if (code in navigationCodes) {
+ // arrow key navigation should't work if we're editing
+ if (isEditing) return;
+ event.preventDefault();
+ const [x1, y1] = navigate(navigationCodes[code], code === "Tab");
+ setIsEditing(false);
+ setSelectedCell({
+ row: y1,
+ column: x1,
+ });
+ // any other key (besides shift) activates editing
+ // if the column is editable and a cell is selected
+ } else if (
+ !["ShiftLeft", "ShiftRight"].includes(code) &&
+ !isEditing &&
+ selectedCell &&
+ isColumnEditable(selectedCell.column)
+ ) {
+ setIsEditing(true);
+ }
+ },
+ [
+ isColumnEditable,
+ isEditing,
+ selectedCell,
+ setSelectedCell,
+ table,
+ withSelectableRows,
+ ]
+ );
+
+ // reset the selected cell when the table data changes
+ useEffect(() => {
+ setSelectedCell(null);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [
+ editMode,
+ pagination.pageIndex,
+ pagination.pageSize,
+ columnOrder,
+ columnVisibility,
+ ]);
+
+ useMount(() => {
+ setColumnOrder(table.getAllLeafColumns().map((column) => column.id));
+ });
+
+ const rows = table.getRowModel().rows;
+
+ return (
+ <VStack spacing={0} className="h-full">
+ {(withColumnOrdering ||
+ withFilters ||
+ withSelectableRows ||
+ withInlineEditing) && (
+ <TableHeader
+ actions={actions}
+ columnAccessors={columnAccessors}
+ columnOrder={columnOrder}
+ columns={table.getAllLeafColumns()}
+ editMode={editMode}
+ selectedRows={selectedRows}
+ setColumnOrder={setColumnOrder}
+ setEditMode={setEditMode}
+ pagination={pagination}
+ withInlineEditing={withInlineEditing}
+ withColumnOrdering={withColumnOrdering}
+ withFilters={withFilters}
+ withPagination={withPagination}
+ withSelectableRows={withSelectableRows}
+ />
+ )}
+ <div
+ className="w-full h-full bg-card overflow-scroll"
+ style={{ contain: "strict" }}
+ ref={tableContainerRef}
+ onKeyDown={editMode ? onKeyDown : undefined}
+ >
+ <div
+ className={cn(
+ "grid w-full",
+ withColumnOrdering ? "grid-cols-[auto_1fr]" : "grid-cols-1"
+ )}
+ >
+ {/* Pinned left columns */}
+ {withColumnOrdering ? (
+ <TableBase className="bg-background border-r-4 border-border sticky left-0 z-50">
+ <Thead>
+ {table.getLeftHeaderGroups().map((headerGroup) => (
+ <Tr key={headerGroup.id} className="h-10">
+ {headerGroup.headers.map((header) => {
+ const accessorKey = getAccessorKey(
+ header.column.columnDef
+ );
+ const sortable =
+ withSimpleSorting &&
+ accessorKey &&
+ !accessorKey.endsWith(".id") &&
+ header.column.columnDef.enableSorting !== false;
+
+ const sorted = isSorted(accessorKey ?? "");
+
+ return (
+ <Th
+ key={header.id}
+ // layout
+ onClick={
+ sortable && !editMode
+ ? () => toggleSortBy(accessorKey ?? "")
+ : undefined
+ }
+ className={cn(
+ "px-4 py-2 whitespace-nowrap",
+ editMode && "cursor-pointer border-r border-border"
+ )}
+ colSpan={header.colSpan}
+ >
+ {header.isPlaceholder ? null : (
+ <div className="flex justify-start items-center text-xs text-muted-foreground">
+ {flexRender(
+ header.column.columnDef.header,
+ header.getContext()
+ )}
+ <span className="pl-4">
+ {sorted ? (
+ sorted === -1 ? (
+ <FaSortDown aria-label="sorted descending" />
+ ) : (
+ <FaSortUp aria-label="sorted ascending" />
+ )
+ ) : sortable ? (
+ <FaSort aria-label="sort" />
+ ) : null}
+ </span>
+ </div>
+ )}
+ </Th>
+ );
+ })}
+ </Tr>
+ ))}
+ </Thead>
+ <Tbody>
+ {rows.map((row) => {
+ return renderContextMenu ? (
+ <Menu type="context" key={row.index}>
+ <ContextMenu>
+ <ContextMenuTrigger asChild>
+ <Row
+ editableComponents={editableComponents}
+ isEditing={isEditing}
+ isEditMode={editMode}
+ isFrozenColumn
+ isRowSelected={
+ row.index in rowSelection &&
+ !!rowSelection[row.index]
+ }
+ selectedCell={selectedCell}
+ row={row}
+ rowIsSelected={selectedCell?.row === row.index}
+ withColumnOrdering={withColumnOrdering}
+ onCellClick={onCellClick}
+ onCellUpdate={onCellUpdate}
+ />
+ </ContextMenuTrigger>
+ <ContextMenuContent className="w-128">
+ {renderContextMenu(row.original)}
+ </ContextMenuContent>
+ </ContextMenu>
+ </Menu>
+ ) : (
+ <Row
+ key={row.id}
+ editableComponents={editableComponents}
+ isEditing={isEditing}
+ isEditMode={editMode}
+ isFrozenColumn
+ isRowSelected={
+ row.index in rowSelection && !!rowSelection[row.index]
+ }
+ selectedCell={selectedCell}
+ row={row}
+ rowIsSelected={selectedCell?.row === row.index}
+ withColumnOrdering={withColumnOrdering}
+ onCellClick={onCellClick}
+ onCellUpdate={onCellUpdate}
+ />
+ );
+ })}
+ </Tbody>
+ </TableBase>
+ ) : null}
+
+ {/* Unpinned columns */}
+ <TableBase>
+ <Thead>
+ {(withColumnOrdering
+ ? table.getCenterHeaderGroups()
+ : table.getHeaderGroups()
+ ).map((headerGroup) => (
+ <Tr key={headerGroup.id} className="h-10">
+ {headerGroup.headers.map((header) => {
+ const accessorKey = getAccessorKey(header.column.columnDef);
+
+ const sortable =
+ withSimpleSorting &&
+ accessorKey &&
+ !accessorKey.endsWith(".id") &&
+ header.column.columnDef.enableSorting !== false;
+ const sorted = isSorted(accessorKey ?? "");
+
+ return (
+ <Th
+ key={header.id}
+ colSpan={header.colSpan}
+ onClick={
+ sortable
+ ? () => toggleSortBy(accessorKey ?? "")
+ : undefined
+ }
+ className={cn(
+ "px-4 py-3 whitespace-nowrap",
+ editMode && "border-r-1 border-border",
+ sortable && "cursor-pointer"
+ )}
+ style={{ width: header.getSize() }}
+ >
+ {header.isPlaceholder ? null : (
+ <div className="flex justify-start items-center text-xs text-muted-foreground">
+ {flexRender(
+ header.column.columnDef.header,
+ header.getContext()
+ )}
+ <span className="pl-4">
+ {sorted ? (
+ sorted === -1 ? (
+ <FaSortDown aria-label="sorted descending" />
+ ) : (
+ <FaSortUp aria-label="sorted ascending" />
+ )
+ ) : sortable ? (
+ <FaSort
+ aria-label="sort"
+ style={{ opacity: 0.4 }}
+ />
+ ) : null}
+ </span>
+ </div>
+ )}
+ </Th>
+ );
+ })}
+ </Tr>
+ ))}
+ </Thead>
+ <Tbody>
+ {rows.map((row) => {
+ return renderContextMenu ? (
+ <Menu type="context" key={row.index}>
+ <ContextMenu>
+ <ContextMenuTrigger asChild>
+ <Row
+ editableComponents={editableComponents}
+ isEditing={isEditing}
+ isEditMode={editMode}
+ isRowSelected={
+ row.index in rowSelection &&
+ !!rowSelection[row.index]
+ }
+ pinnedColumns={
+ columnPinning?.left
+ ? columnPinning.left?.length -
+ (withSelectableRows ? 1 : 0)
+ : 0
+ }
+ selectedCell={selectedCell}
+ row={row}
+ rowIsSelected={selectedCell?.row === row.index}
+ withColumnOrdering={withColumnOrdering}
+ onCellClick={onCellClick}
+ onCellUpdate={onCellUpdate}
+ />
+ </ContextMenuTrigger>
+ <ContextMenuContent className="w-128">
+ {renderContextMenu(row.original)}
+ </ContextMenuContent>
+ </ContextMenu>
+ </Menu>
+ ) : (
+ <Row
+ key={row.id}
+ editableComponents={editableComponents}
+ isEditing={isEditing}
+ isEditMode={editMode}
+ isRowSelected={
+ row.index in rowSelection && !!rowSelection[row.index]
+ }
+ pinnedColumns={
+ columnPinning?.left
+ ? columnPinning.left?.length -
+ (withSelectableRows ? 1 : 0)
+ : 0
+ }
+ selectedCell={selectedCell}
+ row={row}
+ rowIsSelected={selectedCell?.row === row.index}
+ withColumnOrdering={withColumnOrdering}
+ onCellClick={onCellClick}
+ onCellUpdate={onCellUpdate}
+ />
+ );
+ })}
+ </Tbody>
+ </TableBase>
+ </div>
+ </div>
+ {withPagination && <Pagination {...pagination} />}
+ </VStack>
+ );
+};
+
+function getRowSelectionColumn<T>(): ColumnDef<T>[] {
+ return [
+ {
+ id: "Select",
+ size: 40,
+ header: ({ table }) => (
+ <IndeterminateCheckbox
+ {...{
+ checked: table.getIsAllRowsSelected(),
+ indeterminate: table.getIsSomeRowsSelected(),
+ onChange: table.getToggleAllRowsSelectedHandler(),
+ }}
+ />
+ ),
+ cell: ({ row }) => (
+ <IndeterminateCheckbox
+ {...{
+ checked: row.getIsSelected(),
+ indeterminate: row.getIsSomeSelected(),
+ onChange: row.getToggleSelectedHandler(),
+ }}
+ />
+ ),
+ },
+ ];
+}
+
+function getActionColumn<T>(
+ renderContextMenu: (item: T) => JSX.Element | null
+): ColumnDef<T>[] {
+ return [
+ {
+ id: "Actions",
+ header: () => <span className="sr-only">Actions</span>,
+ cell: (item) => (
+ <div className="flex justify-end">
+ <ActionMenu>{renderContextMenu(item.row.original)}</ActionMenu>
+ </div>
+ ),
+ },
+ ];
+}
+
+export default Table;
diff --git a/apps/carbon/app/components/TableOld/components/Actions.tsx b/apps/carbon/app/components/TableOld/components/Actions.tsx
new file mode 100644
index 0000000000..8de66cbf35
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/Actions.tsx
@@ -0,0 +1,45 @@
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@carbon/react";
+import { IoMdCheckboxOutline } from "react-icons/io";
+import type { TableAction } from "../types";
+
+type ActionsProps<T> = {
+ actions: TableAction<T>[];
+ selectedRows: T[];
+};
+
+const Actions = <T extends Object>({
+ actions,
+ selectedRows,
+}: ActionsProps<T>) => {
+ const disabled = selectedRows.length === 0;
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button leftIcon={<IoMdCheckboxOutline />} variant="ghost">
+ Actions
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-48">
+ {actions.map((action) => (
+ <DropdownMenuItem
+ key={action.label}
+ onClick={() => action.onClick(selectedRows)}
+ disabled={disabled || action.disabled}
+ >
+ {action.icon && <DropdownMenuIcon icon={action.icon} />}
+ {action.label}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
+
+export default Actions;
diff --git a/apps/carbon/app/components/Table/components/Animations.tsx b/apps/carbon/app/components/TableOld/components/Animations.tsx
similarity index 100%
rename from apps/carbon/app/components/Table/components/Animations.tsx
rename to apps/carbon/app/components/TableOld/components/Animations.tsx
diff --git a/apps/carbon/app/components/TableOld/components/Cell.tsx b/apps/carbon/app/components/TableOld/components/Cell.tsx
new file mode 100644
index 0000000000..55420cad00
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/Cell.tsx
@@ -0,0 +1,102 @@
+import { Td, cn } from "@carbon/react";
+import type { Cell as CellType } from "@tanstack/react-table";
+import { flexRender } from "@tanstack/react-table";
+import { memo, useState } from "react";
+import type { EditableTableCellComponent } from "~/components/Editable";
+import { useMovingCellRef } from "~/hooks";
+import { getAccessorKey } from "../utils";
+
+type CellProps<T> = {
+ cell: CellType<T, unknown>;
+ columnIndex: number;
+ editableComponents?: Record<string, EditableTableCellComponent<T>>;
+ editedCells?: string[];
+ isEditing: boolean;
+ isEditMode: boolean;
+ isRowSelected: boolean;
+ isSelected: boolean;
+ onClick?: () => void;
+ onUpdate?: (updates: Record<string, unknown>) => void;
+};
+
+const Cell = <T extends object>({
+ cell,
+ columnIndex,
+ editableComponents,
+ editedCells,
+ isEditing,
+ isEditMode,
+ isSelected,
+ onClick,
+ onUpdate,
+}: CellProps<T>) => {
+ const { ref, tabIndex, onFocus } = useMovingCellRef(isSelected);
+ const [hasError, setHasError] = useState(false);
+ const accessorKey = getAccessorKey(cell.column.columnDef);
+
+ const wasEdited =
+ !!editedCells && !!accessorKey && editedCells.includes(accessorKey);
+
+ const hasEditableTableCellComponent =
+ accessorKey !== undefined &&
+ editableComponents &&
+ accessorKey in editableComponents;
+
+ const editableCell = hasEditableTableCellComponent
+ ? editableComponents[accessorKey]
+ : null;
+
+ return (
+ <Td
+ className={cn(
+ "relative px-4 whitespace-nowrap text-sm outline-none",
+ wasEdited && "bg-yellow-100 dark:bg-yellow-900",
+ isEditing && !hasEditableTableCellComponent && "bg-muted/50",
+ isEditMode && "border-border border-r",
+ hasError && "ring-inset ring-2 ring-red-500",
+ isSelected && "ring-inset ring-2 ring-ring"
+ )}
+ ref={ref}
+ data-row={cell.row.index}
+ data-column={columnIndex}
+ tabIndex={tabIndex}
+ onClick={onClick}
+ onFocus={onFocus}
+ >
+ {isSelected && isEditing && hasEditableTableCellComponent ? (
+ <div className="mx-[-0.65rem] my-[-0.25rem]">
+ {hasEditableTableCellComponent
+ ? flexRender(editableCell, {
+ accessorKey,
+ value: cell.renderValue(),
+ row: cell.row.original,
+ onUpdate: onUpdate
+ ? onUpdate
+ : () => console.error("No update function provided"),
+ onError: () => {
+ setHasError(true);
+ },
+ })
+ : null}
+ </div>
+ ) : (
+ <div ref={ref}>
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </div>
+ )}
+ </Td>
+ );
+};
+
+const MemoizedCell = memo(
+ Cell,
+ (prev, next) =>
+ next.isRowSelected === prev.isRowSelected &&
+ next.isSelected === prev.isSelected &&
+ next.isEditing === prev.isEditing &&
+ next.isEditMode === prev.isEditMode &&
+ next.cell.getValue() === prev.cell.getValue() &&
+ next.cell.getContext() === prev.cell.getContext()
+) as typeof Cell;
+
+export default MemoizedCell;
diff --git a/apps/carbon/app/components/TableOld/components/Columns.tsx b/apps/carbon/app/components/TableOld/components/Columns.tsx
new file mode 100644
index 0000000000..4ec8728807
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/Columns.tsx
@@ -0,0 +1,120 @@
+import {
+ Button,
+ HStack,
+ IconButton,
+ Popover,
+ PopoverContent,
+ PopoverHeader,
+ PopoverTrigger,
+} from "@carbon/react";
+import type { Column, ColumnOrderState } from "@tanstack/react-table";
+import { Reorder } from "framer-motion";
+import {
+ BsEyeFill,
+ BsEyeSlash,
+ BsLayoutThreeColumns,
+ BsPin,
+ BsPinFill,
+} from "react-icons/bs";
+import { MdOutlineDragIndicator } from "react-icons/md";
+
+type ColumnsProps<T> = {
+ columns: Column<T, unknown>[];
+ columnOrder: ColumnOrderState;
+ withSelectableRows: boolean;
+ setColumnOrder: (newOrder: ColumnOrderState) => void;
+};
+
+const Columns = <T extends object>({
+ columns,
+ columnOrder,
+ withSelectableRows,
+ setColumnOrder,
+}: ColumnsProps<T>) => {
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button variant="ghost" leftIcon={<BsLayoutThreeColumns />}>
+ Columns
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-96">
+ <PopoverHeader>
+ <p className="text-sm">Edit column view</p>
+ <p className="text-xs text-muted-foreground">
+ Manage and reorder columns
+ </p>
+ </PopoverHeader>
+
+ <div className="max-h-48 overflow-y-auto">
+ <Reorder.Group
+ axis="y"
+ values={columnOrder}
+ onReorder={(newOrder: ColumnOrderState) => {
+ if (withSelectableRows) newOrder.unshift("select");
+ setColumnOrder(newOrder);
+ }}
+ className="space-y-2"
+ >
+ {columns.reduce<JSX.Element[]>((acc, column) => {
+ if (isColumnToggable(column))
+ acc.push(
+ <Reorder.Item
+ key={column.id}
+ value={column.id}
+ className="rounded-lg"
+ >
+ <HStack>
+ <IconButton
+ aria-label="Drag handle"
+ icon={<MdOutlineDragIndicator />}
+ variant="ghost"
+ />
+ <span className="text-sm flex-grow">
+ <>{column.columnDef.header}</>
+ </span>
+ <IconButton
+ aria-label="Toggle column"
+ icon={column.getIsPinned() ? <BsPinFill /> : <BsPin />}
+ onClick={(e) => {
+ if (column.getIsPinned()) {
+ column.pin(false);
+ } else {
+ column.pin("left");
+ // when a column is pinned, we assure that it's visible
+ if (!column.getIsVisible()) {
+ column.getToggleVisibilityHandler()(e);
+ }
+ }
+ }}
+ variant="ghost"
+ />
+ <IconButton
+ aria-label="Toggle column"
+ icon={
+ column.getIsVisible() ? <BsEyeFill /> : <BsEyeSlash />
+ }
+ onClick={column.getToggleVisibilityHandler()}
+ variant="ghost"
+ />
+ </HStack>
+ </Reorder.Item>
+ );
+ return acc;
+ }, [])}
+ </Reorder.Group>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+};
+
+function isColumnToggable<T>(column: Column<T, unknown>): boolean {
+ return (
+ column.columnDef.id !== "select" &&
+ typeof column.columnDef.header === "string" &&
+ column.columnDef.header !== ""
+ );
+}
+
+export default Columns;
diff --git a/apps/carbon/app/components/TableOld/components/Filter/Filter.tsx b/apps/carbon/app/components/TableOld/components/Filter/Filter.tsx
new file mode 100644
index 0000000000..b82408589b
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/Filter/Filter.tsx
@@ -0,0 +1,91 @@
+import {
+ Button,
+ Popover,
+ PopoverContent,
+ PopoverFooter,
+ PopoverHeader,
+ PopoverTrigger,
+ VStack,
+} from "@carbon/react";
+import { BsFilter, BsPlus } from "react-icons/bs";
+import { useUrlParams } from "~/hooks";
+import FilterRow from "./FilterRow";
+
+type FilterProps = {
+ columnAccessors: Record<string, string>;
+};
+
+const Filter = ({ columnAccessors }: FilterProps) => {
+ const [params, setParams] = useUrlParams();
+ const filters = params.getAll("filter");
+
+ const addFilter = () => {
+ const defaultFilter = `${Object.keys(columnAccessors)[0]}:contains:`;
+ setParams({ filter: filters.concat(defaultFilter) });
+ };
+
+ const removeFilter = (filterIndex: number) => {
+ setParams({
+ filter: filters.filter((_, index) => index !== filterIndex),
+ });
+ };
+
+ const updateFilter = (filterIndex: number, newFilter: string) => {
+ setParams({
+ filter: filters.map((filter, index) =>
+ index === filterIndex ? newFilter : filter
+ ),
+ });
+ };
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant={filters.length === 0 ? "ghost" : "primary"}
+ leftIcon={<BsFilter />}
+ >
+ {filters.length === 0 ? "Filter" : "Filtered"}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[520px]">
+ {filters.length === 0 && (
+ <PopoverHeader>
+ <p className="text-sm">No filters applied to this view</p>
+ <p className="text-xs text-muted-foreground">
+ Add a column below to sort the view
+ </p>
+ </PopoverHeader>
+ )}
+
+ {filters.length > 0 && (
+ <VStack>
+ {filters.reduce<JSX.Element[]>((acc, filter, index) => {
+ const [column, operator, searchValue] = filter.split(":");
+ if (!column || !operator) return acc;
+ acc.push(
+ <FilterRow
+ key={`filter-${column}-${[index]}`}
+ column={column}
+ columnAccessors={columnAccessors}
+ operator={operator}
+ searchValue={searchValue}
+ onRemove={() => removeFilter(index)}
+ onUpdate={(newFilter) => updateFilter(index, newFilter)}
+ />
+ );
+ return acc;
+ }, [])}
+ </VStack>
+ )}
+ <PopoverFooter>
+ <Button variant="secondary" leftIcon={<BsPlus />} onClick={addFilter}>
+ Add Filter
+ </Button>
+ </PopoverFooter>
+ </PopoverContent>
+ </Popover>
+ );
+};
+
+export default Filter;
diff --git a/apps/carbon/app/components/Table/components/Filter/FilterRow.tsx b/apps/carbon/app/components/TableOld/components/Filter/FilterRow.tsx
similarity index 100%
rename from apps/carbon/app/components/Table/components/Filter/FilterRow.tsx
rename to apps/carbon/app/components/TableOld/components/Filter/FilterRow.tsx
diff --git a/apps/carbon/app/components/TableOld/components/Filter/index.ts b/apps/carbon/app/components/TableOld/components/Filter/index.ts
new file mode 100644
index 0000000000..0cea50296e
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/Filter/index.ts
@@ -0,0 +1,3 @@
+import Filter from "./Filter";
+
+export default Filter;
diff --git a/apps/carbon/app/components/TableOld/components/IndeterminateCheckbox.tsx b/apps/carbon/app/components/TableOld/components/IndeterminateCheckbox.tsx
new file mode 100644
index 0000000000..bd4faf3360
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/IndeterminateCheckbox.tsx
@@ -0,0 +1,38 @@
+import { Checkbox } from "@carbon/react";
+import type { MouseEvent } from "react";
+
+type IndeterminateCheckboxProps = {
+ checked: boolean;
+ indeterminate: boolean;
+ onChange: (e: MouseEvent<HTMLInputElement>) => void;
+ [key: string]: any;
+};
+
+const IndeterminateCheckbox = ({
+ indeterminate,
+ checked,
+ onChange,
+ ...rest
+}: IndeterminateCheckboxProps) => {
+ const handleChange = (checked: boolean) => {
+ onChange({
+ target: { checked },
+ } as unknown as MouseEvent<HTMLInputElement>);
+ };
+
+ return (
+ <Checkbox
+ isChecked={!!checked || !!indeterminate}
+ isIndeterminate={indeterminate}
+ className="ml-2"
+ onCheckedChange={handleChange}
+ {...rest}
+ >
+ <span className="sr-only">Select Row</span>
+ </Checkbox>
+ );
+};
+
+IndeterminateCheckbox.displayName = "IndeterminateCheckbox";
+
+export default IndeterminateCheckbox;
diff --git a/apps/carbon/app/components/TableOld/components/Pagination/Pagination.tsx b/apps/carbon/app/components/TableOld/components/Pagination/Pagination.tsx
new file mode 100644
index 0000000000..09e7fff041
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/Pagination/Pagination.tsx
@@ -0,0 +1,182 @@
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+ useKeyboardShortcuts,
+} from "@carbon/react";
+import { useRef } from "react";
+import { BsChevronLeft, BsChevronRight } from "react-icons/bs";
+
+export type PaginationProps = {
+ count: number;
+ offset: number;
+ pageIndex: number;
+ pageSize: number;
+ canPreviousPage: boolean;
+ canNextPage: boolean;
+ pageCount: number;
+ gotoPage: (page: number) => void;
+ nextPage: () => void;
+ previousPage: () => void;
+ setPageSize: (size: number) => void;
+};
+
+const Pagination = (props: PaginationProps) => {
+ const { pageSize, setPageSize } = props;
+
+ const pageSizes = [15, 25, 50, 100];
+ const pageSizeLabel = "results per page";
+ if (!pageSizes.includes(pageSize)) {
+ pageSizes.push(pageSize);
+ pageSizes.sort();
+ }
+
+ return (
+ <HStack
+ className="text-center bg-background border-t border-border justify-between px-4 py-2 w-full z-[1]"
+ spacing={6}
+ >
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost">
+ {pageSize} {pageSizeLabel}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-48">
+ <DropdownMenuLabel>Results per page</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuRadioGroup value={`${pageSize}`}>
+ {pageSizes.map((size) => (
+ <DropdownMenuRadioItem
+ key={`${size}`}
+ value={`${size}`}
+ onClick={() => {
+ setPageSize(size);
+ }}
+ >
+ {size} {pageSizeLabel}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <HStack>
+ <PaginationButtons {...props} />
+ </HStack>
+ </HStack>
+ );
+};
+
+export const PaginationButtons = ({
+ condensed = false,
+ canNextPage,
+ canPreviousPage,
+ count,
+ nextPage,
+ offset,
+ pageSize,
+ previousPage,
+}: PaginationProps & { condensed?: boolean }) => {
+ const nextButtonRef = useRef<HTMLButtonElement>(null);
+ const previousButtonRef = useRef<HTMLButtonElement>(null);
+
+ useKeyboardShortcuts({
+ j: (event: KeyboardEvent) => {
+ event.stopPropagation();
+ nextButtonRef.current?.click();
+ },
+ f: (event: KeyboardEvent) => {
+ event.stopPropagation();
+ previousButtonRef.current?.click();
+ },
+ });
+
+ return (
+ <>
+ {condensed ? (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <IconButton
+ aria-label="Previous"
+ icon={<BsChevronLeft />}
+ isDisabled={!canPreviousPage}
+ onClick={previousPage}
+ variant="secondary"
+ />
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>F</HStack>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger>
+ <IconButton
+ aria-label="Next"
+ icon={<BsChevronRight />}
+ isDisabled={!canNextPage}
+ onClick={nextPage}
+ variant="secondary"
+ />
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>J</HStack>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ ) : (
+ <TooltipProvider>
+ <div className="text-foreground flex text-sm font-medium align-center">
+ {count > 0 ? offset + 1 : 0} - {Math.min(offset + pageSize, count)}{" "}
+ of {count}
+ </div>
+ <Tooltip>
+ <TooltipTrigger>
+ <Button
+ ref={previousButtonRef}
+ variant="secondary"
+ isDisabled={!canPreviousPage}
+ onClick={previousPage}
+ leftIcon={<BsChevronLeft />}
+ >
+ Previous
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>F</HStack>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger>
+ <Button
+ ref={nextButtonRef}
+ variant="secondary"
+ isDisabled={!canNextPage}
+ onClick={nextPage}
+ rightIcon={<BsChevronRight />}
+ >
+ Next
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>J</HStack>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ )}
+ </>
+ );
+};
+
+export default Pagination;
diff --git a/apps/carbon/app/components/TableOld/components/Pagination/index.ts b/apps/carbon/app/components/TableOld/components/Pagination/index.ts
new file mode 100644
index 0000000000..6b12b9ba4d
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/Pagination/index.ts
@@ -0,0 +1,6 @@
+import Pagination, { PaginationButtons } from "./Pagination";
+import type { PaginationProps } from "./Pagination";
+import { usePagination } from "./usePagination";
+
+export { Pagination, PaginationButtons, usePagination };
+export type { PaginationProps };
diff --git a/apps/carbon/app/components/TableOld/components/Pagination/usePagination.tsx b/apps/carbon/app/components/TableOld/components/Pagination/usePagination.tsx
new file mode 100644
index 0000000000..fc04a6bc20
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/Pagination/usePagination.tsx
@@ -0,0 +1,61 @@
+import type { RowSelectionState } from "@tanstack/react-table";
+import type { Dispatch, SetStateAction } from "react";
+import { flushSync } from "react-dom";
+import { useUrlParams } from "~/hooks";
+import { parseNumberFromUrlParam } from "~/utils/http";
+
+export function usePagination(
+ count: number,
+ setRowSelections: Dispatch<SetStateAction<RowSelectionState>>
+) {
+ const [params, setParams] = useUrlParams();
+ const pageSize = parseNumberFromUrlParam(params, "limit", 15);
+ const offset = parseNumberFromUrlParam(params, "offset", 0);
+
+ const pageIndex = Math.floor(offset / pageSize) + 1;
+ const pageCount = Math.ceil(count / pageSize);
+ const canPreviousPage = pageIndex > 1;
+ const canNextPage = pageIndex < Math.ceil(count / pageSize);
+
+ const gotoPage = (page: number) => {
+ flushSync(() => {
+ setRowSelections({});
+ setParams({
+ ...Object.fromEntries(params),
+ offset: (page - 1) * pageSize,
+ limit: pageSize,
+ });
+ });
+
+ window?.scrollTo({ top: 0, behavior: "smooth" });
+ };
+
+ const previousPage = () => {
+ gotoPage(pageIndex - 1);
+ };
+
+ const nextPage = () => {
+ gotoPage(pageIndex + 1);
+ };
+
+ const setPageSize = (pageSize: number) => {
+ setParams({
+ offset: 0,
+ limit: pageSize,
+ });
+ };
+
+ return {
+ count,
+ offset,
+ pageIndex,
+ pageCount,
+ pageSize,
+ canPreviousPage,
+ canNextPage,
+ gotoPage,
+ nextPage,
+ previousPage,
+ setPageSize,
+ };
+}
diff --git a/apps/carbon/app/components/TableOld/components/Row.tsx b/apps/carbon/app/components/TableOld/components/Row.tsx
new file mode 100644
index 0000000000..a2e8953ea8
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/Row.tsx
@@ -0,0 +1,110 @@
+import { Tr, cn } from "@carbon/react";
+import type { Row as RowType } from "@tanstack/react-table";
+import type { ComponentProps } from "react";
+import { memo } from "react";
+import type {
+ EditableTableCellComponent,
+ Position,
+} from "~/components/Editable";
+import Cell from "./Cell";
+
+type RowProps<T> = ComponentProps<typeof Tr> & {
+ editableComponents?: Record<string, EditableTableCellComponent<T> | object>;
+ editedCells?: string[];
+ isEditing: boolean;
+ isEditMode: boolean;
+ isFrozenColumn?: boolean;
+ isRowSelected?: boolean;
+ pinnedColumns?: number;
+ selectedCell: Position;
+ row: RowType<T>;
+ rowIsSelected: boolean;
+ withColumnOrdering: boolean;
+ onCellClick: (row: number, column: number) => void;
+ onCellUpdate: (row: number) => (updates: Record<string, unknown>) => void;
+};
+
+const Row = <T extends object>({
+ editableComponents,
+ editedCells,
+ isEditing,
+ isEditMode,
+ isFrozenColumn = false,
+ isRowSelected = false,
+ pinnedColumns = 0,
+ row,
+ rowIsSelected,
+ selectedCell,
+ withColumnOrdering,
+ onCellClick,
+ onCellUpdate,
+ ...props
+}: RowProps<T>) => {
+ const onUpdate = isEditMode ? onCellUpdate(row.index) : undefined;
+
+ return (
+ <Tr
+ key={row.id}
+ className={cn(
+ "border-b border-border transition-colors",
+ isFrozenColumn && "bg-card"
+ )}
+ {...props}
+ >
+ {(isFrozenColumn
+ ? row.getLeftVisibleCells()
+ : withColumnOrdering
+ ? row.getCenterVisibleCells()
+ : row.getVisibleCells()
+ ).map((cell, columnIndex) => {
+ const isSelected = isFrozenColumn
+ ? selectedCell?.row === cell.row.index &&
+ selectedCell?.column === columnIndex - 1
+ : selectedCell?.row === cell.row.index &&
+ selectedCell?.column === columnIndex + pinnedColumns;
+
+ return (
+ <Cell<T>
+ key={cell.id}
+ cell={cell}
+ columnIndex={columnIndex}
+ // @ts-ignore
+ editableComponents={editableComponents}
+ editedCells={editedCells}
+ isRowSelected={isRowSelected}
+ isSelected={isSelected}
+ isEditing={isEditing}
+ isEditMode={isEditMode}
+ onClick={
+ isEditMode
+ ? () =>
+ onCellClick(
+ cell.row.index,
+ isFrozenColumn
+ ? columnIndex - 1
+ : columnIndex + pinnedColumns
+ )
+ : undefined
+ }
+ onUpdate={onUpdate}
+ />
+ );
+ })}
+ </Tr>
+ );
+};
+
+const MemoizedRow = memo(
+ Row,
+ (prev, next) =>
+ next.rowIsSelected === false &&
+ prev.rowIsSelected === false &&
+ next.isRowSelected === prev.isRowSelected &&
+ next.selectedCell?.row === prev.row.index &&
+ next.row.index === prev.selectedCell?.row &&
+ next.selectedCell?.column === prev.selectedCell?.column &&
+ next.isEditing === prev.isEditing &&
+ next.isEditMode === prev.isEditMode
+) as typeof Row;
+
+export default MemoizedRow;
diff --git a/apps/carbon/app/components/TableOld/components/Sort/Sort.tsx b/apps/carbon/app/components/TableOld/components/Sort/Sort.tsx
new file mode 100644
index 0000000000..9565255b90
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/Sort/Sort.tsx
@@ -0,0 +1,130 @@
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ Popover,
+ PopoverContent,
+ PopoverFooter,
+ PopoverHeader,
+ PopoverTrigger,
+ Switch,
+} from "@carbon/react";
+import { Reorder } from "framer-motion";
+import { BsChevronDown, BsListUl } from "react-icons/bs";
+import { IoMdClose } from "react-icons/io";
+import { MdOutlineDragIndicator } from "react-icons/md";
+import { useSort } from "./useSort";
+
+type SortProps = {
+ columnAccessors: Record<string, string>;
+};
+
+const Sort = ({ columnAccessors }: SortProps) => {
+ const {
+ sorts,
+ removeSortBy,
+ reorderSorts,
+ toggleSortBy,
+ toggleSortByDirection,
+ } = useSort();
+ const hasNoSorts = sorts.length === 0;
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant={hasNoSorts ? "ghost" : "primary"}
+ leftIcon={<BsListUl />}
+ >
+ {hasNoSorts ? "Sort" : "Sorted"}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[420px]">
+ {hasNoSorts && (
+ <PopoverHeader>
+ <p className="text-sm">No sorts applied to this view</p>
+ <p className="text-xs text-muted-foreground">
+ Add a column below to sort the view
+ </p>
+ </PopoverHeader>
+ )}
+
+ {!hasNoSorts && (
+ <Reorder.Group
+ axis="y"
+ values={sorts}
+ onReorder={reorderSorts}
+ className="space-y-2"
+ >
+ {sorts.map((sort) => {
+ const [column, direction] = sort.split(":");
+ return (
+ <Reorder.Item key={sort} value={sort} className="rounded-lg">
+ <HStack>
+ <IconButton
+ aria-label="Drag handle"
+ icon={<MdOutlineDragIndicator />}
+ variant="ghost"
+ />
+ <span className="text-sm flex-grow">
+ <>{columnAccessors[column] ?? ""}</>
+ </span>
+ <Switch
+ checked={direction === "asc"}
+ onCheckedChange={() => toggleSortByDirection(column)}
+ />
+ <span className="text-sm text-muted-foreground">
+ Ascending
+ </span>
+ <IconButton
+ aria-label="Remove sort by column"
+ icon={<IoMdClose />}
+ onClick={() => removeSortBy(sort)}
+ variant="ghost"
+ />
+ </HStack>
+ </Reorder.Item>
+ );
+ })}
+ </Reorder.Group>
+ )}
+
+ <PopoverFooter>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button rightIcon={<BsChevronDown />} variant="secondary">
+ Pick a column to sort by
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="w-48">
+ {Object.keys(columnAccessors)
+ .filter((columnAccessor) => {
+ return !sorts
+ .map((sort) => sort.split(":")[0])
+ .includes(columnAccessor);
+ })
+ .map((columnAccessor) => {
+ return (
+ <DropdownMenuItem
+ key={columnAccessor}
+ onClick={() => toggleSortBy(columnAccessor)}
+ >
+ <DropdownMenuIcon icon={<BsListUl />} />
+ {columnAccessors[columnAccessor]}
+ </DropdownMenuItem>
+ );
+ })}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </PopoverFooter>
+ </PopoverContent>
+ </Popover>
+ );
+};
+
+export default Sort;
diff --git a/apps/carbon/app/components/TableOld/components/Sort/index.ts b/apps/carbon/app/components/TableOld/components/Sort/index.ts
new file mode 100644
index 0000000000..684f8ac27f
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/Sort/index.ts
@@ -0,0 +1,5 @@
+import Sort from "./Sort";
+import { useSort } from "./useSort";
+
+export default Sort;
+export { useSort };
diff --git a/apps/carbon/app/components/TableOld/components/Sort/useSort.tsx b/apps/carbon/app/components/TableOld/components/Sort/useSort.tsx
new file mode 100644
index 0000000000..e92dbf9c52
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/Sort/useSort.tsx
@@ -0,0 +1,61 @@
+import { useUrlParams } from "~/hooks";
+
+export function useSort() {
+ const [params, setParams] = useUrlParams();
+ const sorts = params.getAll("sort");
+
+ const isSorted = (columnId: string): -1 | null | 1 => {
+ if (sorts.includes(`${columnId}:asc`)) return 1;
+ if (sorts.includes(`${columnId}:desc`)) return -1;
+ return null;
+ };
+
+ const reorderSorts = (newOrder: string[]) => {
+ setParams({ sort: newOrder });
+ };
+
+ const removeSortBy = (sort: string) => {
+ setParams({ sort: sorts.filter((s) => s !== sort) });
+ };
+
+ const toggleSortBy = (columnId: string) => {
+ const existingSort = [...sorts];
+ const sortAsc = `${columnId}:asc`;
+ const sortDesc = `${columnId}:desc`;
+
+ if (existingSort.includes(sortAsc)) {
+ setParams({
+ sort: existingSort.filter((s) => s !== sortAsc).concat(sortDesc),
+ });
+ } else if (existingSort.includes(sortDesc)) {
+ setParams({ sort: existingSort.filter((s) => s !== sortDesc) });
+ } else {
+ setParams({ sort: existingSort.concat(sortAsc) });
+ }
+ };
+
+ const toggleSortByDirection = (columnId: string) => {
+ const existingSort = [...sorts];
+ const sortAsc = `${columnId}:asc`;
+ const sortDesc = `${columnId}:desc`;
+
+ if (existingSort.includes(sortAsc)) {
+ setParams({
+ sort: existingSort.map((s) => (s === sortAsc ? sortDesc : s)),
+ });
+ } else if (existingSort.includes(sortDesc)) {
+ setParams({
+ sort: existingSort.map((s) => (s === sortDesc ? sortAsc : s)),
+ });
+ }
+ };
+
+ return {
+ sorts,
+ isSorted,
+ reorderSorts,
+ removeSortBy,
+ toggleSortBy,
+ toggleSortByDirection,
+ };
+}
diff --git a/apps/carbon/app/components/TableOld/components/TableHeader.tsx b/apps/carbon/app/components/TableOld/components/TableHeader.tsx
new file mode 100644
index 0000000000..9365a8ecd3
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/TableHeader.tsx
@@ -0,0 +1,92 @@
+import { Button, HStack } from "@carbon/react";
+import type { Column, ColumnOrderState } from "@tanstack/react-table";
+import { BsFillCheckCircleFill } from "react-icons/bs";
+import { MdOutlineEditNote } from "react-icons/md";
+import type { TableAction } from "../types";
+import Actions from "./Actions";
+import Columns from "./Columns";
+import Filter from "./Filter";
+import type { PaginationProps } from "./Pagination";
+import { PaginationButtons } from "./Pagination";
+import Sort from "./Sort";
+
+type HeaderProps<T> = {
+ actions: TableAction<T>[];
+ columnAccessors: Record<string, string>;
+ columnOrder: ColumnOrderState;
+ columns: Column<T, unknown>[];
+ editMode: boolean;
+ pagination: PaginationProps;
+ selectedRows: T[];
+ setColumnOrder: (newOrder: ColumnOrderState) => void;
+ setEditMode: (editMode: boolean) => void;
+ withColumnOrdering: boolean;
+ withFilters: boolean;
+ withInlineEditing: boolean;
+ withPagination: boolean;
+ withSelectableRows: boolean;
+};
+
+const TableHeader = <T extends object>({
+ actions,
+ columnAccessors,
+ columnOrder,
+ columns,
+ editMode,
+ pagination,
+ selectedRows,
+ setColumnOrder,
+ setEditMode,
+ withColumnOrdering,
+ withFilters,
+ withInlineEditing,
+ withPagination,
+ withSelectableRows,
+}: HeaderProps<T>) => {
+ return (
+ <HStack className="px-4 py-1.5 justify-between bg-background border-b border-border w-full">
+ <HStack>
+ {withSelectableRows && actions.length > 0 && (
+ <Actions actions={actions} selectedRows={selectedRows} />
+ )}
+ {withInlineEditing &&
+ (editMode ? (
+ <Button
+ leftIcon={<BsFillCheckCircleFill />}
+ onClick={() => setEditMode(false)}
+ >
+ Finish Editing
+ </Button>
+ ) : (
+ <Button
+ leftIcon={<MdOutlineEditNote />}
+ variant="ghost"
+ onClick={() => setEditMode(true)}
+ >
+ Edit
+ </Button>
+ ))}
+ </HStack>
+ <HStack>
+ {withFilters && (
+ <>
+ <Filter columnAccessors={columnAccessors} />
+ <Sort columnAccessors={columnAccessors} />
+ </>
+ )}
+
+ {withColumnOrdering && (
+ <Columns
+ columnOrder={columnOrder}
+ columns={columns}
+ setColumnOrder={setColumnOrder}
+ withSelectableRows={withSelectableRows}
+ />
+ )}
+ {withPagination && <PaginationButtons {...pagination} condensed />}
+ </HStack>
+ </HStack>
+ );
+};
+
+export default TableHeader;
diff --git a/apps/carbon/app/components/TableOld/components/index.ts b/apps/carbon/app/components/TableOld/components/index.ts
new file mode 100644
index 0000000000..ef990dded6
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/components/index.ts
@@ -0,0 +1,21 @@
+import { Td, Th, Tr, spring } from "./Animations";
+import Cell from "./Cell";
+import TableHeader from "./TableHeader";
+import IndeterminateCheckbox from "./IndeterminateCheckbox";
+import { Pagination, usePagination } from "./Pagination";
+import Row from "./Row";
+import { useSort } from "./Sort";
+
+export {
+ Cell,
+ IndeterminateCheckbox,
+ Pagination,
+ Row,
+ TableHeader,
+ Tr,
+ Td,
+ Th,
+ spring,
+ usePagination,
+ useSort,
+};
diff --git a/apps/carbon/app/components/TableOld/index.ts b/apps/carbon/app/components/TableOld/index.ts
new file mode 100644
index 0000000000..ec5c448a93
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/index.ts
@@ -0,0 +1,3 @@
+import Table from "./Table";
+
+export default Table;
diff --git a/apps/carbon/app/components/TableOld/types.ts b/apps/carbon/app/components/TableOld/types.ts
new file mode 100644
index 0000000000..473bbe3da2
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/types.ts
@@ -0,0 +1,6 @@
+export interface TableAction<T> {
+ label: string;
+ onClick: (rows: T[]) => void;
+ disabled?: boolean;
+ icon?: JSX.Element;
+}
diff --git a/apps/carbon/app/components/TableOld/utils.ts b/apps/carbon/app/components/TableOld/utils.ts
new file mode 100644
index 0000000000..278ebdc510
--- /dev/null
+++ b/apps/carbon/app/components/TableOld/utils.ts
@@ -0,0 +1,22 @@
+import type { ColumnDef } from "@tanstack/react-table";
+
+export function getAccessorKey<T>(columnDef: ColumnDef<T, unknown>) {
+ return "accessorKey" in columnDef
+ ? columnDef?.accessorKey.toString()
+ : undefined;
+}
+
+export function updateNestedProperty(
+ obj: object,
+ path: string | string[],
+ value: unknown
+): unknown {
+ if (typeof path == "string")
+ return updateNestedProperty(obj, path.split("_"), value);
+ else if (path.length == 1 && value !== undefined)
+ // @ts-ignore
+ return (obj[path[0]] = value);
+ else if (path.length == 0) return obj;
+ // @ts-ignore
+ else return updateNestedProperty(obj[path[0]], path.slice(1), value);
+}
diff --git a/apps/carbon/app/components/index.ts b/apps/carbon/app/components/index.ts
index 8d8fa51559..db7d7a7488 100644
--- a/apps/carbon/app/components/index.ts
+++ b/apps/carbon/app/components/index.ts
@@ -7,7 +7,8 @@ import CreatableCombobox from "./CreateableCombobox";
import MultiSelect from "./MultiSelect";
import New from "./New";
import Select from "./Select";
-import Table from "./Table";
+import TableNew from "./Table";
+import Table from "./TableOld";
export {
Address,
@@ -22,4 +23,5 @@ export {
New,
Select,
Table,
+ TableNew,
};
diff --git a/apps/carbon/app/modules/parts/parts.service.ts b/apps/carbon/app/modules/parts/parts.service.ts
index 32ea8b4f76..f2b2eb2afd 100644
--- a/apps/carbon/app/modules/parts/parts.service.ts
+++ b/apps/carbon/app/modules/parts/parts.service.ts
@@ -132,8 +132,6 @@ export async function getParts(
client: SupabaseClient<Database>,
args: GenericQueryFilters & {
search: string | null;
- type: string | null;
- group: string | null;
supplierId: string | null;
}
) {
@@ -147,14 +145,6 @@ export async function getParts(
);
}
- if (args.type) {
- query = query.eq("partType", args.type);
- }
-
- if (args.group) {
- query = query.eq("partGroupId", args.group);
- }
-
if (args.supplierId) {
query = query.contains("supplierIds", [args.supplierId]);
}
diff --git a/apps/carbon/app/modules/parts/ui/Parts/PartsTable.tsx b/apps/carbon/app/modules/parts/ui/Parts/PartsTable.tsx
index 635c95e423..7d8b363774 100644
--- a/apps/carbon/app/modules/parts/ui/Parts/PartsTable.tsx
+++ b/apps/carbon/app/modules/parts/ui/Parts/PartsTable.tsx
@@ -3,19 +3,23 @@ import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
import { BsFillPenFill } from "react-icons/bs";
-import { Table } from "~/components";
-import { useUrlParams } from "~/hooks";
+import { TableNew } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
import type { Part } from "~/modules/parts";
+import { partReplenishmentSystems, partTypes } from "~/modules/parts";
+import type { ListItem } from "~/types";
import { path } from "~/utils/path";
type PartsTableProps = {
data: Part[];
+ partGroups: ListItem[];
count: number;
};
-const PartsTable = memo(({ data, count }: PartsTableProps) => {
+const PartsTable = memo(({ data, count, partGroups }: PartsTableProps) => {
const navigate = useNavigate();
const [params] = useUrlParams();
+ const permissions = usePermissions();
const columns = useMemo<ColumnDef<Part>[]>(() => {
return [
@@ -42,16 +46,43 @@ const PartsTable = memo(({ data, count }: PartsTableProps) => {
accessorKey: "partType",
header: "Part Type",
cell: (item) => <Enumerable value={item.getValue<string>()} />,
+ meta: {
+ filter: {
+ type: "static",
+ options: partTypes.map((type) => ({
+ value: type,
+ label: <Enumerable value={type} />,
+ })),
+ },
+ },
},
{
accessorKey: "replenishmentSystem",
header: "Replenishment",
cell: (item) => <Enumerable value={item.getValue<string>()} />,
+ meta: {
+ filter: {
+ type: "static",
+ options: partReplenishmentSystems.map((type) => ({
+ value: type,
+ label: <Enumerable value={type} />,
+ })),
+ },
+ },
},
{
accessorKey: "partGroup",
header: "Part Group",
cell: (item) => <Enumerable value={item.getValue<string>()} />,
+ meta: {
+ filter: {
+ type: "static",
+ options: partGroups.map(({ id, name }) => ({
+ value: id,
+ label: <Enumerable value={name} />,
+ })),
+ },
+ },
},
];
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -69,11 +100,13 @@ const PartsTable = memo(({ data, count }: PartsTableProps) => {
return (
<>
- <Table<Part>
+ <TableNew<Part>
count={count}
columns={columns}
data={data}
- withPagination
+ label="Part"
+ newPath={path.to.newPart}
+ newPermission={permissions.can("create", "parts")}
renderContextMenu={renderContextMenu}
/>
</>
diff --git a/apps/carbon/app/modules/parts/ui/Parts/PartsTableFilters.tsx b/apps/carbon/app/modules/parts/ui/Parts/PartsTableFilters.tsx
deleted file mode 100644
index 7ae08a633c..0000000000
--- a/apps/carbon/app/modules/parts/ui/Parts/PartsTableFilters.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-import { HStack } from "@carbon/react";
-import { Combobox, New, Select } from "~/components";
-import { TableFilters } from "~/components/Layout";
-import { DebouncedInput } from "~/components/Search";
-import { usePermissions, useUrlParams } from "~/hooks";
-import { partTypes } from "~/modules/parts";
-import type { ListItem } from "~/types";
-import { path } from "~/utils/path";
-
-type PartsTableFiltersProps = {
- partGroups: ListItem[];
-};
-
-const PartsTableFilters = ({ partGroups }: PartsTableFiltersProps) => {
- const [params, setParams] = useUrlParams();
- const permissions = usePermissions();
- const partTypeOptions = partTypes.map((type) => ({
- value: type,
- label: type,
- }));
-
- const partGroupsOptions = partGroups.map((group) => ({
- value: group.id,
- label: group.name,
- }));
-
- return (
- <TableFilters>
- <HStack>
- <DebouncedInput param="search" size="sm" placeholder="Search Parts" />
- {partGroupsOptions.length > 0 && (
- <Combobox
- size="sm"
- isClearable
- value={params.get("group") ?? ""}
- options={partGroupsOptions}
- onChange={(selected) => {
- setParams({ group: selected });
- }}
- aria-label="Groups"
- placeholder="Part Groups"
- />
- )}
- {partTypeOptions.length > 0 && (
- <Select
- size="sm"
- value={params.get("type") ?? ""}
- isClearable
- options={partTypeOptions}
- onChange={(selected) => {
- setParams({ type: selected });
- }}
- aria-label="Part Type"
- placeholder="Part Type"
- />
- )}
- </HStack>
- <HStack>
- {permissions.can("create", "parts") && (
- <New to={path.to.newPart} label="Part" />
- )}
- </HStack>
- </TableFilters>
- );
-};
-
-export default PartsTableFilters;
diff --git a/apps/carbon/app/modules/parts/ui/Parts/index.ts b/apps/carbon/app/modules/parts/ui/Parts/index.ts
index 27b98ba2ee..9151d32583 100644
--- a/apps/carbon/app/modules/parts/ui/Parts/index.ts
+++ b/apps/carbon/app/modules/parts/ui/Parts/index.ts
@@ -1,4 +1,3 @@
import PartsTable from "./PartsTable";
-import PartsTableFilters from "./PartsTableFilters";
-export { PartsTable, PartsTableFilters };
+export { PartsTable };
diff --git a/apps/carbon/app/modules/parts/ui/Services/ServicesTable.tsx b/apps/carbon/app/modules/parts/ui/Services/ServicesTable.tsx
index fe6fb167e1..8df1d83980 100644
--- a/apps/carbon/app/modules/parts/ui/Services/ServicesTable.tsx
+++ b/apps/carbon/app/modules/parts/ui/Services/ServicesTable.tsx
@@ -3,80 +3,106 @@ import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
import { BsFillPenFill } from "react-icons/bs";
-import { Table } from "~/components";
-import { useUrlParams } from "~/hooks";
-import type { Service } from "~/modules/parts";
+import { TableNew } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import { serviceType, type Service } from "~/modules/parts";
+import type { ListItem } from "~/types";
import { path } from "~/utils/path";
type ServicesTableProps = {
data: Service[];
count: number;
+ partGroups: ListItem[];
};
-const ServicesTable = memo(({ data, count }: ServicesTableProps) => {
- const navigate = useNavigate();
- const [params] = useUrlParams();
+const ServicesTable = memo(
+ ({ data, count, partGroups }: ServicesTableProps) => {
+ const navigate = useNavigate();
+ const [params] = useUrlParams();
+ const permissions = usePermissions();
- const columns = useMemo<ColumnDef<Service>[]>(() => {
- return [
- {
- accessorKey: "id",
- header: "Service ID",
- cell: ({ row }) => (
- <Hyperlink
- onClick={() => navigate(path.to.service(row.original.id!))}
- >
- {row.original.id}
- </Hyperlink>
- ),
- },
- {
- accessorKey: "name",
- header: "Name",
- cell: (item) => item.getValue(),
- },
- {
- accessorKey: "description",
- header: "Description",
- cell: (item) => item.getValue(),
- },
- {
- accessorKey: "serviceType",
- header: "Type",
- cell: (item) => <Enumerable value={item.getValue<string>()} />,
- },
- {
- // @ts-ignore
- accessorKey: "partGroup",
- header: "Part Group",
- cell: (item) => <Enumerable value={item.getValue<string>()} />,
- },
- ];
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [params]);
+ const columns = useMemo<ColumnDef<Service>[]>(() => {
+ return [
+ {
+ accessorKey: "id",
+ header: "Service ID",
+ cell: ({ row }) => (
+ <Hyperlink
+ onClick={() => navigate(path.to.service(row.original.id!))}
+ >
+ {row.original.id}
+ </Hyperlink>
+ ),
+ },
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "description",
+ header: "Description",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "serviceType",
+ header: "Type",
+ cell: (item) => <Enumerable value={item.getValue<string>()} />,
+ meta: {
+ filter: {
+ type: "static",
+ options: serviceType.map((type) => ({
+ value: type,
+ label: <Enumerable value={type} />,
+ })),
+ },
+ },
+ },
+ {
+ // @ts-ignore
+ accessorKey: "partGroup",
+ header: "Part Group",
+ cell: (item) => <Enumerable value={item.getValue<string>()} />,
+ meta: {
+ filter: {
+ type: "static",
+ options: partGroups.map(({ id, name }) => ({
+ value: id,
+ label: <Enumerable value={name} />,
+ })),
+ },
+ },
+ },
+ ];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [params]);
- const renderContextMenu = useMemo(() => {
- // eslint-disable-next-line react/display-name
- return (row: Service) => (
- <MenuItem onClick={() => navigate(path.to.service(row.id!))}>
- <MenuIcon icon={<BsFillPenFill />} />
- Edit Service
- </MenuItem>
- );
- }, [navigate]);
+ const renderContextMenu = useMemo(() => {
+ // eslint-disable-next-line react/display-name
+ return (row: Service) => (
+ <MenuItem onClick={() => navigate(path.to.service(row.id!))}>
+ <MenuIcon icon={<BsFillPenFill />} />
+ Edit Service
+ </MenuItem>
+ );
+ }, [navigate]);
- return (
- <>
- <Table<Service>
- count={count}
- columns={columns}
- data={data}
- withPagination
- renderContextMenu={renderContextMenu}
- />
- </>
- );
-});
+ return (
+ <>
+ <TableNew<Service>
+ count={count}
+ columns={columns}
+ data={data}
+ label="Service"
+ newPath={path.to.newService}
+ newPermission={permissions.can("create", "parts")}
+ withPagination
+ renderContextMenu={renderContextMenu}
+ />
+ </>
+ );
+ }
+);
ServicesTable.displayName = "ServicesTable";
diff --git a/apps/carbon/app/modules/parts/ui/Services/ServicesTableFilters.tsx b/apps/carbon/app/modules/parts/ui/Services/ServicesTableFilters.tsx
deleted file mode 100644
index 3084a2bfc8..0000000000
--- a/apps/carbon/app/modules/parts/ui/Services/ServicesTableFilters.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { HStack } from "@carbon/react";
-import { Combobox, New, Select } from "~/components";
-import { TableFilters } from "~/components/Layout";
-import { DebouncedInput } from "~/components/Search";
-import { usePermissions, useUrlParams } from "~/hooks";
-import { serviceType } from "~/modules/parts";
-import type { ListItem } from "~/types";
-import { path } from "~/utils/path";
-
-type ServicesTableFiltersProps = {
- partGroups: ListItem[];
-};
-
-const ServicesTableFilters = ({ partGroups }: ServicesTableFiltersProps) => {
- const [params, setParams] = useUrlParams();
- const permissions = usePermissions();
- const serviceTypeOptions = serviceType.map((type) => ({
- value: type,
- label: type,
- }));
-
- const partGroupsOptions = partGroups.map((group) => ({
- value: group.id,
- label: group.name,
- }));
-
- return (
- <TableFilters>
- <HStack>
- <DebouncedInput
- param="search"
- size="sm"
- placeholder="Search Services"
- />
- {partGroupsOptions.length > 0 && (
- <Combobox
- size="sm"
- isClearable
- value={params.get("group") ?? ""}
- options={partGroupsOptions}
- onChange={(selected) => {
- setParams({ group: selected });
- }}
- aria-label="Groups"
- placeholder="Service Groups"
- />
- )}
- {serviceTypeOptions.length > 0 && (
- <Select
- size="sm"
- value={params.get("type") ?? ""}
- isClearable
- options={serviceTypeOptions}
- onChange={(selected) => {
- setParams({ type: selected });
- }}
- aria-label="Service Type"
- placeholder="Service Type"
- />
- )}
- </HStack>
- <HStack>
- {permissions.can("create", "parts") && (
- <New label="Service" to={path.to.newService} />
- )}
- </HStack>
- </TableFilters>
- );
-};
-
-export default ServicesTableFilters;
diff --git a/apps/carbon/app/modules/parts/ui/Services/index.ts b/apps/carbon/app/modules/parts/ui/Services/index.ts
index 53360b1197..2dee3cefba 100644
--- a/apps/carbon/app/modules/parts/ui/Services/index.ts
+++ b/apps/carbon/app/modules/parts/ui/Services/index.ts
@@ -1,4 +1,3 @@
import ServicesTable from "./ServicesTable";
-import ServicesTableFilters from "./ServicesTableFilters";
-export { ServicesTable, ServicesTableFilters };
+export { ServicesTable };
diff --git a/apps/carbon/app/routes/x+/parts+/search.tsx b/apps/carbon/app/routes/x+/parts+/search.tsx
index 6316074fe8..1a87140d72 100644
--- a/apps/carbon/app/routes/x+/parts+/search.tsx
+++ b/apps/carbon/app/routes/x+/parts+/search.tsx
@@ -2,12 +2,7 @@ import { VStack } from "@carbon/react";
import type { LoaderFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Outlet, useLoaderData } from "@remix-run/react";
-import {
- PartsTable,
- PartsTableFilters,
- getPartGroupsList,
- getParts,
-} from "~/modules/parts";
+import { PartsTable, getPartGroupsList, getParts } from "~/modules/parts";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session.server";
import { path } from "~/utils/path";
@@ -22,8 +17,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
const url = new URL(request.url);
const searchParams = new URLSearchParams(url.search);
const search = searchParams.get("search");
- const type = searchParams.get("type");
- const group = searchParams.get("group");
const supplierId = searchParams.get("supplierId");
const { limit, offset, sorts, filters } =
@@ -32,8 +25,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
const [parts, partGroups] = await Promise.all([
getParts(client, {
search,
- type,
- group,
supplierId,
limit,
offset,
@@ -62,8 +53,7 @@ export default function PartsSearchRoute() {
return (
<VStack spacing={0} className="h-full">
- <PartsTableFilters partGroups={partGroups} />
- <PartsTable data={parts} count={count} />
+ <PartsTable data={parts} count={count} partGroups={partGroups} />
<Outlet />
</VStack>
);
diff --git a/apps/carbon/app/routes/x+/parts+/services.tsx b/apps/carbon/app/routes/x+/parts+/services.tsx
index d1f64582ee..236e84e652 100644
--- a/apps/carbon/app/routes/x+/parts+/services.tsx
+++ b/apps/carbon/app/routes/x+/parts+/services.tsx
@@ -2,12 +2,7 @@ import { VStack } from "@carbon/react";
import type { LoaderFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Outlet, useLoaderData } from "@remix-run/react";
-import {
- ServicesTable,
- ServicesTableFilters,
- getPartGroupsList,
- getServices,
-} from "~/modules/parts";
+import { ServicesTable, getPartGroupsList, getServices } from "~/modules/parts";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session.server";
import type { Handle } from "~/utils/handle";
@@ -68,8 +63,7 @@ export default function ServicesSearchRoute() {
return (
<VStack spacing={0} className="h-full">
- <ServicesTableFilters partGroups={partGroups} />
- <ServicesTable data={services} count={count} />
+ <ServicesTable data={services} count={count} partGroups={partGroups} />
<Outlet />
</VStack>
);
diff --git a/apps/carbon/app/utils/query.ts b/apps/carbon/app/utils/query.ts
index 640bbf62f6..269d27f68b 100644
--- a/apps/carbon/app/utils/query.ts
+++ b/apps/carbon/app/utils/query.ts
@@ -85,6 +85,9 @@ export function getGenericFilter<
return query.ilike(column, `%${value}%`);
case "startsWith":
return query.ilike(column, `${value}%`);
+ case "in":
+ const values = value.split(",");
+ return query.in(column, values);
default:
throw badRequest(`Invalid filter operator: ${operator}`);
}
diff --git a/packages/react/src/Button.tsx b/packages/react/src/Button.tsx
index 3325fc28f7..295ee0eb78 100644
--- a/packages/react/src/Button.tsx
+++ b/packages/react/src/Button.tsx
@@ -24,6 +24,7 @@ const buttonVariants = cva(
link: "text-foreground hover:text-foreground underline-offset-4 hover:underline",
},
size: {
+ sm: "h-6 rounded-sm text-xs",
md: "h-8 rounded-md text-sm",
lg: "h-11 rounded-lg text-base",
},
@@ -43,6 +44,11 @@ const buttonVariants = cva(
},
},
compoundVariants: [
+ {
+ size: "md",
+ isIcon: true,
+ class: "w-6 p-1",
+ },
{
size: "md",
isIcon: true,
@@ -53,6 +59,11 @@ const buttonVariants = cva(
isIcon: true,
class: "w-11 p-2",
},
+ {
+ size: "sm",
+ isIcon: false,
+ class: "px-2",
+ },
{
size: "md",
isIcon: false,
diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsx
index 4f0b3b37a7..4fa2db8f42 100644
--- a/packages/react/src/index.tsx
+++ b/packages/react/src/index.tsx
@@ -228,7 +228,7 @@ import {
useOutsideClick,
} from "./hooks";
import { cn } from "./utils/cn";
-import { getValidChildren } from "./utils/react";
+import { getValidChildren, reactNodeToString } from "./utils/react";
export {
ActionMenu,
@@ -429,6 +429,7 @@ export {
cn,
getValidChildren,
multiSelectTriggerVariants,
+ reactNodeToString,
toast,
useDebounce,
useDisclosure,
diff --git a/packages/react/src/utils/react.ts b/packages/react/src/utils/react.ts
index 3df138ec0f..4163c6086e 100644
--- a/packages/react/src/utils/react.ts
+++ b/packages/react/src/utils/react.ts
@@ -1,3 +1,9 @@
+import type {
+ MutableRefObject,
+ ReactElement,
+ ReactNode,
+ RefCallback,
+} from "react";
import { Children, isValidElement } from "react";
/**
@@ -6,19 +12,40 @@ import { Children, isValidElement } from "react";
*
* @param children the children
*/
-export function getValidChildren(children: React.ReactNode) {
+export function getValidChildren(children: ReactNode) {
return Children.toArray(children).filter((child) =>
isValidElement(child)
- ) as React.ReactElement[];
+ ) as ReactElement[];
}
+export const reactNodeToString = function (reactNode: ReactNode): string {
+ let string = "";
+
+ if (typeof reactNode === "string") {
+ string = reactNode;
+ } else if (typeof reactNode === "number") {
+ string = reactNode.toString();
+ } else if (reactNode instanceof Array) {
+ reactNode.forEach(function (child) {
+ string += reactNodeToString(child);
+ });
+ } else if (isValidElement(reactNode)) {
+ if (reactNode.props.value) {
+ // for Enumerable component
+ string += reactNode.props.value;
+ } else {
+ string += reactNodeToString(reactNode.props.children);
+ }
+ }
+
+ return string;
+};
+
export type Merge<T, P> = P & Omit<T, keyof P>;
-export type MaybeRenderProp<P> =
- | React.ReactNode
- | ((props: P) => React.ReactNode);
+export type MaybeRenderProp<P> = ReactNode | ((props: P) => ReactNode);
-export type ReactRef<T> = React.RefCallback<T> | React.MutableRefObject<T>;
+export type ReactRef<T> = RefCallback<T> | MutableRefObject<T>;
export function assignRef<T = any>(
ref: ReactRef<T> | null | undefined,