diff --git a/.gitignore b/.gitignore index cdf90783..b69d2af1 100644 --- a/.gitignore +++ b/.gitignore @@ -38,4 +38,7 @@ yarn-error.log* next-env.d.ts # eslint -.eslintcache \ No newline at end of file +.eslintcache + +# storybook +**/.cache diff --git a/package-lock.json b/package-lock.json index 3a31a4b6..a1e5b77e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8603,6 +8603,37 @@ "@swc/counter": "^0.1.3" } }, + "node_modules/@tanstack/react-table": { + "version": "8.20.5", + "resolved": "https://registry.npmjs.org/@tanstack/react-table/-/react-table-8.20.5.tgz", + "integrity": "sha512-WEHopKw3znbUZ61s9i0+i9g8drmDo6asTWbrQh8Us63DAk/M0FkmIqERew6P71HI75ksZ2Pxyuf4vvKh9rAkiA==", + "dependencies": { + "@tanstack/table-core": "8.20.5" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": ">=16.8", + "react-dom": ">=16.8" + } + }, + "node_modules/@tanstack/table-core": { + "version": "8.20.5", + "resolved": "https://registry.npmjs.org/@tanstack/table-core/-/table-core-8.20.5.tgz", + "integrity": "sha512-P9dF7XbibHph2PFRz8gfBKEXEY/HJPOhym8CHmjF8y3q5mWpKx9xtZapXQUWCgkqvsK0R46Azuz+VaxD4Xl+Tg==", + "engines": { + "node": ">=12" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, "node_modules/@testing-library/dom": { "version": "10.4.0", "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.0.tgz", @@ -23496,10 +23527,9 @@ } }, "node_modules/react-virtuoso": { - "version": "4.7.11", - "resolved": "https://registry.npmjs.org/react-virtuoso/-/react-virtuoso-4.7.11.tgz", - "integrity": "sha512-Kdn9qEtQI2ulEuBMzW2BTkDsfijB05QUd6lpZ1K36oyA3k65Cz4lG4EKrh2pCfUafX4C2uMSZOwzMOhbrMOTFA==", - "license": "MIT", + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/react-virtuoso/-/react-virtuoso-4.12.0.tgz", + "integrity": "sha512-oHrKlU7xHsrnBQ89ecZoMPAK0tHnI9s1hsFW3KKg5ZGeZ5SWvbGhg/QFJFY4XETAzoCUeu+Xaxn1OUb/PGtPlA==", "engines": { "node": ">=10" }, @@ -28259,6 +28289,7 @@ "@mui/material": "^5.15.18", "@mui/utils": "^5.15.14", "@mui/x-date-pickers": "^7.14.0", + "@tanstack/react-table": "^8.20.5", "@types/node": "20.11.30", "@types/react": "18.3.3", "@types/react-dom": "18.3.0", @@ -28302,7 +28333,6 @@ "react-test-renderer": "^18.3.1", "storybook": "^8.2.9", "ts-jest": "^29.1.2", - "tsc-files": "^1.1.4", "tsup": "^8.0.2", "typescript": "^5.4.5" } diff --git a/packages/diracx-web-components/.eslintrc.json b/packages/diracx-web-components/.eslintrc.json index 93679404..e880c722 100644 --- a/packages/diracx-web-components/.eslintrc.json +++ b/packages/diracx-web-components/.eslintrc.json @@ -17,7 +17,46 @@ "import/no-useless-path-segments": ["error"], "import/no-unresolved": ["off"], "react/prop-types": "off", - "react/react-in-jsx-scope": "off" + "react/react-in-jsx-scope": "off", + "react/destructuring-assignment": ["error", "always"], + "no-restricted-properties": [ + "error", + { + "object": "React", + "property": "useCallback", + "message": "Please import 'useCallback' directly from 'react' instead of 'React.useCallback'." + }, + { + "object": "React", + "property": "useContext", + "message": "Please import 'useContext' directly from 'react' instead of 'React.useContext'." + }, + { + "object": "React", + "property": "useEffect", + "message": "Please import 'useEffect' directly from 'react' instead of 'React.useEffect'." + }, + { + "object": "React", + "property": "useMemo", + "message": "Please import 'useMemo' directly from 'react' instead of 'React.useMemo'." + }, + { + "object": "React", + "property": "useReducer", + "message": "Please import 'useReducer' directly from 'react' instead of 'React.useReducer'." + }, + { + "object": "React", + "property": "useRef", + "message": "Please import 'useRef' directly from 'react' instead of 'React.useRef'." + }, + { + "object": "React", + "property": "useState", + "message": "Please import 'useState' directly from 'react' instead of 'React.useState'." + } + ] }, "parser": "@typescript-eslint/parser", "parserOptions": { diff --git a/packages/diracx-web-components/components/BaseApp/BaseApp.stories.tsx b/packages/diracx-web-components/components/BaseApp/BaseApp.stories.tsx index ff68e576..62582a64 100644 --- a/packages/diracx-web-components/components/BaseApp/BaseApp.stories.tsx +++ b/packages/diracx-web-components/components/BaseApp/BaseApp.stories.tsx @@ -1,12 +1,11 @@ import React from "react"; import { StoryObj, Meta } from "@storybook/react"; -import { ThemeProvider as MUIThemeProvider } from "@mui/material/styles"; import { Paper } from "@mui/material"; import { Apps } from "@mui/icons-material"; import { useOidcAccessToken } from "../../mocks/react-oidc.mock"; -import { useMUITheme } from "../../hooks/theme"; import { ApplicationsContext } from "../../contexts/ApplicationsProvider"; import { NavigationProvider } from "../../contexts/NavigationProvider"; +import { ThemeProvider } from "../../contexts/ThemeProvider"; import BaseApp from "./BaseApp"; const meta = { @@ -16,18 +15,14 @@ const meta = { layout: "centered", }, tags: ["autodocs"], - argTypes: { - headerSize: { control: "radio" }, - }, decorators: [ (Story) => { - const theme = useMUITheme(); return ( - + - + ); }, (Story) => ( @@ -76,9 +71,7 @@ export default meta; type Story = StoryObj; export const LoggedIn: Story = { - args: { - headerSize: undefined, - }, + args: {}, render: (props) => { useOidcAccessToken.mockReturnValue({ accessTokenPayload: { preferred_username: "John Doe" }, @@ -88,9 +81,7 @@ export const LoggedIn: Story = { }; export const LoggedOff: Story = { - args: { - headerSize: undefined, - }, + args: {}, render: (props) => { useOidcAccessToken.mockReturnValue({ accessTokenPayload: null, diff --git a/packages/diracx-web-components/components/BaseApp/BaseApp.tsx b/packages/diracx-web-components/components/BaseApp/BaseApp.tsx index 49c7a8f0..ae8ef5c0 100644 --- a/packages/diracx-web-components/components/BaseApp/BaseApp.tsx +++ b/packages/diracx-web-components/components/BaseApp/BaseApp.tsx @@ -1,19 +1,13 @@ "use client"; import { useOidcAccessToken } from "@axa-fr/react-oidc/"; import { useOIDCContext } from "@/hooks/oidcConfiguration"; -import ApplicationHeader from "@/components/shared/ApplicationHeader"; /** * Build the User Dashboard page * * @returns User Dashboard content */ -export default function BaseApplication({ - headerSize, -}: { - /** The size of the header, optional, will default to h4 */ - headerSize?: "h1" | "h2" | "h3" | "h4" | "h5" | "h6"; -}) { +export default function BaseApplication() { const { configuration } = useOIDCContext(); const { accessTokenPayload } = useOidcAccessToken(configuration?.scope); @@ -23,7 +17,6 @@ export default function BaseApplication({ return (
-

Hello {accessTokenPayload["preferred_username"]}

To start with, select an application in the side bar

diff --git a/packages/diracx-web-components/components/DashboardLayout/ApplicationDialog.stories.tsx b/packages/diracx-web-components/components/DashboardLayout/ApplicationDialog.stories.tsx index f1a6320e..9931a9b6 100644 --- a/packages/diracx-web-components/components/DashboardLayout/ApplicationDialog.stories.tsx +++ b/packages/diracx-web-components/components/DashboardLayout/ApplicationDialog.stories.tsx @@ -1,13 +1,12 @@ import React from "react"; import type { Meta, StoryObj } from "@storybook/react"; -import { ThemeProvider } from "@mui/material"; import { useArgs } from "@storybook/core/preview-api"; import { ApplicationsContext } from "../../contexts/ApplicationsProvider"; import { useOidcAccessToken } from "../../mocks/react-oidc.mock"; import { applicationList } from "../ApplicationList"; -import { useMUITheme } from "../../hooks/theme"; +import { ThemeProvider } from "../../contexts/ThemeProvider"; import ApplicationDialog from "./ApplicationDialog"; const meta = { @@ -31,9 +30,8 @@ const meta = { ); }, (Story) => { - const theme = useMUITheme(); return ( - + ); diff --git a/packages/diracx-web-components/components/DashboardLayout/ApplicationDialog.tsx b/packages/diracx-web-components/components/DashboardLayout/ApplicationDialog.tsx index 232a2314..2412674e 100644 --- a/packages/diracx-web-components/components/DashboardLayout/ApplicationDialog.tsx +++ b/packages/diracx-web-components/components/DashboardLayout/ApplicationDialog.tsx @@ -1,4 +1,4 @@ -import React from "react"; +import { useState, useContext } from "react"; import { Dialog, DialogTitle, @@ -12,6 +12,15 @@ import { import { Close, SvgIconComponent } from "@mui/icons-material"; import { ApplicationsContext } from "@/contexts/ApplicationsProvider"; +interface AppDialogProps { + /** Determines whether the dialog is open or not. */ + appDialogOpen: boolean; + /** Function to set the open state of the dialog. */ + setAppDialogOpen: React.Dispatch>; + /** Function to handle the creation of a new application. */ + handleCreateApp: (name: string, icon: SvgIconComponent) => void; +} + /** * Renders a dialog component for creating a new application. * @@ -22,16 +31,9 @@ export default function AppDialog({ appDialogOpen, setAppDialogOpen, handleCreateApp, -}: { - /** Determines whether the dialog is open or not. */ - appDialogOpen: boolean; - /** Function to set the open state of the dialog. */ - setAppDialogOpen: React.Dispatch>; - /** Function to handle the creation of a new application. */ - handleCreateApp: (name: string, icon: SvgIconComponent) => void; -}) { - const [appType, setAppType] = React.useState(""); - const applicationList = React.useContext(ApplicationsContext)[2]; +}: AppDialogProps) { + const [appType, setAppType] = useState(""); + const applicationList = useContext(ApplicationsContext)[2]; return ( { - const [userDashboard, setUserDashboard] = React.useState< - DashboardGroup[] - >([ + const [userDashboard, setUserDashboard] = useState([ { title: "Group Title", extended: true, diff --git a/packages/diracx-web-components/components/DashboardLayout/Dashboard.tsx b/packages/diracx-web-components/components/DashboardLayout/Dashboard.tsx index 3949dfba..d616ffd9 100644 --- a/packages/diracx-web-components/components/DashboardLayout/Dashboard.tsx +++ b/packages/diracx-web-components/components/DashboardLayout/Dashboard.tsx @@ -1,17 +1,16 @@ "use client"; -import React from "react"; +import { useState } from "react"; import AppBar from "@mui/material/AppBar"; import Box from "@mui/material/Box"; -import CssBaseline from "@mui/material/CssBaseline"; import IconButton from "@mui/material/IconButton"; import { Menu } from "@mui/icons-material"; import Toolbar from "@mui/material/Toolbar"; import Stack from "@mui/material/Stack"; -import { ThemeProvider as MUIThemeProvider } from "@mui/material/styles"; +import { Typography, useMediaQuery, useTheme } from "@mui/material"; import { ProfileButton } from "./ProfileButton"; import { ThemeToggleButton } from "./ThemeToggleButton"; import DashboardDrawer from "./DashboardDrawer"; -import { useMUITheme } from "@/hooks/theme"; +import { useApplicationTitle, useApplicationType } from "@/hooks/application"; interface DashboardProps { /** The content to be displayed in the main area */ @@ -29,86 +28,126 @@ interface DashboardProps { * @param props - children, drawerWidth, logoURL * @return an dashboard layout */ -export default function Dashboard(props: DashboardProps) { - const theme = useMUITheme(); +export default function Dashboard({ + children, + drawerWidth = 240, + logoURL, +}: DashboardProps) { + const appTitle = useApplicationTitle(); + const appType = useApplicationType(); + + /** Theme and media query */ + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + /** State management for mobile drawer */ - const [mobileOpen, setMobileOpen] = React.useState(false); + const [mobileOpen, setMobileOpen] = useState(false); const handleDrawerToggle = () => { setMobileOpen(!mobileOpen); }; - /** Drawer width */ - const drawerWidth = props.drawerWidth || 240; - return ( - - - - - + + + + {isMobile && ( - + -
- - - - - + {appTitle} + + + {appType} + - - - {/* Here two types of drawers are rendered: - 1. Temporary drawer: Visible on small screens (xs) and is collapsible. - 2. Permanent drawer: Visible on larger screens (sm) and stays fixed. - Depending on the screen size, only one will be visible at a time. */} - - - - - {props.children} - - + + + + + + + + + + + + + + + {children} + ); } diff --git a/packages/diracx-web-components/components/DashboardLayout/DashboardDrawer.stories.tsx b/packages/diracx-web-components/components/DashboardLayout/DashboardDrawer.stories.tsx index 7d1f633d..9f0e4638 100644 --- a/packages/diracx-web-components/components/DashboardLayout/DashboardDrawer.stories.tsx +++ b/packages/diracx-web-components/components/DashboardLayout/DashboardDrawer.stories.tsx @@ -1,14 +1,13 @@ -import React from "react"; +import React, { useState } from "react"; import type { Meta, StoryObj } from "@storybook/react"; import { Box } from "@mui/material"; import { Dashboard } from "@mui/icons-material"; -import { ThemeProvider as MUIThemeProvider } from "@mui/material/styles"; -import { useMUITheme } from "../../hooks/theme"; import { useOidc, useOidcAccessToken } from "../../mocks/react-oidc.mock"; import { ApplicationsContext } from "../../contexts/ApplicationsProvider"; import { applicationList } from "../ApplicationList"; import { DashboardGroup } from "../../types"; +import { ThemeProvider } from "../../contexts/ThemeProvider"; import DashboardDrawer from "./DashboardDrawer"; const meta = { @@ -20,10 +19,7 @@ const meta = { tags: ["autodocs"], decorators: [ (Story) => { - const theme = useMUITheme(); - const [userDashboard, setUserDashboard] = React.useState< - DashboardGroup[] - >([ + const [userDashboard, setUserDashboard] = useState([ { title: "Group Title", extended: true, @@ -41,11 +37,11 @@ const meta = { - + - + ); }, diff --git a/packages/diracx-web-components/components/DashboardLayout/DashboardDrawer.tsx b/packages/diracx-web-components/components/DashboardLayout/DashboardDrawer.tsx index 6edcb0e0..2f92b458 100644 --- a/packages/diracx-web-components/components/DashboardLayout/DashboardDrawer.tsx +++ b/packages/diracx-web-components/components/DashboardLayout/DashboardDrawer.tsx @@ -12,20 +12,15 @@ import { Popover, TextField, Toolbar, + useTheme, } from "@mui/material"; import { MenuBook, Add, SvgIconComponent } from "@mui/icons-material"; -import React, { - ReactEventHandler, - useContext, - useEffect, - useState, -} from "react"; +import React, { useContext, useEffect, useState } from "react"; import { monitorForElements } from "@atlaskit/pragmatic-drag-and-drop/element/adapter"; import { extractClosestEdge } from "@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge"; import DrawerItemGroup from "./DrawerItemGroup"; import AppDialog from "./ApplicationDialog"; import { ApplicationsContext } from "@/contexts/ApplicationsProvider"; -import { useMUITheme } from "@/hooks/theme"; import { DashboardGroup } from "@/types"; interface DashboardDrawerProps { @@ -36,7 +31,7 @@ interface DashboardDrawerProps { /** The width of the drawer. */ width: number; /** The function to handle the drawer toggle. */ - handleDrawerToggle: ReactEventHandler; + handleDrawerToggle: React.ReactEventHandler; /** The URL for the logo image. */ logoURL?: string; } @@ -48,16 +43,22 @@ interface DashboardDrawerProps { * @param {DashboardDrawerProps} props - The props for the DashboardDrawer component. * @returns {JSX.Element} The rendered DashboardDrawer component. */ -export default function DashboardDrawer(props: DashboardDrawerProps) { +export default function DashboardDrawer({ + variant, + mobileOpen, + width, + handleDrawerToggle, + logoURL = "/DIRAC-logo.png", +}: DashboardDrawerProps) { // Determine the container for the Drawer based on whether the window object exists. const container = window !== undefined ? () => window.document.body : undefined; // Check if the drawer is in "temporary" mode. - const isTemporary = props.variant === "temporary"; + const isTemporary = variant === "temporary"; // Whether the modal for Application Creation is open const [appDialogOpen, setAppDialogOpen] = useState(false); - const [contextMenu, setContextMenu] = React.useState<{ + const [contextMenu, setContextMenu] = useState<{ mouseX: number; mouseY: number; } | null>(null); @@ -67,18 +68,16 @@ export default function DashboardDrawer(props: DashboardDrawerProps) { id: string | null; }>({ type: null, id: null }); - const [popAnchorEl, setPopAnchorEl] = React.useState( - null, - ); - const [renameValue, setRenameValue] = React.useState(""); + const [popAnchorEl, setPopAnchorEl] = useState(null); + const [renamingItemId, setRenamingItemId] = useState(null); + const [renamingGroupId, setRenamingGroupId] = useState(null); + const [renameValue, setRenameValue] = useState(""); // Define the applications that are accessible to users. // Each application has an associated icon and path. const [userDashboard, setUserDashboard] = useContext(ApplicationsContext); - const logoURL = props.logoURL || "/DIRAC-logo.png"; - - const theme = useMUITheme(); + const theme = useTheme(); useEffect(() => { // Handle changes to app instances when drag and drop occurs. @@ -306,8 +305,14 @@ export default function DashboardDrawer(props: DashboardDrawerProps) { handleCloseContextMenu(); }; - const handleRenameClick = (event: React.MouseEvent) => { - setPopAnchorEl(event.currentTarget); + const handleRenameClick = () => { + if (contextState.type === "group") { + setRenamingGroupId(contextState.id); + } else if (contextState.type === "item") { + setRenamingItemId(contextState.id); + } + setRenameValue(""); + handleCloseContextMenu(); }; const popClose = () => { @@ -352,9 +357,9 @@ export default function DashboardDrawer(props: DashboardDrawerProps) { <>
))} @@ -443,8 +454,9 @@ export default function DashboardDrawer(props: DashboardDrawerProps) { {contextState.type && ( Delete )} - - New Group + {contextState.type === null && ( + New Group + )}
{ - const theme = useMUITheme(); return ( - + - +
); }, ], diff --git a/packages/diracx-web-components/components/DashboardLayout/DrawerItem.tsx b/packages/diracx-web-components/components/DashboardLayout/DrawerItem.tsx index 994d4aa2..10f72dd7 100644 --- a/packages/diracx-web-components/components/DashboardLayout/DrawerItem.tsx +++ b/packages/diracx-web-components/components/DashboardLayout/DrawerItem.tsx @@ -1,10 +1,12 @@ -import React, { useEffect, useState } from "react"; +import React, { useEffect, useRef, useState } from "react"; import { createRoot } from "react-dom/client"; import { ListItemButton, ListItemIcon, Icon, ListItemText, + useTheme, + TextField, } from "@mui/material"; import { DragIndicator } from "@mui/icons-material"; import { combine } from "@atlaskit/pragmatic-drag-and-drop/combine"; @@ -19,11 +21,29 @@ import { extractClosestEdge, } from "@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge"; import { setCustomNativeDragPreview } from "@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview"; -import { ThemeProvider as MUIThemeProvider } from "@mui/material/styles"; import { ThemeProvider } from "@/contexts/ThemeProvider"; -import { useMUITheme } from "@/hooks/theme"; import { useSearchParamsUtils } from "@/hooks/searchParamsUtils"; import { useApplicationId } from "@/hooks/application"; +import { DashboardGroup } from "@/types"; + +interface DrawerItemProps { + /** The item object containing the title, id, and icon. */ + item: { title: string; id: string; icon: React.ComponentType }; + /** The index of the item. */ + index: number; + /** The title of the group. */ + groupTitle: string; + /** The ID of the item being renamed. */ + renamingItemId: string | null; + /** The function to set the renaming item ID. */ + setRenamingItemId: React.Dispatch>; + /** The value of the rename input. */ + renameValue: string; + /** The function to set the rename input value. */ + setRenameValue: React.Dispatch>; + /** The function to set the user dashboard state. */ + setUserDashboard: React.Dispatch>; +} /** * Represents a drawer item component. @@ -34,19 +54,17 @@ export default function DrawerItem({ item: { title, id, icon }, index, groupTitle, -}: { - /** The item object containing the title, id, and icon. */ - item: { title: string; id: string; icon: React.ComponentType }; - /** The index of the item. */ - index: number; - /** The title of the group. */ - groupTitle: string; -}) { + renamingItemId, + setRenamingItemId, + renameValue, + setRenameValue, + setUserDashboard, +}: DrawerItemProps) { // Ref to use for the draggable element - const dragRef = React.useRef(null); + const dragRef = useRef(null); // Ref to use for the handle of the draggable element, must be a child of the draggable element - const handleRef = React.useRef(null); - const theme = useMUITheme(); + const handleRef = useRef(null); + const theme = useTheme(); const { setParam } = useSearchParamsUtils(); // Represents the closest edge to the mouse cursor const [closestEdge, setClosestEdge] = useState(null); @@ -75,15 +93,13 @@ export default function DrawerItem({ // Wraps the preview in the theme provider to ensure the correct theme is applied // This is necessary because the preview is rendered outside the main app - -
- -
-
+
+ +
, ); return () => root.unmount(); @@ -143,6 +159,26 @@ export default function DrawerItem({ ); }, [index, groupTitle, icon, theme, title, id]); + // Handle renaming of the item + const handleItemRename = () => { + if (renameValue.trim() === "") return; + setUserDashboard((groups) => + groups.map((group) => { + if (group.title === groupTitle) { + return { + ...group, + items: group.items.map((item) => + item.id === id ? { ...item, title: renameValue } : item, + ), + }; + } + return group; + }), + ); + setRenamingItemId(null); + setRenameValue(""); + }; + return ( <> - + {renamingItemId === id ? ( + setRenameValue(e.target.value)} + onBlur={handleItemRename} + onKeyDown={(e) => { + if (e.key === "Enter") { + handleItemRename(); + } else if (e.key === "Escape") { + setRenamingItemId(null); + } + }} + autoFocus + size="small" + /> + ) : ( + + )} - + diff --git a/packages/diracx-web-components/components/DashboardLayout/DrawerItemGroup.stories.tsx b/packages/diracx-web-components/components/DashboardLayout/DrawerItemGroup.stories.tsx index 798d2fbf..112fe598 100644 --- a/packages/diracx-web-components/components/DashboardLayout/DrawerItemGroup.stories.tsx +++ b/packages/diracx-web-components/components/DashboardLayout/DrawerItemGroup.stories.tsx @@ -2,11 +2,10 @@ import React from "react"; import type { Meta, StoryObj } from "@storybook/react"; import { useArgs } from "@storybook/core/preview-api"; import { Paper } from "@mui/material"; -import { ThemeProvider as MUIThemeProvider } from "@mui/material/styles"; import { Dashboard } from "@mui/icons-material"; -import { useMUITheme } from "../../hooks/theme"; import { useOidc, useOidcAccessToken } from "../../mocks/react-oidc.mock"; import { DashboardGroup } from "../../types/DashboardGroup"; +import { ThemeProvider } from "../../contexts/ThemeProvider"; import DrawerItemGroup from "./DrawerItemGroup"; const meta = { @@ -18,13 +17,12 @@ const meta = { tags: ["autodocs"], decorators: [ (Story) => { - const theme = useMUITheme(); return ( - + - + ); }, ], diff --git a/packages/diracx-web-components/components/DashboardLayout/DrawerItemGroup.tsx b/packages/diracx-web-components/components/DashboardLayout/DrawerItemGroup.tsx index a2b07184..d04120ef 100644 --- a/packages/diracx-web-components/components/DashboardLayout/DrawerItemGroup.tsx +++ b/packages/diracx-web-components/components/DashboardLayout/DrawerItemGroup.tsx @@ -1,11 +1,40 @@ "use client"; -import { Accordion, AccordionDetails, AccordionSummary } from "@mui/material"; +import { + Accordion, + AccordionDetails, + AccordionSummary, + TextField, +} from "@mui/material"; import { ExpandMore, Apps } from "@mui/icons-material"; -import React, { useEffect } from "react"; +import React, { useEffect, useRef, useState } from "react"; import { dropTargetForElements } from "@atlaskit/pragmatic-drag-and-drop/element/adapter"; import DrawerItem from "./DrawerItem"; import { DashboardGroup } from "@/types/DashboardGroup"; +interface DrawerItemGroupProps { + /** The group object containing the title, expanded state, and items. */ + group: DashboardGroup; + /** The function to set the user dashboard state. */ + setUserDashboard: React.Dispatch>; + /** The function to handle the context menu. */ + handleContextMenu: ( + type: "group" | "item" | null, + id: string | null, + ) => (event: React.MouseEvent) => void; + /** The ID of the group being renamed. */ + renamingGroupId: string | null; + /** The function to set the renaming group ID. */ + setRenamingGroupId: React.Dispatch>; + /** The ID of the item being renamed. */ + renamingItemId: string | null; + /** The function to set the renaming item ID. */ + setRenamingItemId: React.Dispatch>; + /** The value of the rename input. */ + renameValue: string; + /** The function to set the rename input value. */ + setRenameValue: React.Dispatch>; +} + /** * Represents a group of items in a drawer. * @@ -17,21 +46,17 @@ export default function DrawerItemGroup({ group: { title, extended: expanded, items }, setUserDashboard, handleContextMenu, -}: { - /** The group object containing the title, expanded state, and items. */ - group: DashboardGroup; - /** The function to set the user dashboard state. */ - setUserDashboard: React.Dispatch>; - /** The function to handle the context menu. */ - handleContextMenu: ( - type: "group" | "item" | null, - id: string | null, - ) => (event: React.MouseEvent) => void; -}) { + renamingGroupId, + setRenamingGroupId, + renamingItemId, + setRenamingItemId, + renameValue, + setRenameValue, +}: DrawerItemGroupProps) { // Ref to use for the drag and drop target - const dropRef = React.useRef(null); + const dropRef = useRef(null); // State to track whether the user is hovering over the item during a drag operation - const [hovered, setHovered] = React.useState(false); + const [hovered, setHovered] = useState(false); useEffect(() => { if (!dropRef.current) return; @@ -61,6 +86,19 @@ export default function DrawerItemGroup({ ), ); }; + + // Handle renaming of the group + const handleGroupRename = () => { + if (renameValue.trim() === "") return; + setUserDashboard((groups) => + groups.map((group) => + group.title === title ? { ...group, title: renameValue } : group, + ), + ); + setRenamingGroupId(null); + setRenameValue(""); + }; + return ( {/* Accordion summary */} - }>{title} + }> + {renamingGroupId === title ? ( + setRenameValue(e.target.value)} + onBlur={handleGroupRename} + onKeyDown={(e) => { + if (e.key === "Enter") { + handleGroupRename(); + } else if (e.key === "Escape") { + setRenamingGroupId(null); + } + }} + autoFocus + size="small" + /> + ) : ( +
{title}
+ )} +
{/* Accordion details */} {items.map(({ title: itemTitle, id, icon }, index) => ( @@ -82,6 +139,11 @@ export default function DrawerItemGroup({ item={{ title: itemTitle, id, icon: icon || Apps }} index={index} groupTitle={title} + renamingItemId={renamingItemId} + setRenamingItemId={setRenamingItemId} + renameValue={renameValue} + setRenameValue={setRenameValue} + setUserDashboard={setUserDashboard} />
))} diff --git a/packages/diracx-web-components/components/DashboardLayout/ProfileButton.stories.tsx b/packages/diracx-web-components/components/DashboardLayout/ProfileButton.stories.tsx index 31f54922..8b919929 100644 --- a/packages/diracx-web-components/components/DashboardLayout/ProfileButton.stories.tsx +++ b/packages/diracx-web-components/components/DashboardLayout/ProfileButton.stories.tsx @@ -2,9 +2,8 @@ import React from "react"; import type { Meta, StoryObj } from "@storybook/react"; import { Paper } from "@mui/material"; -import { ThemeProvider as MUIThemeProvider } from "@mui/material/styles"; -import { useMUITheme } from "../../hooks/theme"; import { useOidc, useOidcAccessToken } from "../../mocks/react-oidc.mock"; +import { ThemeProvider } from "../../contexts/ThemeProvider"; import { ProfileButton } from "./ProfileButton"; const meta = { @@ -16,13 +15,12 @@ const meta = { tags: ["autodocs"], decorators: [ (Story) => { - const theme = useMUITheme(); return ( - + - + ); }, ], diff --git a/packages/diracx-web-components/components/DashboardLayout/ProfileButton.tsx b/packages/diracx-web-components/components/DashboardLayout/ProfileButton.tsx index f6b55313..08535370 100644 --- a/packages/diracx-web-components/components/DashboardLayout/ProfileButton.tsx +++ b/packages/diracx-web-components/components/DashboardLayout/ProfileButton.tsx @@ -25,9 +25,9 @@ import { Stack, Tooltip, Typography, + useTheme, } from "@mui/material"; -import { cyan } from "@mui/material/colors"; -import React from "react"; +import React, { useState } from "react"; import { useOIDCContext } from "@/hooks/oidcConfiguration"; /** @@ -35,11 +35,13 @@ import { useOIDCContext } from "@/hooks/oidcConfiguration"; * @returns a Button */ export function ProfileButton() { + const theme = useTheme(); + const { configuration, setConfiguration } = useOIDCContext(); const { accessTokenPayload } = useOidcAccessToken(configuration?.scope); const { logout, isAuthenticated } = useOidc(configuration?.scope); - const [anchorEl, setAnchorEl] = React.useState(null); + const [anchorEl, setAnchorEl] = useState(null); const open = Boolean(anchorEl); const handleClick = (event: React.MouseEvent) => { @@ -76,7 +78,7 @@ export function ProfileButton() { aria-haspopup="true" aria-expanded={open ? "true" : undefined} > - + {accessTokenPayload["preferred_username"][0]} diff --git a/packages/diracx-web-components/components/DashboardLayout/ThemeToggleButton.stories.tsx b/packages/diracx-web-components/components/DashboardLayout/ThemeToggleButton.stories.tsx index 74b59232..c49e98c9 100644 --- a/packages/diracx-web-components/components/DashboardLayout/ThemeToggleButton.stories.tsx +++ b/packages/diracx-web-components/components/DashboardLayout/ThemeToggleButton.stories.tsx @@ -2,8 +2,7 @@ import React from "react"; import type { Meta, StoryObj } from "@storybook/react"; import { Paper } from "@mui/material"; -import { ThemeProvider as MUIThemeProvider } from "@mui/material/styles"; -import { useMUITheme } from "../../hooks/theme"; +import { ThemeProvider } from "../../contexts/ThemeProvider"; import { ThemeToggleButton } from "./ThemeToggleButton"; const meta = { @@ -15,13 +14,12 @@ const meta = { tags: ["autodocs"], decorators: [ (Story) => { - const theme = useMUITheme(); return ( - + - + ); }, ], diff --git a/packages/diracx-web-components/components/JobMonitor/JobDataTable.stories.tsx b/packages/diracx-web-components/components/JobMonitor/JobDataTable.stories.tsx index 870dc92d..b85e4466 100644 --- a/packages/diracx-web-components/components/JobMonitor/JobDataTable.stories.tsx +++ b/packages/diracx-web-components/components/JobMonitor/JobDataTable.stories.tsx @@ -1,9 +1,8 @@ import React from "react"; import { StoryObj, Meta } from "@storybook/react"; -import { ThemeProvider as MUIThemeProvider } from "@mui/material/styles"; -import { useMUITheme } from "../../hooks/theme"; import { useJobs } from "../../mocks/JobDataService.mock"; import { useOidcAccessToken } from "../../mocks/react-oidc.mock"; +import { ThemeProvider } from "../../contexts/ThemeProvider"; import { JobDataTable } from "./JobDataTable"; const meta = { @@ -25,11 +24,10 @@ const meta = { }, decorators: [ (Story) => { - const theme = useMUITheme(); return ( - + - + ); }, ], diff --git a/packages/diracx-web-components/components/JobMonitor/JobDataTable.tsx b/packages/diracx-web-components/components/JobMonitor/JobDataTable.tsx index 0e0ea3b8..a44caca3 100644 --- a/packages/diracx-web-components/components/JobMonitor/JobDataTable.tsx +++ b/packages/diracx-web-components/components/JobMonitor/JobDataTable.tsx @@ -1,4 +1,4 @@ -import React from "react"; +import React, { useCallback, useMemo, useState } from "react"; import Box from "@mui/material/Box"; import { blue, @@ -18,14 +18,23 @@ import { AlertColor, IconButton, Tooltip, - useMediaQuery, - useTheme, Backdrop, CircularProgress, Snackbar, + lighten, + darken, + useTheme, } from "@mui/material"; import { useOidcAccessToken } from "@axa-fr/react-oidc"; import { Delete, Clear, Replay } from "@mui/icons-material"; +import { + createColumnHelper, + ColumnPinningState, + RowSelectionState, + useReactTable, + getCoreRowModel, + VisibilityState, +} from "@tanstack/react-table"; import { useOIDCContext } from "../../hooks/oidcConfiguration"; import { DataTable, MenuItem } from "../shared/DataTable"; import { JobHistoryDialog } from "./JobHistoryDialog"; @@ -37,116 +46,177 @@ import { rescheduleJobs, useJobs, } from "./JobDataService"; -import { Column } from "@/types/Column"; -import { InternalFilter } from "@/types/Filter"; import { JobHistory } from "@/types/JobHistory"; import { Job, SearchBody } from "@/types"; -const statusColors: { [key: string]: string } = { - Submitting: purple[500], - Received: blueGrey[500], - Checking: teal[500], - Staging: lightBlue[500], - Waiting: amber[600], - Matched: blue[300], - Running: blue[900], - Rescheduled: lime[700], - Completing: orange[500], - Completed: green[300], - Done: green[500], - Failed: red[500], - Stalled: amber[900], - Killed: red[900], - Deleted: grey[500], -}; - -/** - * Renders the status cell with colors - */ -const renderStatusCell = (status: unknown) => { - if (typeof status !== "string") { - return null; // or handle other types as needed - } - return ( - - {status} - - ); -}; - -/** - * The head cells for the data grid (desktop version) - */ -const headCells: Column[] = [ - { id: "JobID", label: "Job ID", type: "number" }, - { id: "JobName", label: "Job Name" }, - { id: "Site", label: "Site" }, - { - id: "Status", - label: "Status", - render: renderStatusCell, - type: Object.keys(statusColors).sort(), - }, - { - id: "MinorStatus", - label: "Minor Status", - }, - { - id: "SubmissionTime", - label: "Submission Time", - type: "DateTime", - }, -]; - -/** - * The head cells for the data grid (mobile version) - */ -const mobileHeadCells: Column[] = [ - { id: "JobID", label: "Job ID" }, - { id: "JobName", label: "Job Name" }, - { id: "Status", label: "Status", render: renderStatusCell }, -]; - -type Order = "asc" | "desc"; - /** * The data grid for the jobs */ export function JobDataTable() { const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [selected, setSelected] = React.useState([]); + // Authentication const { configuration } = useOIDCContext(); const { accessToken } = useOidcAccessToken(configuration?.scope); - const [backdropOpen, setBackdropOpen] = React.useState(false); - const [snackbarInfo, setSnackbarInfo] = React.useState({ + + // State for loading elements + const [backdropOpen, setBackdropOpen] = useState(false); + const [snackbarInfo, setSnackbarInfo] = useState({ open: false, message: "", severity: "success", }); - // State for sorting - const [order, setOrder] = React.useState("asc"); - const [orderBy, setOrderBy] = React.useState("JobID"); - // State for pagination - const [page, setPage] = React.useState(0); - const [rowsPerPage, setRowsPerPage] = React.useState(25); - // State for filters - const [filters, setFilters] = React.useState([]); + + // States for table settings + const [columnVisibility, setColumnVisibility] = useState({ + JobGroup: false, + JobType: false, + Owner: false, + OwnerGroup: false, + VO: false, + StartExecTime: false, + EndExecTime: false, + UserPriority: false, + }); + const [columnPinning, setColumnPinning] = useState({ + left: ["JobID"], // Pin JobID column by default + }); + const [rowSelection, setRowSelection] = useState({}); + const [pagination, setPagination] = useState({ + pageIndex: 0, + pageSize: 25, + }); + // State for search body - const [searchBody, setSearchBody] = React.useState({}); + const [searchBody, setSearchBody] = useState({ + sort: [{ parameter: "JobID", direction: "asc" }], + }); + + // State for selected job + const [selectedJobId, setSelectedJobId] = useState(null); + // State for job history - const [isHistoryDialogOpen, setIsHistoryDialogOpen] = React.useState(false); - const [jobHistoryData, setJobHistoryData] = React.useState([]); + const [isHistoryDialogOpen, setIsHistoryDialogOpen] = useState(false); + const [jobHistoryData, setJobHistoryData] = useState([]); + + // Status colors + const statusColors: Record = useMemo( + () => ({ + Submitting: purple[500], + Received: blueGrey[500], + Checking: teal[500], + Staging: lightBlue[500], + Waiting: amber[600], + Matched: blue[300], + Running: blue[900], + Rescheduled: lime[700], + Completing: orange[500], + Completed: green[300], + Done: green[500], + Failed: red[500], + Stalled: amber[900], + Killed: red[900], + Deleted: grey[500], + }), + [], + ); + + /** + * Renders the status cell with colors + */ + const renderStatusCell = useCallback( + (status: string) => { + return ( + + {status} + + ); + }, + [theme, statusColors], + ); + + const columnHelper = useMemo(() => createColumnHelper(), []); + + /** + * The head cells for the data grid (desktop version) + */ + const columns = useMemo( + () => [ + columnHelper.accessor("JobID", { + header: "ID", + meta: { type: "number" }, + }), + columnHelper.accessor("Status", { + header: "Status", + cell: (info) => renderStatusCell(info.getValue()), + meta: { type: "category", values: Object.keys(statusColors).sort() }, + }), + columnHelper.accessor("MinorStatus", { + header: "Minor Status", + }), + columnHelper.accessor("ApplicationStatus", { + header: "Application Status", + }), + columnHelper.accessor("Site", { + header: "Site", + }), + columnHelper.accessor("JobName", { + header: "Name", + }), + columnHelper.accessor("JobGroup", { + header: "Job Group", + }), + columnHelper.accessor("JobType", { + header: "Type", + }), + columnHelper.accessor("LastUpdateTime", { + header: "Last Update Time", + meta: { type: "date" }, + }), + columnHelper.accessor("HeartBeatTime", { + header: "Last Sign of Life", + meta: { type: "date" }, + }), + columnHelper.accessor("SubmissionTime", { + header: "Submission Time", + meta: { type: "date" }, + }), + columnHelper.accessor("Owner", { + header: "Owner", + }), + columnHelper.accessor("OwnerGroup", { + header: "Owner Group", + }), + columnHelper.accessor("VO", { + header: "VO", + }), + columnHelper.accessor("StartExecTime", { + header: "Start Execution Time", + meta: { type: "date" }, + }), + columnHelper.accessor("EndExecTime", { + header: "End Execution Time", + meta: { type: "date" }, + }), + columnHelper.accessor("UserPriority", { + header: "User Priority", + meta: { type: "number" }, + }), + ], + [columnHelper, renderStatusCell, statusColors], + ); /** * Fetches the jobs from the /api/jobs/search endpoint @@ -154,12 +224,12 @@ export function JobDataTable() { const { data, error, isLoading, isValidating } = useJobs( accessToken, searchBody, - page, - rowsPerPage, + pagination.pageIndex, + pagination.pageSize, ); const dataHeader = data?.headers; - const results = data?.data || []; + const results = useMemo(() => data?.data || [], [data?.data]); // Parse the headers to get the first item, last item and number of items const contentRange = dataHeader?.get("content-range"); @@ -174,18 +244,23 @@ export function JobDataTable() { totalJobs = results.length; } - const columns = isMobile ? mobileHeadCells : headCells; - const clearSelected = () => setSelected([]); + const clearSelected = () => setRowSelection({}); /** * Handle the deletion of the selected jobs */ - const handleDelete = async (selectedIds: readonly number[]) => { + const handleDelete = useCallback(async () => { setBackdropOpen(true); try { + const selectedIds = Object.keys(rowSelection).map(Number); await deleteJobs(selectedIds, accessToken); setBackdropOpen(false); - refreshJobs(accessToken, searchBody, page, rowsPerPage); + refreshJobs( + accessToken, + searchBody, + pagination.pageIndex, + pagination.pageSize, + ); clearSelected(); setSnackbarInfo({ open: true, @@ -206,17 +281,29 @@ export function JobDataTable() { } finally { setBackdropOpen(false); } - }; + }, [ + accessToken, + rowSelection, + searchBody, + pagination.pageIndex, + pagination.pageSize, + ]); /** * Handle the killing of the selected jobs */ - const handleKill = async (selectedIds: readonly number[]) => { + const handleKill = useCallback(async () => { setBackdropOpen(true); try { + const selectedIds = Object.keys(rowSelection).map(Number); await killJobs(selectedIds, accessToken); setBackdropOpen(false); - refreshJobs(accessToken, searchBody, page, rowsPerPage); + refreshJobs( + accessToken, + searchBody, + pagination.pageIndex, + pagination.pageSize, + ); clearSelected(); setSnackbarInfo({ open: true, @@ -237,17 +324,29 @@ export function JobDataTable() { } finally { setBackdropOpen(false); } - }; + }, [ + accessToken, + rowSelection, + searchBody, + pagination.pageIndex, + pagination.pageSize, + ]); /** * Handle the rescheduling of the selected jobs */ - const handleReschedule = async (selectedIds: readonly number[]) => { + const handleReschedule = useCallback(async () => { setBackdropOpen(true); try { + const selectedIds = Object.keys(rowSelection).map(Number); await rescheduleJobs(selectedIds, accessToken); setBackdropOpen(false); - refreshJobs(accessToken, searchBody, page, rowsPerPage); + refreshJobs( + accessToken, + searchBody, + pagination.pageIndex, + pagination.pageSize, + ); clearSelected(); setSnackbarInfo({ open: true, @@ -268,35 +367,45 @@ export function JobDataTable() { } finally { setBackdropOpen(false); } - }; + }, [ + accessToken, + rowSelection, + searchBody, + pagination.pageIndex, + pagination.pageSize, + ]); /** * Handle the history of the selected job */ - const handleHistory = async (selectedId: number | null) => { - if (!selectedId) return; - setBackdropOpen(true); - try { - const { data } = await getJobHistory(selectedId, accessToken); - setBackdropOpen(false); - // Show the history - setJobHistoryData(data[selectedId]); - setIsHistoryDialogOpen(true); - } catch (error: unknown) { - let errorMessage = "An unknown error occurred"; + const handleHistory = useCallback( + async (selectedId: number | null) => { + if (!selectedId) return; + setBackdropOpen(true); + setSelectedJobId(selectedId); + try { + const { data } = await getJobHistory(selectedId, accessToken); + setBackdropOpen(false); + // Show the history + setJobHistoryData(data[selectedId]); + setIsHistoryDialogOpen(true); + } catch (error: unknown) { + let errorMessage = "An unknown error occurred"; - if (error instanceof Error) { - errorMessage = error.message; + if (error instanceof Error) { + errorMessage = error.message; + } + setSnackbarInfo({ + open: true, + message: "Fetching history failed: " + errorMessage, + severity: "error", + }); + } finally { + setBackdropOpen(false); } - setSnackbarInfo({ - open: true, - message: "Fetching history failed: " + errorMessage, - severity: "error", - }); - } finally { - setBackdropOpen(false); - } - }; + }, + [accessToken], + ); const handleHistoryClose = () => { setIsHistoryDialogOpen(false); @@ -305,62 +414,87 @@ export function JobDataTable() { /** * The toolbar components for the data grid */ - const toolbarComponents = ( - <> - - handleReschedule(selected)}> - - - - - handleKill(selected)}> - - - - - handleDelete(selected)}> - - - - + const toolbarComponents = useMemo( + () => ( + <> + + handleReschedule()}> + + + + + handleKill()}> + + + + + handleDelete()}> + + + + + ), + [handleReschedule, handleKill, handleDelete], ); /** * The menu items */ - const menuItems: MenuItem[] = [ - { label: "Get history", onClick: (id: number | null) => handleHistory(id) }, - ]; + const menuItems: MenuItem[] = useMemo( + () => [ + { + label: "Get history", + onClick: (id: number | null) => handleHistory(id), + }, + ], + [handleHistory], + ); /** - * The main component + * Table instance */ + const table = useReactTable({ + data: results, + columns, + state: { + columnVisibility, + columnPinning, + rowSelection, + pagination, + }, + getRowId: (row) => row.JobID.toString(), + onColumnVisibilityChange: setColumnVisibility, + onColumnPinningChange: setColumnPinning, + onRowSelectionChange: setRowSelection, + onPaginationChange: setPagination, + getCoreRowModel: getCoreRowModel(), + enablePinning: true, + enableColumnResizing: true, + columnResizeMode: "onChange", + manualPagination: true, + }); + /** + * The main component + */ return ( - + title="List of Jobs" - page={page} - setPage={setPage} - rowsPerPage={rowsPerPage} - setRowsPerPage={setRowsPerPage} - order={order} - setOrder={setOrder} - orderBy={orderBy} - setOrderBy={setOrderBy} + table={table} totalRows={totalJobs} - selected={selected} - setSelected={setSelected} - filters={filters} - setFilters={setFilters} + searchBody={searchBody} setSearchBody={setSearchBody} - columns={columns} - rows={results} error={error} isLoading={isLoading} isValidating={isValidating} - rowIdentifier="JobID" - isMobile={isMobile} toolbarComponents={toolbarComponents} menuItems={menuItems} /> @@ -387,6 +521,7 @@ export function JobDataTable() { open={isHistoryDialogOpen} onClose={handleHistoryClose} historyData={jobHistoryData} + jobId={selectedJobId ?? 0} /> ); diff --git a/packages/diracx-web-components/components/JobMonitor/JobHistoryDialog.stories.tsx b/packages/diracx-web-components/components/JobMonitor/JobHistoryDialog.stories.tsx index 3b162dc0..d3c08c6f 100644 --- a/packages/diracx-web-components/components/JobMonitor/JobHistoryDialog.stories.tsx +++ b/packages/diracx-web-components/components/JobMonitor/JobHistoryDialog.stories.tsx @@ -1,8 +1,7 @@ import React from "react"; import { StoryObj, Meta } from "@storybook/react"; import { useArgs } from "@storybook/core/preview-api"; -import { ThemeProvider } from "@mui/material"; -import { useMUITheme } from "../../hooks/theme"; +import { ThemeProvider } from "../../contexts/ThemeProvider"; import { JobHistoryDialog } from "./JobHistoryDialog"; const meta = { @@ -19,9 +18,8 @@ const meta = { }, decorators: [ (Story) => { - const theme = useMUITheme(); return ( - + ); @@ -45,6 +43,7 @@ export const Default: Story = { ], open: true, onClose: () => {}, + jobId: 1234, }, render: (props) => { const [, updateArgs] = useArgs(); diff --git a/packages/diracx-web-components/components/JobMonitor/JobHistoryDialog.tsx b/packages/diracx-web-components/components/JobMonitor/JobHistoryDialog.tsx index 96ea10b0..45aaface 100644 --- a/packages/diracx-web-components/components/JobMonitor/JobHistoryDialog.tsx +++ b/packages/diracx-web-components/components/JobMonitor/JobHistoryDialog.tsx @@ -8,8 +8,17 @@ import { TableCell, TableHead, TableRow, + TableContainer, + useTheme, } from "@mui/material"; import { Close } from "@mui/icons-material"; +import React, { useMemo } from "react"; +import { + useReactTable, + createColumnHelper, + getCoreRowModel, + flexRender, +} from "@tanstack/react-table"; import { JobHistory } from "@/types/JobHistory"; interface JobHistoryDialogProps { @@ -17,10 +26,10 @@ interface JobHistoryDialogProps { open: boolean; /** The function to close the dialog */ onClose: () => void; - /** - * The data for the job history dialog - */ + /** The data for the job history dialog */ historyData: JobHistory[]; + /** The job ID */ + jobId: number; } /** @@ -28,11 +37,52 @@ interface JobHistoryDialogProps { * * @returns The rendered JobHistoryDialog component. */ -export function JobHistoryDialog(props: JobHistoryDialogProps) { - const { open, onClose, historyData } = props; +export function JobHistoryDialog({ + open, + onClose, + historyData, + jobId, +}: JobHistoryDialogProps) { + const theme = useTheme(); + + // Create column helper + const columnHelper = createColumnHelper(); + + // Define columns + const columns = useMemo( + () => [ + columnHelper.accessor("Status", { + header: "Status", + }), + columnHelper.accessor("MinorStatus", { + header: "Minor Status", + }), + columnHelper.accessor("ApplicationStatus", { + header: "Application Status", + }), + columnHelper.accessor("StatusTime", { + header: "Status Time", + }), + columnHelper.accessor("Source", { + header: "Source", + }), + ], + [columnHelper], + ); + + // Create table instance + const table = useReactTable({ + data: historyData, + columns, + getCoreRowModel: getCoreRowModel(), + state: {}, + enableColumnResizing: true, // Enable column resizing + columnResizeMode: "onChange", // Column resize mode + }); + return ( - Job History + Job History: {jobId} theme.palette.grey[500], + color: theme.palette.grey[500], }} > + - - - - Status - Minor Status - Application Status - Status Time - Source - - - - {historyData.map((history, index) => ( - - {history.Status} - {history.MinorStatus} - {history.ApplicationStatus} - {history.StatusTime} - {history.Source} - - ))} - -
+ + + + {table.getHeaderGroups().map((headerGroup) => ( + + {headerGroup.headers.map((header) => ( + + {header.isPlaceholder ? null : ( + <> + {flexRender( + header.column.columnDef.header, + header.getContext(), + )} + {header.column.getCanResize() && ( +
+ )} + + )} + + ))} + + ))} + + + {table.getRowModel().rows.map((row) => ( + + {row.getVisibleCells().map((cell) => ( + + {flexRender( + cell.column.columnDef.cell, + cell.getContext(), + )} + + ))} + + ))} + +
+
); diff --git a/packages/diracx-web-components/components/JobMonitor/JobMonitor.stories.tsx b/packages/diracx-web-components/components/JobMonitor/JobMonitor.stories.tsx index 1920bbf0..16a91474 100644 --- a/packages/diracx-web-components/components/JobMonitor/JobMonitor.stories.tsx +++ b/packages/diracx-web-components/components/JobMonitor/JobMonitor.stories.tsx @@ -1,11 +1,11 @@ import React from "react"; import { StoryObj, Meta } from "@storybook/react"; -import { Paper, ThemeProvider } from "@mui/material"; +import { Paper } from "@mui/material"; import { useJobs } from "../../mocks/JobDataService.mock"; import { useOidcAccessToken } from "../../mocks/react-oidc.mock"; import { ApplicationsContext } from "../../contexts/ApplicationsProvider"; import { NavigationProvider } from "../../contexts/NavigationProvider"; -import { useMUITheme } from "../../hooks/theme"; +import { ThemeProvider } from "../../contexts/ThemeProvider"; import JobMonitor from "./JobMonitor"; const meta = { @@ -15,14 +15,10 @@ const meta = { layout: "centered", }, tags: ["autodocs"], - argTypes: { - headerSize: { control: "select" }, - }, decorators: [ (Story) => { - const theme = useMUITheme(); return ( - + diff --git a/packages/diracx-web-components/components/JobMonitor/JobMonitor.tsx b/packages/diracx-web-components/components/JobMonitor/JobMonitor.tsx index 6967f527..d080ae1c 100644 --- a/packages/diracx-web-components/components/JobMonitor/JobMonitor.tsx +++ b/packages/diracx-web-components/components/JobMonitor/JobMonitor.tsx @@ -1,23 +1,23 @@ "use client"; -import React from "react"; +import { Box } from "@mui/material"; import { JobDataTable } from "./JobDataTable"; -import ApplicationHeader from "@/components/shared/ApplicationHeader"; /** * Build the Job Monitor application * * @returns Job Monitor content */ -export default function JobMonitor({ - headerSize, -}: { - /** The size of the header, optional */ - headerSize?: "h1" | "h2" | "h3" | "h4" | "h5" | "h6"; -}) { +export default function JobMonitor() { return ( -
- + -
+
); } diff --git a/packages/diracx-web-components/components/Login/LoginForm.stories.tsx b/packages/diracx-web-components/components/Login/LoginForm.stories.tsx index 5ceb9ad0..d593efe5 100644 --- a/packages/diracx-web-components/components/Login/LoginForm.stories.tsx +++ b/packages/diracx-web-components/components/Login/LoginForm.stories.tsx @@ -1,9 +1,9 @@ import React from "react"; import { StoryObj, Meta } from "@storybook/react"; -import { Paper, ThemeProvider } from "@mui/material"; +import { Paper } from "@mui/material"; import { useMetadata } from "../../mocks/metadata.mock"; import { useOidc } from "../../mocks/react-oidc.mock"; -import { useMUITheme } from "../../hooks/theme"; +import { ThemeProvider } from "../../contexts/ThemeProvider"; import { LoginForm } from "./LoginForm"; const meta = { @@ -24,9 +24,8 @@ const meta = { }, decorators: [ (Story) => { - const theme = useMUITheme(); return ( - + diff --git a/packages/diracx-web-components/components/Login/LoginForm.tsx b/packages/diracx-web-components/components/Login/LoginForm.tsx index 13f5dc4d..5ffe4b66 100644 --- a/packages/diracx-web-components/components/Login/LoginForm.tsx +++ b/packages/diracx-web-components/components/Login/LoginForm.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { useState, useEffect } from "react"; +import React, { useState, useEffect, useContext } from "react"; import Box from "@mui/material/Box"; import Typography from "@mui/material/Typography"; import FormControl from "@mui/material/FormControl"; @@ -10,16 +10,19 @@ import MenuItem from "@mui/material/MenuItem"; import Button from "@mui/material/Button"; import Autocomplete from "@mui/material/Autocomplete"; import TextField from "@mui/material/TextField"; -import { CssBaseline, Stack } from "@mui/material"; -import { ThemeProvider as MUIThemeProvider } from "@mui/material/styles"; +import { Stack } from "@mui/material"; import { useOidc } from "@axa-fr/react-oidc"; import { useMetadata, Metadata } from "../../hooks/metadata"; import { useOIDCContext } from "@/hooks/oidcConfiguration"; -import { useMUITheme } from "@/hooks/theme"; import { useSearchParamsUtils } from "@/hooks/searchParamsUtils"; import { NavigationContext } from "@/contexts/NavigationProvider"; +interface LoginFormProps { + /** The URL of the logo, optional */ + logoURL?: string; +} + /** * Login form * @@ -27,12 +30,8 @@ import { NavigationContext } from "@/contexts/NavigationProvider"; */ export function LoginForm({ logoURL = "/DIRAC-logo-minimal.png", -}: { - /** The URL of the logo, optional */ - logoURL?: string; -}) { - const theme = useMUITheme(); - const { setPath } = React.useContext(NavigationContext); +}: LoginFormProps) { + const { setPath } = useContext(NavigationContext); const { metadata, error, isLoading } = useMetadata(); const [selectedVO, setSelectedVO] = useState(null); const [selectedGroup, setSelectedGroup] = useState(null); @@ -129,109 +128,105 @@ export function LoginForm({ return ( - - - + - + + {singleVO ? ( + + {selectedVO} + + ) : ( + option} + renderInput={(params) => ( + + )} + value={selectedVO} + onChange={handleVOChange} sx={{ - width: "100%", - display: "flex", - justifyContent: "center", - paddingTop: "10%", - paddingBottom: "10%", + "& .MuiAutocomplete-root": { + // Style changes when an option is selected + opacity: selectedVO ? 0.5 : 1, + }, }} - > - DIRAC logo - - {singleVO ? ( + /> + )} + {selectedVO && ( + + + Select a Group + + + + + + - {selectedVO} + Need help?{" "} + {metadata.virtual_organizations[selectedVO].support.message} - ) : ( - option} - renderInput={(params) => ( - - )} - value={selectedVO} - onChange={handleVOChange} - sx={{ - "& .MuiAutocomplete-root": { - // Style changes when an option is selected - opacity: selectedVO ? 0.5 : 1, - }, - }} - /> - )} - {selectedVO && ( - - - Select a Group - - - - - - - - Need help?{" "} - {metadata.virtual_organizations[selectedVO].support.message} - - - )} - - + + )} + ); } diff --git a/packages/diracx-web-components/components/OIDC/OIDCProvider.tsx b/packages/diracx-web-components/components/OIDC/OIDCProvider.tsx index 62bc7893..1376f431 100644 --- a/packages/diracx-web-components/components/OIDC/OIDCProvider.tsx +++ b/packages/diracx-web-components/components/OIDC/OIDCProvider.tsx @@ -14,7 +14,7 @@ interface OIDCProviderProps { * @param props - configuration of the OIDC provider * @returns the wrapper around OidcProvider */ -export function OIDCProvider(props: OIDCProviderProps) { +export function OIDCProvider({ children }: OIDCProviderProps) { const { configuration, setConfiguration } = useOIDCContext(); const diracxUrl = useDiracxUrl(); @@ -58,7 +58,7 @@ export function OIDCProvider(props: OIDCProviderProps) { configurationName={configuration.scope} withCustomHistory={withCustomHistory} > -
{props.children}
+
{children}
); diff --git a/packages/diracx-web-components/components/OIDC/OIDCSecure.tsx b/packages/diracx-web-components/components/OIDC/OIDCSecure.tsx index 12b6418a..bea4fc73 100644 --- a/packages/diracx-web-components/components/OIDC/OIDCSecure.tsx +++ b/packages/diracx-web-components/components/OIDC/OIDCSecure.tsx @@ -1,5 +1,5 @@ "use client"; -import React, { useEffect } from "react"; +import React, { useContext, useEffect } from "react"; import { useOidc } from "@axa-fr/react-oidc"; import { useOIDCContext } from "@/hooks/oidcConfiguration"; import { NavigationContext } from "@/contexts/NavigationProvider"; @@ -16,7 +16,7 @@ interface OIDCProps { export function OIDCSecure({ children }: OIDCProps) { const { configuration } = useOIDCContext(); const { isAuthenticated } = useOidc(configuration?.scope); - const { setPath } = React.useContext(NavigationContext); + const { setPath } = useContext(NavigationContext); useEffect(() => { // Redirect to login page if not authenticated diff --git a/packages/diracx-web-components/components/shared/ApplicationHeader.stories.tsx b/packages/diracx-web-components/components/shared/ApplicationHeader.stories.tsx deleted file mode 100644 index 004af940..00000000 --- a/packages/diracx-web-components/components/shared/ApplicationHeader.stories.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import React from "react"; -import { StoryObj, Meta } from "@storybook/react"; -import { Paper, ThemeProvider } from "@mui/material"; -import { useMUITheme } from "../../hooks/theme"; -import { ApplicationsContext } from "../../contexts/ApplicationsProvider"; -import { NavigationProvider } from "../../contexts/NavigationProvider"; -import ApplicationHeader from "./ApplicationHeader"; - -const meta = { - title: "shared/ApplicationHeader", - component: ApplicationHeader, - parameters: { - layout: "centered", - }, - tags: ["autodocs"], - argTypes: { - type: { control: "text" }, - size: { options: ["h1", "h2", "h3", "h4", "h5", "h6"] }, - }, -} satisfies Meta; - -export default meta; -type Story = StoryObj; - -export const Default: Story = { - args: { - type: "App Type", - }, - decorators: [ - (Story) => { - const theme = useMUITheme(); - return ( - - - - - - ); - }, - (Story) => ( - "/"} - setPath={() => {}} - getSearchParams={() => { - const url = new URLSearchParams(); - url.append("appId", "example"); - return url; - }} - > - {}, - [], - ]} - > - - - - ), - ], -}; diff --git a/packages/diracx-web-components/components/shared/ApplicationHeader.tsx b/packages/diracx-web-components/components/shared/ApplicationHeader.tsx deleted file mode 100644 index 3a1bc15b..00000000 --- a/packages/diracx-web-components/components/shared/ApplicationHeader.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import React from "react"; -import { Stack, Typography, useMediaQuery, useTheme } from "@mui/material"; -import { useApplicationTitle } from "@/hooks/application"; - -export interface ApplicationHeaderProps { - /** The type of the application. */ - type: string; - /** The size of the header, default is h4 */ - size?: "h1" | "h2" | "h3" | "h4" | "h5" | "h6"; -} - -/** - * Application Header component with the application title and type - * - * @returns The Application Header component - */ -export default function ApplicationHeader({ - type, - size = "h5", -}: ApplicationHeaderProps) { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const appTitle = useApplicationTitle(); - - return ( -
- - {appTitle && ( - - {appTitle} - - )} - - {type} - - -
- ); -} diff --git a/packages/diracx-web-components/components/shared/DataTable.stories.tsx b/packages/diracx-web-components/components/shared/DataTable.stories.tsx index 4db01c0f..207b03a8 100644 --- a/packages/diracx-web-components/components/shared/DataTable.stories.tsx +++ b/packages/diracx-web-components/components/shared/DataTable.stories.tsx @@ -1,122 +1,96 @@ import React from "react"; -import { StoryObj, Meta } from "@storybook/react"; -import { useArgs } from "@storybook/core/preview-api"; -import { ThemeProvider as MUIThemeProvider } from "@mui/material/styles"; -import { useMUITheme } from "../../hooks/theme"; -import { DataTable } from "./DataTable"; +import { Meta, StoryObj } from "@storybook/react"; +import { + createColumnHelper, + getCoreRowModel, + useReactTable, +} from "@tanstack/react-table"; +import { ThemeProvider } from "../../contexts/ThemeProvider"; +import { DataTable, DataTableProps } from "./DataTable"; -const meta = { +interface SimpleItem extends Record { + id: number; + name: string; + email: string; +} + +const columnHelper = createColumnHelper(); + +const columnDefs = [ + columnHelper.accessor("id", { + header: "ID", + meta: { type: "number" }, + }), + columnHelper.accessor("name", { + header: "Name", + meta: { type: "string" }, + }), + columnHelper.accessor("email", { + header: "Email", + meta: { type: "string" }, + }), +]; + +const data: SimpleItem[] = [ + { id: 1, name: "John Doe", email: "john@example.com" }, +]; + +// Wrapper component to initialize the table +const DataTableWrapper: React.FC, "table">> = ( + props, +) => { + const table = useReactTable({ + data, + columns: columnDefs, + getCoreRowModel: getCoreRowModel(), + }); + + return {...props} table={table} />; +}; + +const meta: Meta = { title: "shared/DataTable", - component: DataTable, + component: DataTableWrapper, parameters: { layout: "centered", }, tags: ["autodocs"], argTypes: { title: { control: "text" }, - page: { control: "number" }, - setPage: { control: false }, - rowsPerPage: { control: "number" }, - setRowsPerPage: { control: false }, - order: { control: "radio" }, - setOrder: { control: false }, - orderBy: { control: "text" }, - setOrderBy: { control: false }, + table: { control: false, description: "tan stack `Table`", required: true }, totalRows: { control: "number" }, - selected: { control: "object" }, - setSelected: { control: false }, - filters: { control: "object" }, - setFilters: { control: false }, + searchBody: { control: false }, setSearchBody: { control: false }, - columns: { control: "object" }, - rows: { control: "object" }, error: { control: "text" }, isValidating: { control: "boolean" }, isLoading: { control: "boolean" }, - rowIdentifier: { control: "text" }, - isMobile: { control: "boolean" }, toolbarComponents: { control: false }, menuItems: { control: "object" }, }, - args: {}, decorators: [ - (Story) => { - const theme = useMUITheme(); - return ( - + (Story) => ( + +
- - ); - }, +
+
+ ), ], -} satisfies Meta; +}; export default meta; type Story = StoryObj; export const Default: Story = { - decorators: [ - (Story) => ( -
- -
- ), - ], args: { title: "Data Table", - page: 0, - setPage: () => {}, - rowsPerPage: 25, - setRowsPerPage: () => {}, - order: "asc", - setOrder: () => {}, - orderBy: "id", - setOrderBy: () => {}, - totalRows: 1, - selected: [], - setSelected: () => {}, - filters: [], - setFilters: () => {}, + totalRows: data.length, + searchBody: { sort: [{ parameter: "id", direction: "asc" }] }, setSearchBody: () => {}, - columns: [ - { id: "id", label: "ID" }, - { id: "name", label: "Name" }, - { id: "email", label: "Email" }, - ], - rows: [{ id: 1, name: "John Doe", email: "john@example.com" }], - error: "", + error: null, isValidating: false, isLoading: false, - rowIdentifier: "id", - isMobile: false, toolbarComponents: <>, menuItems: [{ label: "Edit", onClick: () => {} }], }, - render: (props) => { - const [, updateArgs] = useArgs(); - props.setPage = (newPage) => { - if (typeof newPage === "function") newPage = newPage(props.page); - updateArgs({ page: newPage }); - }; - props.setRowsPerPage = (newRowsPerPage) => { - if (typeof newRowsPerPage === "function") - newRowsPerPage = newRowsPerPage(props.rowsPerPage); - updateArgs({ rowsPerPage: newRowsPerPage }); - }; - props.setOrder = (newOrder) => { - if (typeof newOrder === "function") newOrder = newOrder(props.order); - updateArgs({ order: newOrder }); - }; - props.setOrderBy = (newOrderBy) => { - if (typeof newOrderBy === "function") - newOrderBy = newOrderBy(props.orderBy); - updateArgs({ orderBy: newOrderBy }); - }; - props.setSelected = (newSelected) => { - if (typeof newSelected === "function") - newSelected = newSelected(props.selected); - updateArgs({ selected: newSelected }); - }; - return ; - }, }; diff --git a/packages/diracx-web-components/components/shared/DataTable.tsx b/packages/diracx-web-components/components/shared/DataTable.tsx index 05611e83..01757e0b 100644 --- a/packages/diracx-web-components/components/shared/DataTable.tsx +++ b/packages/diracx-web-components/components/shared/DataTable.tsx @@ -1,5 +1,11 @@ "use client"; -import React from "react"; +import React, { + useCallback, + useContext, + useEffect, + useMemo, + useState, +} from "react"; import { alpha } from "@mui/material/styles"; import Box from "@mui/material/Box"; import Table from "@mui/material/Table"; @@ -12,25 +18,27 @@ import TableRow from "@mui/material/TableRow"; import TableSortLabel from "@mui/material/TableSortLabel"; import Paper from "@mui/material/Paper"; import Checkbox from "@mui/material/Checkbox"; -import { visuallyHidden } from "@mui/utils"; import Toolbar from "@mui/material/Toolbar"; import Typography from "@mui/material/Typography"; import Tooltip from "@mui/material/Tooltip"; import IconButton from "@mui/material/IconButton"; -import { FormatListBulleted } from "@mui/icons-material"; +import { FormatListBulleted, Visibility } from "@mui/icons-material"; import { Alert, Menu, MenuItem, + Popover, Skeleton, Snackbar, Stack, + Switch, + useMediaQuery, + useTheme, } from "@mui/material"; -import { cyan } from "@mui/material/colors"; +import { flexRender, Row, Table as TanstackTable } from "@tanstack/react-table"; import { TableComponents, TableVirtuoso } from "react-virtuoso"; import { FilterToolbar } from "./FilterToolbar"; import { InternalFilter } from "@/types/Filter"; -import { Column } from "@/types/Column"; import { useSearchParamsUtils } from "@/hooks/searchParamsUtils"; import { ApplicationsContext } from "@/contexts/ApplicationsProvider"; import { DashboardGroup, SearchBody } from "@/types"; @@ -50,8 +58,9 @@ export interface MenuItem { * @property {number[]} selectedIds - the ids of the selected rows * @property {function} clearSelected - the function to call when the selected rows are cleared */ -interface DataTableToolbarProps { +interface DataTableToolbarProps> { title: string; + table: TanstackTable; numSelected: number; selectedIds: readonly number[]; toolbarComponents: JSX.Element; @@ -61,9 +70,26 @@ interface DataTableToolbarProps { * Data table toolbar component * @param {DataTableToolbarProps} props - the props for the component */ -function DataTableToolbar(props: DataTableToolbarProps) { - const { title, numSelected, selectedIds, toolbarComponents } = props; - const [snackbarOpen, setSnackbarOpen] = React.useState(false); +function DataTableToolbar>({ + title, + table, + numSelected, + selectedIds, + toolbarComponents, +}: DataTableToolbarProps) { + const [snackbarOpen, setSnackbarOpen] = useState(false); + const [anchorEl, setAnchorEl] = useState(null); + + const handleVisibilityClick = (event: React.MouseEvent) => { + setAnchorEl(event.currentTarget); + }; + + const handlePopoverClose = () => { + setAnchorEl(null); + }; + + const open = Boolean(anchorEl); + const id = open ? "simple-popover" : undefined; /** * Handle the copy of the selected IDs @@ -87,7 +113,10 @@ function DataTableToolbar(props: DataTableToolbarProps) { sx={{ ...(numSelected > 0 && { bgcolor: (theme) => - alpha(cyan[500], theme.palette.action.activatedOpacity), + alpha( + theme.palette.secondary.main, + theme.palette.action.activatedOpacity, + ), }), }} > @@ -121,12 +150,51 @@ function DataTableToolbar(props: DataTableToolbarProps) { open={snackbarOpen} autoHideDuration={6000} onClose={() => setSnackbarOpen(false)} - message="Job IDs copied to clipboard" + message="IDs copied to clipboard" /> {toolbarComponents} ) : ( - <> + + + + + + + + + + + + {table.getAllLeafColumns().map((column) => ( + + + {String(column.columnDef.header)} + + ))} + + + + + )} ); @@ -135,68 +203,33 @@ function DataTableToolbar(props: DataTableToolbarProps) { /** * Data table props * @property {string} title - the title of the table - * @property {number} page - the current page - * @property {function} setPage - the function to call when the page changes - * @property {number} rowsPerPage - the number of rows per page - * @property {function} setRowsPerPage - the function to call when the rows per page change - * @property {number[]} selected - the selected rows - * @property {function} setSelected - the function to call when the selected rows change - * @property {Filter[]} filters - the filters to apply - * @property {function} setFilters - the function to call when the filters change + * @property {TanstackTable} table - the table + * @property {number} totalRows - the total number of rows + * @property {number} searchBody - the search body to send along with the request * @property {function} setSearchBody - the function to call when the search body changes - * @property {Column[]} columns - the columns of the table + * @property {Column[]} columns - the columns of the table * @property {T[]} rows - the rows of the table * @property {string | null} error - the error message - * @property {string} rowIdentifier - the identifier for the rows - * @property {boolean} isMobile - whether the table is displayed on a mobile device * @property {JSX.Element} toolbarComponents - the components to display in the toolbar * @property {MenuItem[]} menuItems - the menu items */ -interface DataTableProps> { +export interface DataTableProps> { /** The title of the table */ title: string; - /** The current page */ - page: number; - /** The function to call when the page changes */ - setPage: React.Dispatch>; - /** The number of rows per page */ - rowsPerPage: number; - /** The function to call when the rows per page change */ - setRowsPerPage: React.Dispatch>; - /** The order of the table, either "asc" or "desc" */ - order: "asc" | "desc"; - /** The function to call when the order changes */ - setOrder: React.Dispatch>; - /** The column to order by */ - orderBy: string | number; - /** The function to call when the order by changes */ - setOrderBy: React.Dispatch>; + /** The table */ + table: TanstackTable; /** The total number of rows */ totalRows: number; - /** The selected rows */ - selected: readonly number[]; - /** The function to call when the selected rows change */ - setSelected: React.Dispatch>; - /** The filters to apply */ - filters: InternalFilter[]; - /** The function to call when the filters change */ - setFilters: React.Dispatch>; + /** The search body to send along with the request */ + searchBody: SearchBody; /** The function to call when the search body changes */ setSearchBody: React.Dispatch>; - /** The columns of the table */ - columns: Column[]; - /** The rows of the table */ - rows: T[]; /** The error message */ error: string | null; /** Whether the table is validating */ isValidating: boolean; /** Whether the table is loading */ isLoading: boolean; - /** The identifier for the rows */ - rowIdentifier: keyof T; - /** Whether the table is displayed on a mobile device */ - isMobile: boolean; /** The components to display in the toolbar */ toolbarComponents: JSX.Element; /** The context menu items */ @@ -208,48 +241,38 @@ interface DataTableProps> { * * @returns a DataTable component */ -export function DataTable>( - props: DataTableProps, -) { - const { - title, - page, - setPage, - rowsPerPage, - setRowsPerPage, - order, - setOrder, - orderBy, - setOrderBy, - totalRows, - selected, - setSelected, - filters, - setFilters, - setSearchBody, - columns, - rows, - error, - isLoading, - isValidating, - rowIdentifier, - isMobile, - toolbarComponents, - menuItems, - } = props; +export function DataTable>({ + title, + table, + totalRows, + searchBody, + setSearchBody, + error, + isLoading, + isValidating, + toolbarComponents, + menuItems, +}: DataTableProps) { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + // State for the context menu - const [contextMenu, setContextMenu] = React.useState<{ + const [contextMenu, setContextMenu] = useState<{ mouseX: number | null; mouseY: number | null; id: number | null; }>({ mouseX: null, mouseY: null, id: null }); + + // State for the search parameters const { getParam, setParam } = useSearchParamsUtils(); const appId = getParam("appId"); + // State for filters + const [filters, setFilters] = useState([]); const [appliedFilters, setAppliedFilters] = - React.useState(filters); + useState(filters); - const updateFiltersAndUrl = React.useCallback( + const updateFiltersAndUrl = useCallback( (newFilters: InternalFilter[]) => { // Update the filters in the URL using the setParam function setParam( @@ -263,9 +286,9 @@ export function DataTable>( [setParam], ); - const [userDashboard, setUserDashboard] = - React.useContext(ApplicationsContext); - const updateGroupFilters = React.useCallback( + // State for the user dashboard + const [userDashboard, setUserDashboard] = useContext(ApplicationsContext); + const updateGroupFilters = useCallback( (newFilters: InternalFilter[]) => { const appId = getParam("appId"); @@ -299,17 +322,30 @@ export function DataTable>( value: filter.value, values: filter.values, })); - setSearchBody({ search: jsonFilters }); - setPage(0); + setSearchBody((prevState) => ({ + ...prevState, + search: jsonFilters, + })); + table.setPageIndex(0); setAppliedFilters(filters); - // Update the filters in the URL updateFiltersAndUrl(filters); - // Update the filters in the groups updateGroupFilters(filters); }; - const DashboardItem = React.useMemo( + const handleRemoveAllFilters = useCallback(() => { + setSearchBody((prevState) => ({ + ...prevState, + search: [], + })); + table.setPageIndex(0); + setAppliedFilters([]); + + updateFiltersAndUrl([]); + updateGroupFilters([]); + }, [setFilters]); + + const DashboardItem = useMemo( () => userDashboard .find((group) => group.items.some((item) => item.id === appId)) @@ -317,7 +353,7 @@ export function DataTable>( [appId, userDashboard], ); - React.useEffect(() => { + useEffect(() => { if (DashboardItem?.data) { setFilters(DashboardItem.data); setAppliedFilters(DashboardItem.data); @@ -327,337 +363,343 @@ export function DataTable>( value: filter.value, values: filter.values, })); - setSearchBody({ search: jsonFilters }); + setSearchBody((prevState) => ({ + ...prevState, + search: jsonFilters, + })); } else { setFilters([]); - setSearchBody({ search: [] }); + setSearchBody((prevState) => ({ + ...prevState, + search: [], + })); } }, [DashboardItem?.data, setFilters, setSearchBody]); // Manage sorting - const handleRequestSort = ( - event: React.MouseEvent, - property: string, - ) => { - const isAsc = orderBy === property && order === "asc"; - setOrder(isAsc ? "desc" : "asc"); - setOrderBy(property); - setSearchBody((prevState: SearchBody) => ({ - ...prevState, - sort: [{ parameter: property, direction: isAsc ? "desc" : "asc" }], - })); - }; - - // Manage selection - const handleSelectAllClick = (event: React.ChangeEvent) => { - if (event.target.checked) { - const newSelected = rows.map((n: T) => n[rowIdentifier] as number); - setSelected(newSelected); - return; - } - setSelected([]); - }; - - const handleClick = (event: React.MouseEvent, id: number) => { - const selectedIndex = selected.indexOf(id); - let newSelected: readonly number[] = []; - - if (selectedIndex === -1) { - newSelected = newSelected.concat(selected, id); - } else if (selectedIndex === 0) { - newSelected = newSelected.concat(selected.slice(1)); - } else if (selectedIndex === selected.length - 1) { - newSelected = newSelected.concat(selected.slice(0, -1)); - } else if (selectedIndex > 0) { - newSelected = newSelected.concat( - selected.slice(0, selectedIndex), - selected.slice(selectedIndex + 1), - ); - } - - setSelected(newSelected); - }; + const handleRequestSort = useCallback( + (_event: React.MouseEvent, property: string) => { + const isAsc = + searchBody.sort && + searchBody.sort[0]?.parameter === property && + searchBody.sort[0]?.direction === "asc"; + setSearchBody((prevState: SearchBody) => ({ + ...prevState, + sort: [{ parameter: property, direction: isAsc ? "desc" : "asc" }], + })); + }, + [searchBody, setSearchBody], + ); // Manage pagination - const handleChangePage = (event: unknown, newPage: number) => { - setPage(newPage); - }; - - const handleChangeRowsPerPage = ( - event: React.ChangeEvent, - ) => { - setRowsPerPage(parseInt(event.target.value, 10)); - setPage(0); - }; + const handleChangePage = useCallback( + (_event: unknown, newPage: number) => { + table.setPageIndex(newPage); + }, + [table], + ); - const isSelected = (name: number) => selected.indexOf(name) !== -1; + const handleChangeRowsPerPage = useCallback( + (event: React.ChangeEvent) => { + table.setPageSize(Number(event.target.value)); + table.setPageIndex(0); + }, + [table], + ); // Manage context menu - const handleContextMenu = (event: React.MouseEvent, id: number) => { - event.preventDefault(); // Prevent default context menu - setContextMenu({ - mouseX: event.clientX - 2, - mouseY: event.clientY - 4, - id, - }); - }; + const handleContextMenu = useCallback( + (event: React.MouseEvent, id: number) => { + event.preventDefault(); + setContextMenu({ + mouseX: event.clientX - 2, + mouseY: event.clientY - 4, + id, + }); + }, + [], + ); - const handleCloseContextMenu = () => { + const handleCloseContextMenu = useCallback(() => { setContextMenu({ mouseX: null, mouseY: null, id: null }); - }; - - // Virtuoso table components: https://virtuoso.dev/ - // Used to render large tables with virtualization, which improves performance - interface TableContextProps { - rowIdentifier: keyof T; - handleClick: (event: React.MouseEvent, id: number) => void; - handleContextMenu: (event: React.MouseEvent, id: number) => void; - isSelected: (id: number) => boolean; - isMobile: boolean; - } - - interface TableRowProps { - item: T; - context?: TableContextProps; - "data-index"?: number; - } - - const VirtuosoTableComponents: TableComponents = { - Scroller: React.forwardRef(function Scroller(props, ref) { - return ; - }), - Table: function VirtuosoTable(props) { - const { isMobile } = props.context as TableContextProps; - return ( + }, []); + + // Virtualizer + const VirtuosoTableComponents: TableComponents, unknown> = useMemo( + () => ({ + Scroller: React.forwardRef(function Scroller(props, ref) { + return ; + }), + Table: (props) => ( - ); - }, - TableHead: React.forwardRef( - function VirtuosoTableHead(props, ref) { - return ; - }, - ), - TableRow: function VirtuosoTableRow(props: TableRowProps) { - const { item, context } = props; - - if (!context) { - return ; - } - - const { rowIdentifier, handleClick, handleContextMenu, isSelected } = - context || {}; - - const itemId = item[rowIdentifier]; - if (typeof itemId !== "number") { - return ; - } - - return ( + ), + TableHead: React.forwardRef( + function TableHeadRef(props, ref) { + return ; + }, + ), + TableRow: ({ item, ...props }) => ( handleClick(event, itemId)} - role="checkbox" - aria-checked={isSelected(itemId)} - tabIndex={-1} - key={itemId} - selected={isSelected(itemId)} - onContextMenu={(event) => handleContextMenu(event, itemId)} + key={item.id} + onClick={() => item.toggleSelected()} style={{ cursor: "context-menu" }} + onContextMenu={(event) => handleContextMenu(event, Number(item.id))} + {...props} /> - ); - }, - TableBody: React.forwardRef( - function VirtuosoTableBody(props, ref) { - return ; - }, - ), - }; + ), + TableBody: React.forwardRef( + function TableBodyRef(props, ref) { + return ; + }, + ), + }), + [handleContextMenu], + ); // Wait for the data to load - if (isValidating || isLoading) { - return ( - <> - - - - - - ); - } - - // Handle errors - if (error) { - return ( - <> - - - - An error occurred while fetching data. Reload the page. - - - - ); - } + const rows = table.getRowModel().rows; // Handle no data - if (!rows || rows.length === 0) { + const noData = !rows || rows.length === 0; + + if (isValidating || isLoading || error || noData) { return ( <> - - No data or no results match your filters. - + {isValidating || isLoading ? ( + + ) : error ? ( + + An error occurred while fetching data. Reload the page. + + ) : ( + + No data or no results match your filters. + + )} ); } + const checkboxWidth = 50; + return ( - + - + - - - data={rows} - components={VirtuosoTableComponents} - context={{ - rowIdentifier, - handleClick, - handleContextMenu, - isSelected, - isMobile, - }} - fixedHeaderContent={() => { - const createSortHandler = - (property: string) => (event: React.MouseEvent) => { - handleRequestSort(event, property); - }; - - return ( - - + ( + <> + {table.getHeaderGroups().map((headerGroup) => ( + + 0 && selected.length < rows.length + table.getIsSomeRowsSelected() && + !table.getIsAllRowsSelected() } - checked={ - rows.length > 0 && selected.length === rows.length - } - onChange={handleSelectAllClick} - inputProps={{ "aria-label": "select all items" }} + checked={table.getIsAllRowsSelected()} + onChange={table.getToggleAllRowsSelectedHandler()} /> - {columns.map((headCell) => ( + {headerGroup.headers.map((header) => ( - - {headCell.label} - {orderBy === headCell.id ? ( - - {order === "desc" - ? "sorted descending" - : "sorted ascending"} - - ) : null} - + {header.isPlaceholder ? null : ( + + handleRequestSort(event, header.id) + } + data-testid={`sort-${header.id}`} + > + {flexRender( + header.column.columnDef.header, + header.getContext(), + )} + + )} + {header.column.getCanResize() && ( + + )} ))} - ); - }} - itemContent={(index: number, row: T) => { - const isItemSelected = isSelected(row[rowIdentifier] as number); - const labelId = `enhanced-table-checkbox-${index}`; - - return ( - <> - - - - {columns.map((column) => { - const cellValue = row[column.id]; - return ( - - {column.render - ? column.render(cellValue) - : String(cellValue)} - - ); - })} - - ); - }} - /> - + ))} + + )} + itemContent={(_index, row: Row) => ( + <> + + + + {row.getVisibleCells().map((cell) => ( + + {flexRender(cell.column.columnDef.cell, cell.getContext())} + + ))} + + )} + /> { + id: number; + name: string; + email: string; +} + +const columnHelper = createColumnHelper(); + +const columnDefs = [ + columnHelper.accessor("id", { + header: "ID", + meta: { type: "number" }, + }), + columnHelper.accessor("name", { + header: "Name", + meta: { type: "string" }, + }), + columnHelper.accessor("email", { + header: "Email", + meta: { type: "string" }, + }), +]; + +const data: SimpleItem[] = [ + { id: 1, name: "John Doe", email: "john@example.com" }, +]; + +// Wrapper component to initialize the table +const FilterFormWrapper: React.FC< + Omit, "columns"> +> = (props) => { + const table = useReactTable({ + data, + columns: columnDefs, + getCoreRowModel: getCoreRowModel(), + }); + + return {...props} columns={table.getAllColumns()} />; +}; const meta = { title: "shared/FilterForm", - component: FilterForm, + component: FilterFormWrapper, parameters: { layout: "centered", }, tags: ["autodocs"], argTypes: { - columns: { control: "object" }, + columns: { + control: false, + description: "`array` of tan stack `Column`", + required: true, + }, filters: { control: "object" }, setFilters: { control: "object" }, handleFilterChange: { control: "object" }, @@ -22,29 +70,23 @@ const meta = { }, decorators: [ (Story) => { - const theme = useMUITheme(); return ( - + - + ); }, ], -} satisfies Meta; +}; export default meta; type Story = StoryObj; export const Default: Story = { args: { - columns: [ - { id: "id", label: "ID" }, - { id: "name", label: "Name" }, - { id: "age", label: "Age" }, - ], - filters: [{ id: 0, column: "id", operator: "eq", value: "1" }], + filters: [{ id: 0, parameter: "id", operator: "eq", value: "1" }], setFilters: () => {}, handleFilterChange: () => {}, handleFilterMenuClose: () => {}, diff --git a/packages/diracx-web-components/components/shared/FilterForm.tsx b/packages/diracx-web-components/components/shared/FilterForm.tsx index 4899d509..5189332d 100644 --- a/packages/diracx-web-components/components/shared/FilterForm.tsx +++ b/packages/diracx-web-components/components/shared/FilterForm.tsx @@ -1,36 +1,32 @@ -import React from "react"; -import { CheckCircle } from "@mui/icons-material"; +import React, { useEffect, useState } from "react"; import { - Box, + Button, FormControl, - IconButton, InputLabel, MenuItem, Select, SelectChangeEvent, Stack, TextField, - Tooltip, - Typography, } from "@mui/material"; import { DateTimePicker, LocalizationProvider } from "@mui/x-date-pickers"; import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"; +import { Column } from "@tanstack/react-table"; import dayjs from "dayjs"; -import { Column } from "@/types/Column"; import { InternalFilter } from "@/types/Filter"; import "dayjs/locale/en-gb"; // needed by LocalizationProvider to format Dates to dd-mm-yyyy /** * Filter form props - * @property {Column[]} columns - the columns on which to filter + * @property {AccessorKeyColumnDef[]} columns - the columns on which to filter * @property {function} handleFilterChange - the function to call when a filter is changed * @property {function} handleFilterMenuClose - the function to call when the filter menu is closed * @property {InternalFilter[]} filters - the filters for the table * @property {number} selectedFilterId - the id of the selected filter */ -interface FilterFormProps { +export interface FilterFormProps> { /** The columns of the data table */ - columns: Column[]; + columns: Column[]; /** The function to call when a filter is changed */ handleFilterChange: (index: number, tempFilter: InternalFilter) => void; /** The function to call when the filter menu is closed */ @@ -48,24 +44,20 @@ interface FilterFormProps { * * @returns a FilterForm component */ -export function FilterForm(props: FilterFormProps) { - const { - columns, - filters, - setFilters, - handleFilterChange, - handleFilterMenuClose, - selectedFilterId, - } = props; - const [tempFilter, setTempFilter] = React.useState( - null, - ); - +export function FilterForm>({ + columns, + filters, + setFilters, + handleFilterChange, + handleFilterMenuClose, + selectedFilterId, +}: FilterFormProps) { + const [tempFilter, setTempFilter] = useState(null); // Find the index using the filter ID const filterIndex = filters.findIndex((f) => f.id === selectedFilterId); // Set the temp filter - React.useEffect(() => { + useEffect(() => { if (filterIndex !== -1) { setTempFilter(filters[filterIndex]); } else { @@ -105,20 +97,20 @@ export function FilterForm(props: FilterFormProps) { const selectedColumn = columns.find((c) => c.id == tempFilter.parameter); - const columnType = selectedColumn?.type; - const isCategory = Array.isArray(columnType); - const isDateTime = columnType === "DateTime"; + const columnType = selectedColumn?.columnDef.meta?.type || "default"; + const isCategory = Array.isArray(selectedColumn?.columnDef.meta?.values); + const isDateTime = columnType === "date"; const isNumber = columnType === "number"; const operatorOptions = { - DateTime: ["last", "gt", "lt"], + date: ["last", "gt", "lt"], category: ["eq", "neq", "in", "not in", "like"], number: ["eq", "neq", "gt", "lt", "in", "not in", "like"], default: ["eq", "neq", "gt", "lt", "like"], }; const defaultOperators = { - DateTime: "last", + date: "last", category: "eq", number: "eq", default: "eq", @@ -136,18 +128,17 @@ export function FilterForm(props: FilterFormProps) { }; const getOperatorType = () => { - if (isDateTime) return "DateTime"; + if (isDateTime) return "date"; if (isCategory) return "category"; if (isNumber) return "number"; return "default"; }; const operatorType = getOperatorType(); - const operators = operatorOptions[operatorType]; const operatorSelector = ( - + Operator + Value ); @@ -258,7 +248,7 @@ export function FilterForm(props: FilterFormProps) { if (isNumber) { if (!["in", "not in", "like"].includes(tempFilter.operator)) { return ( - + + + - - - Edit Filter - - - - Parameter - { + const parameter = e.target.value; + onChange("parameter", parameter); - const column = columns.find((v) => v.id === parameter); - const colType = column?.type; - const typeKey = - colType === "DateTime" - ? "DateTime" - : Array.isArray(colType) - ? "category" - : colType === "number" - ? "number" - : "default"; + const column = columns.find((v) => v.id === parameter); + const colType = column?.columnDef.meta?.type || "default"; + const typeKey = + colType === "date" + ? "date" + : Array.isArray(colType) + ? "category" + : colType === "number" + ? "number" + : "default"; - const defaultOp = defaultOperators[typeKey]; - onChange("operator", defaultOp); - }} - label="Parameter" - labelId="parameter" - data-testid="filter-form-select-parameter" - sx={{ minWidth: 120 }} + const defaultOp = defaultOperators[typeKey]; + onChange("operator", defaultOp); + onChange("value", ""); + }} + label="Parameter" + labelId="parameter" + data-testid="filter-form-select-parameter" + > + {columns.map((column) => ( + - {columns.map((column) => ( - - {column.label} - - ))} - - + {column.columnDef.header?.toString()} + + ))} + + - {operatorSelector} + {operatorSelector} - {valueSelector()} + {valueSelector()} - - applyChanges()} color="success"> - - - - - - + + ); } diff --git a/packages/diracx-web-components/components/shared/FilterToolbar.stories.tsx b/packages/diracx-web-components/components/shared/FilterToolbar.stories.tsx index 9d90c997..3d551f14 100644 --- a/packages/diracx-web-components/components/shared/FilterToolbar.stories.tsx +++ b/packages/diracx-web-components/components/shared/FilterToolbar.stories.tsx @@ -1,60 +1,106 @@ import React from "react"; -import { StoryObj, Meta } from "@storybook/react"; +import { StoryObj } from "@storybook/react"; import { useArgs } from "@storybook/core/preview-api"; -import { ThemeProvider as MUIThemeProvider } from "@mui/material/styles"; import { Paper } from "@mui/material"; -import { useMUITheme } from "../../hooks/theme"; -import { FilterToolbar } from "./FilterToolbar"; +import { + createColumnHelper, + getCoreRowModel, + useReactTable, +} from "@tanstack/react-table"; +import { ThemeProvider } from "../../contexts/ThemeProvider"; +import { FilterToolbar, FilterToolbarProps } from "./FilterToolbar"; + +interface SimpleItem extends Record { + id: number; + name: string; + email: string; +} + +const columnHelper = createColumnHelper(); + +const columnDefs = [ + columnHelper.accessor("id", { + header: "ID", + meta: { type: "number" }, + }), + columnHelper.accessor("name", { + header: "Name", + meta: { type: "string" }, + }), + columnHelper.accessor("email", { + header: "Email", + meta: { type: "string" }, + }), +]; + +const data: SimpleItem[] = [ + { id: 1, name: "John Doe", email: "john@example.com" }, +]; + +// Wrapper component to initialize the table +const FilterToolbarWrapper: React.FC< + Omit, "columns"> +> = (props) => { + const table = useReactTable({ + data, + columns: columnDefs, + getCoreRowModel: getCoreRowModel(), + }); + + return ( + {...props} columns={table.getAllColumns()} /> + ); +}; const meta = { title: "shared/FilterToolbar", - component: FilterToolbar, + component: FilterToolbarWrapper, parameters: { layout: "centered", }, tags: ["autodocs"], argTypes: { - columns: { control: "object" }, + columns: { + control: false, + description: "`array` of tan stack `Column`", + required: true, + }, filters: { control: "object" }, setFilters: { control: "object" }, handleApplyFilters: { control: "object" }, + handleClearFilters: { control: "object" }, }, decorators: [ (Story) => { - const theme = useMUITheme(); return ( - + - + ); }, ], -} satisfies Meta; +}; export default meta; type Story = StoryObj; export const Default: Story = { args: { - columns: [ - { id: "id", label: "ID" }, - { id: "name", label: "Name" }, - { id: "age", label: "Age" }, - ], filters: [ - { id: 0, column: "id", operator: "eq", value: "1" }, - { id: 1, column: "id", operator: "neq", value: "2" }, + { id: 0, parameter: "id", operator: "eq", value: "1" }, + { id: 1, parameter: "id", operator: "neq", value: "2" }, ], setFilters: () => {}, handleApplyFilters: () => {}, - appliedFilters: [{ id: 0, column: "id", operator: "eq", value: "1" }], + handleClearFilters: () => {}, + appliedFilters: [{ id: 0, parameter: "id", operator: "eq", value: "1" }], }, render: (props) => { const [{ filters }, updateArgs] = useArgs(); props.setFilters = (filters) => updateArgs({ filters }); props.handleApplyFilters = () => updateArgs({ appliedFilters: filters }); - return ; + return ; }, }; diff --git a/packages/diracx-web-components/components/shared/FilterToolbar.tsx b/packages/diracx-web-components/components/shared/FilterToolbar.tsx index 6c29d14d..75ebff3e 100644 --- a/packages/diracx-web-components/components/shared/FilterToolbar.tsx +++ b/packages/diracx-web-components/components/shared/FilterToolbar.tsx @@ -1,20 +1,21 @@ -import React from "react"; -import { FilterList, Delete, Send } from "@mui/icons-material"; +import React, { useCallback, useEffect, useRef, useState } from "react"; +import { grey } from "@mui/material/colors"; +import { FilterList, Delete, Send, Refresh } from "@mui/icons-material"; import Chip from "@mui/material/Chip"; import Button from "@mui/material/Button"; -import { Alert, Popover, Stack, Tooltip } from "@mui/material"; +import { Alert, Box, Popover, Stack, Tooltip } from "@mui/material"; +import { Column } from "@tanstack/react-table"; import { FilterForm } from "./FilterForm"; import { InternalFilter } from "@/types/Filter"; -import { Column } from "@/types/Column"; import "@/hooks/theme"; /** * Filter toolbar component * @param {FilterToolbarProps} props - the props for the component */ -interface FilterToolbarProps { +export interface FilterToolbarProps> { /** The columns of the data table */ - columns: Column[]; + columns: Column[]; /** The filters to apply */ filters: InternalFilter[]; /** The function to set the filters */ @@ -23,6 +24,8 @@ interface FilterToolbarProps { appliedFilters: InternalFilter[]; /** The function to apply the filters */ handleApplyFilters: () => void; + /** The function to remove all filters */ + handleClearFilters: () => void; } /** @@ -30,16 +33,22 @@ interface FilterToolbarProps { * * @returns a FilterToolbar component */ -export function FilterToolbar(props: FilterToolbarProps) { - const { columns, filters, setFilters, appliedFilters, handleApplyFilters } = - props; - const [anchorEl, setAnchorEl] = React.useState(null); - const [selectedFilter, setSelectedFilter] = - React.useState(null); - const addFilterButtonRef = React.useRef(null); +export function FilterToolbar>({ + columns, + filters, + setFilters, + appliedFilters, + handleApplyFilters, + handleClearFilters, +}: FilterToolbarProps) { + const [anchorEl, setAnchorEl] = useState(null); + const [selectedFilter, setSelectedFilter] = useState( + null, + ); + const addFilterButtonRef = useRef(null); // Filter actions - const handleAddFilter = React.useCallback(() => { + const handleAddFilter = useCallback(() => { // Create a new filter: it will not be used // It is just a placeholder to open the filter form const newFilter = { @@ -52,10 +61,6 @@ export function FilterToolbar(props: FilterToolbarProps) { setAnchorEl(addFilterButtonRef.current); }, [setSelectedFilter, setAnchorEl]); - const handleRemoveAllFilters = React.useCallback(() => { - setFilters([]); - }, [setFilters]); - const handleFilterChange = (index: number, newFilter: InternalFilter) => { const updatedFilters = filters.map((filter, i) => i === index ? newFilter : filter, @@ -85,11 +90,11 @@ export function FilterToolbar(props: FilterToolbarProps) { setFilters(filters.filter((_, i) => i !== index)); }; - const changesUnapplied = React.useCallback(() => { + const changesUnapplied = useCallback(() => { return JSON.stringify(filters) !== JSON.stringify(appliedFilters); }, [filters, appliedFilters]); - const isApplied = React.useCallback( + const isApplied = useCallback( (filter: InternalFilter) => { return appliedFilters.some((f) => f.id == filter.id); }, @@ -109,7 +114,7 @@ export function FilterToolbar(props: FilterToolbarProps) { } // Keyboard shortcuts - React.useEffect(() => { + useEffect(() => { const handleKeyPress = (event: KeyboardEvent) => { if (event.altKey && event.shiftKey) { switch (event.key.toLowerCase()) { @@ -126,7 +131,7 @@ export function FilterToolbar(props: FilterToolbarProps) { case "c": event.preventDefault(); event.stopPropagation(); - handleRemoveAllFilters(); + handleClearFilters(); break; default: break; @@ -144,7 +149,7 @@ export function FilterToolbar(props: FilterToolbarProps) { return () => { window.removeEventListener("keydown", debouncedHandleKeyPress); }; - }, [handleAddFilter, handleApplyFilters, handleRemoveAllFilters]); + }, [handleAddFilter, handleApplyFilters, handleClearFilters]); return ( <> @@ -165,11 +170,12 @@ export function FilterToolbar(props: FilterToolbarProps) { @@ -178,7 +184,7 @@ export function FilterToolbar(props: FilterToolbarProps) {