### DataGrid Context Menu: Full Customization Example Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/CONTEXT_MENU_GUIDE.md Demonstrates how to assemble custom cell and header context menus using a selection of individual utility items. It shows how to define menu items with custom logic using `useMemo` and integrate them into the `DataGrid` component. This example highlights the flexibility of picking and choosing specific menu functionalities. ```tsx import { useMemo } from 'react'; import { copyCellItem, copyRowItem, editCellItem, deleteRowItem, cellSeparator, sortAscendingItem, sortDescendingItem, clearSortItem, filterColumnItem, clearFilterItem, pinLeftItem, pinRightItem, unpinColumnItem, hideColumnItem, autoResizeColumnItem, headerSeparator } from './components/data-grid/context-menu-utils'; function MyComponent() { // Pick only what you need for cell context menu const cellItems = useMemo(() => [ copyCellItem(), copyRowItem(), cellSeparator('sep-1'), editCellItem((row, column, value) => { // Custom edit logic handleEdit(row.original, column.id, value); }), deleteRowItem((row) => { // Custom delete logic handleDelete(row.original); }), ], []); // Pick only what you need for header context menu const headerItems = useMemo(() => [ sortAscendingItem(), sortDescendingItem(), clearSortItem(), headerSeparator('sep-1'), filterColumnItem((column) => { openFilterDialog(column.id); }), clearFilterItem(), headerSeparator('sep-2'), hideColumnItem(), autoResizeColumnItem(), ], []); return ( ); } ``` -------------------------------- ### Clone and Run DataGrid Repository Locally Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md Provides a sequence of commands to clone the DataGrid repository, install its dependencies, and start the local development server for direct contribution or in-depth testing. ```bash git clone cd datagrid-shadcn npm install npm run dev ``` -------------------------------- ### DataGrid Server-Side REST API Fetch Example Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/SERVER_SIDE_GUIDE.md Provides an example `fetchData` function demonstrating how to construct a REST API request with query parameters for pagination, sorting, search, and dynamic filters. This function is suitable for integration with a server-side DataGrid implementation's `onDataChange` handler. ```tsx async function fetchData(params) { const queryParams = new URLSearchParams({ page: params.page.toString(), pageSize: params.pageSize.toString(), ...(params.sortBy && { sortBy: params.sortBy }), ...(params.sortOrder && { sortOrder: params.sortOrder }), ...(params.search && { search: params.search }), }); // Add filters params.filters.forEach((filter, index) => { queryParams.append(`filters[${index}][field]`, filter.id); queryParams.append(`filters[${index}][value]`, filter.value); }); const response = await fetch(`/api/users?${queryParams}`); return response.json(); } ``` -------------------------------- ### Start Local Development Server Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md Starts the development server for the DataGrid project, enabling local testing and development. ```bash npm run dev ``` -------------------------------- ### DataGrid Basic Server-Side Operations Implementation Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/SERVER_SIDE_GUIDE.md Illustrates a comprehensive setup for server-side DataGrid operations, including state management for data, loading, and total counts, and an asynchronous `onDataChange` handler to fetch data from a backend based on pagination, sorting, filtering, and search parameters. It requires setting `manualPagination`, `manualSorting`, and `manualFiltering` to true. ```tsx import { useState, useEffect } from 'react'; import { DataGrid, DataChangeParams } from './components/data-grid'; function ServerSideDataGrid() { const [data, setData] = useState([]); const [loading, setLoading] = useState(false); const [totalCount, setTotalCount] = useState(0); const [pageCount, setPageCount] = useState(0); const handleDataChange = async (params: DataChangeParams) => { setLoading(true); try { const response = await fetchData({ page: params.pagination.pageIndex, pageSize: params.pagination.pageSize, sortBy: params.sorting[0]?.id, sortOrder: params.sorting[0]?.desc ? 'desc' : 'asc', filters: params.filters, search: params.globalFilter, }); setData(response.data); setTotalCount(response.totalCount); setPageCount(Math.ceil(response.totalCount / params.pagination.pageSize)); } catch (error) { console.error('Failed to fetch data:', error); } finally { setLoading(false); } }; return ( ); } ``` -------------------------------- ### Install DataGrid from Local Development Server Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md Installs the DataGrid component into another project from a locally running development server, useful for testing local changes against a local registry. ```bash npx shadcn@latest add http://localhost:5173/r/data-grid.json ``` -------------------------------- ### Custom DataGrid Registry URL Example Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md An example URL for a custom-deployed DataGrid registry, indicating where it would be accessible after deployment to a static hosting service. ```bash https://your-domain.com/r/data-grid.json ``` -------------------------------- ### Install DataGrid Manual Dependencies Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md Installs the core dependencies required for the DataGrid component, including TanStack Table, React Virtual, and various UI utilities, using npm. ```bash npm install @tanstack/react-table @tanstack/react-virtual lucide-react class-variance-authority clsx tailwind-merge ``` -------------------------------- ### Install Required shadcn UI Components Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md Installs additional shadcn/ui components that the DataGrid depends on, such as button, checkbox, and input, using the shadcn CLI. ```bash npx shadcn@latest add button checkbox input select context-menu dropdown-menu ``` -------------------------------- ### DataGrid Mixed Client-Server Operations Configuration Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/SERVER_SIDE_GUIDE.md Shows how to configure DataGrid to use a mix of server-side and client-side operations. This example enables server-side pagination and sorting by setting their respective `manual` props to `true`, while keeping filtering client-side by setting `manualFiltering` to `false`. ```tsx ``` -------------------------------- ### Install DataGrid Component with shadcn CLI Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md Installs the DataGrid component into your project using the shadcn CLI, which is the recommended method. This command works with various package managers like npm, yarn, pnpm, and bun. ```bash npx shadcn@latest add https://datagrid-shadcn.netlify.app/r/data-grid.json ``` -------------------------------- ### Optimizing DataGrid Search Input with Debouncing Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/SERVER_SIDE_GUIDE.md This example illustrates how to apply debouncing to the `onDataChange` event of a DataGrid using `useDebouncedCallback` from `use-debounce`. This technique prevents excessive API calls during rapid user input, such as typing in a search bar, by delaying the state update until a specified period of inactivity. ```tsx import { useDebouncedCallback } from 'use-debounce'; function OptimizedDataGrid() { const [params, setParams] = useState(initialParams); const debouncedDataChange = useDebouncedCallback( (newParams: DataChangeParams) => { setParams(newParams); }, 300 // 300ms debounce for search ); return ( ); } ``` -------------------------------- ### Basic DataGrid Component Usage Example Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md Demonstrates the fundamental usage of the DataGrid component in a React application, including defining columns, actions, and rendering the component with basic features like row selection, sorting, global filtering, and pagination. ```tsx import { DataGrid, DataGridColumn, DataGridAction } from './components/data-grid' interface User { id: string firstName: string lastName: string email: string role: string status: 'active' | 'inactive' | 'pending' } const columns: DataGridColumn[] = [ { id: 'firstName', header: 'First Name', accessorKey: 'firstName', enableSorting: true, enableFiltering: true, }, { id: 'email', header: 'Email', accessorKey: 'email', enableSorting: true, enableFiltering: true, }, // ... more columns ] const actions: DataGridAction[] = [ { id: 'delete', label: 'Delete Selected', icon: , variant: 'destructive', onClick: (selectedRows) => { // Handle delete action }, isEnabled: (selectedRows) => selectedRows.length > 0, }, // ... more actions ] function App() { return ( ) } ``` -------------------------------- ### DataGrid Context Menu: Using Convenience Bundles Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/CONTEXT_MENU_GUIDE.md Illustrates the use of pre-configured common item bundles for DataGrid context menus, providing a quick way to include standard functionalities. It also shows how to combine these bundles with custom menu items for extended flexibility. Requires `commonCellItems` and `commonHeaderItems` from `context-menu-utils`. ```tsx import { commonCellItems, commonHeaderItems } from './context-menu-utils'; // Use pre-configured common items const cellItems = commonCellItems(); const headerItems = commonHeaderItems(); // Or mix with custom items const cellItems = [ ...commonCellItems(), cellSeparator('custom-sep'), customMenuItem(), ]; ``` -------------------------------- ### DataGrid Client-Side Operations Configuration Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/SERVER_SIDE_GUIDE.md Demonstrates the default client-side configuration for DataGrid, where sorting, pagination, and filtering are handled by the component itself without server interaction. No additional props are needed for client-side functionality beyond enabling the features. ```tsx ``` -------------------------------- ### Complete DataGrid Cell Editing Configuration Example Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/docs/cell-editing.md Provides a comprehensive example of the `CellEditConfig` object for a DataGrid, showcasing various options like enabling editing, setting the edit mode, specifying a custom component, defining placeholders, implementing validation, handling save and cancel actions, and conditionally disabling editing. ```tsx const editConfig: CellEditConfig = { enabled: true, mode: 'click', component: TextEditInput, placeholder: 'Enter value...', validate: (value, row) => { if (!value) return 'Required'; return null; }, onSave: async (value, row, column) => { return await saveToServer(value, row.original.id, column.id); }, onCancel: (row, column) => { console.log('Edit cancelled'); }, disabled: (row) => row.original.readonly, }; ``` -------------------------------- ### DataGrid Cell Context Menu: Copy Operations Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/CONTEXT_MENU_GUIDE.md Provides utilities to copy data from DataGrid cells. Includes functions to copy an individual cell's value or an entire row as JSON. Requires `copyCellItem` and `copyRowItem` from `context-menu-utils`. ```tsx import { copyCellItem, copyRowItem } from './context-menu-utils'; // Copy individual cell value copyCellItem() // Copy entire row as JSON copyRowItem() ``` -------------------------------- ### DataGrid Data Caching with React Query Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/SERVER_SIDE_GUIDE.md This snippet demonstrates how to implement data caching for a DataGrid using `@tanstack/react-query`. It shows how to use `useQuery` with `queryKey` and `keepPreviousData` to provide a smoother user experience by displaying stale data while new data is being fetched, and how to configure `staleTime` for cache invalidation. ```tsx import { useQuery } from '@tanstack/react-query'; function CachedDataGrid() { const [params, setParams] = useState(initialParams); const { data, isLoading, error } = useQuery({ queryKey: ['users', params], queryFn: () => fetchUsers(params), keepPreviousData: true, // Keep previous data while loading new staleTime: 5 * 60 * 1000, // 5 minutes }); return ( ); } ``` -------------------------------- ### Configure SelectEditInput Component Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/docs/cell-editing.md Example of configuring SelectEditInput for a column, demonstrating how to create a select component with predefined options using createSelectEditComponent. ```tsx import { createSelectEditComponent } from '@/components/ui/data-grid'; const StatusSelect = createSelectEditComponent([ { value: 'active', label: 'Active' }, { value: 'inactive', label: 'Inactive' }, ]); { enableEditing: { component: StatusSelect, } } ``` -------------------------------- ### Configure TextEditInput Component Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/docs/cell-editing.md Example of configuring TextEditInput as the editing component for a column, including setting a placeholder. ```tsx { enableEditing: { component: TextEditInput, placeholder: 'Enter text...', } } ``` -------------------------------- ### Server-Side DataGrid with GraphQL and Apollo Client Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/SERVER_SIDE_GUIDE.md This snippet demonstrates how to integrate a server-side DataGrid with a GraphQL API using Apollo Client. It defines a GraphQL query for fetching user data with pagination, sorting, searching, and filtering parameters, and shows how to manage state and update query variables based on DataGrid interactions. ```tsx import { gql, useQuery } from '@apollo/client'; const GET_USERS = gql` query GetUsers( $page: Int! $pageSize: Int! $sortBy: String $sortOrder: SortOrder $search: String $filters: [FilterInput!] ) { users( page: $page pageSize: $pageSize sortBy: $sortBy sortOrder: $sortOrder search: $search filters: $filters ) { data { id firstName lastName email role status } totalCount pageCount } } `; function ServerSideDataGrid() { const [params, setParams] = useState({ page: 0, pageSize: 10, sortBy: null, sortOrder: null, search: '', filters: [], }); const { data, loading, error } = useQuery(GET_USERS, { variables: params, }); const handleDataChange = (newParams: DataChangeParams) => { setParams({ page: newParams.pagination.pageIndex, pageSize: newParams.pagination.pageSize, sortBy: newParams.sorting[0]?.id || null, sortOrder: newParams.sorting[0]?.desc ? 'DESC' : 'ASC', search: newParams.globalFilter, filters: newParams.filters, }); }; return ( ); } ``` -------------------------------- ### Configure DataGrid for Server-Side Operations Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md This example shows how to enable server-side pagination, sorting, and filtering for the DataGrid component. By setting "manualPagination", "manualSorting", and "manualFiltering" to true, the component delegates data fetching and manipulation to callback functions. ```tsx { // Fetch data for new page }} onSortingChange={(sorting) => { // Apply sorting on server }} onGlobalFilterChange={(filter) => { // Apply global filter on server }} /> ``` -------------------------------- ### DataGrid Context Menu: Separator Items Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/CONTEXT_MENU_GUIDE.md Provides utility functions to insert visual separators within DataGrid cell and header context menus. Each separator requires a unique ID for proper rendering. Requires `cellSeparator` and `headerSeparator` from `context-menu-utils`. ```tsx import { cellSeparator, headerSeparator } from './context-menu-utils'; // For cell context menus cellSeparator('unique-id') // For header context menus headerSeparator('unique-id') ``` -------------------------------- ### DataGrid Header Context Menu: Column Management Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/CONTEXT_MENU_GUIDE.md Provides comprehensive utilities for managing DataGrid columns through header context menus. This includes pinning columns to the left or right, unpinning, hiding, showing, and automatically resizing columns. Requires various column management items from `context-menu-utils`. ```tsx import { pinLeftItem, pinRightItem, unpinColumnItem, hideColumnItem, showColumnItem, autoResizeColumnItem } from './context-menu-utils'; // Pin operations pinLeftItem() pinRightItem() unpinColumnItem() // Visibility hideColumnItem() showColumnItem() // Resize autoResizeColumnItem() ``` -------------------------------- ### Configure DateEditInput Component Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/docs/cell-editing.md Example of configuring DateEditInput as the editing component for a date column. ```tsx { enableEditing: { component: DateEditInput, } } ``` -------------------------------- ### DataGrid DataChangeParams Interface Definition Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/SERVER_SIDE_GUIDE.md Defines the `DataChangeParams` interface, which specifies the structure of the object passed to the `onDataChange` callback for server-side DataGrid operations. It includes parameters for pagination (page index and size), sorting (column ID and direction), filters (column ID and value), and a global search term. ```APIDOC interface DataChangeParams { pagination: { pageIndex: number; // 0-based page index pageSize: number; // Number of rows per page }; sorting: Array<{ id: string; // Column ID desc: boolean; // Sort direction }>; filters: Array<{ id: string; // Column ID value: any; // Filter value }>; globalFilter: string; // Global search term } ``` -------------------------------- ### Configure NumberEditInput Component Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/docs/cell-editing.md Example of configuring NumberEditInput as the editing component for a column, including custom validation for positive numbers. ```tsx { enableEditing: { component: NumberEditInput, validate: (value) => value >= 0 ? null : 'Must be positive', } } ``` -------------------------------- ### Implement Column Hiding/Visibility with TanStack Table and shadcn/ui Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md This snippet details the API and components for managing column visibility. A key consideration is persisting user preferences for column visibility, for example, via localStorage or server-side storage. ```APIDOC TanStack Table API/Hook: column.getIsVisible() column.toggleVisibility() allColumns shadcn/ui Component(s): DropdownMenu with Checkbox items ``` -------------------------------- ### Configure CheckboxEditInput Component Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/docs/cell-editing.md Example of configuring CheckboxEditInput as the editing component for a boolean column. ```tsx { enableEditing: { component: CheckboxEditInput, } } ``` -------------------------------- ### DataGrid Cell Context Menu: Edit Operations Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/CONTEXT_MENU_GUIDE.md Offers utilities for editing DataGrid cell values. Provides a basic edit function that logs to the console by default, and allows for a custom edit handler to integrate with external dialogs or logic. Requires `editCellItem` from `context-menu-utils`. ```tsx import { editCellItem } from './context-menu-utils'; // Basic edit (logs to console by default) editCellItem() // Custom edit handler editCellItem((row, column, value) => { openEditDialog(row.original, column.id, value); }) ``` -------------------------------- ### Configure EmailEditInput Component Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/docs/cell-editing.md Example of configuring EmailEditInput as the editing component for an email column, including built-in email format validation. ```tsx { enableEditing: { component: EmailEditInput, validate: (value) => /^[^s@]+@[^s@]+\.[^\s@]+$/.test(value) ? null : 'Invalid email', } } ``` -------------------------------- ### DataGrid Header Context Menu: Filtering Operations Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/CONTEXT_MENU_GUIDE.md Offers utilities for filtering DataGrid columns from header context menus. Includes functions to open a filter dialog for a specific column and to clear any existing filters. Requires `filterColumnItem` and `clearFilterItem` from `context-menu-utils`. ```tsx import { filterColumnItem, clearFilterItem } from './context-menu-utils'; // Open filter dialog filterColumnItem((column) => { openFilterDialog(column.id); }) // Clear filter clearFilterItem() ``` -------------------------------- ### DataGrid Header Context Menu: Sorting Operations Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/CONTEXT_MENU_GUIDE.md Provides utilities for sorting DataGrid columns via header context menus. Functions allow for ascending sort, descending sort, and clearing the current sort order. Requires `sortAscendingItem`, `sortDescendingItem`, and `clearSortItem` from `context-menu-utils`. ```tsx import { sortAscendingItem, sortDescendingItem, clearSortItem } from './context-menu-utils'; // Sort ascending sortAscendingItem() // Sort descending sortDescendingItem() // Clear sort clearSortItem() ``` -------------------------------- ### DataGrid Cell Context Menu: Row Operations Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/src/components/data-grid/CONTEXT_MENU_GUIDE.md Includes utilities for performing actions on DataGrid rows. Functions are available for toggling row selection, deleting rows with a custom confirmation handler, and viewing row details by navigating to a specific route. Requires `selectRowItem`, `deleteRowItem`, and `viewRowDetailsItem` from `context-menu-utils`. ```tsx import { selectRowItem, deleteRowItem, viewRowDetailsItem } from './context-menu-utils'; // Toggle row selection selectRowItem() // Delete row with custom handler deleteRowItem((row) => { if (confirm(`Delete ${row.original.name}?`)) { deleteUser(row.original.id); } }) // View row details viewRowDetailsItem((row) => { navigate(`/users/${row.original.id}`); }) ``` -------------------------------- ### Run DataGrid Component Tests Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md Provides commands to execute tests for the DataGrid component, including options for running all tests, generating coverage reports, and running tests in watch mode for continuous development. ```bash # Run tests npm run test # Run tests with coverage npm run test:coverage # Run tests in watch mode npm run test:watch ``` -------------------------------- ### DataGrid Live Registry URL Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md The URL for the live registry where the DataGrid component is deployed and available for consumption by the shadcn CLI. ```bash https://datagrid-shadcn.netlify.app/r/data-grid.json ``` -------------------------------- ### Build DataGrid Registry Locally Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md Generates local registry files in the `public/r/` directory, which can be used by the shadcn CLI for local development and testing. ```bash npm run registry:build ``` -------------------------------- ### TanStack Virtual Row Virtualization Concepts Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md Explains the core concepts and properties from TanStack Virtual used for implementing row virtualization, optimizing rendering performance for large datasets. ```APIDOC virtualItem.start: number Purpose: The offset from the top (or left) of the scrollable container where the virtual item should be positioned. virtualItem.size: number Purpose: The height (or width) of the virtual item. ``` -------------------------------- ### DataGrid Project Directory Structure Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md Outlines the file and directory organization of the DataGrid component project, detailing the location of main components, UI elements, sample data, utility functions, and application entry points. ```text src/ ├── components/ │ ├── data-grid/ │ │ ├── data-grid.tsx # Main DataGrid component │ │ ├── data-grid-header.tsx # Header component │ │ ├── data-grid-body.tsx # Body component │ │ ├── data-grid-pagination.tsx # Pagination component │ │ ├── data-grid-filters.tsx # Filters component │ │ ├── data-grid-action-dock.tsx # Action dock component │ │ ├── context.tsx # React context │ │ ├── types.ts # TypeScript interfaces │ │ └── index.ts # Exports │ └── ui/ # shadcn/ui components ├── data/ │ └── sample-data.ts # Sample data for demo ├── lib/ │ └── utils.ts # Utility functions ├── App.tsx # Demo application ├── main.jsx # React entry point └── index.css # Global styles ``` -------------------------------- ### Datagrid Contextual Actions API Endpoints Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md Defines the initial set of bulk actions available in the contextual action dock, specifying their descriptions, enabling conditions, and corresponding API endpoints or client-side behaviors. ```APIDOC Action Name: Delete Selected Description: Permanently removes the selected items. Icon: TrashIcon Enabling Condition: At least one row selected. Expected Behavior / API Endpoint: Calls DELETE /api/items with selected item IDs. Action Name: Export Selected Description: Exports the data of selected rows to CSV. Icon: DownloadIcon Enabling Condition: At least one row selected. Expected Behavior / API Endpoint: Triggers client-side CSV generation and download. Action Name: Mark as Processed Description: Updates the status of selected items. Icon: CheckCircleIcon Enabling Condition: At least one row selected; selected items have status 'Pending'. Expected Behavior / API Endpoint: Calls PUT /api/items/status with selected IDs. Action Name: Archive Selected Description: Moves selected items to an archive. Icon: ArchiveIcon Enabling Condition: At least one row selected. Expected Behavior / API Endpoint: Calls POST /api/items/archive with selected IDs. ``` -------------------------------- ### DataGrid Component Props API Reference Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md This section provides a detailed reference for all available props of the DataGrid component. It lists each prop, its type, default value, and a brief description of its functionality, covering data handling, selection, sorting, filtering, pagination, and virtualization. ```APIDOC DataGrid Props: data: TData[] - Array of data objects to display columns: DataGridColumn[] - Column definitions actions: DataGridAction[] - [] - Bulk actions for selected rows enableRowSelection: boolean - false - Enable row selection with checkboxes enableMultiRowSelection: boolean - true - Allow multiple row selection enableSorting: boolean - true - Enable column sorting enableMultiSort: boolean - false - Allow sorting by multiple columns enableGlobalFilter: boolean - true - Enable global search filter enableColumnFilters: boolean - true - Enable per-column filtering enablePagination: boolean - true - Enable pagination pageSize: number - 10 - Number of rows per page pageSizeOptions: number[] - [10, 20, 50, 100] - Available page size options enableVirtualization: boolean - false - Enable row virtualization for large datasets estimateSize: number - 35 - Estimated row height for virtualization isLoading: boolean - false - Show loading state error: string | null - null - Error message to display ``` -------------------------------- ### TanStack Table Client-Side Pagination APIs Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md Outlines the key TanStack Table APIs for managing client-side pagination, enabling navigation and state control for moderate-sized datasets. ```APIDOC table.getCanPreviousPage(): boolean Purpose: Checks if there is a previous page available. table.getCanNextPage(): boolean Purpose: Checks if there is a next page available. table.nextPage(): void Purpose: Navigates to the next page. table.previousPage(): void Purpose: Navigates to the previous page. table.setPageIndex(updater: number | ((old: number) => number)): void Purpose: Sets the current page index. table.getPageCount(): number Purpose: Returns the total number of pages. ``` -------------------------------- ### Implement Pagination with TanStack Table and shadcn/ui Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md This snippet details the API and components for pagination. It supports both client-side and server-side pagination (manualPagination) and emphasizes clear feedback on page changes. ```APIDOC TanStack Table API/Hook: getPaginationRowModel setPageIndex setPageSize getPageCount getCanNextPage getCanPreviousPage shadcn/ui Component(s): Pagination component Select (for page size) ``` -------------------------------- ### shadcn/ui Table Components for Structured Data Display Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md Lists the standard shadcn/ui components used to construct a basic HTML table structure, providing the visual building blocks for the datagrid. ```APIDOC shadcn/ui Table Components: - Component: Description: The main container for the table. - Component: Description: Container for the table's header section. - Component: Description: Container for the table's body rows. - Component: Description: Container for the table's footer section. - Component: Description: Represents a single row within the table body, header, or footer. - Component: Description: Represents a header cell within a in . - Component: Description: Represents a data cell within a in or . ``` -------------------------------- ### Implement Row Virtualization with TanStack Table and shadcn/ui Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md This snippet details the API and components for row virtualization, which is crucial for large datasets. It emphasizes accurately estimating row heights and ensuring a smooth scrolling experience. ```APIDOC TanStack Table API/Hook: useVirtualizer (from @tanstack/react-virtual) integration with getRowModel().rows shadcn/ui Component(s): Scrollable container absolutely positioned TableRow elements ``` -------------------------------- ### Implement Column Resizing with TanStack Table and shadcn/ui Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md This snippet describes the API and components for column resizing. It focuses on providing visual feedback during resize operations and persisting column widths. ```APIDOC TanStack Table API/Hook: columnSizing state header.getResizeHandler() shadcn/ui Component(s): Draggable handles on TableHead borders ``` -------------------------------- ### TanStack Table Server-Side Pagination Configuration Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md Details the configuration options and data requirements for implementing server-side pagination with TanStack Table, where data fetching is managed by the application. ```APIDOC Table Instance Configuration: manualPagination: true Purpose: Configures TanStack Table to handle pagination manually, delegating data fetching to the application. pageCount: number (optional) Purpose: Total number of pages. rowCount: number (optional) Purpose: Total number of items in the dataset. Note: Either pageCount or rowCount should be provided for pagination metadata calculation. ``` -------------------------------- ### Implement Advanced Grouping with TanStack Table and shadcn/ui Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md This snippet describes the API and components for advanced grouping functionality. It highlights performance implications for large grouped datasets and the UI for expand/collapse all actions. ```APIDOC TanStack Table API/Hook: getGroupedRowModel() getExpandedRowModel() row.getToggleExpandedHandler() shadcn/ui Component(s): Custom row renderers for group headers expand/collapse icons (ChevronRightIcon, etc.) ``` -------------------------------- ### TanStack Table Core API Methods for Data Display Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md Describes key methods and utilities from @tanstack/react-table used for accessing structured data for table rendering, including header groups, row models, footer groups, and flexible content rendering. ```APIDOC @tanstack/react-table: - Method: getHeaderGroups() Description: Returns an array of header groups, representing the hierarchical structure of table headers. Returns: Array - Method: getRowModel() Description: Returns the row model, containing all rows and their associated data, ready for rendering. Returns: RowModel - Method: getFooterGroups() Description: Returns an array of footer groups, similar to header groups but for table footers. Returns: Array - Utility: flexRender(content, props) Description: Utility function to flexibly render content (data values or React components) within table headers, cells, or footers. Parameters: - name: content type: any description: The content to render, can be a primitive value or a React component. - name: props type: object description: An object of props to pass to the content if it's a React component. Returns: ReactNode ``` -------------------------------- ### Enable Row Virtualization for Large DataGrid Datasets Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md This snippet demonstrates how to enable row virtualization in the DataGrid component for improved performance with large datasets. Setting "enableVirtualization" to true and providing an "estimateSize" helps optimize rendering by only displaying visible rows. ```tsx ``` -------------------------------- ### Implement Server-Side Data Syncing with TanStack Table Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md This snippet outlines the TanStack Table APIs for server-side data syncing, including manual pagination, sorting, and filtering. It also covers managing loading/error states and debouncing/throttling requests. ```APIDOC TanStack Table API/Hook: manualPagination manualSorting manualFiltering state management for server parameters shadcn/ui Component(s): N/A (Logic for API calls) ``` -------------------------------- ### DataGridAction Interface Definition Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md This defines the "DataGridAction" interface, used for specifying bulk actions that can be performed on selected rows in the DataGrid. It includes properties for action identification, label, optional icon and variant, and a callback function to execute the action, along with visibility and enablement conditions. ```tsx interface DataGridAction { id: string label: string icon?: ReactNode variant?: 'default' | 'destructive' | 'outline' | 'secondary' | 'ghost' | 'link' onClick: (selectedRows: Row[]) => void | Promise isEnabled?: (selectedRows: Row[]) => boolean isVisible?: (selectedRows: Row[]) => boolean } ``` -------------------------------- ### TanStack Table API for Grouping Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md Outlines the TanStack Table APIs relevant for implementing row grouping functionality, including structuring grouped data and managing the expand/collapse state of groups. ```APIDOC TanStack Table API for Grouping: - getGroupedRowModel(): Used for structuring the grouped data. - getExpandedRowModel(): Used for managing the expand/collapse state of groups. ``` -------------------------------- ### Implement Contextual Actions with TanStack Table and shadcn/ui Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md This snippet describes the API and components for enabling contextual actions based on row selection. It covers enabling/disabling actions based on selection, displaying the selected count, and ensuring accessibility of action elements. ```APIDOC TanStack Table API/Hook: getSelectedRowModel() getState().rowSelection shadcn/ui Component(s): Button DropdownMenu custom dock container ``` -------------------------------- ### Implement Column and Global Filtering with TanStack Table and shadcn/ui Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md This snippet outlines the API and components for implementing column and global filtering. Key considerations include debouncing for input-based filters, supporting different filter types based on data, and providing clear visual feedback. ```APIDOC TanStack Table API/Hook: getFilteredRowModel() column.setFilterValue() table.setGlobalFilter() shadcn/ui Component(s): Input Select (within or near headers) ``` -------------------------------- ### Implement Sorting with TanStack Table and shadcn/ui Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md This snippet details the API and components required for implementing sorting functionality. It covers visual indicators for sort state, support for single/multi-column sorting, and accessibility considerations for sort controls. ```APIDOC TanStack Table API/Hook: getSortedRowModel() column.getToggleSortingHandler() shadcn/ui Component(s): TableHead (with click handlers & icons) ``` -------------------------------- ### Implement Multi-Row Selection with TanStack Table and shadcn/ui Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md This snippet outlines the API and components for multi-row selection. Important notes include using getRowId for stable selection and handling the indeterminate state for the header checkbox. ```APIDOC TanStack Table API/Hook: rowSelection state onRowSelectionChange row.getIsSelected() table.getToggleAllRowsSelectedHandler() shadcn/ui Component(s): Checkbox (in header and rows) ``` -------------------------------- ### TanStack Table API for Sorting Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md Describes the TanStack Table APIs used to implement sorting functionality in the datagrid, including accessing sorted data and handling click-to-sort behavior on column headers. ```APIDOC TanStack Table API for Sorting: - getSortedRowModel(): Used for accessing the sorted row data. - column.getToggleSortingHandler(): API for implementing the click-to-sort behavior on column headers. ``` -------------------------------- ### Implement Cell Customization with TanStack Table and shadcn/ui Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md This snippet outlines the API and components for customizing cell rendering. It allows for rich data presentation (e.g., badges, avatars, progress bars) and highlights the performance considerations of custom renderers. ```APIDOC TanStack Table API/Hook: flexRender columnDef.cell columnDef.header shadcn/ui Component(s): Custom React components passed to cell/header definitions ``` -------------------------------- ### TanStack Table API for Filtering Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md Details the TanStack Table APIs utilized for implementing filtering capabilities, covering both global and per-column filtering, and managing filter states. ```APIDOC TanStack Table API for Filtering: - getFilteredRowModel(): Provides the filtered data. - column.setFilterValue(value: any): Manages the filter state for a specific column. ``` -------------------------------- ### TanStack Table Column Visibility APIs Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md Describes the TanStack Table APIs used to control column visibility, allowing users to show or hide columns in the datagrid. ```APIDOC column.getIsVisible(): boolean Purpose: Checks if a column is currently visible. column.toggleVisibility(value?: boolean): void Purpose: Toggles the visibility of a column. If a boolean value is provided, sets the visibility to that value. ``` -------------------------------- ### Implement WAI-ARIA Attributes for Datagrid Accessibility Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/data_grid_prd.md This section details the essential WAI-ARIA roles, states, and properties required for the datagrid component to ensure semantic information is provided to assistive technologies. It outlines specific attributes for the grid container, headers, rows, and cells, emphasizing the need for careful integration with shadcn/ui components to maintain and enhance these attributes. ```APIDOC WAI-ARIA Attributes for Datagrid: - role="grid": For the main table container. - role="columnheader": For header cells, with aria-sort to indicate sort status. - role="row": For table rows. - role="gridcell": For data cells. - aria-selected: For selectable rows. - aria-labelledby: To associate labels with interactive elements. - aria-describedby: To associate descriptions with interactive elements. ``` -------------------------------- ### DataGridColumn Interface Definition Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md This defines the "DataGridColumn" interface, specifying the structure for individual column definitions within the DataGrid. It includes properties for column identification, header rendering, data access, cell rendering, and various column behaviors like sorting, filtering, and resizing. ```tsx interface DataGridColumn { id: string header: string | ReactNode accessorKey?: keyof TData cell?: ({ row }: { row: Row }) => ReactNode enableSorting?: boolean enableFiltering?: boolean enableHiding?: boolean enableResizing?: boolean size?: number minSize?: number maxSize?: number } ``` -------------------------------- ### Customize DataGrid Styling with Tailwind CSS Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md This snippet shows how to apply custom styling to the DataGrid component using Tailwind CSS classes. The "className" prop allows for easy modification of the component's appearance through utility classes. ```tsx ``` -------------------------------- ### Create Custom Input Component for DataGrid Cell Editing Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/docs/cell-editing.md Demonstrates how to create a custom input component for DataGrid cell editing by implementing the `CellEditComponentProps` interface. This component manages its own input state, handles keyboard events (Enter to save, Escape to cancel), and triggers save on blur, providing a tailored editing experience. ```tsx import { CellEditComponentProps } from '@/components/ui/data-grid'; function CustomInput({ value, onChange, onSave, onCancel, row, column, placeholder, disabled, autoFocus, }: CellEditComponentProps) { const [inputValue, setInputValue] = useState(value || ''); const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter') { onChange(inputValue); onSave(); } else if (e.key === 'Escape') { onCancel(); } }; return ( setInputValue(e.target.value)} onKeyDown={handleKeyDown} onBlur={() => { onChange(inputValue); onSave(); }} placeholder={placeholder} disabled={disabled} autoFocus={autoFocus} /> ); } ``` -------------------------------- ### Handle Server-Side Persistence for DataGrid Cell Edits Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/docs/cell-editing.md Explains how to implement server-side saving for DataGrid cell edits using the `onCellEdit` callback. This asynchronous function handles API calls to persist changes, updates local state optimistically, and returns `true` for success or `false` for failure, which can trigger error feedback. ```tsx const handleCellEdit = async (value, row, column) => { try { // Make API call const response = await fetch(`/api/users/${row.original.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ [column.accessorKey]: value, }), }); if (!response.ok) { throw new Error('Failed to save'); } // Update local state optimistically updateLocalData(row.original.id, column.accessorKey, value); return true; // Success } catch (error) { console.error('Save failed:', error); return false; // Failure - will show error } }; ``` -------------------------------- ### Customize DataGrid Header Component in React TSX Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/README.md Demonstrates how to replace the default DataGrid header with a custom React component using the `components` prop. The custom component can access the table instance via `useDataGrid()` for advanced customization. ```tsx // Custom header component const CustomHeader = () => { const { table } = useDataGrid() // Custom implementation } // Use in your DataGrid ``` -------------------------------- ### Configure DataGrid Edit Modes and Validation Source: https://github.com/abaktiar/datagrid-shadcn/blob/main/docs/cell-editing.md Shows how to set column-specific edit modes (e.g., doubleClick) and custom validation functions, as well as global DataGrid properties like enableCellEditing and defaultEditMode. ```tsx import { DataGrid, TextEditInput } from '@/components/ui/data-grid'; const columns = [ { id: 'name', accessorKey: 'name', header: 'Name', enableEditing: true, // Simple boolean enables editing with default settings }, { id: 'email', accessorKey: 'email', header: 'Email', enableEditing: { enabled: true, mode: 'doubleClick', component: EmailEditInput, validate: (value) => { const emailRegex = /^[^s@]+@[^s@]+\.[^\s@]+$/; return emailRegex.test(value) ? null : 'Invalid email format'; }, }, }, ]; ```