Simplify editable cell signature
Signed-off-by: Jonathan <contact@grafikart.fr>
This commit is contained in:
@@ -9,6 +9,7 @@ import {
|
||||
Button,
|
||||
Cell,
|
||||
CellHead,
|
||||
EditableRow,
|
||||
IconCheckmark1,
|
||||
Row,
|
||||
RowButton,
|
||||
@@ -19,8 +20,8 @@ import { useMutateField } from "/hooks/useMutateField.tsx";
|
||||
import { type ReactNode } from "react";
|
||||
import { useToggle } from "@probo/hooks";
|
||||
import { useStateWithSchema } from "/hooks/useStateWithSchema.ts";
|
||||
import { useMutation } from "react-relay";
|
||||
import clsx from "clsx";
|
||||
import { useMutationWithToasts } from "/hooks/useMutationWithToasts.ts";
|
||||
|
||||
type ColumnDefinition = { label: string; field: string } | string;
|
||||
|
||||
@@ -65,7 +66,7 @@ export function EditableTable<
|
||||
|
||||
return (
|
||||
<SortableDataTable
|
||||
columns={[...props.columns.map(() => "1fr"), "56px"]}
|
||||
columns={[...props.columns.map(() => "minmax(min-content, 1fr)"), "56px"]}
|
||||
refetch={props.pagination.refetch}
|
||||
hasNext={props.pagination.hasNext}
|
||||
isLoadingNext={props.pagination.isLoadingNext}
|
||||
@@ -78,14 +79,14 @@ export function EditableTable<
|
||||
<CellHead />
|
||||
</Row>
|
||||
{props.items.map((item) => (
|
||||
<Row key={item.id}>
|
||||
<EditableRow onUpdate={(k, v) => update(item.id, k, v)} key={item.id}>
|
||||
{props.row({
|
||||
item,
|
||||
onUpdate: (key, value) => update(item.id, key as string, value),
|
||||
errors: {},
|
||||
})}
|
||||
<Cell>{props.action({ item })}</Cell>
|
||||
</Row>
|
||||
</EditableRow>
|
||||
))}
|
||||
{showAdd ? (
|
||||
<NewItemRow
|
||||
@@ -94,6 +95,7 @@ export function EditableTable<
|
||||
connectionId={props.connectionId}
|
||||
row={props.row}
|
||||
mutation={props.createMutation}
|
||||
onSuccess={toggleAdd}
|
||||
/>
|
||||
) : (
|
||||
<RowButton onClick={toggleAdd}>{props.addLabel}</RowButton>
|
||||
@@ -107,13 +109,14 @@ function NewItemRow<S extends z.ZodSchema>(props: {
|
||||
defaultValue: z.infer<S>;
|
||||
connectionId: string;
|
||||
mutation: GraphQLTaggedNode;
|
||||
onSuccess: () => void;
|
||||
row: (props: EditableTableRowProps<any, S>) => ReactNode;
|
||||
}) {
|
||||
const { update, errors, value } = useStateWithSchema(
|
||||
props.schema,
|
||||
props.defaultValue,
|
||||
);
|
||||
const [mutate, isMutating] = useMutation(props.mutation);
|
||||
const [mutate, isMutating] = useMutationWithToasts(props.mutation);
|
||||
const isOk = Object.keys(errors ?? {}).length === 0;
|
||||
|
||||
const onSubmit = async () => {
|
||||
@@ -122,15 +125,16 @@ function NewItemRow<S extends z.ZodSchema>(props: {
|
||||
alert("Please fix the errors before submitting.");
|
||||
return;
|
||||
}
|
||||
mutate({
|
||||
await mutate({
|
||||
variables: {
|
||||
input: value,
|
||||
connections: [props.connectionId],
|
||||
},
|
||||
onSuccess: props.onSuccess,
|
||||
});
|
||||
};
|
||||
return (
|
||||
<Row>
|
||||
<EditableRow onUpdate={update} errors={errors}>
|
||||
{props.row({ errors, onUpdate: update })}
|
||||
<Cell>
|
||||
<Button
|
||||
@@ -142,7 +146,7 @@ function NewItemRow<S extends z.ZodSchema>(props: {
|
||||
{isMutating ? <Spinner size={16} /> : <IconCheckmark1 size={16} />}
|
||||
</Button>
|
||||
</Cell>
|
||||
</Row>
|
||||
</EditableRow>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
137
apps/console/src/components/table/GraphQLCell.tsx
Normal file
137
apps/console/src/components/table/GraphQLCell.tsx
Normal file
@@ -0,0 +1,137 @@
|
||||
import { type ReactNode, Suspense } from "react";
|
||||
import { useEditableCellRef } from "@probo/ui/src/Molecules/Table/EditableCell.tsx";
|
||||
import { getKey } from "@probo/ui/src/Molecules/Table/utils.ts";
|
||||
import { useStateWithRef } from "@probo/hooks";
|
||||
import { useEditableRowContext } from "@probo/ui/src/Molecules/Table/EditableRow.tsx";
|
||||
import { EditableCell, selectCell, SelectValue, Spinner } from "@probo/ui";
|
||||
import { Command } from "cmdk";
|
||||
import type {
|
||||
GraphQLTaggedNode,
|
||||
OperationType,
|
||||
VariablesOf,
|
||||
} from "relay-runtime";
|
||||
import { useLazyLoadQuery } from "react-relay";
|
||||
import { useTranslate } from "@probo/i18n";
|
||||
|
||||
type Props<Q extends OperationType, T> = {
|
||||
name: string;
|
||||
query: GraphQLTaggedNode;
|
||||
variables: VariablesOf<Q>;
|
||||
items: (v: ReturnType<typeof useLazyLoadQuery<Q>>) => T[];
|
||||
itemRenderer: (v: { item: T; onRemove?: (item: T) => void }) => ReactNode;
|
||||
} & (
|
||||
| { defaultValue?: T; multiple?: undefined }
|
||||
| { defaultValue: T[]; multiple: true }
|
||||
);
|
||||
|
||||
export function GraphQLCell<Q extends OperationType, T>(props: Props<Q, T>) {
|
||||
const [value, setValue, valueRef] = useStateWithRef<T | T[] | undefined>(
|
||||
props.defaultValue,
|
||||
);
|
||||
const cellRef = useEditableCellRef();
|
||||
const { __ } = useTranslate();
|
||||
const usedKeys = new Set<string>(
|
||||
Array.isArray(value) ? value.map(getKey) : [getKey(value)],
|
||||
);
|
||||
const { onUpdate } = useEditableRowContext();
|
||||
|
||||
const onSelect = (item: T) => {
|
||||
if (props.multiple) {
|
||||
setValue([...((valueRef.current as T[]) ?? []), item]);
|
||||
return;
|
||||
}
|
||||
setValue(item);
|
||||
cellRef.current?.close();
|
||||
};
|
||||
|
||||
const onClose = () => {
|
||||
if (valueRef.current === props.defaultValue) {
|
||||
return;
|
||||
}
|
||||
// Only send ids when updating the value
|
||||
onUpdate(
|
||||
props.name,
|
||||
Array.isArray(valueRef.current)
|
||||
? valueRef.current.map(getKey)
|
||||
: getKey(valueRef.current),
|
||||
);
|
||||
};
|
||||
|
||||
const classNames = selectCell();
|
||||
|
||||
return (
|
||||
<EditableCell
|
||||
name={props.name}
|
||||
label={<SelectValue value={value} itemRenderer={props.itemRenderer} />}
|
||||
onClose={onClose}
|
||||
ref={cellRef}
|
||||
>
|
||||
<Command className={classNames.command()}>
|
||||
<div
|
||||
className={classNames.value()}
|
||||
style={{
|
||||
paddingLeft: "var(--padding)",
|
||||
minHeight: "var(--height)",
|
||||
}}
|
||||
>
|
||||
{" "}
|
||||
<SelectValue
|
||||
onValueChange={setValue}
|
||||
value={value}
|
||||
itemRenderer={props.itemRenderer}
|
||||
/>
|
||||
</div>{" "}
|
||||
{props.multiple && (
|
||||
<Command.Input
|
||||
className={classNames.input()}
|
||||
placeholder={__("Search")}
|
||||
/>
|
||||
)}
|
||||
<Command.List>
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="py-2 px-3 flex items-center justify-center">
|
||||
<Spinner />
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<ItemList
|
||||
{...props}
|
||||
usedKeys={usedKeys}
|
||||
className={classNames.item()}
|
||||
onSelect={onSelect}
|
||||
/>
|
||||
</Suspense>
|
||||
</Command.List>
|
||||
</Command>
|
||||
</EditableCell>
|
||||
);
|
||||
}
|
||||
|
||||
function ItemList<Q extends OperationType, T>(
|
||||
props: Props<Q, T> & {
|
||||
className: string;
|
||||
onSelect: (item: T) => void;
|
||||
usedKeys: Set<string>;
|
||||
},
|
||||
) {
|
||||
const data = useLazyLoadQuery<Q>(props.query, props.variables, {
|
||||
fetchPolicy: "network-only",
|
||||
});
|
||||
const items = props.items(data);
|
||||
return (
|
||||
<>
|
||||
{items
|
||||
.filter((item) => !props.usedKeys.has(getKey(item)))
|
||||
.map((item) => (
|
||||
<Command.Item
|
||||
key={getKey(item)}
|
||||
className={props.className}
|
||||
onSelect={() => props.onSelect(item)}
|
||||
>
|
||||
{props.itemRenderer({ item })}
|
||||
</Command.Item>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
33
apps/console/src/components/table/PeopleCell.tsx
Normal file
33
apps/console/src/components/table/PeopleCell.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import { GraphQLCell } from "/components/table/GraphQLCell.tsx";
|
||||
import type { PeopleGraphQuery } from "/hooks/graph/__generated__/PeopleGraphQuery.graphql.ts";
|
||||
import { peopleQuery } from "/hooks/graph/PeopleGraph.ts";
|
||||
import { Avatar } from "@probo/ui";
|
||||
|
||||
type Props = {
|
||||
name: string;
|
||||
defaultValue?: { fullName: string; id: string };
|
||||
organizationId: string;
|
||||
};
|
||||
|
||||
export function PeopleCell(props: Props) {
|
||||
return (
|
||||
<GraphQLCell<PeopleGraphQuery, { fullName: string }>
|
||||
name={props.name}
|
||||
query={peopleQuery}
|
||||
variables={{
|
||||
organizationId: props.organizationId,
|
||||
filter: { excludeContractEnded: true },
|
||||
}}
|
||||
items={(data) =>
|
||||
data.organization?.peoples?.edges.map((edge) => edge.node) ?? []
|
||||
}
|
||||
itemRenderer={({ item }) => (
|
||||
<div className="flex gap-2 whitespace-nowrap items-center text-xs">
|
||||
<Avatar name={item.fullName} />
|
||||
{item.fullName}
|
||||
</div>
|
||||
)}
|
||||
defaultValue={props.defaultValue}
|
||||
/>
|
||||
);
|
||||
}
|
||||
63
apps/console/src/components/table/VendorsCell.tsx
Normal file
63
apps/console/src/components/table/VendorsCell.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import { GraphQLCell } from "/components/table/GraphQLCell.tsx";
|
||||
import { vendorsSelectQuery } from "/hooks/graph/VendorGraph";
|
||||
import { Avatar, Badge, IconCrossLargeX } from "@probo/ui";
|
||||
import { faviconUrl } from "@probo/helpers";
|
||||
type Vendor = {
|
||||
id: string;
|
||||
name: string;
|
||||
websiteUrl: string | null | undefined;
|
||||
};
|
||||
import type { VendorGraphSelectQuery } from "/hooks/graph/__generated__/VendorGraphSelectQuery.graphql.ts";
|
||||
|
||||
type Props = {
|
||||
name: string;
|
||||
defaultValue?: Vendor[];
|
||||
organizationId: string;
|
||||
};
|
||||
|
||||
const empty = [] as Vendor[];
|
||||
|
||||
export function VendorsCell(props: Props) {
|
||||
return (
|
||||
<GraphQLCell<VendorGraphSelectQuery, Vendor>
|
||||
multiple
|
||||
name={props.name}
|
||||
query={vendorsSelectQuery}
|
||||
variables={{
|
||||
organizationId: props.organizationId,
|
||||
}}
|
||||
items={(data) =>
|
||||
data.organization?.vendors?.edges.map((edge) => edge.node) ?? []
|
||||
}
|
||||
itemRenderer={({ item, onRemove }) => (
|
||||
<VendorBadge vendor={item} onRemove={onRemove} />
|
||||
)}
|
||||
defaultValue={props.defaultValue ?? empty}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function VendorBadge({
|
||||
vendor,
|
||||
onRemove,
|
||||
}: {
|
||||
vendor: Vendor;
|
||||
onRemove?: (v: Vendor) => void;
|
||||
}) {
|
||||
return (
|
||||
<Badge variant="neutral" className="flex items-center gap-1">
|
||||
<Avatar name={vendor.name} src={faviconUrl(vendor.websiteUrl)} size="s" />
|
||||
<span className="max-w-[100px] text-ellipsis overflow-hidden min-w-0 block">
|
||||
{vendor.name}
|
||||
</span>
|
||||
{onRemove && (
|
||||
<button
|
||||
onClick={() => onRemove(vendor)}
|
||||
className="size-4 hover:text-txt-primary cursor-pointer"
|
||||
>
|
||||
<IconCrossLargeX size={14} />
|
||||
</button>
|
||||
)}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
@@ -52,7 +52,7 @@ export const createAssetMutation = graphql`
|
||||
$connections: [ID!]!
|
||||
) {
|
||||
createAsset(input: $input) {
|
||||
assetEdge @prependEdge(connections: $connections) {
|
||||
assetEdge @appendEdge(connections: $connections) {
|
||||
node {
|
||||
id
|
||||
snapshotId
|
||||
|
||||
@@ -12,14 +12,23 @@ import type { PeopleGraphPaginatedQuery } from "./__generated__/PeopleGraphPagin
|
||||
import type { PeopleGraphPaginatedFragment$key } from "./__generated__/PeopleGraphPaginatedFragment.graphql";
|
||||
import { useConfirm, useToast } from "@probo/ui";
|
||||
import type { PeopleGraphDeleteMutation } from "./__generated__/PeopleGraphDeleteMutation.graphql";
|
||||
import { promisifyMutation, sprintf, formatError, type GraphQLError } from "@probo/helpers";
|
||||
import {
|
||||
promisifyMutation,
|
||||
sprintf,
|
||||
formatError,
|
||||
type GraphQLError,
|
||||
} from "@probo/helpers";
|
||||
import { useTranslate } from "@probo/i18n";
|
||||
|
||||
const peopleQuery = graphql`
|
||||
export const peopleQuery = graphql`
|
||||
query PeopleGraphQuery($organizationId: ID!, $filter: PeopleFilter) {
|
||||
organization: node(id: $organizationId) {
|
||||
... on Organization {
|
||||
peoples(first: 1000, orderBy: { direction: ASC, field: FULL_NAME }, filter: $filter) {
|
||||
peoples(
|
||||
first: 1000
|
||||
orderBy: { direction: ASC, field: FULL_NAME }
|
||||
filter: $filter
|
||||
) {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
@@ -36,14 +45,17 @@ const peopleQuery = graphql`
|
||||
/**
|
||||
* Return a list of people (used for people selectors)
|
||||
*/
|
||||
export function usePeople(organizationId: string, { excludeContractEnded }: { excludeContractEnded?: boolean } = {}) {
|
||||
export function usePeople(
|
||||
organizationId: string,
|
||||
{ excludeContractEnded }: { excludeContractEnded?: boolean } = {},
|
||||
) {
|
||||
const data = useLazyLoadQuery<PeopleGraphQuery>(
|
||||
peopleQuery,
|
||||
{
|
||||
organizationId: organizationId,
|
||||
filter: excludeContractEnded ? { excludeContractEnded: true } : null,
|
||||
},
|
||||
{ fetchPolicy: "network-only" }
|
||||
{ fetchPolicy: "network-only" },
|
||||
);
|
||||
return useMemo(() => {
|
||||
return data.organization?.peoples?.edges.map((edge) => edge.node) ?? [];
|
||||
@@ -66,7 +78,10 @@ export const paginatedPeopleFragment = graphql`
|
||||
@refetchable(queryName: "PeopleListQuery")
|
||||
@argumentDefinitions(
|
||||
first: { type: "Int", defaultValue: 50 }
|
||||
order: { type: "PeopleOrder", defaultValue: { direction: ASC, field: FULL_NAME } }
|
||||
order: {
|
||||
type: "PeopleOrder"
|
||||
defaultValue: { direction: ASC, field: FULL_NAME }
|
||||
}
|
||||
filter: { type: "PeopleFilter", defaultValue: null }
|
||||
after: { type: "CursorKey", defaultValue: null }
|
||||
before: { type: "CursorKey", defaultValue: null }
|
||||
@@ -98,12 +113,12 @@ export const paginatedPeopleFragment = graphql`
|
||||
`;
|
||||
|
||||
export function usePeopleQuery(
|
||||
queryRef: PreloadedQuery<PeopleGraphPaginatedQuery>
|
||||
queryRef: PreloadedQuery<PeopleGraphPaginatedQuery>,
|
||||
) {
|
||||
const data = usePreloadedQuery(paginatedPeopleQuery, queryRef);
|
||||
const pagination = usePaginationFragment(
|
||||
paginatedPeopleFragment,
|
||||
data.organization as PeopleGraphPaginatedFragment$key
|
||||
data.organization as PeopleGraphPaginatedFragment$key,
|
||||
);
|
||||
const people = pagination.data.peoples?.edges.map((edge) => edge.node);
|
||||
return {
|
||||
@@ -128,7 +143,7 @@ export const PeopleConnectionKey = "PeopleGraphPaginatedQuery_peoples";
|
||||
|
||||
export const useDeletePeople = (
|
||||
people: { id?: string; fullName?: string },
|
||||
connectionId: string
|
||||
connectionId: string,
|
||||
) => {
|
||||
const [mutate] = useMutation<PeopleGraphDeleteMutation>(deletePeopleMutation);
|
||||
const confirm = useConfirm();
|
||||
@@ -151,18 +166,21 @@ export const useDeletePeople = (
|
||||
}).catch((error) => {
|
||||
toast({
|
||||
title: __("Error"),
|
||||
description: formatError(__("Failed to delete people"), error as GraphQLError),
|
||||
description: formatError(
|
||||
__("Failed to delete people"),
|
||||
error as GraphQLError,
|
||||
),
|
||||
variant: "error",
|
||||
});
|
||||
}),
|
||||
{
|
||||
message: sprintf(
|
||||
__(
|
||||
'This will permanently delete "%s". This action cannot be undone.'
|
||||
'This will permanently delete "%s". This action cannot be undone.',
|
||||
),
|
||||
people.fullName
|
||||
people.fullName,
|
||||
),
|
||||
}
|
||||
},
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -37,7 +37,7 @@ export function useCreateVendorMutation() {
|
||||
{
|
||||
successMessage: __("Vendor created successfully."),
|
||||
errorMessage: __("Failed to create vendor"),
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ const deleteVendorMutation = graphql`
|
||||
|
||||
export const useDeleteVendor = (
|
||||
vendor: { id?: string; name?: string },
|
||||
connectionId: string
|
||||
connectionId: string,
|
||||
) => {
|
||||
const [mutate] = useMutation<VendorGraphDeleteMutation>(deleteVendorMutation);
|
||||
const confirm = useConfirm();
|
||||
@@ -77,11 +77,11 @@ export const useDeleteVendor = (
|
||||
{
|
||||
message: sprintf(
|
||||
__(
|
||||
'This will permanently delete vendor "%s". This action cannot be undone.'
|
||||
'This will permanently delete vendor "%s". This action cannot be undone.',
|
||||
),
|
||||
vendor.name
|
||||
vendor.name,
|
||||
),
|
||||
}
|
||||
},
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -171,7 +171,7 @@ export const vendorNodeQuery = graphql`
|
||||
}
|
||||
`;
|
||||
|
||||
const vendorsSelectQuery = graphql`
|
||||
export const vendorsSelectQuery = graphql`
|
||||
query VendorGraphSelectQuery($organizationId: ID!) {
|
||||
organization: node(id: $organizationId) {
|
||||
... on Organization {
|
||||
@@ -195,7 +195,7 @@ export function useVendors(organizationId: string) {
|
||||
{
|
||||
organizationId: organizationId,
|
||||
},
|
||||
{ fetchPolicy: "network-only" }
|
||||
{ fetchPolicy: "network-only" },
|
||||
);
|
||||
return useMemo(() => {
|
||||
return data.organization?.vendors?.edges.map((edge) => edge.node) ?? [];
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @generated SignedSource<<0f47a0632a7158414d8c87cf9de16a7a>>
|
||||
* @generated SignedSource<<9ebcbef6d786f85d0b88c881d1478938>>
|
||||
* @lightSyntaxTransform
|
||||
* @nogrep
|
||||
*/
|
||||
@@ -262,7 +262,7 @@ return {
|
||||
"alias": null,
|
||||
"args": null,
|
||||
"filters": null,
|
||||
"handle": "prependEdge",
|
||||
"handle": "appendEdge",
|
||||
"key": "",
|
||||
"kind": "LinkedHandle",
|
||||
"name": "assetEdge",
|
||||
@@ -290,6 +290,6 @@ return {
|
||||
};
|
||||
})();
|
||||
|
||||
(node as any).hash = "1d36f3080ab525417516779740f5977c";
|
||||
(node as any).hash = "92fca40d88a9ea68f013e9953d46388e";
|
||||
|
||||
export default node;
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import {
|
||||
ActionDropdown,
|
||||
Avatar,
|
||||
Badge,
|
||||
Button,
|
||||
DropdownItem,
|
||||
EditableCell,
|
||||
IconCrossLargeX,
|
||||
IconPencil,
|
||||
IconPlusLarge,
|
||||
IconTrashCan,
|
||||
PageHeader,
|
||||
SelectCell,
|
||||
TextCell,
|
||||
useConfirm,
|
||||
} from "@probo/ui";
|
||||
import { useTranslate } from "@probo/i18n";
|
||||
@@ -21,17 +21,15 @@ import {
|
||||
usePreloadedQuery,
|
||||
} from "react-relay";
|
||||
import { useOrganizationId } from "/hooks/useOrganizationId";
|
||||
import { useParams } from "react-router";
|
||||
import { CreateAssetDialog } from "./dialogs/CreateAssetDialog";
|
||||
import { Link, useParams } from "react-router";
|
||||
import {
|
||||
assetsQuery,
|
||||
createAssetMutation,
|
||||
deleteAssetMutation,
|
||||
updateAssetMutation,
|
||||
} from "../../../hooks/graph/AssetGraph";
|
||||
} from "/hooks/graph/AssetGraph";
|
||||
import type { AssetGraphListQuery } from "/hooks/graph/__generated__/AssetGraphListQuery.graphql";
|
||||
import {
|
||||
faviconUrl,
|
||||
getAssetTypeVariant,
|
||||
promisifyMutation,
|
||||
sprintf,
|
||||
@@ -39,9 +37,10 @@ import {
|
||||
import type { AssetsPageFragment$key } from "./__generated__/AssetsPageFragment.graphql";
|
||||
import { SnapshotBanner } from "/components/SnapshotBanner";
|
||||
import z from "zod";
|
||||
import { usePeople } from "/hooks/graph/PeopleGraph.ts";
|
||||
import { useVendors } from "/hooks/graph/VendorGraph.ts";
|
||||
import { EditableTable } from "/components/table/EditableTable.tsx";
|
||||
import { PeopleCell } from "/components/table/PeopleCell.tsx";
|
||||
import { VendorsCell } from "/components/table/VendorsCell.tsx";
|
||||
import { CreateAssetDialog } from "./dialogs/CreateAssetDialog";
|
||||
import { Authorized, isAuthorized } from "/permissions";
|
||||
|
||||
const paginatedAssetsFragment = graphql`
|
||||
@@ -98,7 +97,7 @@ type Props = {
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().trim().min(1, "Name is required"),
|
||||
amount: z.coerce.number().min(0, "Amount is required"),
|
||||
amount: z.coerce.number().min(1, "Amount is required"),
|
||||
assetType: z.enum(["PHYSICAL", "VIRTUAL"]),
|
||||
ownerId: z.string().trim().min(1, "Owner is required"),
|
||||
vendorIds: z.array(z.string()).optional(),
|
||||
@@ -122,6 +121,11 @@ export default function AssetsPage(props: Props) {
|
||||
const { snapshotId } = useParams<{ snapshotId?: string }>();
|
||||
const isSnapshotMode = Boolean(snapshotId);
|
||||
|
||||
const assetUrl = (entry: { id: string }) =>
|
||||
isSnapshotMode && snapshotId
|
||||
? `/organizations/${organizationId}/snapshots/${snapshotId}/assets/${entry.id}`
|
||||
: `/organizations/${organizationId}/assets/${entry.id}`;
|
||||
|
||||
const data = usePreloadedQuery(assetsQuery, props.queryRef);
|
||||
const pagination = usePaginationFragment(
|
||||
paginatedAssetsFragment,
|
||||
@@ -177,78 +181,59 @@ export default function AssetsPage(props: Props) {
|
||||
...defaultValue,
|
||||
organizationId,
|
||||
}}
|
||||
action={({ item }) => (
|
||||
<ActionDropdown>
|
||||
<DropdownItem
|
||||
onClick={() => deleteAsset(item)}
|
||||
variant="danger"
|
||||
icon={IconTrashCan}
|
||||
>
|
||||
{__("Delete")}
|
||||
</DropdownItem>
|
||||
</ActionDropdown>
|
||||
)}
|
||||
row={({ item, onUpdate, errors }) => (
|
||||
action={({ item }) =>
|
||||
hasAnyAction ? (
|
||||
<ActionDropdown>
|
||||
<DropdownItem asChild>
|
||||
<Link to={assetUrl(item)}>
|
||||
<IconPencil size={16} />
|
||||
{__("Edit")}
|
||||
</Link>
|
||||
</DropdownItem>
|
||||
<DropdownItem
|
||||
onClick={() => deleteAsset(item)}
|
||||
variant="danger"
|
||||
icon={IconTrashCan}
|
||||
>
|
||||
{__("Delete")}
|
||||
</DropdownItem>
|
||||
</ActionDropdown>
|
||||
) : null
|
||||
}
|
||||
row={({ item }) => (
|
||||
<>
|
||||
<EditableCell
|
||||
type="text"
|
||||
value={item?.name ?? ""}
|
||||
onValueChange={(v) => onUpdate("name", v)}
|
||||
blink={Boolean(errors?.name)}
|
||||
/>
|
||||
<EditableCell
|
||||
type="select"
|
||||
<TextCell name="name" defaultValue={item?.name ?? ""} required />
|
||||
<SelectCell
|
||||
name="assetType"
|
||||
items={["VIRTUAL", "PHYSICAL"]}
|
||||
value={item?.assetType ?? "VIRTUAL"}
|
||||
itemRenderer={({ item }) => (
|
||||
<Badge variant={getAssetTypeVariant(item ?? "VIRTUAL")}>
|
||||
{item === "PHYSICAL" ? __("Physical") : __("Virtual")}
|
||||
</Badge>
|
||||
)}
|
||||
onValueChange={(v) => onUpdate("assetType", v)}
|
||||
blink={Boolean(errors?.assetType)}
|
||||
defaultValue={item?.assetType ?? defaultValue.assetType}
|
||||
/>
|
||||
<EditableCell
|
||||
type="text"
|
||||
value={item?.dataTypesStored ?? ""}
|
||||
onValueChange={(v) => onUpdate("dataTypesStored", v)}
|
||||
blink={Boolean(errors?.dataTypesStored)}
|
||||
/>
|
||||
<EditableCell
|
||||
type="text"
|
||||
value={item?.amount.toString() ?? "0"}
|
||||
onValueChange={(v) => onUpdate("amount", v)}
|
||||
blink={Boolean(errors?.amount)}
|
||||
/>
|
||||
<EditableCell
|
||||
type="select"
|
||||
items={() =>
|
||||
usePeople(organizationId, { excludeContractEnded: true })
|
||||
<TextCell
|
||||
name="dataTypesStored"
|
||||
defaultValue={
|
||||
item?.dataTypesStored ?? defaultValue.dataTypesStored
|
||||
}
|
||||
value={item?.owner}
|
||||
itemRenderer={({ item }) => (
|
||||
<div className="flex gap-2">
|
||||
<Avatar name={item.fullName} />
|
||||
{item.fullName}
|
||||
</div>
|
||||
)}
|
||||
onValueChange={(v) => onUpdate("ownerId", v.id)}
|
||||
blink={Boolean(errors?.ownerId)}
|
||||
required
|
||||
/>
|
||||
<EditableCell
|
||||
type="multiple"
|
||||
items={() => useVendors(organizationId)}
|
||||
value={item?.vendors.edges.map((edge) => edge.node)}
|
||||
itemRenderer={({ item, onRemove }) => (
|
||||
<VendorBadge key={item.id} vendor={item} onRemove={onRemove} />
|
||||
)}
|
||||
onValueChange={(v) =>
|
||||
onUpdate(
|
||||
"vendorIds",
|
||||
v.map((v) => v.id),
|
||||
)
|
||||
}
|
||||
blink={Boolean(errors?.vendorIds)}
|
||||
<TextCell
|
||||
name="amount"
|
||||
defaultValue={(item?.amount ?? defaultValue.amount).toString()}
|
||||
required
|
||||
/>
|
||||
<PeopleCell
|
||||
name="ownerId"
|
||||
defaultValue={item?.owner}
|
||||
organizationId={organizationId}
|
||||
/>
|
||||
<VendorsCell
|
||||
name="vendorIds"
|
||||
organizationId={organizationId}
|
||||
defaultValue={item?.vendors.edges.map((edge) => edge.node) ?? []}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
@@ -257,37 +242,6 @@ export default function AssetsPage(props: Props) {
|
||||
);
|
||||
}
|
||||
|
||||
type Vendor = {
|
||||
id: string;
|
||||
name: string;
|
||||
websiteUrl: string | null | undefined;
|
||||
};
|
||||
|
||||
function VendorBadge({
|
||||
vendor,
|
||||
onRemove,
|
||||
}: {
|
||||
vendor: Vendor;
|
||||
onRemove?: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Badge variant="neutral" className="flex items-center gap-1">
|
||||
<Avatar name={vendor.name} src={faviconUrl(vendor.websiteUrl)} size="s" />
|
||||
<span className="max-w-[100px] text-ellipsis overflow-hidden min-w-0 block">
|
||||
{vendor.name}
|
||||
</span>
|
||||
{onRemove && (
|
||||
<button
|
||||
onClick={onRemove}
|
||||
className="size-4 hover:text-txt-primary cursor-pointer"
|
||||
>
|
||||
<IconCrossLargeX size={14} />
|
||||
</button>
|
||||
)}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
const useDeleteAsset = (connectionId: string) => {
|
||||
const [mutate] = useMutation(deleteAssetMutation);
|
||||
const confirm = useConfirm();
|
||||
|
||||
@@ -26,6 +26,15 @@ export const assetRoutes = [
|
||||
}),
|
||||
Component: lazy(() => import("/pages/organizations/assets/AssetsPage")),
|
||||
},
|
||||
{
|
||||
path: "assets/:assetId",
|
||||
fallback: PageSkeleton,
|
||||
queryLoader: (params: Record<string, string>) =>
|
||||
loadQuery(relayEnvironment, assetNodeQuery, { assetId: params.assetId }),
|
||||
Component: lazy(
|
||||
() => import("/pages/organizations/assets/AssetDetailsPage"),
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "snapshots/:snapshotId/assets/:assetId",
|
||||
fallback: PageSkeleton,
|
||||
|
||||
@@ -2,3 +2,4 @@ export { usePageTitle } from "./usePageTitle";
|
||||
export { useToggle } from "./useToggle";
|
||||
export { useRefSync } from "./useRefSync";
|
||||
export { useList } from "./useList";
|
||||
export { useStateWithRef } from "./useStateWithRef";
|
||||
|
||||
18
packages/hooks/src/useStateWithRef.ts
Normal file
18
packages/hooks/src/useStateWithRef.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
|
||||
/**
|
||||
* A useState hook that also returns a ref to the current state (usable in callbacks)
|
||||
*/
|
||||
export function useStateWithRef<T>(initialValue: T) {
|
||||
const [state, setState] = useState(initialValue);
|
||||
const ref = useRef(state);
|
||||
|
||||
return [
|
||||
state,
|
||||
useCallback((v: T) => {
|
||||
setState(v);
|
||||
ref.current = v;
|
||||
}, []),
|
||||
ref,
|
||||
] as const;
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
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>
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -21,16 +21,17 @@ export function DataTable({
|
||||
};
|
||||
}
|
||||
return {
|
||||
gridTemplateColumns: columns
|
||||
.map((col) => `minmax(0, ${col})`)
|
||||
.join(" "),
|
||||
gridTemplateColumns: columns.join(" "),
|
||||
};
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="overflow-auto relative w-full p-1 -m-1">
|
||||
<Card
|
||||
className={clsx(className, "w-full text-left grid")}
|
||||
className={clsx(
|
||||
className,
|
||||
"min-w-min text-left grid overflow-hidden",
|
||||
)}
|
||||
style={style()}
|
||||
>
|
||||
{children}
|
||||
|
||||
65
packages/ui/src/Molecules/Table/DataTable.stories.tsx
Normal file
65
packages/ui/src/Molecules/Table/DataTable.stories.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react";
|
||||
import { type FC, Fragment, useState } from "react";
|
||||
import { CellHead, DataTable, Row } from "../../Atoms/DataTable/DataTable.tsx";
|
||||
import { EditableRow } from "./EditableRow.tsx";
|
||||
import { TextCell } from "./TextCell.tsx";
|
||||
import { fn } from "@storybook/test";
|
||||
import { SelectCell } from "./SelectCell.tsx";
|
||||
import { Badge } from "../../Atoms/Badge/Badge.tsx";
|
||||
|
||||
type Component = FC<{ onUpdate: (key: string, value: unknown) => void }>;
|
||||
|
||||
export default {
|
||||
title: "Atoms/DataTable/Cells",
|
||||
component: Fragment as Component,
|
||||
argTypes: {},
|
||||
args: { onUpdate: fn() },
|
||||
} satisfies Meta<Component>;
|
||||
|
||||
type Story = StoryObj<Component>;
|
||||
|
||||
export const Default: Story = {
|
||||
render: ({ onUpdate }) => {
|
||||
const [state, setState] = useState({
|
||||
name: "John",
|
||||
status: "delivered",
|
||||
statuses: ["delivered", "pending"],
|
||||
});
|
||||
const updateField = (key: string, value: unknown) => {
|
||||
onUpdate(key, value);
|
||||
setState({
|
||||
...state,
|
||||
[key]: value,
|
||||
});
|
||||
};
|
||||
return (
|
||||
<DataTable columns={["1fr", "1fr", "1fr"]}>
|
||||
<Row>
|
||||
<CellHead>Nom</CellHead>
|
||||
<CellHead>Status</CellHead>
|
||||
<CellHead>Statuses</CellHead>
|
||||
</Row>
|
||||
<EditableRow onUpdate={updateField}>
|
||||
<TextCell required name="name" defaultValue={state.name} />
|
||||
<SelectCell
|
||||
items={["delivered", "pending"]}
|
||||
itemRenderer={({ item }) => <Badge>{item}</Badge>}
|
||||
name="status"
|
||||
defaultValue={state.status}
|
||||
/>
|
||||
<SelectCell
|
||||
multiple
|
||||
items={["delivered", "pending"]}
|
||||
itemRenderer={({ item, onRemove }) => (
|
||||
<Badge onClick={() => onRemove?.(item)}>
|
||||
{item}
|
||||
</Badge>
|
||||
)}
|
||||
name="statuses"
|
||||
defaultValue={state.statuses}
|
||||
/>
|
||||
</EditableRow>
|
||||
</DataTable>
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -1,79 +1,39 @@
|
||||
import * as Popover from "@radix-ui/react-popover";
|
||||
import {
|
||||
type CSSProperties,
|
||||
type KeyboardEventHandler,
|
||||
type ReactNode,
|
||||
Suspense,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { Cell } from "../../Atoms/DataTable/DataTable.tsx";
|
||||
import { Command } from "cmdk";
|
||||
import { useTranslate } from "@probo/i18n";
|
||||
import { Spinner } from "../../Atoms/Spinner/Spinner.tsx";
|
||||
import { focusSiblingElement } from "@probo/helpers";
|
||||
import { useEditableRowContext } from "./EditableRow.tsx";
|
||||
|
||||
type Props<T> =
|
||||
| {
|
||||
type: "text";
|
||||
value?: T;
|
||||
blink?: boolean;
|
||||
onValueChange: (value: string) => void;
|
||||
itemRenderer?: undefined;
|
||||
}
|
||||
| {
|
||||
type: "select";
|
||||
items: T[] | (() => T[]);
|
||||
itemRenderer: (v: { item: T }) => ReactNode;
|
||||
value?: T;
|
||||
blink?: boolean;
|
||||
onValueChange: (value: T) => void;
|
||||
}
|
||||
| {
|
||||
type: "multiple";
|
||||
items: T[] | (() => T[]);
|
||||
itemRenderer: (v: { item: T; onRemove?: () => void }) => ReactNode;
|
||||
value?: T[];
|
||||
blink?: boolean;
|
||||
onValueChange: (value: T[]) => void;
|
||||
};
|
||||
|
||||
type PropsField<Type, T> = Props<T> & {
|
||||
type: Type;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
padding: string;
|
||||
height: number;
|
||||
};
|
||||
|
||||
function getKey<T>(item: T): string {
|
||||
if (
|
||||
item &&
|
||||
typeof item === "object" &&
|
||||
"id" in item &&
|
||||
typeof item.id === "string"
|
||||
) {
|
||||
return item.id.toString();
|
||||
}
|
||||
if (typeof item === "string" || typeof item === "number") {
|
||||
return item.toString();
|
||||
}
|
||||
if (item === undefined) {
|
||||
return "";
|
||||
}
|
||||
console.error("Cannot compute a key from item", item);
|
||||
return "";
|
||||
export function useEditableCellRef() {
|
||||
return useRef<{ close: () => void } | null>(null);
|
||||
}
|
||||
|
||||
export function EditableCell<T>(props: Props<T>) {
|
||||
/**
|
||||
* Base component to create an editable table cell
|
||||
*/
|
||||
export function EditableCell(props: {
|
||||
// Name of the field (used to retrieve errors)
|
||||
name?: string;
|
||||
// Label displayed inside the cell
|
||||
label: ReactNode;
|
||||
// Callback when the edit is dismissed
|
||||
onClose: () => void;
|
||||
// Content of the popover (e.g. a field)
|
||||
children: ReactNode;
|
||||
// Ref used to control the popover (used to close it programatically)
|
||||
ref: ReturnType<typeof useEditableCellRef>;
|
||||
}) {
|
||||
const { errors } = useEditableRowContext();
|
||||
const [isOpen, setOpen] = useState(false);
|
||||
const [value, setValueState] = useState(props.value);
|
||||
const [height, setHeight] = useState<number | undefined>(undefined);
|
||||
const [padding, setPadding] = useState("12px");
|
||||
const td = useRef<HTMLTableCellElement>(null);
|
||||
const valueRef = useRef(value);
|
||||
const setValue = (value: T) => {
|
||||
valueRef.current = value;
|
||||
setValueState(value);
|
||||
};
|
||||
|
||||
// When opening the popover, remember the height and padding of the cell
|
||||
const onOpenChange = (open: boolean) => {
|
||||
@@ -81,37 +41,17 @@ export function EditableCell<T>(props: Props<T>) {
|
||||
setHeight(td.current?.offsetHeight ?? undefined);
|
||||
setPadding(getComputedStyle(td.current!).paddingLeft);
|
||||
} else {
|
||||
props.onClose();
|
||||
setHeight(undefined);
|
||||
}
|
||||
// Send the value when closing the popover
|
||||
if (!open && valueRef.current !== props.value) {
|
||||
// @ts-expect-error - cannot unpack value type
|
||||
props.onValueChange(valueRef.current);
|
||||
}
|
||||
setOpen(open);
|
||||
};
|
||||
|
||||
const fieldProps = {
|
||||
height,
|
||||
onValueChange: setValue,
|
||||
onOpenChange,
|
||||
padding,
|
||||
value,
|
||||
} as any;
|
||||
|
||||
const children = (() => {
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
if (props.type === "select") {
|
||||
// @ts-expect-error TS cannot understand the link between props.type and value
|
||||
return props.itemRenderer({ item: value });
|
||||
}
|
||||
if (Array.isArray(value) && props.type === "multiple") {
|
||||
return <>{value.map((v) => props.itemRenderer({ item: v }))}</>;
|
||||
}
|
||||
return value as ReactNode;
|
||||
})();
|
||||
if (props.ref) {
|
||||
props.ref.current = {
|
||||
close: () => onOpenChange(false),
|
||||
};
|
||||
}
|
||||
|
||||
// Handle keyboard navigation inside the cells
|
||||
const onKeyDown: KeyboardEventHandler<HTMLButtonElement> = (e) => {
|
||||
@@ -129,6 +69,7 @@ export function EditableCell<T>(props: Props<T>) {
|
||||
);
|
||||
}
|
||||
};
|
||||
const hasError = errors && props.name && props.name in errors;
|
||||
|
||||
return (
|
||||
<Popover.Root onOpenChange={onOpenChange} open={isOpen}>
|
||||
@@ -140,9 +81,9 @@ export function EditableCell<T>(props: Props<T>) {
|
||||
className="flex flex-row justify-start hover:bg-level-2 flex-wrap gap-1 items-center relative"
|
||||
style={{ height }}
|
||||
>
|
||||
{children}
|
||||
{props.blink && (
|
||||
<div className="size-2 bg-txt-accent rounded-full top-1/2 right-3 absolute -translate-y-1/2 animate-pulse" />
|
||||
{props.label}
|
||||
{hasError && (
|
||||
<div className="size-2 bg-txt-danger rounded-full top-1/2 right-3 absolute -translate-y-1/2 animate-pulse" />
|
||||
)}
|
||||
</button>
|
||||
</Cell>
|
||||
@@ -153,205 +94,18 @@ export function EditableCell<T>(props: Props<T>) {
|
||||
side="bottom"
|
||||
align="start"
|
||||
sideOffset={height ? height * -1 : 0}
|
||||
style={{
|
||||
minHeight: height,
|
||||
}}
|
||||
style={
|
||||
{
|
||||
minHeight: height,
|
||||
"--padding": padding,
|
||||
"--height": height + "px",
|
||||
} as CSSProperties
|
||||
}
|
||||
className="border border-border-low bg-level-2 min-w-[200px] flex flex-col justify-center rounded-sm"
|
||||
>
|
||||
{props.type === "text" && (
|
||||
<Input {...props} {...fieldProps} />
|
||||
)}
|
||||
{props.type === "select" && (
|
||||
<Select {...props} {...fieldProps} />
|
||||
)}
|
||||
{props.type === "multiple" && (
|
||||
<Multiple {...props} {...fieldProps} />
|
||||
)}
|
||||
{props.children}
|
||||
</Popover.Content>
|
||||
</Popover.Portal>
|
||||
</Popover.Root>
|
||||
);
|
||||
}
|
||||
|
||||
function Input(props: PropsField<"text", string>) {
|
||||
const blurOnTab: KeyboardEventHandler<HTMLInputElement> = (e) => {
|
||||
if (e.key === "Tab") {
|
||||
props.onOpenChange(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
defaultValue={props.value}
|
||||
onKeyDown={blurOnTab}
|
||||
className="text-sm text-txt-primary outline-none"
|
||||
onChange={(e) => props.onValueChange(e.currentTarget.value)}
|
||||
style={{ paddingLeft: props.padding }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function Select<T>(props: PropsField<"select", T>) {
|
||||
const { __ } = useTranslate();
|
||||
const showSearch = false;
|
||||
return (
|
||||
<Command className="text-txt-primary absolute left-0 top-0 right-0 bg-level-2 border border-border-low rounded-b-sm">
|
||||
<div
|
||||
style={{ height: props.height, paddingLeft: props.padding }}
|
||||
className="flex flex-col justify-center"
|
||||
onClick={() => props.onOpenChange(false)}
|
||||
>
|
||||
{props.value ? props.itemRenderer({ item: props.value }) : ""}
|
||||
</div>
|
||||
{showSearch && (
|
||||
<Command.Input
|
||||
className="text-sm text-txt-secondary border-y border-border-low py-2 px-3 w-full focus:outline-txt-accent outline"
|
||||
placeholder={__("Search")}
|
||||
/>
|
||||
)}
|
||||
<Command.List>
|
||||
{Array.isArray(props.items) ? (
|
||||
props.items
|
||||
.filter((item) => item !== props.value)
|
||||
.map((item) => (
|
||||
<Command.Item
|
||||
key={getKey(item)}
|
||||
className="py-2 px-3 hover:bg-level-3 data-[selected]:bg-level-3"
|
||||
onSelect={() => {
|
||||
props.onValueChange(item);
|
||||
props.onOpenChange(false);
|
||||
}}
|
||||
>
|
||||
{props.itemRenderer({ item })}
|
||||
</Command.Item>
|
||||
))
|
||||
) : (
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="py-2 px-3">
|
||||
<Spinner />
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<SelectItems
|
||||
value={props.value}
|
||||
itemRenderer={props.itemRenderer}
|
||||
items={props.items}
|
||||
onSelect={(item) => {
|
||||
props.onValueChange(item);
|
||||
props.onOpenChange(false);
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
</Command.List>
|
||||
</Command>
|
||||
);
|
||||
}
|
||||
|
||||
function Multiple<T>(props: PropsField<"multiple", T>) {
|
||||
const { __ } = useTranslate();
|
||||
const showSearch = true;
|
||||
|
||||
const pushValue = (item: T) => {
|
||||
props.onValueChange([...(props.value ?? []), item]);
|
||||
};
|
||||
|
||||
const removeValue = (item: T) => {
|
||||
props.onValueChange(
|
||||
props.value!.filter((v) => getKey(v) !== getKey(item)),
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Command className="text-txt-primary absolute left-0 top-0 right-0 bg-level-2 border border-border-low rounded-b-sm">
|
||||
{props.value && props.value.length > 0 && (
|
||||
<div
|
||||
className="flex flex-col gap-2 py-3"
|
||||
style={{
|
||||
paddingLeft: props.padding,
|
||||
}}
|
||||
>
|
||||
{props.value &&
|
||||
props.value.map((item) =>
|
||||
props.itemRenderer({
|
||||
item,
|
||||
onRemove: () => removeValue(item),
|
||||
}),
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{showSearch && (
|
||||
<Command.Input
|
||||
className="text-sm text-txt-secondary border-y border-border-low py-2 px-3 w-full focus:outline-txt-accent outline"
|
||||
placeholder={__("Search")}
|
||||
/>
|
||||
)}
|
||||
<Command.List>
|
||||
{Array.isArray(props.items) ? (
|
||||
props.items
|
||||
.filter((item) => item !== props.value)
|
||||
.map((item, k) => (
|
||||
<Command.Item
|
||||
key={k}
|
||||
className="py-2 px-3 hover:bg-level-3 data-[selected]:bg-level-3"
|
||||
onSelect={() => {
|
||||
pushValue(item);
|
||||
}}
|
||||
>
|
||||
{props.itemRenderer({
|
||||
item,
|
||||
})}
|
||||
</Command.Item>
|
||||
))
|
||||
) : (
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="py-2 px-3">
|
||||
<Spinner />
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<SelectItems
|
||||
value={props.value}
|
||||
itemRenderer={props.itemRenderer}
|
||||
items={props.items}
|
||||
onSelect={(item) => {
|
||||
pushValue(item);
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
</Command.List>
|
||||
</Command>
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Resolve items with a suspense
|
||||
*/
|
||||
function SelectItems<T>(props: {
|
||||
value?: T | T[];
|
||||
itemRenderer: (v: { item: T }) => ReactNode;
|
||||
items: () => T[];
|
||||
onSelect: (item: T) => void;
|
||||
}) {
|
||||
const items = props.items();
|
||||
const keys = Array.isArray(props.value)
|
||||
? props.value.map(getKey)
|
||||
: [getKey(props.value)];
|
||||
return (
|
||||
<>
|
||||
{items
|
||||
.filter((item) => !keys.includes(getKey(item)))
|
||||
.map((item) => (
|
||||
<Command.Item
|
||||
key={getKey(item)}
|
||||
className="py-2 px-3 hover:bg-level-3 data-[selected]:bg-level-3"
|
||||
onSelect={() => props.onSelect(item)}
|
||||
>
|
||||
{props.itemRenderer({ item })}
|
||||
</Command.Item>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
46
packages/ui/src/Molecules/Table/EditableRow.tsx
Normal file
46
packages/ui/src/Molecules/Table/EditableRow.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import {
|
||||
createContext,
|
||||
type ReactNode,
|
||||
useContext,
|
||||
useMemo,
|
||||
useRef,
|
||||
} from "react";
|
||||
import { Row } from "../../Atoms/DataTable/DataTable.tsx";
|
||||
|
||||
type Props = {
|
||||
onUpdate: (key: string, value: unknown) => void;
|
||||
errors?: Record<string, string>;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
export const EditableRowContext = createContext<null | Omit<Props, "children">>(
|
||||
null,
|
||||
);
|
||||
|
||||
export const useEditableRowContext = () => {
|
||||
const context = useContext(EditableRowContext);
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
"useEditableRowContext must be used within an EditableRow",
|
||||
);
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export function EditableRow(props: Props) {
|
||||
const onUpdateRef = useRef(props.onUpdate);
|
||||
onUpdateRef.current = props.onUpdate;
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
errors: props.errors,
|
||||
onUpdate: (key: string, value: unknown) =>
|
||||
onUpdateRef.current(key, value),
|
||||
}),
|
||||
[props.errors],
|
||||
);
|
||||
return (
|
||||
<EditableRowContext value={value}>
|
||||
<Row>{props.children}</Row>
|
||||
</EditableRowContext>
|
||||
);
|
||||
}
|
||||
164
packages/ui/src/Molecules/Table/SelectCell.tsx
Normal file
164
packages/ui/src/Molecules/Table/SelectCell.tsx
Normal file
@@ -0,0 +1,164 @@
|
||||
import { EditableCell, useEditableCellRef } from "./EditableCell.tsx";
|
||||
import { Command } from "cmdk";
|
||||
import { Fragment, type ReactNode } from "react";
|
||||
import { getKey } from "./utils.ts";
|
||||
import { useTranslate } from "@probo/i18n";
|
||||
import { useEditableRowContext } from "./EditableRow.tsx";
|
||||
import { useStateWithRef } from "@probo/hooks";
|
||||
import { tv } from "tailwind-variants";
|
||||
import { Badge } from "../../Atoms/Badge/Badge.tsx";
|
||||
|
||||
type Props<T> = {
|
||||
name: string;
|
||||
items: T[];
|
||||
itemRenderer: (v: { item: T; onRemove?: (item: T) => void }) => ReactNode;
|
||||
} & (
|
||||
| { defaultValue: T; multiple?: undefined }
|
||||
| { defaultValue: T[]; multiple: true }
|
||||
);
|
||||
|
||||
export const selectCell = tv({
|
||||
slots: {
|
||||
command:
|
||||
"text-txt-primary absolute left-0 top-0 right-0 bg-level-2 border border-border-low rounded-b-sm",
|
||||
value: "flex flex-col gap-2 py-3 justify-center",
|
||||
input: "text-sm text-txt-secondary border-y border-border-low py-2 px-3 w-full focus:outline-txt-accent outline",
|
||||
item: "py-2 px-3 hover:bg-level-3 data-[selected=true]:bg-level-3",
|
||||
},
|
||||
});
|
||||
|
||||
export function SelectCell<T>(props: Props<T>) {
|
||||
const [value, setValue, valueRef] = useStateWithRef<T | T[]>(
|
||||
props.defaultValue,
|
||||
);
|
||||
const cellRef = useEditableCellRef();
|
||||
const { __ } = useTranslate();
|
||||
const usedKeys = new Set<string>(
|
||||
Array.isArray(value) ? value.map(getKey) : [getKey(value)],
|
||||
);
|
||||
const { onUpdate } = useEditableRowContext();
|
||||
|
||||
const onSelect = (item: T) => {
|
||||
if (props.multiple) {
|
||||
setValue([...((valueRef.current as T[]) ?? []), item]);
|
||||
return;
|
||||
}
|
||||
setValue(item);
|
||||
cellRef.current?.close();
|
||||
};
|
||||
|
||||
const onClose = () => {
|
||||
if (valueRef.current === props.defaultValue) {
|
||||
return;
|
||||
}
|
||||
onUpdate(props.name, valueRef.current);
|
||||
};
|
||||
|
||||
const classNames = selectCell();
|
||||
|
||||
return (
|
||||
<EditableCell
|
||||
name={props.name}
|
||||
label={
|
||||
<SelectValue value={value} itemRenderer={props.itemRenderer} />
|
||||
}
|
||||
onClose={onClose}
|
||||
ref={cellRef}
|
||||
>
|
||||
<Command className={classNames.command()}>
|
||||
<div
|
||||
className={classNames.value()}
|
||||
style={{
|
||||
paddingLeft: "var(--padding)",
|
||||
minHeight: "var(--height)",
|
||||
}}
|
||||
>
|
||||
{" "}
|
||||
<SelectValue
|
||||
onValueChange={setValue}
|
||||
value={value}
|
||||
itemRenderer={props.itemRenderer}
|
||||
/>
|
||||
</div>{" "}
|
||||
{props.multiple && (
|
||||
<Command.Input
|
||||
className={classNames.input()}
|
||||
placeholder={__("Search")}
|
||||
/>
|
||||
)}
|
||||
<Command.List>
|
||||
{props.items
|
||||
.filter((item) => !usedKeys.has(getKey(item)))
|
||||
.map((item) => (
|
||||
<Command.Item
|
||||
key={getKey(item)}
|
||||
className={classNames.item()}
|
||||
onSelect={() => onSelect(item)}
|
||||
>
|
||||
{props.itemRenderer({ item })}
|
||||
</Command.Item>
|
||||
))}
|
||||
</Command.List>
|
||||
</Command>
|
||||
</EditableCell>
|
||||
);
|
||||
}
|
||||
|
||||
export function SelectValue<T>(props: {
|
||||
itemRenderer: Props<T>["itemRenderer"];
|
||||
onValueChange?: (value: T | T[]) => void;
|
||||
value: T | T[] | undefined;
|
||||
}) {
|
||||
if (!props.value) {
|
||||
return "";
|
||||
}
|
||||
if (!Array.isArray(props.value)) {
|
||||
return props.value ? props.itemRenderer({ item: props.value }) : "";
|
||||
}
|
||||
|
||||
const removeValue = (item: T) => {
|
||||
if (!Array.isArray(props.value) || !props.onValueChange) {
|
||||
return;
|
||||
}
|
||||
props.onValueChange(
|
||||
props.value!.filter((v) => getKey(v) !== getKey(item)),
|
||||
);
|
||||
};
|
||||
|
||||
if (!props.onValueChange && props.value.length > 0) {
|
||||
return (
|
||||
<>
|
||||
{props.value.slice(0, 3).map((item) => (
|
||||
<Fragment key={getKey(item)}>
|
||||
{props.itemRenderer({
|
||||
item,
|
||||
onRemove: props.onValueChange
|
||||
? () => removeValue(item)
|
||||
: undefined,
|
||||
})}
|
||||
</Fragment>
|
||||
))}
|
||||
{props.value.length > 3 && (
|
||||
<Badge className="text-txt-secondary">
|
||||
+{props.value.length - 3}
|
||||
</Badge>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{props.value.map((item) => (
|
||||
<Fragment key={getKey(item)}>
|
||||
{props.itemRenderer({
|
||||
item,
|
||||
onRemove: props.onValueChange
|
||||
? () => removeValue(item)
|
||||
: undefined,
|
||||
})}
|
||||
</Fragment>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
47
packages/ui/src/Molecules/Table/TextCell.tsx
Normal file
47
packages/ui/src/Molecules/Table/TextCell.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import { EditableCell, useEditableCellRef } from "./EditableCell.tsx";
|
||||
import { type KeyboardEventHandler, useRef, useState } from "react";
|
||||
import { useEditableRowContext } from "./EditableRow.tsx";
|
||||
|
||||
type Props = {
|
||||
name: string;
|
||||
defaultValue: string;
|
||||
required?: boolean;
|
||||
};
|
||||
|
||||
export function TextCell(props: Props) {
|
||||
const [value, setValue] = useState(props.defaultValue);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const cellRef = useEditableCellRef();
|
||||
const blurOnTab: KeyboardEventHandler<HTMLInputElement> = (e) => {
|
||||
if (e.key === "Tab") {
|
||||
cellRef.current?.close();
|
||||
}
|
||||
};
|
||||
const { onUpdate } = useEditableRowContext();
|
||||
const onClose = () => {
|
||||
const inputValue = (inputRef.current?.value ?? "").trim();
|
||||
// Do not propagate empty value for required fields
|
||||
if (props.required && inputValue === "") {
|
||||
return;
|
||||
}
|
||||
setValue(inputValue);
|
||||
onUpdate(props.name, inputValue);
|
||||
};
|
||||
return (
|
||||
<EditableCell
|
||||
name={props.name}
|
||||
label={value}
|
||||
ref={cellRef}
|
||||
onClose={onClose}
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
ref={inputRef}
|
||||
defaultValue={props.defaultValue}
|
||||
onKeyDown={blurOnTab}
|
||||
className="text-sm text-txt-primary outline-none"
|
||||
style={{ paddingLeft: "var(--padding)" }}
|
||||
/>
|
||||
</EditableCell>
|
||||
);
|
||||
}
|
||||
18
packages/ui/src/Molecules/Table/utils.ts
Normal file
18
packages/ui/src/Molecules/Table/utils.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
export function getKey<T>(item: T): string {
|
||||
if (
|
||||
item &&
|
||||
typeof item === "object" &&
|
||||
"id" in item &&
|
||||
typeof item.id === "string"
|
||||
) {
|
||||
return item.id.toString();
|
||||
}
|
||||
if (typeof item === "string" || typeof item === "number") {
|
||||
return item.toString();
|
||||
}
|
||||
if (item === undefined) {
|
||||
return "";
|
||||
}
|
||||
console.error("Cannot compute a key from item", item);
|
||||
return "";
|
||||
}
|
||||
@@ -79,6 +79,13 @@ export { ImpactOptions } from "./Molecules/Select/ImpactOptions";
|
||||
export { DurationPicker } from "./Molecules/DurationPicker/DurationPicker";
|
||||
export { FrameworkLogo } from "./Molecules/Badge/FrameworkLogo";
|
||||
export { EditableCell } from "./Molecules/Table/EditableCell";
|
||||
export { TextCell } from "./Molecules/Table/TextCell";
|
||||
export {
|
||||
SelectCell,
|
||||
selectCell,
|
||||
SelectValue,
|
||||
} from "./Molecules/Table/SelectCell";
|
||||
export { EditableRow } from "./Molecules/Table/EditableRow";
|
||||
|
||||
// Hooks
|
||||
export { useToast, Toasts } from "./Atoms/Toasts/Toasts";
|
||||
|
||||
Reference in New Issue
Block a user