diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml index 982959d81..44ce432d3 100644 --- a/frontend/pnpm-lock.yaml +++ b/frontend/pnpm-lock.yaml @@ -574,7 +574,23 @@ importers: specifier: ^10.6.0 version: 10.6.7(@types/react@18.3.31)(prettier@3.9.10)(react@18.3.1) - workflows-ui: {} + workflows-ui: + dependencies: + '@emotion/react': + specifier: ^11.14.0 + version: 11.14.0(@types/react@18.3.31)(react@18.3.1)(supports-color@7.2.0) + '@emotion/styled': + specifier: ^11.14.1 + version: 11.14.1(@emotion/react@11.14.0(@types/react@18.3.31)(react@18.3.1)(supports-color@7.2.0))(@types/react@18.3.31)(react@18.3.1)(supports-color@7.2.0) + '@mui/material': + specifier: ^7.0.0 + version: 7.3.11(@emotion/react@11.14.0(@types/react@18.3.31)(react@18.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@18.3.31)(react@18.3.1)(supports-color@7.2.0))(@types/react@18.3.31)(react@18.3.1)(supports-color@7.2.0))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + react: + specifier: ^18.3.1 + version: 18.3.1 + react-dom: + specifier: ^18.3.1 + version: 18.3.1(react@18.3.1) packages: diff --git a/frontend/workflows-lib-shared/.storybook/preview.ts b/frontend/workflows-lib-shared/.storybook/preview.ts index 740f3f32c..523b3ec58 100644 --- a/frontend/workflows-lib-shared/.storybook/preview.ts +++ b/frontend/workflows-lib-shared/.storybook/preview.ts @@ -1,6 +1,25 @@ import type { Preview } from "@storybook/react-vite"; const preview: Preview = { + globalTypes: { + diamondMode: { + description: "Diamond colour scheme", + toolbar: { + title: "Diamond Mode", + icon: "circlehollow", + items: [ + { value: "light", title: "Light" }, + { value: "dark", title: "Dark" }, + ], + dynamicTitle: true, + }, + }, + }, + + initialGlobals: { + diamondMode: "light", + }, + parameters: { controls: { matchers: { diff --git a/frontend/workflows-lib-shared/lib/components/common/TemplateFilter.md b/frontend/workflows-lib-shared/lib/components/common/TemplateFilter.md new file mode 100644 index 000000000..4b9cce611 --- /dev/null +++ b/frontend/workflows-lib-shared/lib/components/common/TemplateFilter.md @@ -0,0 +1,214 @@ +# TemplateFilter + +A reusable React component for filtering workflow templates or other +categories, such as Science Groups. + +The component uses Material UI Select and supports multiple selections +without checkboxes. + +## Features + +- Select multiple values from a dropdown. +- Display selected values in a compact format. +- Highlight selected options in the dropdown. +- Clear all selections using the "Clear all" option. +- Support configurable filter labels. +- Control selected values through component props. +- Responsive layout using Material UI. +- Independent of GraphQL, Apollo, Relay, and React Router. + +## Props + +| Prop | Type | Description | +| --- | --- | --- | +| `label` | `string` | Optional dropdown label. Defaults to "Science Group". | +| `templates` | `string[]` | Available options displayed in the dropdown. | +| `selectedTemplates` | `string[]` | Currently selected values, controlled by the parent. | +| `onChange` | `(selectedTemplates: string[]) => void` | Called when the selection changes or is cleared. | + +## Example + +```tsx +import { useState } from "react"; +import { TemplateFilter } from "@diamondlightsource/workflows-lib-shared"; + +const scienceGroups = [ + "No Group", + "MX", + "Examples", + "Magnetic Materials", + "Soft Condensed Matter", + "Imaging and Microscopy", + "Biological Cryo-Imaging", + "Structures and Surfaces", + "Crystallography", + "Spectroscopy", +]; + +export function WorkflowFilters() { + const [selectedScienceGroups, setSelectedScienceGroups] = + useState([]); + + return ( + + ); +} +``` + +## Selection behaviour + +The dropdown supports multiple selections without displaying checkboxes. + +Selected options are highlighted when the dropdown is opened. + +The closed dropdown displays the first selected value followed by +the number of additional selections. + +### Examples + +| Selected values | Display | +| --- | --- | +| None | All science groups | +| MX | MX | +| MX, Imaging and Microscopy | MX +1 more | +| MX, Imaging and Microscopy, Spectroscopy | MX +2 more | +| Four selected values | First selection +3 more | + +This keeps the dropdown compact even when multiple options are selected. + +## Clear all + +The dropdown includes a "Clear all" option at the top. + +Selecting "Clear all" calls: + +```tsx +onChange([]); +``` + +The parent component is responsible for updating the selected state. + +The "Clear all" option is disabled when no values are selected. + +## Controlled state + +`TemplateFilter` is a controlled React component. + +It does not maintain its own selected values. + +Instead, the parent supplies the current selection through: + +```tsx +selectedTemplates={selectedScienceGroups} +``` + +When the user changes the selection, the component calls: + +```tsx +onChange(updatedSelection); +``` + +The parent updates its state and React re-renders the component +with the new selected values. + +An empty `selectedTemplates` array represents no selection. + +## Styling + +The component follows the Material UI outlined Select design. + +- Variant: Outlined +- Size: Medium +- Height: Approximately 56px +- Border radius: 4px +- Width: 100% of the parent container +- Background: Transparent +- Multiple selection without checkboxes + +The component uses Material UI styling and can inherit the +Diamond Design System theme from the consuming application. + +## Data handling + +The component only manages the user interface for selecting filters. + +It does not: + +- Fetch workflow templates. +- Execute GraphQL queries. +- Filter workflow results. +- Manage pagination. +- Depend on Apollo or Relay. +- Access application-specific routing. + +The consuming application is responsible for retrieving available +options and applying the selected filters. + +## Testing + +Component tests are located at: + +`tests/components/TemplateFilter.test.tsx` + +Tests should cover: + +- Rendering the dropdown. +- Displaying available options. +- Selecting one option. +- Selecting multiple options. +- Highlighting selected options. +- Displaying the selection count. +- Clearing all selections. +- Updating the selection through props. +- Handling an empty options list. + +Run the component tests: + +`pnpm exec vitest run tests/components/TemplateFilter.test.tsx` + +Run all shared-library tests: + +`pnpm exec vitest run` + +## Storybook + +Interactive examples are located at: + +`stories/TemplateFilter.stories.tsx` + +Stories demonstrate: + +- Default state with no selection. +- One preselected value. +- Multiple preselected values. +- Empty options list. + +Run Storybook: + +`pnpm storybook` + +## Architecture + +The component belongs to: + +`frontend/workflows-lib-shared/lib/components/common/TemplateFilter.tsx` + +It is exported through: + +`frontend/workflows-lib-shared/lib/main.ts` + +The component can be imported using: + +```tsx +import { TemplateFilter } from "@diamondlightsource/workflows-lib-shared"; +``` + +It is reusable across workflow dashboards regardless of whether +the application uses Apollo, Relay, REST, or another data source. + +The component remains independent of the GraphQL integration layer. diff --git a/frontend/workflows-lib-shared/lib/components/common/TemplateFilter.tsx b/frontend/workflows-lib-shared/lib/components/common/TemplateFilter.tsx new file mode 100644 index 000000000..fcb345587 --- /dev/null +++ b/frontend/workflows-lib-shared/lib/components/common/TemplateFilter.tsx @@ -0,0 +1,187 @@ +import { + Checkbox, + Divider, + FormControl, + InputLabel, + ListItemText, + MenuItem, + Select, + type SelectChangeEvent, +} from "@mui/material"; +import { useEffect, useId, useRef, useState } from "react"; + +export interface TemplateFilterProps { + label?: string; + emptyLabel?: string; + filterValues: string[]; + selectedTemplates: string[]; + onChange: (selectedTemplates: string[]) => void; + variant?: "outlined" | "filled" | "standard"; +} + +const CLEAR_ALL_VALUE = "__clear_all__"; + +const TemplateFilter = ({ + label, + emptyLabel = "All ", + filterValues, + selectedTemplates, + onChange, + variant = "outlined", +}: TemplateFilterProps) => { + const id = useId(); + + const selectRef = useRef(null); + const [availableWidth, setAvailableWidth] = useState(0); + + useEffect(() => { + const element = selectRef.current; + + if (!element) return; + + const observer = new ResizeObserver(([entry]) => { + setAvailableWidth(entry.contentRect.width); + }); + + observer.observe(element); + + return () => { + observer.disconnect(); + }; + }, []); + + const selectId = `${id}-select`; + const labelId = `${id}-label`; + const handleChange = (event: SelectChangeEvent) => { + const value = event.target.value; + + const selected = typeof value === "string" ? value.split(",") : value; + + if (selected.includes(CLEAR_ALL_VALUE)) { + onChange([]); + return; + } + + onChange(selected); + }; + const renderSelectedValues = (selected: string[]) => { + if (selected.length === 0) { + return emptyLabel; + } + + if (selected.length === 1) { + return selected[0]; + } + + const element = selectRef.current; + + if (!element || availableWidth === 0) { + return `${selected[0]} +${String(selected.length - 1)} more`; + } + + const canvas = document.createElement("canvas"); + const context = canvas.getContext("2d"); + + if (!context) { + return `${selected[0]} +${String(selected.length - 1)} more`; + } + + context.font = getComputedStyle(element).font; + + const measure = (text: string) => context.measureText(text).width; + + const maxWidth = Math.max(0, availableWidth - 40); + + const visible: string[] = []; + + for (let i = 0; i < selected.length; i++) { + const remaining = selected.length - i - 1; + + const candidate = [...visible, selected[i]].join(", "); + + const display = + remaining > 0 ? `${candidate} +${String(remaining)} more` : candidate; + + if (measure(display) > maxWidth) { + break; + } + + visible.push(selected[i]); + } + + if (visible.length === selected.length) { + return visible.join(", "); + } + + if (visible.length === 0) { + return `+${String(selected.length)} more`; + } + + return `${visible.join(", ")} +${String(selected.length - visible.length)} more`; + }; + + return ( + + {label && ( + + {label} + + )} + + + ); +}; + +export default TemplateFilter; diff --git a/frontend/workflows-lib-shared/lib/main.ts b/frontend/workflows-lib-shared/lib/main.ts index c57153c9a..a55d9a2b4 100644 --- a/frontend/workflows-lib-shared/lib/main.ts +++ b/frontend/workflows-lib-shared/lib/main.ts @@ -4,3 +4,7 @@ export { } from "./components/common/AuthStatusIndicator"; export * from "./hooks/useAuthStatus"; export * from "./utils/authUtils"; +export { + default as TemplateFilter, + type TemplateFilterProps, +} from "./components/common/TemplateFilter"; diff --git a/frontend/workflows-lib-shared/stories/TemplateFilter.stories.tsx b/frontend/workflows-lib-shared/stories/TemplateFilter.stories.tsx new file mode 100644 index 000000000..2e7553896 --- /dev/null +++ b/frontend/workflows-lib-shared/stories/TemplateFilter.stories.tsx @@ -0,0 +1,171 @@ +import { useEffect, useState } from "react"; +import { useColorScheme } from "@mui/material/styles"; +import type { Meta, StoryObj } from "@storybook/react"; +import { + ThemeProvider, + DiamondDSTheme, +} from "@diamondlightsource/sci-react-ui"; +import { TemplateFilter, type TemplateFilterProps } from "../lib/main"; + +const templates = [ + "mx-processing", + "tomography", + "visr-reconstruction", + "data-analysis", +]; +const StoryTheme = ({ + children, + mode, +}: { + children: React.ReactNode; + mode: "light" | "dark"; +}) => { + return ( + + {children} + + ); +}; + +const ThemeMode = ({ + children, + mode, +}: { + children: React.ReactNode; + mode: "light" | "dark"; +}) => { + const { setMode } = useColorScheme(); + + useEffect(() => { + setMode(mode); + + // Synchronise Diamond Design System CSS variables. + document.documentElement.setAttribute("data-mode", mode); + }, [mode, setMode]); + + return <>{children}; +}; + +const meta: Meta = { + title: "TemplateFilter", + component: TemplateFilter, + decorators: [ + (Story, context) => { + console.log("Diamond mode:", context.globals.diamondMode); + + return ( + + + + ); + }, + ], +}; + +export default meta; + +type Story = StoryObj; + +// Wrapper to manage controlled filter state +const ControlledTemplateFilter = ({ + selectedTemplates: initialSelection, + ...props +}: TemplateFilterProps) => { + const [selectedTemplates, setSelectedTemplates] = useState(initialSelection); + + return ( + + ); +}; + +export const Default: Story = { + args: { + label: "Science Group", + filterValues: templates, + selectedTemplates: [], + variant: "outlined", + }, + render: (args) => , +}; + +export const Preselected: Story = { + args: { + label: "Science Group", + filterValues: templates, + selectedTemplates: ["tomography"], + }, + render: (args) => , +}; + +export const MultipleSelected: Story = { + args: { + filterValues: templates, + selectedTemplates: ["tomography", "mx-processing"], + }, + render: (args) => , +}; + +export const Empty: Story = { + args: { + filterValues: [], + selectedTemplates: [], + }, + render: (args) => , +}; + +export const MultipleFilters: Story = { + args: { + filterValues: templates, + selectedTemplates: [], + }, + render: (args) => ( +
+ + + + + +
+ ), +}; + +export const ResponsiveWidth: Story = { + args: { + filterValues: templates, + selectedTemplates: ["tomography", "mx-processing", "visr-reconstruction"], + }, + render: (args) => ( +
+
+ +
+ +
+ +
+ +
+ +
+
+ ), +}; diff --git a/frontend/workflows-lib-shared/tests/components/TemplateFilter.test.tsx b/frontend/workflows-lib-shared/tests/components/TemplateFilter.test.tsx new file mode 100644 index 000000000..ff086a1b5 --- /dev/null +++ b/frontend/workflows-lib-shared/tests/components/TemplateFilter.test.tsx @@ -0,0 +1,242 @@ +import { render, screen } from "@testing-library/react"; +import "@testing-library/jest-dom"; +import userEvent from "@testing-library/user-event"; +import { TemplateFilter } from "../../lib/main"; + +const templates = ["mx-processing", "tomography", "visr-reconstruction"]; + +describe("TemplateFilter", () => { + it("renders the template filter", () => { + render( + , + ); + + expect( + screen.getByRole("combobox", { name: "Science Group" }), + ).toBeInTheDocument(); + }); + + it("displays available templates", async () => { + const user = userEvent.setup(); + + render( + , + ); + + await user.click(screen.getByRole("combobox")); + + expect( + screen.getByRole("option", { name: "mx-processing" }), + ).toBeInTheDocument(); + + expect( + screen.getByRole("option", { name: "tomography" }), + ).toBeInTheDocument(); + }); + + it("calls onChange when a template is selected", async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + render( + , + ); + + await user.click(screen.getByRole("combobox")); + + await user.click(screen.getByRole("option", { name: "tomography" })); + + expect(onChange).toHaveBeenCalledWith(["tomography"]); + }); + + it("displays templates selected through props", () => { + render( + , + ); + + expect(screen.getByRole("combobox")).toHaveTextContent("tomography"); + }); + + it("updates the selection when props change", () => { + const onChange = vi.fn(); + + const { rerender } = render( + , + ); + + expect(screen.getByRole("combobox")).toHaveTextContent("tomography"); + + rerender( + , + ); + + expect(screen.getByRole("combobox")).toHaveTextContent("mx-processing"); + + expect(screen.getByRole("combobox")).not.toHaveTextContent("tomography"); + }); + + it("calls onChange when a selected template is removed", async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + render( + , + ); + + await user.click(screen.getByRole("combobox")); + + await user.click(screen.getByRole("option", { name: "tomography" })); + + expect(onChange).toHaveBeenCalledTimes(1); + expect(onChange).toHaveBeenLastCalledWith([]); + }); + + it("handles an empty template list", async () => { + const user = userEvent.setup(); + + render( + , + ); + + expect(screen.getByRole("combobox")).toHaveTextContent("All"); + + await user.click(screen.getByRole("combobox")); + + expect( + screen.queryByRole("option", { name: "tomography" }), + ).not.toBeInTheDocument(); + }); + + it("supports multiple template selections", async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + const { rerender } = render( + , + ); + + await user.click(screen.getByRole("combobox")); + + await user.click(screen.getByRole("option", { name: "tomography" })); + + expect(onChange).toHaveBeenLastCalledWith(["tomography"]); + + // Simulate the parent updating the controlled state. + rerender( + , + ); + + await user.click(screen.getByRole("option", { name: "mx-processing" })); + + expect(onChange).toHaveBeenLastCalledWith(["tomography", "mx-processing"]); + }); + + it("clears all selected templates", async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + render( + , + ); + + await user.click(screen.getByRole("combobox")); + + await user.click(screen.getByText("Clear all")); + + expect(onChange).toHaveBeenCalledTimes(1); + expect(onChange).toHaveBeenLastCalledWith([]); + }); + + it("displays the selected templates", () => { + render( + , + ); + + expect(screen.getByRole("combobox")).toHaveTextContent("tomography"); + }); + + it("generates unique IDs for multiple filters", () => { + const { container } = render( + <> + + + + , + ); + + const filters = container.querySelectorAll('[role="combobox"]'); + + expect(filters).toHaveLength(2); + + const firstFilter = filters[0]; + const secondFilter = filters[1]; + + expect(firstFilter.id).toBeTruthy(); + expect(secondFilter.id).toBeTruthy(); + + expect(firstFilter.id).not.toBe(secondFilter.id); + }); +}); diff --git a/frontend/workflows-lib/.storybook/preview.ts b/frontend/workflows-lib/.storybook/preview.ts index 740f3f32c..523b3ec58 100644 --- a/frontend/workflows-lib/.storybook/preview.ts +++ b/frontend/workflows-lib/.storybook/preview.ts @@ -1,6 +1,25 @@ import type { Preview } from "@storybook/react-vite"; const preview: Preview = { + globalTypes: { + diamondMode: { + description: "Diamond colour scheme", + toolbar: { + title: "Diamond Mode", + icon: "circlehollow", + items: [ + { value: "light", title: "Light" }, + { value: "dark", title: "Dark" }, + ], + dynamicTitle: true, + }, + }, + }, + + initialGlobals: { + diamondMode: "light", + }, + parameters: { controls: { matchers: { diff --git a/frontend/workflows-ui/lib/components/common/TemplateFilter.md b/frontend/workflows-ui/lib/components/common/TemplateFilter.md new file mode 100644 index 000000000..4b9cce611 --- /dev/null +++ b/frontend/workflows-ui/lib/components/common/TemplateFilter.md @@ -0,0 +1,214 @@ +# TemplateFilter + +A reusable React component for filtering workflow templates or other +categories, such as Science Groups. + +The component uses Material UI Select and supports multiple selections +without checkboxes. + +## Features + +- Select multiple values from a dropdown. +- Display selected values in a compact format. +- Highlight selected options in the dropdown. +- Clear all selections using the "Clear all" option. +- Support configurable filter labels. +- Control selected values through component props. +- Responsive layout using Material UI. +- Independent of GraphQL, Apollo, Relay, and React Router. + +## Props + +| Prop | Type | Description | +| --- | --- | --- | +| `label` | `string` | Optional dropdown label. Defaults to "Science Group". | +| `templates` | `string[]` | Available options displayed in the dropdown. | +| `selectedTemplates` | `string[]` | Currently selected values, controlled by the parent. | +| `onChange` | `(selectedTemplates: string[]) => void` | Called when the selection changes or is cleared. | + +## Example + +```tsx +import { useState } from "react"; +import { TemplateFilter } from "@diamondlightsource/workflows-lib-shared"; + +const scienceGroups = [ + "No Group", + "MX", + "Examples", + "Magnetic Materials", + "Soft Condensed Matter", + "Imaging and Microscopy", + "Biological Cryo-Imaging", + "Structures and Surfaces", + "Crystallography", + "Spectroscopy", +]; + +export function WorkflowFilters() { + const [selectedScienceGroups, setSelectedScienceGroups] = + useState([]); + + return ( + + ); +} +``` + +## Selection behaviour + +The dropdown supports multiple selections without displaying checkboxes. + +Selected options are highlighted when the dropdown is opened. + +The closed dropdown displays the first selected value followed by +the number of additional selections. + +### Examples + +| Selected values | Display | +| --- | --- | +| None | All science groups | +| MX | MX | +| MX, Imaging and Microscopy | MX +1 more | +| MX, Imaging and Microscopy, Spectroscopy | MX +2 more | +| Four selected values | First selection +3 more | + +This keeps the dropdown compact even when multiple options are selected. + +## Clear all + +The dropdown includes a "Clear all" option at the top. + +Selecting "Clear all" calls: + +```tsx +onChange([]); +``` + +The parent component is responsible for updating the selected state. + +The "Clear all" option is disabled when no values are selected. + +## Controlled state + +`TemplateFilter` is a controlled React component. + +It does not maintain its own selected values. + +Instead, the parent supplies the current selection through: + +```tsx +selectedTemplates={selectedScienceGroups} +``` + +When the user changes the selection, the component calls: + +```tsx +onChange(updatedSelection); +``` + +The parent updates its state and React re-renders the component +with the new selected values. + +An empty `selectedTemplates` array represents no selection. + +## Styling + +The component follows the Material UI outlined Select design. + +- Variant: Outlined +- Size: Medium +- Height: Approximately 56px +- Border radius: 4px +- Width: 100% of the parent container +- Background: Transparent +- Multiple selection without checkboxes + +The component uses Material UI styling and can inherit the +Diamond Design System theme from the consuming application. + +## Data handling + +The component only manages the user interface for selecting filters. + +It does not: + +- Fetch workflow templates. +- Execute GraphQL queries. +- Filter workflow results. +- Manage pagination. +- Depend on Apollo or Relay. +- Access application-specific routing. + +The consuming application is responsible for retrieving available +options and applying the selected filters. + +## Testing + +Component tests are located at: + +`tests/components/TemplateFilter.test.tsx` + +Tests should cover: + +- Rendering the dropdown. +- Displaying available options. +- Selecting one option. +- Selecting multiple options. +- Highlighting selected options. +- Displaying the selection count. +- Clearing all selections. +- Updating the selection through props. +- Handling an empty options list. + +Run the component tests: + +`pnpm exec vitest run tests/components/TemplateFilter.test.tsx` + +Run all shared-library tests: + +`pnpm exec vitest run` + +## Storybook + +Interactive examples are located at: + +`stories/TemplateFilter.stories.tsx` + +Stories demonstrate: + +- Default state with no selection. +- One preselected value. +- Multiple preselected values. +- Empty options list. + +Run Storybook: + +`pnpm storybook` + +## Architecture + +The component belongs to: + +`frontend/workflows-lib-shared/lib/components/common/TemplateFilter.tsx` + +It is exported through: + +`frontend/workflows-lib-shared/lib/main.ts` + +The component can be imported using: + +```tsx +import { TemplateFilter } from "@diamondlightsource/workflows-lib-shared"; +``` + +It is reusable across workflow dashboards regardless of whether +the application uses Apollo, Relay, REST, or another data source. + +The component remains independent of the GraphQL integration layer. diff --git a/frontend/workflows-ui/lib/components/common/TemplateFilter.tsx b/frontend/workflows-ui/lib/components/common/TemplateFilter.tsx new file mode 100644 index 000000000..3709c36bc --- /dev/null +++ b/frontend/workflows-ui/lib/components/common/TemplateFilter.tsx @@ -0,0 +1,91 @@ +import { + Divider, + FormControl, + InputLabel, + ListItemText, + MenuItem, + Select, + type SelectChangeEvent, +} from "@mui/material"; + +export interface TemplateFilterProps { + label?: string; + emptyLabel?: string; + templates: string[]; + selectedTemplates: string[]; + onChange: (selectedTemplates: string[]) => void; +} + +const CLEAR_ALL_VALUE = "__clear_all__"; + +const TemplateFilter = ({ + label = "Science Group", + emptyLabel = "All ", + templates, + selectedTemplates, + onChange, +}: TemplateFilterProps) => { + const handleChange = (event: SelectChangeEvent) => { + const value = event.target.value; + + const selected = typeof value === "string" ? value.split(",") : value; + + if (selected.includes(CLEAR_ALL_VALUE)) { + onChange([]); + return; + } + + onChange(selected); + }; + + const renderSelectedValues = (selected: string[]) => { + if (selected.length === 0) { + return emptyLabel; + } + + if (selected.length === 1) { + return selected[0]; + } + + return `${selected[0]} +${String(selected.length - 1)} more`; + }; + + return ( + + + {label} + + + + + ); +}; + +export default TemplateFilter; diff --git a/frontend/workflows-ui/lib/main.ts b/frontend/workflows-ui/lib/main.ts index e69de29bb..741cfab94 100644 --- a/frontend/workflows-ui/lib/main.ts +++ b/frontend/workflows-ui/lib/main.ts @@ -0,0 +1,4 @@ +export { + default as TemplateFilter, + type TemplateFilterProps, +} from "./components/common/TemplateFilter"; diff --git a/frontend/workflows-ui/package.json b/frontend/workflows-ui/package.json index b9a495cca..c8d19ec7b 100644 --- a/frontend/workflows-ui/package.json +++ b/frontend/workflows-ui/package.json @@ -9,7 +9,13 @@ "prebuild": "rm -rf dist", "build": "tsc --build && vite build && tsc -p tsconfig.build.json" }, - "peerDependencies": {}, + "peerDependencies": { + "@emotion/react": "^11.14.0", + "@emotion/styled": "^11.14.1", + "@mui/material": "^7.0.0", + "react": "^18.3.1", + "react-dom": "^18.3.1" + }, "devDependencies": {}, "eslintConfig": {} } diff --git a/frontend/workflows-ui/tests/components/TemplateFilter.test.tsx b/frontend/workflows-ui/tests/components/TemplateFilter.test.tsx new file mode 100644 index 000000000..9081ec41c --- /dev/null +++ b/frontend/workflows-ui/tests/components/TemplateFilter.test.tsx @@ -0,0 +1,203 @@ +import { render, screen } from "@testing-library/react"; +import "@testing-library/jest-dom"; +import userEvent from "@testing-library/user-event"; +import { TemplateFilter } from "../../lib/main"; + +const templates = ["mx-processing", "tomography", "visr-reconstruction"]; + +describe("TemplateFilter", () => { + it("renders the template filter", () => { + render( + , + ); + + expect( + screen.getByRole("combobox", { name: "Science Group" }), + ).toBeInTheDocument(); + }); + + it("displays available templates", async () => { + const user = userEvent.setup(); + render( + , + ); + + await user.click(screen.getByRole("combobox")); + expect( + screen.getByRole("option", { name: "mx-processing" }), + ).toBeInTheDocument(); + expect( + screen.getByRole("option", { name: "tomography" }), + ).toBeInTheDocument(); + }); + + it("calls onChange when a template is selected", async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + render( + , + ); + await user.click(screen.getByRole("combobox")); + await user.click(screen.getByRole("option", { name: "tomography" })); + expect(onChange).toHaveBeenCalledWith(["tomography"]); + }); + + it("displays templates selected through props", () => { + render( + , + ); + expect(screen.getByRole("combobox")).toHaveTextContent("tomography"); + }); + + it("updates the selection when props change", () => { + const onChange = vi.fn(); + const { rerender } = render( + , + ); + expect(screen.getByRole("combobox")).toHaveTextContent("tomography"); + rerender( + , + ); + expect(screen.getByRole("combobox")).toHaveTextContent("mx-processing"); + expect(screen.getByRole("combobox")).not.toHaveTextContent("tomography"); + }); + + it("calls onChange when a selected template is removed", async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + render( + , + ); + await user.click(screen.getByRole("combobox")); + await user.click(screen.getByRole("option", { name: "tomography" })); + expect(onChange).toHaveBeenCalledTimes(1); + expect(onChange).toHaveBeenLastCalledWith([]); + }); + + it("handles an empty template list", async () => { + const user = userEvent.setup(); + render( + , + ); + expect(screen.getByRole("combobox")).toHaveTextContent("All"); + await user.click(screen.getByRole("combobox")); + expect( + screen.queryByRole("option", { name: "tomography" }), + ).not.toBeInTheDocument(); + }); + + it("supports multiple template selections", async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + const { rerender } = render( + , + ); + await user.click(screen.getByRole("combobox")); + await user.click(screen.getByRole("option", { name: "tomography" })); + expect(onChange).toHaveBeenLastCalledWith(["tomography"]); + // Simulate the parent updating the controlled state. + rerender( + , + ); + await user.click(screen.getByRole("option", { name: "mx-processing" })); + expect(onChange).toHaveBeenLastCalledWith(["tomography", "mx-processing"]); + }); + + it("clears all selected templates", async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + render( + , + ); + await user.click(screen.getByRole("combobox")); + await user.click(screen.getByText("Clear all")); + expect(onChange).toHaveBeenCalledTimes(1); + expect(onChange).toHaveBeenLastCalledWith([]); + }); + + it("displays the selected templates", () => { + render( + , + ); + expect(screen.getByRole("combobox")).toHaveTextContent("tomography"); + }); + + it.skip("generates unique IDs for multiple filters", () => { + render( + <> + + + , + ); + const firstFilter = screen.getByRole("combobox", { name: "Science Group" }); + const secondFilter = screen.getByRole("combobox", { + name: "Workflow Templates", + }); + expect(firstFilter.id).toBeTruthy(); + expect(secondFilter.id).toBeTruthy(); + expect(firstFilter.id).not.toBe(secondFilter.id); + }); +});