Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 157 additions & 0 deletions src/components/datadisplay/DataCard/DataTag.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import { LucideStar } from "lucide-react";
import { render, screen } from "@testing-library/react";
import { DataTag, DataTagGrid } from "./DataTag";

describe("DataTag Component", () => {
it("renders the label and value correctly when strings provided", () => {
const value = "Test Value";
render(<DataTag label="Test Label" value={value} />);
expect(screen.getByText("Test Label")).toBeInTheDocument();
expect(screen.getByText(value)).toBeInTheDocument();
});

it("renders the label and value correctly when number provided", () => {
const value = 2;
render(<DataTag label="Test number Label" value={value} />);
expect(screen.getByText("Test number Label")).toBeInTheDocument();
expect(screen.getByText(value)).toBeInTheDocument();
});

it("renders '?' if value is undefined or empty and 'hideOnNullish' is set to false", () => {
render(
<DataTag label="Test number Label" value={undefined} hideIf="never" />,
);
const dataElement = screen.getByRole("data");

expect(screen.getByText("?")).toBeInTheDocument();
expect(dataElement).toHaveAttribute(
"aria-details",
"data-tag-textDisabled",
);
});

it("renders an icon if provided", () => {
render(<DataTag label="Icon Test" value="Test" icon={LucideStar} />);
expect(screen.getByTitle("datafield-icon")).toBeInTheDocument();

Check failure on line 35 in src/components/datadisplay/DataCard/DataTag.test.tsx

View workflow job for this annotation

GitHub Actions / build (22.20.0)

src/components/datadisplay/DataCard/DataTag.test.tsx > DataTag Component > renders an icon if provided

TestingLibraryElementError: Unable to find an element with the title: datafield-icon. Ignored nodes: comments, script, style <body> <div> <div class="MuiGrid-root MuiGrid-direction-xs-row css-8rq5uk-MuiGrid-root" > <div aria-details="data-tag" class="MuiStack-root css-hjnmnq-MuiStack-root" role="data" > <svg aria-hidden="true" class="lucide lucide-star" fill="none" height="12px" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewBox="0 0 24 24" width="12px" xmlns="http://www.w3.org/2000/svg" > <path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z" /> </svg> <p class="MuiTypography-root MuiTypography-body2 css-7ctihp-MuiTypography-root" > Icon Test </p> <div aria-orientation="vertical" class="MuiDivider-root MuiDivider-fullWidth MuiDivider-vertical MuiDivider-flexItem css-1160sub-MuiDivider-root" role="separator" /> <p class="MuiTypography-root MuiTypography-body1 css-1ptv1bs-MuiTypography-root" > Test </p> </div> </div> </div> </body> ❯ Object.getElementError node_modules/.pnpm/@testing-library+dom@10.4.2/node_modules/@testing-library/dom/dist/config.js:37:19 ❯ node_modules/.pnpm/@testing-library+dom@10.4.2/node_modules/@testing-library/dom/dist/query-helpers.js:76:38 ❯ node_modules/.pnpm/@testing-library+dom@10.4.2/node_modules/@testing-library/dom/dist/query-helpers.js:52:17 ❯ node_modules/.pnpm/@testing-library+dom@10.4.2/node_modules/@testing-library/dom/dist/query-helpers.js:95:19 ❯ src/components/datadisplay/DataCard/DataTag.test.tsx:35:19
});

it("applies the default aria-details if no indicatorFn is provided", () => {
render(<DataTag label="Default Color Test" value="Test" />);
const dataElement = screen.getByRole("data");
expect(dataElement).toHaveAttribute("aria-details", "data-tag");
});

describe("String matching", () => {
it("applies the correct aria-details for matched string values", () => {
render(
<DataTag
label="String Test"
value="hello"
setColourCallback={(value) =>
value === "hello" ? "success" : "error"
}
/>,
);
const dataElement = screen.getByRole("data");
expect(dataElement).toHaveAttribute("aria-details", "data-tag-success");
});

it("applies the correct aria-details for non-matched string values", () => {
render(
<DataTag
label="String Test"
value="hi"
setColourCallback={(value: string) =>
value === "hello" ? "success" : "error"
}
/>,
);
const dataElement = screen.getByRole("data");
expect(dataElement).toHaveAttribute("aria-details", "data-tag-error");
});
});

describe("Number matching", () => {
it("applies the correct aria-details for numeric value success", () => {
render(
<DataTag
label="Number Test"
value={5}
setColourCallback={(value) => (value > 0 ? "success" : "error")}
/>,
);
const dataElement = screen.getByRole("data");
expect(dataElement).toHaveAttribute("aria-details", "data-tag-success");
});

it("applies the correct aria-details for numeric value error", () => {
render(
<DataTag
label="Number Test"
value={5}
setColourCallback={(value) => (value > 10 ? "success" : "error")}
/>,
);
const dataElement = screen.getByRole("data");
expect(dataElement).toHaveAttribute("aria-details", "data-tag-error");
});

it("renders an optional provided suffix when using number", () => {
const value = 2;
render(<DataTag label="Test" value={value} suffix="s" />);

expect(screen.getByText("Test")).toBeInTheDocument();
expect(screen.getByText(`${value}s`)).toBeInTheDocument();
});

it("renders numbers converted to fixed decimal places when provided", () => {
const value = 0.12345678;
const valueToFixed = value.toFixed(2);

render(<DataTag label="Test" value={value} toFixed={2} />);

expect(screen.getByText("Test")).toBeInTheDocument();
expect(screen.getByText(valueToFixed)).toBeInTheDocument();
});

it("should hide data field if value is null or undefined", () => {
render(
<DataTag
label="Test"
value={undefined}
toFixed={2}
hideIf="nullOrUndefined"
/>,
);

expect(screen.getByText("Test")).not.toBeVisible();
});

it("should hide data field if value is falsy", () => {
render(<DataTag label="Test" value={0} toFixed={2} hideIf="falsy" />);

expect(screen.getByText("Test")).not.toBeVisible();
});
});

describe("DataTagGrid Component", () => {
it("renders a collection of DataTags correctly", () => {
render(
<DataTagGrid>
<DataTag label={"Sensor 1"} value={20} />
<DataTag label={"Sensor 2"} value={"connected"} />
<DataTag label={"Sensor 3"} value={156.2356} suffix={"°"} />
<DataTag label={"Sensor 4"} value={"Active"} />
</DataTagGrid>,
);

const collection = screen.getByRole("grid");

expect(collection).toBeInTheDocument();
expect(screen.getAllByRole("data").length).toEqual(4);

expect(screen.getByText("Sensor 1")).toBeInTheDocument();
expect(screen.getByText(/156.2356°/)).toBeInTheDocument();
});
});
});
162 changes: 162 additions & 0 deletions src/components/datadisplay/DataCard/DataTag.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
"use client";

import {
Box,
Divider,
Grid,
GridProps,
Stack,
Typography,
TypographyProps,
} from "@mui/material";
import { ReactElement } from "react";
import type { LucideIcon } from "lucide-react";

const defaultTextColour: TypographyProps["color"] = "inherit";

interface DataDisplayProps<T extends string | number> {
label: string;
icon?: LucideIcon;
value?: T;
setColourCallback?: (value: T) => TypographyProps["color"];
}

// This is to preserve the T typeguard, so numbers and strings are only allowed certain props
export type DataTagProps<T extends string | number> = DataDisplayProps<T> &
(T extends number ? { suffix?: string; toFixed?: number } : object) & {
size?: number | "full";
/** When to hide data field. Null or undefined only hides if value is null or undefined, falsy hides it if the value is 0, false or any other falsy value */
hideIf?: "nullOrUndefined" | "falsy" | "never";
/** Shrink width of data tag, as opposed to taking up whole column */
shrinkWidth?: boolean;
};

export const DataTag = <T extends string | number>({
label,
value,
hideIf = "nullOrUndefined",
shrinkWidth = false,
size = 1,
setColourCallback = () => defaultTextColour,
...props
}: DataTagProps<T>) => {
const colVal: TypographyProps["color"] = value
? setColourCallback(value)
: "textDisabled";

let formattedValue: string | undefined;

if (typeof value === "number") {
const numericProps = props as DataTagProps<number>;
formattedValue = value.toString();
if (numericProps.toFixed)
formattedValue = value.toFixed(numericProps.toFixed);
if (numericProps.suffix)
formattedValue = `${formattedValue}${numericProps.suffix}`;
} else {
formattedValue = value;
}

const handleCopy = () => {
if (formattedValue) {
navigator.clipboard.writeText(formattedValue);
}
};

const hideField = () => {
switch (hideIf) {
// This is a switch case in case we want to add more conditions in the future
case "falsy":
return !value;
case "nullOrUndefined":
return formattedValue === null || formattedValue === undefined;
default:
return false;
}
};

const gridColumn =
size === "full" ? "1 / -1" : size > 1 ? `span ${size}` : "auto";

const contentFitProps = shrinkWidth
? {
maxWidth: "fit-content",
minHeight: "fit-content",
maxHeight: "fit-content",
}
: {};

const Icon = props.icon;
return (
<Grid
display={hideField() ? "none" : "grid"}
gridColumn={gridColumn}
minWidth="fit-content"
onClick={handleCopy}
{...contentFitProps}
sx={{
cursor: "copy",
flex: "1 1 100px",
}}
>
<Stack
role={"data"}
aria-details={`data-tag${colVal === defaultTextColour ? `` : `-${colVal}`}`}
direction="row"
alignItems="center"
borderLeft={8}
pl={1}
borderColor={`${colVal}.main`}
gap={1}
padding={"xs"}
pr={1}
bgcolor="surface.subtle"
color="text.tertiary"
minHeight={"1.5rem"}
minWidth="fit-content"
height="100%"
>
{Icon && <Icon size="12px" />}
<Typography variant={"body2"}>{label}</Typography>
<Divider orientation={"vertical"} flexItem />
<Typography
variant={"body1"}
color={"inherit"}
fontWeight={"bold"}
flexGrow={1}
>
{formattedValue ?? "?"}
</Typography>
</Stack>
</Grid>
);
};

export interface ResponsiveColumnGridProps extends Pick<GridProps, "spacing"> {
children: ReactElement<DataTagProps<string | number>>[];
}

export const DataTagGrid = ({
children,
spacing = "0.2rem",
...rest
}: ResponsiveColumnGridProps) => {
return (
<Box flexGrow={1} minWidth="180px">
<Box
display="grid"
{...rest}
role={"grid"}
gridTemplateColumns={{
xs: "minmax(100px, 1fr)",
lg: "repeat(1, 1fr) minmax(100px, 1fr)",
xl: "repeat(2, 1fr) minmax(100px, 1fr)",
}}
gap={spacing}
minWidth="fit-content"
>
{children}
</Box>
</Box>
);
};
1 change: 1 addition & 0 deletions src/components/datadisplay/DataCard/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export { DataCard } from "./DataCard";
export type { DataCardProps } from "./DataCard";
export { DataGroup } from "./DataGroup";
export { DataTag, DataTagGrid, type DataTagProps } from "./DataTag";
export type { DecoratedValue, DataObjectProps } from "./types";
Loading
Loading