DataTable component

Signed-off-by: Jonathan <contact@grafikart.fr>
This commit is contained in:
Jonathan
2025-11-12 12:29:54 +01:00
committed by Émile Ré
parent 6dc6e2a626
commit 3953a05cf3
12 changed files with 395 additions and 70 deletions

View File

@@ -36,7 +36,10 @@ export function PeopleSelectField({
}
function PeopleSelectWithQuery(
props: Pick<Props, "organizationId" | "control" | "name" | "disabled" | "optional">
props: Pick<
Props,
"organizationId" | "control" | "name" | "disabled" | "optional"
>,
) {
const { __ } = useTranslate();
const { name, organizationId, control } = props;
@@ -53,15 +56,15 @@ function PeopleSelectWithQuery(
id={name}
variant="editor"
placeholder={__("Select an owner")}
onValueChange={(value) => field.onChange(value === "__NONE__" ? null : value)}
onValueChange={(value) =>
field.onChange(value === "__NONE__" ? null : value)
}
key={people?.length.toString() ?? "0"}
{...field}
className="w-full"
value={field.value ?? (props.optional ? "__NONE__" : "")}
>
{props.optional && (
<Option value="__NONE__">{__("None")}</Option>
)}
{props.optional && <Option value="__NONE__">{__("None")}</Option>}
{people?.map((p) => (
<Option key={p.id} value={p.id} className="flex gap-2">
<Avatar name={p.fullName} />
@@ -74,3 +77,44 @@ function PeopleSelectWithQuery(
</>
);
}
type OptionsProps = {
organizationId: string;
optional?: boolean;
} & ComponentProps<typeof Field>;
export function PeopleSelectOptions({
organizationId,
...props
}: OptionsProps) {
return (
<Suspense
fallback={<Select variant="editor" loading placeholder="Loading..." />}
>
<PeopleSelectOptionsWithQuery
organizationId={organizationId}
optional={props.optional}
/>
</Suspense>
);
}
function PeopleSelectOptionsWithQuery(
props: Pick<Props, "organizationId" | "disabled" | "optional">,
) {
const { __ } = useTranslate();
const { organizationId } = props;
const people = usePeople(organizationId, { excludeContractEnded: true });
return (
<>
{props.optional && <Option value="__NONE__">{__("None")}</Option>}
{people?.map((p) => (
<Option key={p.id} value={p.id} className="flex gap-2">
<Avatar name={p.fullName} />
{p.fullName}
</Option>
))}
</>
);
}

View File

@@ -12,6 +12,12 @@ import {
DropdownItem,
IconTrashCan,
Avatar,
EditableCell,
Select,
Option,
DataTable,
CellHead,
Cell,
} from "@probo/ui";
import { useTranslate } from "@probo/i18n";
import { usePageTitle } from "@probo/hooks";
@@ -20,11 +26,16 @@ import {
usePaginationFragment,
usePreloadedQuery,
type PreloadedQuery,
useMutation,
} from "react-relay";
import { useOrganizationId } from "/hooks/useOrganizationId";
import { useParams } from "react-router";
import { CreateAssetDialog } from "./dialogs/CreateAssetDialog";
import { useDeleteAsset, assetsQuery } from "../../../hooks/graph/AssetGraph";
import {
useDeleteAsset,
assetsQuery,
updateAssetMutation,
} from "../../../hooks/graph/AssetGraph";
import type { AssetGraphListQuery } from "/hooks/graph/__generated__/AssetGraphListQuery.graphql";
import { faviconUrl } from "@probo/helpers";
import type { NodeOf } from "/types";
@@ -37,6 +48,7 @@ import { SortableTable } from "/components/SortableTable";
import { SnapshotBanner } from "/components/SnapshotBanner";
import { Authorized } from "/permissions";
import { isAuthorized } from "/permissions";
import { PeopleSelectOptions } from "/components/form/PeopleSelectField.tsx";
const paginatedAssetsFragment = graphql`
fragment AssetsPageFragment on Organization
@@ -101,7 +113,7 @@ export default function AssetsPage(props: Props) {
const data = usePreloadedQuery(assetsQuery, props.queryRef);
const pagination = usePaginationFragment(
paginatedAssetsFragment,
data.node as AssetsPageFragment$key
data.node as AssetsPageFragment$key,
);
const assets = pagination.data.assets?.edges.map((edge) => edge.node);
const connectionId = pagination.data.assets.__id;
@@ -119,7 +131,7 @@ export default function AssetsPage(props: Props) {
<PageHeader
title={__("Assets")}
description={__(
"Manage your organization's assets and their classifications."
"Manage your organization's assets and their classifications.",
)}
>
{!isSnapshotMode && (
@@ -133,28 +145,17 @@ export default function AssetsPage(props: Props) {
</Authorized>
)}
</PageHeader>
<SortableTable {...pagination}>
<Thead>
<Tr>
<Th>{__("Name")}</Th>
<Th>{__("Type")}</Th>
<Th>{__("Amount")}</Th>
<Th>{__("Owner")}</Th>
<Th>{__("Vendors")}</Th>
{hasAnyAction && <Th></Th>}
</Tr>
</Thead>
<Tbody>
{assets.map((entry) => (
<AssetRow
key={entry.id}
entry={entry}
connectionId={connectionId}
hasAnyAction={hasAnyAction}
/>
))}
</Tbody>
</SortableTable>
<DataTable columns={6}>
<CellHead>{__("Name")}</CellHead>
<CellHead>{__("Type")}</CellHead>
<CellHead>{__("Amount")}</CellHead>
<CellHead>{__("Owner")}</CellHead>
<CellHead>{__("Vendors")}</CellHead>
<CellHead></CellHead>
{assets.map((entry) => (
<AssetRow key={entry.id} entry={entry} connectionId={connectionId} />
))}
</DataTable>
</div>
);
}
@@ -162,11 +163,9 @@ export default function AssetsPage(props: Props) {
function AssetRow({
entry,
connectionId,
hasAnyAction,
}: {
entry: AssetEntry;
connectionId: string;
hasAnyAction: boolean;
}) {
const organizationId = useOrganizationId();
const { __ } = useTranslate();
@@ -175,21 +174,71 @@ function AssetRow({
const deleteAsset = useDeleteAsset(entry, connectionId);
const vendors = entry.vendors?.edges.map((edge) => edge.node) ?? [];
const assetUrl = isSnapshotMode && snapshotId
? `/organizations/${organizationId}/snapshots/${snapshotId}/assets/${entry.id}`
: `/organizations/${organizationId}/assets/${entry.id}`;
const assetUrl =
isSnapshotMode && snapshotId
? `/organizations/${organizationId}/snapshots/${snapshotId}/assets/${entry.id}`
: `/organizations/${organizationId}/assets/${entry.id}`;
const [mutate, isLoading] = useMutation(updateAssetMutation);
const updater = (fieldName: keyof typeof entry) => (value: string) => {
// Only send an update if the value changed
if (entry[fieldName] === value) {
return;
}
mutate({
variables: {
input: {
id: entry.id,
[fieldName]: value,
},
},
});
};
return (
<Tr to={assetUrl}>
<Td>{entry.name}</Td>
<Td>
<>
<EditableCell
type="text"
defaultValue={entry.name}
onValueChange={updater("name")}
/>
<EditableCell
type="select"
isLoading={isLoading}
onValueChange={updater("assetType")}
options={
<>
<Option value="VIRTUAL">
<Badge variant={getAssetTypeVariant("VIRTUAL")}>
{__("Virtual")}
</Badge>
</Option>
<Option value="PHYSICAL">
<Badge variant={getAssetTypeVariant("PHYSICAL")}>
{__("Physical")}
</Badge>
</Option>
</>
}
>
<Badge variant={getAssetTypeVariant(entry.assetType)}>
{entry.assetType === "PHYSICAL" ? __("Physical") : __("Virtual")}
</Badge>
</Td>
<Td>{entry.amount}</Td>
<Td>{entry.owner?.fullName ?? __("Unassigned")}</Td>
<Td>
</EditableCell>
<EditableCell
type="text"
defaultValue={entry.amount}
onValueChange={updater("amount")}
/>
<EditableCell
type="select"
isLoading={isLoading}
onValueChange={updater("owner")}
options={<PeopleSelectOptions organizationId={organizationId} />}
>
{entry.owner?.fullName ?? __("Unassigned")}
</EditableCell>
<Cell>
{vendors.length > 0 ? (
<div className="flex flex-wrap gap-1">
{vendors.slice(0, 3).map((vendor) => (
@@ -215,22 +264,20 @@ function AssetRow({
) : (
<span className="text-txt-secondary text-sm">{__("None")}</span>
)}
</Td>
{hasAnyAction && (
<Td noLink width={50} className="text-end">
<Authorized entity="Asset" action="deleteAsset">
<ActionDropdown>
<DropdownItem
onClick={deleteAsset}
variant="danger"
icon={IconTrashCan}
>
{__("Delete")}
</DropdownItem>
</ActionDropdown>
</Authorized>
</Td>
)}
</Tr>
</Cell>
<Cell className="text-end">
{!isSnapshotMode && (
<ActionDropdown>
<DropdownItem
onClick={deleteAsset}
variant="danger"
icon={IconTrashCan}
>
{__("Delete")}
</DropdownItem>
</ActionDropdown>
)}
</Cell>
</>
);
}

View File

@@ -3,5 +3,5 @@ import { useCallback, useState } from "react";
export function useToggle(initialValue: boolean) {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => setValue((prev) => !prev), []);
return [value, toggle] as const;
return [value, toggle, setValue] as const;
}

View File

@@ -17,11 +17,12 @@
"@probo/i18n": "1.0.0",
"@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-portal": "^1.1.10",
"@radix-ui/react-label":"^2.1.8",
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-tabs": "^1.1.13",
"clsx": "^2.1.1",
"react-dropzone": "^14.3.8",
"react-intersection-observer": "^9.16.0",
@@ -34,7 +35,6 @@
"zustand": "^5.0.4"
},
"devDependencies": {
"@tailwindcss/vite": "^4.1.17",
"@chromatic-com/storybook": "^3.2.6",
"@eslint/js": "^9.25.0",
"@probo/prettier": "1.0.0",
@@ -46,6 +46,7 @@
"@storybook/react-vite": "^8.6.13",
"@storybook/test": "^8.6.13",
"@tailwindcss/typography": "^0.5.16",
"@tailwindcss/vite": "^4.1.17",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"@vitejs/plugin-react": "^4.4.1",

View File

@@ -1,10 +1,11 @@
import type { PropsWithChildren } from "react";
import type { CSSProperties, PropsWithChildren } from "react";
import { tv } from "tailwind-variants";
import { Slot } from "../Slot";
type Props = PropsWithChildren<{
padded?: boolean;
className?: string;
style?: CSSProperties;
asChild?: boolean;
}>;
@@ -17,10 +18,16 @@ const card = tv({
},
});
export function Card({ padded = false, children, className, asChild }: Props) {
export function Card({
padded = false,
children,
className,
asChild,
style,
}: Props) {
const Component = asChild ? Slot : "div";
return (
<Component className={card({ padded, className })}>
<Component style={style} className={card({ padded, className })}>
{children}
</Component>
);

View File

@@ -0,0 +1,28 @@
import type { Meta, StoryObj } from "@storybook/react";
import { DataTable, CellHead, Cell } from "./DataTable.tsx";
export default {
title: "Atoms/DataTable",
component: DataTable,
argTypes: {},
} satisfies Meta<typeof DataTable>;
type Story = StoryObj<typeof DataTable>;
export const Default: Story = {
render: () => {
return (
<DataTable columns={3}>
<CellHead>Header 1</CellHead>
<CellHead>Header 2</CellHead>
<CellHead>Header 3</CellHead>
<Cell>Row 1, Cell 1</Cell>
<Cell>Row 1, Cell 2</Cell>
<Cell>Row 1, Cell 3</Cell>
<Cell>Row 2, Cell 1</Cell>
<Cell>Row 2, Cell 2</Cell>
<Cell>Row 2, Cell 3</Cell>
</DataTable>
);
},
};

View File

@@ -0,0 +1,70 @@
import { type ComponentPropsWithRef, type PropsWithChildren } from "react";
import { Card } from "../Card/Card";
import clsx from "clsx";
import { type AsChildProps, Slot } from "../Slot.tsx";
export function DataTable({
children,
className,
columns,
}: PropsWithChildren<{ className?: string; columns: number | string[] }>) {
const style = () => {
if (typeof columns === "number") {
return {
gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,
};
}
return {
gridTemplateColumns: columns
.map((col) => `minmax(0, ${col})`)
.join(" "),
};
};
return (
<div className="overflow-auto relative w-full p-1 -m-1">
<Card
className={clsx(className, "w-full text-left grid")}
style={style()}
>
{children}
</Card>
</div>
);
}
export function CellHead({
children,
className,
...props
}: ComponentPropsWithRef<"div">) {
return (
<div
{...props}
className={clsx(
"text-xs text-txt-tertiary font-semibold border-border-low border-b",
"px-6 whitespace-nowrap py-3",
className,
)}
>
{children}
</div>
);
}
export function Cell({
asChild,
...props
}: AsChildProps<ComponentPropsWithRef<"div">>) {
const Component = asChild ? Slot : "div";
return (
<Component
data-cell
{...props}
className={clsx(
"py-3 px-6 text-sm text-txt-primary bg-tertiary border-t border-border-low flex flex-col justify-center",
props.className,
)}
/>
);
}

View File

@@ -13,16 +13,21 @@ import * as ScrollArea from "@radix-ui/react-scroll-area";
import { Input, input } from "../Input/Input.tsx";
import { IconChevronGrabberVertical } from "../Icons/IconChevronGrabberVertical.tsx";
import { tv } from "tailwind-variants";
import { Children, type ComponentProps, type PropsWithChildren } from "react";
import {
Children,
type ComponentProps,
type PropsWithChildren,
type ReactNode,
} from "react";
import { IconMagnifyingGlass } from "../Icons/IconMagnifyingGlass.tsx";
import { Spinner } from "../Spinner/Spinner.tsx";
type Props<T> = PropsWithChildren<
{
id?: string;
placeholder?: string;
placeholder?: ReactNode;
onValueChange?: (s: NonNullable<T>) => void;
variant?: "default" | "editor" | "dashed";
variant?: "default" | "editor" | "dashed" | "ghost";
invalid?: boolean;
disabled?: boolean;
className?: string;
@@ -71,6 +76,10 @@ const select = tv({
default: {
trigger: input({ class: "w-full gap-4 " }),
},
ghost: {
trigger: "w-full px-3",
content: "bg-level-2",
},
},
},
compoundVariants: [
@@ -96,6 +105,9 @@ export function Select<T>({
onSearch,
searchPlaceholder,
loading,
open,
defaultOpen = false,
onOpenChange,
...props
}: Props<T>) {
const { trigger, content, icon } = select({
@@ -103,7 +115,13 @@ export function Select<T>({
});
return (
<Root onValueChange={onValueChange} value={value as string}>
<Root
defaultOpen={defaultOpen}
open={open}
onOpenChange={onOpenChange}
onValueChange={onValueChange}
value={value as string}
>
<Trigger
{...props}
className={trigger({

View File

@@ -6,6 +6,7 @@ import {
type PropsWithChildren,
type ReactNode,
type ThHTMLAttributes,
type ComponentPropsWithRef,
} from "react";
import { Card } from "../Card/Card";
import { Link } from "react-router";

View File

@@ -0,0 +1,102 @@
import {
type FocusEventHandler,
type KeyboardEventHandler,
type ReactNode,
useRef,
useState,
} from "react";
import * as Popover from "@radix-ui/react-popover";
import { Select } from "../../Atoms/Select/Select.tsx";
import { Spinner } from "../../Atoms/Spinner/Spinner.tsx";
import { Cell } from "../../Atoms/DataTable/DataTable.tsx";
type Props = {
type: "text" | "select";
onValueChange: (value: string) => void;
defaultValue?: ReactNode;
children?: ReactNode;
options?: ReactNode;
isLoading?: boolean;
};
export function EditableCell({
options,
children,
isLoading,
onValueChange,
defaultValue,
type,
}: Props) {
const td = useRef<HTMLTableCellElement>(null);
const [height, setHeight] = useState(0);
const [padding, setPadding] = useState("12px");
const onOpenChange = (open: boolean) => {
if (open) {
setOpen(open);
setHeight(td.current?.offsetHeight ?? 0);
setPadding(getComputedStyle(td.current!).paddingLeft);
}
};
const onInputBlur: FocusEventHandler<HTMLInputElement> = (e) => {
setOpen(false);
onValueChange(e.target.value);
};
const blurOnTab: KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Tab") {
setOpen(false);
onValueChange(e.currentTarget.value);
}
};
const [isOpen, setOpen] = useState(false);
return (
<Popover.Root onOpenChange={onOpenChange} open={isOpen}>
<Popover.Trigger asChild>
<Cell ref={td} asChild>
<button className="flex flex-row space-between gap-2 w-full items-center justify-start">
{" "}
{children ?? defaultValue}
{isLoading && <Spinner size={12} />}
</button>
</Cell>
</Popover.Trigger>
<Popover.Portal>
<Popover.Content
side="bottom"
align="start"
sideOffset={height * -1}
style={{ height, paddingLeft: padding }}
className="border border-border-low bg-level-2 min-w-[200px] min-h-[57px] flex flex-col justify-center rounded-sm"
>
{type === "select" && (
<>
<Select
className="-mx-3"
onValueChange={onValueChange}
onOpenChange={setOpen}
defaultOpen
variant="ghost"
placeholder={children}
>
{options}
</Select>
</>
)}
{type === "text" && (
<input
type="text"
defaultValue={defaultValue?.toString() ?? ""}
className="text-txt-primary text-sm outline-none"
onKeyDown={blurOnTab}
onBlur={onInputBlur}
/>
)}
</Popover.Content>
</Popover.Portal>
</Popover.Root>
);
}

View File

@@ -38,6 +38,7 @@ export { InfiniteScrollTrigger } from "./Atoms/InfiniteScrollTrigger/InfiniteScr
export { PriorityLevel } from "./Atoms/PriorityLevel/PriorityLevel.tsx";
export { TaskStateIcon } from "./Atoms/Icons/TaskStateIcon";
export { Checkbox } from "./Atoms/Checkbox/Checkbox";
export { DataTable, Cell, CellHead } from "./Atoms/DataTable/DataTable";
// Molecules
export {
@@ -71,6 +72,7 @@ export { SentitivityOptions } from "./Molecules/Select/SentitivityOptions";
export { ImpactOptions } from "./Molecules/Select/ImpactOptions";
export { DurationPicker } from "./Molecules/DurationPicker/DurationPicker";
export { FrameworkLogo } from "./Molecules/Badge/FrameworkLogo";
export { EditableCell } from "./Molecules/Table/EditableCell";
// Hooks
export { useToast, Toasts } from "./Atoms/Toasts/Toasts";

View File

@@ -249,6 +249,11 @@ button:focus-visible {
}
}
button[data-cell]:focus-visible {
box-shadow: none;
outline: solid 2px rgba(135, 190, 34, 0.5);
}
/* Allow interpolation : https://developer.chrome.com/docs/css-ui/animate-to-height-auto */
:root {
interpolate-size: allow-keywords;