diff --git a/cypress/e2e/DataView.spec.cy.ts b/cypress/e2e/DataView.spec.cy.ts index 99db58b3..2504ab7b 100644 --- a/cypress/e2e/DataView.spec.cy.ts +++ b/cypress/e2e/DataView.spec.cy.ts @@ -1,17 +1,19 @@ describe('Test the Data view docs page', () => { - + it('displays a layout with a table and paginates', () => { const ouiaId = 'LayoutExample'; + cy.viewport(1400, 2800) - cy.visit('http://localhost:8006/extensions/data-view/layout'); + cy.visit('http://localhost:8006/extensions/data-view/overview'); + cy.get(`[data-ouia-component-id="${ouiaId}-th-0"]`).scrollIntoView().contains('Repository'); cy.get(`[data-ouia-component-id="${ouiaId}Header-pagination"]`).should('exist'); cy.get(`[data-ouia-component-id="${ouiaId}Header-bulk-select"]`).should('exist'); cy.get(`[data-ouia-component-id="${ouiaId}Footer-pagination"]`).should('exist'); cy.get(`[data-ouia-component-id="${ouiaId}Footer-bulk-select"]`).should('not.exist'); - cy.get(`[data-ouia-component-id="${ouiaId}-th-0"]`).contains('Repositories'); + cy.get(`[data-ouia-component-id="${ouiaId}-th-0"]`).contains('Repository'); cy.get(`[data-ouia-component-id="${ouiaId}-th-4"]`).contains('Last commit'); cy.get(`[data-ouia-component-id="${ouiaId}-td-0-0"]`).contains('Repository one'); @@ -27,33 +29,27 @@ describe('Test the Data view docs page', () => { cy.get(`[data-ouia-component-id="${ouiaId}-td-0-4"]`).contains('Timestamp one'); // test bulk select - cy.get(`input[type="checkbox"`).each(($checkbox) => {cy.wrap($checkbox).should('not.be.checked')}); + cy.get(`[data-ouia-component-id="LayoutExample"] input[type="checkbox"]`).each(($checkbox) => {cy.wrap($checkbox).should('not.be.checked')}); // page checkbox select cy.get(`[data-ouia-component-id="BulkSelect-checkbox"`).first().click(); - cy.get(`input[type="checkbox"`).each(($checkbox) => {cy.wrap($checkbox).should('be.checked')}); + cy.get(`[data-ouia-component-id="LayoutExample"] input[type="checkbox"]`).each(($checkbox) => {cy.wrap($checkbox).should('be.checked')}); cy.contains('5 selected').should('exist'); - // select none - cy.get(`[data-ouia-component-id="BulkSelect-toggle"`).first().click({ force: true }); - cy.get(`[data-ouia-component-id="BulkSelect-select-none"`).first().click(); - cy.contains('5 selected').should('not.exist'); - - // select all - cy.get(`[data-ouia-component-id="BulkSelect-toggle"`).first().click({ force: true }); - cy.get(`[data-ouia-component-id="BulkSelect-select-all"`).first().click(); - cy.get(`input[type="checkbox"`).each(($checkbox) => {cy.wrap($checkbox).should('be.checked')}); - cy.contains('6 selected').should('exist'); - // page checkbox deselect cy.get(`[data-ouia-component-id="BulkSelect-checkbox"`).first().click(); - cy.get(`input[type="checkbox"`).each(($checkbox) => {cy.wrap($checkbox).should('not.be.checked')}); - cy.contains('1 selected').should('exist'); + cy.get('[data-ouia-component-id="LayoutExample"] input[type="checkbox"]') + .each(($checkbox) => { + cy.wrap($checkbox).should('not.be.checked'); + }); // select page cy.get(`[data-ouia-component-id="BulkSelect-toggle"`).first().click({ force: true }); cy.get(`[data-ouia-component-id="BulkSelect-select-page"`).first().click(); - cy.get(`input[type="checkbox"`).each(($checkbox) => {cy.wrap($checkbox).should('be.checked')}); - cy.contains('6 selected').should('exist'); + cy.get('[data-ouia-component-id="LayoutExample"] input[type="checkbox"]') + .each(($checkbox) => { + cy.wrap($checkbox).should('be.checked'); + }); + cy.contains('5 selected').should('exist'); }) }); \ No newline at end of file diff --git a/cypress/e2e/DataViewEvents.spec.cy.ts b/cypress/e2e/DataViewEvents.spec.cy.ts index b3035e08..b8104f84 100644 --- a/cypress/e2e/DataViewEvents.spec.cy.ts +++ b/cypress/e2e/DataViewEvents.spec.cy.ts @@ -3,7 +3,7 @@ describe('Test the Data view docs page', () => { it('displays a table and opens detail', () => { const ouiaId = 'ContextExample'; - cy.visit('http://localhost:8006/extensions/data-view/events-context'); + cy.visit('http://localhost:8006/extensions/data-view/overview'); cy.get(`[data-ouia-component-id="${ouiaId}-th-0"]`).contains('Repositories'); cy.get(`[data-ouia-component-id="${ouiaId}-th-4"]`).contains('Last commit'); diff --git a/cypress/e2e/Components.spec.cy.ts b/cypress/e2e/TreeTable.spec.cy.ts similarity index 97% rename from cypress/e2e/Components.spec.cy.ts rename to cypress/e2e/TreeTable.spec.cy.ts index 765da5f6..e03ffafc 100644 --- a/cypress/e2e/Components.spec.cy.ts +++ b/cypress/e2e/TreeTable.spec.cy.ts @@ -3,7 +3,7 @@ describe('Test the Data view docs with tree table', () => { it('displays a a components page with tree table', () => { const ouiaId = 'TreeTableExample'; - cy.visit('http://localhost:8006/extensions/data-view/components'); + cy.visit('http://localhost:8006/extensions/data-view/table'); cy.get(`[data-ouia-component-id="${ouiaId}-th-0"]`).scrollIntoView().contains('Repositories'); cy.get(`[data-ouia-component-id="${ouiaId}-th-1"]`).contains('Branches'); diff --git a/package-lock.json b/package-lock.json index 7de73eef..9e89670e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12585,6 +12585,7 @@ "version": "7.6.2", "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-7.6.2.tgz", "integrity": "sha512-9FhUxK1hVju2+AiQIDJ5Dd//9R2n2RAfJ0qfhF4IHGHgcoEUTMpbTeG/zbEuwaiYXfuAH6XE0/aCyxDdRM+W5w==", + "license": "MIT", "dependencies": { "tabbable": "^6.2.0" } diff --git a/packages/module/patternfly-docs/content/extensions/data-view/about-data-view.md b/packages/module/patternfly-docs/content/extensions/data-view/about-data-view.md deleted file mode 100644 index 0fd1b95e..00000000 --- a/packages/module/patternfly-docs/content/extensions/data-view/about-data-view.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -section: extensions -subsection: Data view -id: About data view -sortValue: 1 ---- - -Data view lives in its own package [`@patternfly/react-data-view`](https://www.npmjs.com/package/@patternfly/react-data-view) - -# Data view - -The data view extension contains implementation of the data view component allowing to display record data in a configured layout. - -If you notice a bug or have a suggestion for the data view, feel free to file an issue in our [GitHub repository](https://github.com/patternfly/react-data-view/issues)! Please make sure to check if there is already a pre-existing issue before creating a new issue. diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Components/Components.md b/packages/module/patternfly-docs/content/extensions/data-view/examples/Components/Components.md deleted file mode 100644 index 628ecd3f..00000000 --- a/packages/module/patternfly-docs/content/extensions/data-view/examples/Components/Components.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -# Sidenav top-level section -# should be the same for all markdown files -section: extensions -subsection: Data view -# Sidenav secondary level section -# should be the same for all markdown files -id: Components -# Tab (react | react-demos | html | html-demos | design-guidelines | accessibility) -source: react -# If you use typescript, the name of the interface to display props for -# These are found through the sourceProps function provided in patternfly-docs.source.js -sortValue: 4 -propComponents: ['DataViewToolbar', 'DataViewTableBasic', 'DataViewTableTree', 'DataViewTrTree', 'DataViewTrObject'] -sourceLink: https://github.com/patternfly/react-data-view/blob/main/packages/module/patternfly-docs/content/extensions/data-view/examples/Components/Components.md ---- -import { Button, EmptyState, EmptyStateActions, EmptyStateBody, EmptyStateFooter } from '@patternfly/react-core'; -import { CubesIcon, FolderIcon, FolderOpenIcon, LeafIcon, ExclamationCircleIcon } from '@patternfly/react-icons'; -import { BulkSelect, ErrorState, ResponsiveAction, ResponsiveActions, SkeletonTableHead, SkeletonTableBody } from '@patternfly/react-component-groups'; -import { DataViewToolbar } from '@patternfly/react-data-view/dist/dynamic/DataViewToolbar'; -import { DataViewTable } from '@patternfly/react-data-view/dist/dynamic/DataViewTable'; -import { useDataViewSelection } from '@patternfly/react-data-view/dist/dynamic/Hooks'; -import { DataView, DataViewState } from '@patternfly/react-data-view/dist/dynamic/DataView'; - -## Data view toolbar - -The **data view toolbar** component renders a default opinionated data view toolbar above or below the data section. - -Data view toolbar can contain a `pagination`, `bulkSelect`, `filters`, `actions` or other children content passed. The preffered way of passing children toolbar items is using the [toolbar item](/components/toolbar#toolbar-items) component. - -### Basic toolbar example - -```js file="./DataViewToolbarExample.tsx" - -``` - -# Toolbar actions -Data view toolbar can display actions using the `actions` property accepting a React node. You can make use of a predefined [responsive actions](/extensions/component-groups/responsive-actions) component from the [component groups](/extensions/component-groups/about-component-groups) extension. - -### Actions configuration - -### Actions example - -```js file="./DataViewToolbarActionsExample.tsx" - -``` - -## Data view table - -The **data view table** component renders your columns and rows definition into a [table](/components/table) component. - -### Rows and columns customization - -This example shows possible formats of `rows` and `columns` passed to the `DataViewTable` which allow you various customizations of the table head and body. - -```js file="./DataViewTableExample.tsx" - -``` - -The `DataViewTable` component accepts the following props: - -- `columns` defining the column heads of the table. Each item in the array can be a `ReactNode` (for simple heads) or an object with the following properties: - - `cell` (`ReactNode`) content to display in the column head. - - optional `props` (`ThProps`) to pass to the `` component, such as `width`, `sort`, and other table head cell properties. - -- `rows` defining the rows to be displayed in the table. Each item in the array can be either an array of `DataViewTd` (for simple rows) or an object with the following properties: - - `row` (`DataViewTd[]`) defining the content for each cell in the row. - - optional `id` (`string`) for the row (can be used to match items in selection). - - optional `props` (`TrProps`) to pass to the `` component, such as `isHoverable`, `isRowSelected`, and other table row properties. - -- optional `ouiaId` - -- optional `props` (`TableProps`) that are passed down to the `` component, except for `onSelect`, which is managed internally. - -It is also possible to disable row selection using the `isSelectDisabled` function passed to the wrapping data view component through `selection`. - -### Tree table example -This example shows the tree table variant with expandable rows, custom icons for leaf and parent nodes. Tree table is turned on by passing `isTreeTable` flag to the `DataViewTable` component. You can pass `collapsedIcon`, `expandedIcon` or `leafIcon` to be displayen rows with given status. The tree table rows have to be defined in a format of object with following keys: - - `row` (`DataViewTd[]`) defining the content for each cell in the row. - - `id` (`string`) for the row (used to match items in selection end expand the rows). - - optional `children` (`DataViewTrTree[]`) defining the children rows. - -It is also possible to disable row selection using the `isSelectDisabled` function passed to the wrapping data view component through `selection`. - -```js file="./DataViewTableTreeExample.tsx" - -``` - -### Empty state example -The data view table supports displaying a custom empty state. You can pass it using the the `headStates` and `bodyStates` properties and their `empty` key. It will be automatically displayed in case there are no rows to be rendered. - -```js file="./DataViewTableEmptyExample.tsx" - -``` - -### Error state example -The data view table also supports displaying an error state. You can pass it using the the `headStates` and `bodyStates` properties and their `error` key. It will be displayed in case the data view recieves its `state` property set to `error`. - -```js file="./DataViewTableErrorExample.tsx" - -``` - -### Loading state example -The data view table also supports displaying a custom loading state. You can pass it using the `headStates` and `bodyStates` properties and their `loading` key. Your state will be displayed in case the data view recieves its `state` property set to `loading`. - -```js file="./DataViewTableLoadingExample.tsx" - -``` diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewToolbarExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewToolbarExample.tsx deleted file mode 100644 index 2827aab8..00000000 --- a/packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewToolbarExample.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import React from 'react'; -import { Pagination } from '@patternfly/react-core'; -import { BulkSelect } from '@patternfly/react-component-groups'; -import DataViewToolbar from '@patternfly/react-data-view/dist/dynamic/DataViewToolbar'; - - -export const BasicExample: React.FunctionComponent = () => ( - null} - /> - } - pagination={ - - } - /> -) diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Layout/AbstractLayoutExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/DataView/AbstractLayoutExample.tsx similarity index 100% rename from packages/module/patternfly-docs/content/extensions/data-view/examples/Layout/AbstractLayoutExample.tsx rename to packages/module/patternfly-docs/content/extensions/data-view/examples/DataView/AbstractLayoutExample.tsx diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/DataView/DataView.md b/packages/module/patternfly-docs/content/extensions/data-view/examples/DataView/DataView.md new file mode 100644 index 00000000..1642e572 --- /dev/null +++ b/packages/module/patternfly-docs/content/extensions/data-view/examples/DataView/DataView.md @@ -0,0 +1,63 @@ +--- +section: extensions +subsection: Data view +id: Overview +title: Data view overview +propComponents: ['DataView'] +sortValue: 1 +sourceLink: https://github.com/patternfly/react-data-view/blob/main/packages/module/patternfly-docs/content/extensions/data-view/examples/DataView/DataView.md +--- +import { useState, useEffect, useRef, useMemo } from 'react'; +import { Drawer, DrawerContent, DrawerContentBody } from '@patternfly/react-core'; +import { CubesIcon } from '@patternfly/react-icons'; +import { useDataViewPagination, useDataViewSelection, useDataViewFilters, useDataViewSort } from '@patternfly/react-data-view/dist/dynamic/Hooks'; +import { BulkSelect, BulkSelectValue, ErrorState, ResponsiveAction, ResponsiveActions, SkeletonTableHead, SkeletonTableBody } from '@patternfly/react-component-groups'; +import { DataView } from '@patternfly/react-data-view/dist/dynamic/DataView'; +import { DataViewToolbar } from '@patternfly/react-data-view/dist/dynamic/DataViewToolbar'; +import { DataViewTable } from '@patternfly/react-data-view/dist/dynamic/DataViewTable'; +import { useDataViewEventsContext, DataViewEventsContext, DataViewEventsProvider, EventTypes } from '@patternfly/react-data-view/dist/dynamic/DataViewEventsContext'; +import { DataViewFilters } from '@patternfly/react-data-view/dist/dynamic/DataViewFilters'; +import { DataViewTextFilter } from '@patternfly/react-data-view/dist/dynamic/DataViewTextFilter'; +import { DataViewCheckboxFilter } from '@patternfly/react-data-view/dist/dynamic/DataViewCheckboxFilter'; + +**Note:** Data view lives in its own package [`@patternfly/react-data-view`](https://www.npmjs.com/package/@patternfly/react-data-view) + +If you notice a bug, or if you have a suggestion for improving the data view extension or its documentation, please file an issue in the [react-data-view](https://github.com/patternfly/react-data-view/issues) repository. Before doing so, please make sure there is not already a pre-existing issue. + +--- + +The **data view** extension enables you to display datasets in organized layouts, with data representations and interactive toolbars for actions like selection and pagination. + +### Layout + +A data view should contain a header, the data representation, and a footer. These parts are organized in a [stack layout](/layouts/stack). + +The data view toolbars and sub-components that display the data (like a card view or table) are always passed as `children` to the `` component. + +```js file="./AbstractLayoutExample.tsx" + +``` + +### Modularity + +The extension's modular architecture lets you efficiently create consistent data views, either by using predefined sub-components and hooks, or by defining your own. You can choose the tools that suit your needs and easily replace any part with a custom implementation. + +The `` component extends the [PatternFly toolbar](/components/toolbar) to support the most common needs. For more details, refer to the [data view toolbar](/extensions/data-view/toolbar) examples. You can also use a custom toolbar component if needed for your use case. + +Data can be presented using the predefined `` component, which is an abstraction above the [PatternFly table](/components/table). For more details, refer to the [data view table](/extensions/data-view/table) examples. If you have more specific data display needs, you can pass a custom implementation as a `` child. In the near future, we are also planning to introduce a predefined card view component. + +```js file="./PredefinedLayoutFullExample.tsx" + +``` + +## Events context + +The `` component is an advanced feature that enables external listening of data view events. In order to share data view context with your other UI components, both your components and your data view should be wrapped with the ``. This is demonstrated in the following example. + +### Row click subscription example +This example uses the `` to display details about a selected row in a [drawer component](/components/drawer). + + +```js file="./EventsExample.tsx" + +``` diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/EventsContext/EventsExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/DataView/EventsExample.tsx similarity index 100% rename from packages/module/patternfly-docs/content/extensions/data-view/examples/EventsContext/EventsExample.tsx rename to packages/module/patternfly-docs/content/extensions/data-view/examples/DataView/EventsExample.tsx diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/DataView/PredefinedLayoutFullExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/DataView/PredefinedLayoutFullExample.tsx new file mode 100644 index 00000000..b4873e9d --- /dev/null +++ b/packages/module/patternfly-docs/content/extensions/data-view/examples/DataView/PredefinedLayoutFullExample.tsx @@ -0,0 +1,275 @@ +/* eslint-disable no-nested-ternary */ +import React, { useEffect, useState, useRef, useMemo } from 'react'; +import { Drawer, DrawerActions, DrawerCloseButton, DrawerContent, DrawerContentBody, DrawerHead, DrawerPanelContent, Title, Content, EmptyState, EmptyStateBody, EmptyStateFooter, EmptyStateActions, Button, } from '@patternfly/react-core'; +import { ActionsColumn, Tbody, Td, ThProps, Tr } from '@patternfly/react-table'; +import { BulkSelect, BulkSelectValue } from '@patternfly/react-component-groups/dist/dynamic/BulkSelect'; +import { Pagination } from '@patternfly/react-core'; +import { DataView } from '@patternfly/react-data-view/dist/dynamic/DataView'; +import { DataViewToolbar } from '@patternfly/react-data-view/dist/dynamic/DataViewToolbar'; +import { DataViewTable, DataViewTh } from '@patternfly/react-data-view/dist/dynamic/DataViewTable'; +import { DataViewEventsProvider, EventTypes, useDataViewEventsContext } from '@patternfly/react-data-view/dist/dynamic/DataViewEventsContext'; +import { useDataViewPagination, useDataViewSelection, useDataViewFilters, useDataViewSort } from '@patternfly/react-data-view/dist/dynamic/Hooks'; +import { ResponsiveAction, ResponsiveActions } from '@patternfly/react-component-groups'; +import { DataViewFilterOption, DataViewFilters } from '@patternfly/react-data-view/dist/dynamic/DataViewFilters'; +import { DataViewTextFilter } from '@patternfly/react-data-view/dist/dynamic/DataViewTextFilter'; +import { DataViewCheckboxFilter } from '@patternfly/react-data-view/dist/dynamic/DataViewCheckboxFilter'; +import { CubesIcon } from '@patternfly/react-icons'; + +const perPageOptions = [ + { title: '5', value: 5 }, + { title: '10', value: 10 } +]; + +interface Repository { + name: string; + branch: string | null; + prs: string | null; + workspace: string; + lastCommit: string; +}; + +interface RepositoryFilters { + name: string, + branch: string, + workspace: string[] +}; + +const repositories: Repository[] = [ + { name: 'Repository one', branch: 'Branch one', prs: 'Pull request one', workspace: 'Workspace one', lastCommit: 'Timestamp one' }, + { name: 'Repository two', branch: 'Branch two', prs: 'Pull request two', workspace: 'Workspace two', lastCommit: 'Timestamp two' }, + { name: 'Repository three', branch: 'Branch three', prs: 'Pull request three', workspace: 'Workspace three', lastCommit: 'Timestamp three' }, + { name: 'Repository four', branch: 'Branch four', prs: 'Pull request four', workspace: 'Workspace four', lastCommit: 'Timestamp four' }, + { name: 'Repository five', branch: 'Branch five', prs: 'Pull request five', workspace: 'Workspace five', lastCommit: 'Timestamp five' }, + { name: 'Repository six', branch: 'Branch six', prs: 'Pull request six', workspace: 'Workspace six', lastCommit: 'Timestamp six' } +]; + +const filterOptions: DataViewFilterOption[] = [ + { label: 'Workspace one', value: 'workspace-one' }, + { label: 'Workspace two', value: 'workspace-two' }, + { label: 'Workspace three', value: 'workspace-three' } +]; + +const COLUMNS = [ + { label: 'Repository', key: 'name', index: 0 }, + { label: 'Branch', key: 'branches', index: 1 }, + { label: 'Pull request', key: 'prs', index: 2 }, + { label: 'Workspace', key: 'workspaces', index: 3 }, + { label: 'Last commit', key: 'lastCommit', index: 4 } +]; + +const ouiaId = 'LayoutExample'; + +const sortData = (data: Repository[], sortBy: string | undefined, direction: 'asc' | 'desc' | undefined) => + sortBy && direction + ? [ ...data ].sort((a, b) => + direction === 'asc' + ? a[sortBy] < b[sortBy] ? -1 : a[sortBy] > b[sortBy] ? 1 : 0 + : a[sortBy] > b[sortBy] ? -1 : a[sortBy] < b[sortBy] ? 1 : 0 + ) + : data; + +const empty = ( + + + + + +); + +interface RepositoryDetailProps { + selectedRepo?: Repository; + setSelectedRepo: React.Dispatch>; +} + +const RepositoryDetail: React.FunctionComponent = ({ selectedRepo, setSelectedRepo }) => { + const context = useDataViewEventsContext(); + + useEffect(() => { + const unsubscribe = context.subscribe(EventTypes.rowClick, (repo: Repository) => { + setSelectedRepo(repo); + }); + + return () => unsubscribe(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + return ( + + + + Detail of {selectedRepo?.name} + + Branch: {selectedRepo?.branch} + Pull requests: {selectedRepo?.prs} + Workspace: {selectedRepo?.workspace} + Last commit: {selectedRepo?.lastCommit} + + setSelectedRepo(undefined)} data-ouia-component-id="detail-drawer-close-btn"/> + + + + ); +}; + +interface RepositoriesTableProps { + selectedRepo?: Repository; +} + +const rowActions = [ + { + title: 'Some action', + onClick: () => console.log('clicked on Some action') // eslint-disable-line no-console + }, + { + title:
Another action
, + onClick: () => console.log('clicked on Another action') // eslint-disable-line no-console + }, + { + isSeparator: true + }, + { + title: 'Third action', + onClick: () => console.log('clicked on Third action') // eslint-disable-line no-console + } +]; + +const RepositoriesTable: React.FunctionComponent = ({ selectedRepo = undefined }) => { + const { filters, onSetFilters, clearAllFilters } = useDataViewFilters({ initialFilters: { name: '', branch: '', workspace: [] } }); + + const pagination = useDataViewPagination({ perPage: 5 }); + const { page, perPage } = pagination; + + const selection = useDataViewSelection({ matchOption: (a, b) => a[0] === b[0] }); + const { selected, onSelect, isSelected } = selection; + + const { trigger } = useDataViewEventsContext(); + + const { sortBy, direction, onSort } = useDataViewSort(); + const sortByIndex = useMemo(() => COLUMNS.findIndex(item => item.key === sortBy), [ sortBy ]); + const getSortParams = (columnIndex: number): ThProps['sort'] => ({ + sortBy: { + index: sortByIndex, + direction, + defaultDirection: 'asc' + }, + onSort: (_event, index, direction) => onSort(_event, COLUMNS[index].key, direction), + columnIndex + }); + + const columns: DataViewTh[] = COLUMNS.map((column, index) => ({ + cell: column.label, + props: { sort: getSortParams(index) } + })); + + const finalData = useMemo(() => sortData(repositories, sortBy, direction).filter(item => + (!filters.name || item.name?.toLocaleLowerCase().includes(filters.name?.toLocaleLowerCase())) && + (!filters.branch || item.branch?.toLocaleLowerCase().includes(filters.branch?.toLocaleLowerCase())) && + (!filters.workspace || filters.workspace.length === 0 || filters.workspace.includes(String(filterOptions.find(option => option.label === item.workspace)?.value))) + ), [ filters, sortBy, direction ]); + + const pageRows = useMemo(() => { + const handleRowClick = (event, repo: Repository | undefined) => { + // prevents drawer toggle on actions or checkbox click + (event.target.matches('td') || event.target.matches('tr')) && trigger(EventTypes.rowClick, repo); + }; + + return finalData.map(repo => ({ + row: [ ...Object.values(repo), { cell: , props: { isActionCell: true } } ], + props: { + isClickable: true, + onRowClick: (event) => handleRowClick(event, selectedRepo?.name === repo.name ? undefined : repo), + isRowSelected: selectedRepo?.name === repo.name + } + })).slice((page - 1) * perPage, ((page - 1) * perPage) + perPage); + }, [ selectedRepo?.name, trigger, page, perPage, finalData ]); + + const handleBulkSelect = (value: BulkSelectValue) => { + value === BulkSelectValue.none && onSelect(false); + value === BulkSelectValue.nonePage && onSelect(false, pageRows); + value === BulkSelectValue.page && onSelect(true, pageRows); + }; + + return ( + 0 ? undefined : 'empty'}> + isSelected(item))} + pagePartiallySelected={pageRows.some(item => isSelected(item)) && !pageRows.every(item => isSelected(item))} + onSelect={handleBulkSelect} + /> + } + filters={ + onSetFilters(values)} values={filters}> + + + + + } + actions={ + + Add repository + Delete repository + + } + pagination={ + + } + /> + + + } + /> + + ); +}; + +export const BasicExample: React.FunctionComponent = () => { + const [ selectedRepo, setSelectedRepo ] = useState(); + const drawerRef = useRef(null); + + return ( + + drawerRef.current?.focus()} data-ouia-component-id="detail-drawer" > + } + > + + + + + + + ); +}; diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/EventsContext/EventsContext.md b/packages/module/patternfly-docs/content/extensions/data-view/examples/EventsContext/EventsContext.md deleted file mode 100644 index 293a1a0c..00000000 --- a/packages/module/patternfly-docs/content/extensions/data-view/examples/EventsContext/EventsContext.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -# Sidenav top-level section -# should be the same for all markdown files -section: extensions -subsection: Data view -# Sidenav secondary level section -# should be the same for all markdown files -id: Events context -# Tab (react | react-demos | html | html-demos | design-guidelines | accessibility) -source: react -# If you use typescript, the name of the interface to display props for -# These are found through the sourceProps function provided in patternfly-docs.source.js -sortValue: 3 -sourceLink: https://github.com/patternfly/react-data-view/blob/main/packages/module/patternfly-docs/content/extensions/data-view/examples/EventsContext/EventsContext.md ---- -import { useState, useEffect, useRef, useMemo } from 'react'; -import { Table, Tbody, Th, Thead, Tr, Td } from '@patternfly/react-table'; -import { DataView } from '@patternfly/react-data-view/dist/dynamic/DataView'; -import { DataViewTable } from '@patternfly/react-data-view/dist/dynamic/DataViewTable'; -import { useDataViewEventsContext, DataViewEventsContext, DataViewEventsProvider, EventTypes } from '@patternfly/react-data-view/dist/dynamic/DataViewEventsContext'; -import { useDataViewSelection } from '@patternfly/react-data-view/dist/dynamic/Hooks'; -import { Drawer, DrawerContent, DrawerContentBody } from '@patternfly/react-core'; - -The **data view events context** provides a way of listening to the data view events from the outside of the component. - -### Row click subscription example -The following example demonstrates how to use the `DataViewEventsContext` to manage shared state and handle events. The `DataViewEventsProvider` is used to wrap components that need access to the shared context. This example illustrates how to set up a layout that listens for data view row click events and displays detailed information about the selected row in a [drawer component](/components/drawer). - - -```js file="./EventsExample.tsx" - -``` - diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Functionality/Functionality.md b/packages/module/patternfly-docs/content/extensions/data-view/examples/Functionality/Functionality.md deleted file mode 100644 index 3e263c56..00000000 --- a/packages/module/patternfly-docs/content/extensions/data-view/examples/Functionality/Functionality.md +++ /dev/null @@ -1,150 +0,0 @@ ---- -# Sidenav top-level section -# should be the same for all markdown files -section: extensions -subsection: Data view -# Sidenav secondary level section -# should be the same for all markdown files -id: Functionality -# Tab (react | react-demos | html | html-demos | design-guidelines | accessibility) -source: react -# If you use typescript, the name of the interface to display props for -# These are found through the sourceProps function provided in patternfly-docs.source.js -sortValue: 3 -propComponents: ['DataViewFilters', 'DataViewTextFilter', 'DataViewCheckboxFilter'] -sourceLink: https://github.com/patternfly/react-data-view/blob/main/packages/module/patternfly-docs/content/extensions/data-view/examples/Functionality/Functionality.md ---- -import { useMemo } from 'react'; -import { BrowserRouter, useSearchParams } from 'react-router-dom'; -import { useDataViewPagination, useDataViewSelection, useDataViewFilters, useDataViewSort } from '@patternfly/react-data-view/dist/dynamic/Hooks'; -import { DataView } from '@patternfly/react-data-view/dist/dynamic/DataView'; -import { BulkSelect, BulkSelectValue } from '@patternfly/react-component-groups/dist/dynamic/BulkSelect'; -import { DataViewToolbar } from '@patternfly/react-data-view/dist/dynamic/DataViewToolbar'; -import { DataViewTable } from '@patternfly/react-data-view/dist/dynamic/DataViewTable'; -import { DataViewFilters } from '@patternfly/react-data-view/dist/dynamic/DataViewFilters'; -import { DataViewTextFilter } from '@patternfly/react-data-view/dist/dynamic/DataViewTextFilter'; -import { DataViewCheckboxFilter } from '@patternfly/react-data-view/dist/dynamic/DataViewCheckboxFilter'; - -This is a list of functionality you can use to manage data displayed in the **data view**. - -# Pagination -Allows to display data records on multiple pages and display the pagination state. - -### Toolbar usage -Data view toolbar can display a pagination using the `pagination` property accepting a React node. You can also pass a custom `ouiaId` for testing purposes. - -### Pagination state - -The `useDataViewPagination` hook manages the pagination state of the data view. - -**Initial values:** -- `perPage` initial value -- optional `page` initial value -- optional `searchParams` object -- optional `setSearchParams` function - -While the hook works seamlessly with React Router library, you do not need to use it to take advantage of URL persistence. The `searchParams` and `setSearchParams` props can be managed using native browser APIs (`URLSearchParams` and `window.history.pushState`) or any other routing library of your choice. If you don't pass these two props, the pagination state will be stored internally without the URL usage. - -You can also pass custom `pageParam` or `perPageParam` names, renaming the pagination parameters in the URL. - -The retrieved values are named to match the PatternFly [pagination](/components/pagination) component props, so you can easily spread them to the component. - -**Return values:** -- current `page` number -- `onSetPage` to modify current page -- items `perPage` value -- `onPerPageSelect` to modify per page value - -### Pagination example -```js file="./PaginationExample.tsx" - -``` - -# Selection -Allows to select data records inside the data view and show the selection state. - -### Toolbar usage -Data view toolbar can display a bulk selection component using the `bulkSelect` property accepting a React node. You can make use of a predefined [bulk select](/extensions/component-groups/bulk-select) component from the [component groups](/extensions/component-groups/about-component-groups) extension. - -### Selection state - -The `useDataViewSelection` hook manages the selection state of the data view. - -**Initial values:** -- optional `initialSelected` array of record's identifiers selected by default -- `matchOption` function to check if given record is selected - -*When no `matchOption` is passed, the `Array.prototype.includes()` operation is performed on the `selected` array.* - -**Return values:** -- `selected` array of currently selected records -- `isSelected` function returning the selection state for given record -- `onSelect` callback to modify the selection state and accepting `isSelecting` flag indicating if records are changing to selected or deselected and `items` containing affected records - -### Selection example - -```js file="./SelectionExample.tsx" - -``` - -# Filters -Enables filtering of data records in the data view and displays the applied filter labels. - -### Toolbar usage -The data view toolbar can include a set of filters by passing a React node to the `filters` property. You can use predefined components `DataViewFilters`, `DataViewTextFilter` and `DataViewCheckboxFilter` to customize and handle filtering directly in the toolbar. The `DataViewFilters` is a wrapper allowing conditional filtering using multiple attributes. If you need just a single filter, you can use `DataViewTextFilter`, `DataViewCheckboxFilter` or a different filter component alone. Props of these filter components are listed at the bottom of this page. - -You can decide between passing `value` and `onChange` event to every filter separately or pass `values` and `onChange` to the `DataViewFilters` wrapper which make them available to its children. Props directly passed to child filters have a higher priority than the "inherited" ones. - -### Filters state - -The `useDataViewFilters` hook manages the filter state of the data view. It allows you to define default filter values, synchronize filter state with URL parameters, and handle filter changes efficiently. - -**Initial values:** -- `initialFilters` object with default filter values (if the filter param allows multiple values, pass an array) -- optional `searchParams` object for managing URL-based filter state -- optional `setSearchParams` function to update the URL when filters are modified - -The `useDataViewFilters` hook works well with the React Router library to support URL-based filtering. Alternatively, you can manage filter state in the URL using `URLSearchParams` and `window.history.pushState` APIs, or other routing libraries. If no URL parameters are provided, the filter state is managed internally. - -**Return values:** -- `filters` object representing the current filter values -- `onSetFilters` function to update the filter state -- `clearAllFilters` function to reset all filters to their initial values - -### Filtering example -This example demonstrates the setup and usage of filters within the data view. It includes text filters for different attributes, the ability to clear all filters, and persistence of filter state in the URL. - -```js file="./FiltersExample.tsx" - -``` - -### Sort state - -The `useDataViewSort` hook manages the sorting state of a data view. It provides an easy way to handle sorting logic, including synchronization with URL parameters and defining default sorting behavior. - -**Initial values:** -- `initialSort` object to set default `sortBy` and `direction` values: - - `sortBy`: key of the initial column to sort. - - `direction`: default sorting direction (`asc` or `desc`). -- Optional `searchParams` object to manage URL-based synchronization of sort state. -- Optional `setSearchParams` function to update the URL parameters when sorting changes. -- `defaultDirection` to set the default direction when no direction is specified. -- Customizable parameter names for the URL: - - `sortByParam`: name of the URL parameter for the column key. - - `directionParam`: name of the URL parameter for the sorting direction. - -The `useDataViewSort` hook integrates seamlessly with React Router to manage sort state via URL parameters. Alternatively, you can use `URLSearchParams` and `window.history.pushState` APIs, or other routing libraries. If URL synchronization is not configured, the sort state is managed internally within the component. - -**Return values:** -- `sortBy`: key of the column currently being sorted. -- `direction`: current sorting direction (`asc` or `desc`). -- `onSort`: function to handle sorting changes programmatically or via user interaction. - -### Sorting example - -This example demonstrates how to set up and use sorting functionality within a data view. The implementation includes dynamic sorting by column with persistence of sort state in the URL using React Router. - - -```js file="./SortingExample.tsx" - -``` diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Layout/Layout.md b/packages/module/patternfly-docs/content/extensions/data-view/examples/Layout/Layout.md deleted file mode 100644 index 13c892d3..00000000 --- a/packages/module/patternfly-docs/content/extensions/data-view/examples/Layout/Layout.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -# Sidenav top-level section -# should be the same for all markdown files -section: extensions -subsection: Data view -# Sidenav secondary level section -# should be the same for all markdown files -id: Layout -# Tab (react | react-demos | html | html-demos | design-guidelines | accessibility) -source: react -# If you use typescript, the name of the interface to display props for -# These are found through the sourceProps function provided in patternfly-docs.source.js -sortValue: 2 -propComponents: ['DataView', 'DataViewState'] -sourceLink: https://github.com/patternfly/react-data-view/blob/main/packages/module/patternfly-docs/content/extensions/data-view/examples/Layout/Layout.md ---- -import { useMemo } from 'react'; -import { useDataViewPagination, useDataViewSelection } from '@patternfly/react-data-view/dist/dynamic/Hooks'; -import { BulkSelect, BulkSelectValue } from '@patternfly/react-component-groups/dist/dynamic/BulkSelect'; -import DataView from '@patternfly/react-data-view/dist/dynamic/DataView'; -import DataViewToolbar from '@patternfly/react-data-view/dist/dynamic/DataViewToolbar'; -import DataViewTable from '@patternfly/react-data-view/dist/dynamic/DataViewTable'; - -The **data view** component renders record data in a configured layout. - -### Layout example - -Data view is expected to consist of header, data part and footer stacked below each other and passed as `children`. - -```js file="./AbstractLayoutExample.tsx" - -``` - -### Predefined layout components - -You can make use of the predefined layout components to display a default header and footer. See [data view toolbar](/extensions/data-view/components#dataviewtoolbar) for more information - -```js file="./PredefinedLayoutExample.tsx" - -``` diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Layout/PredefinedLayoutExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/Layout/PredefinedLayoutExample.tsx deleted file mode 100644 index 7381f544..00000000 --- a/packages/module/patternfly-docs/content/extensions/data-view/examples/Layout/PredefinedLayoutExample.tsx +++ /dev/null @@ -1,89 +0,0 @@ -import React, { useMemo } from 'react'; -import { Pagination } from '@patternfly/react-core'; -import { useDataViewPagination, useDataViewSelection } from '@patternfly/react-data-view/dist/dynamic/Hooks'; -import { BulkSelect, BulkSelectValue } from '@patternfly/react-component-groups/dist/dynamic/BulkSelect'; -import { DataView } from '@patternfly/react-data-view/dist/dynamic/DataView'; -import { DataViewTable } from '@patternfly/react-data-view/dist/dynamic/DataViewTable'; -import { DataViewToolbar } from '@patternfly/react-data-view/dist/dynamic/DataViewToolbar'; - -const perPageOptions = [ - { title: '5', value: 5 }, - { title: '10', value: 10 } -]; - -interface Repository { - name: string; - branches: string | null; - prs: string | null; - workspaces: string; - lastCommit: string; -} - -const repositories: Repository[] = [ - { name: 'Repository one', branches: 'Branch one', prs: 'Pull request one', workspaces: 'Workspace one', lastCommit: 'Timestamp one' }, - { name: 'Repository two', branches: 'Branch two', prs: 'Pull request two', workspaces: 'Workspace two', lastCommit: 'Timestamp two' }, - { name: 'Repository three', branches: 'Branch three', prs: 'Pull request three', workspaces: 'Workspace three', lastCommit: 'Timestamp three' }, - { name: 'Repository four', branches: 'Branch four', prs: 'Pull request four', workspaces: 'Workspace four', lastCommit: 'Timestamp four' }, - { name: 'Repository five', branches: 'Branch five', prs: 'Pull request five', workspaces: 'Workspace five', lastCommit: 'Timestamp five' }, - { name: 'Repository six', branches: 'Branch six', prs: 'Pull request six', workspaces: 'Workspace six', lastCommit: 'Timestamp six' } -]; - -const rows = repositories.map(item => Object.values(item)); - -const columns = [ 'Repositories', 'Branches', 'Pull requests', 'Workspaces', 'Last commit' ]; - -const ouiaId = 'LayoutExample'; - -export const BasicExample: React.FunctionComponent = () => { - const pagination = useDataViewPagination({ perPage: 5 }); - const { page, perPage } = pagination; - const selection = useDataViewSelection({ matchOption: (a, b) => a[0] === b[0] }); - const { selected, onSelect, isSelected } = selection; - - const pageRows = useMemo(() => rows.slice((page - 1) * perPage, ((page - 1) * perPage) + perPage), [ page, perPage ]); - - const handleBulkSelect = (value: BulkSelectValue) => { - value === BulkSelectValue.none && onSelect(false); - value === BulkSelectValue.all && onSelect(true, rows); - value === BulkSelectValue.nonePage && onSelect(false, pageRows); - value === BulkSelectValue.page && onSelect(true, pageRows); - }; - - return ( - - isSelected(item))} - pagePartiallySelected={pageRows.some(item => isSelected(item)) && !pageRows.every(item => isSelected(item))} - onSelect={handleBulkSelect} - /> - } - pagination={ - - } - /> - - - } - /> - - ); -} \ No newline at end of file diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewTableEmptyExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/Table/DataViewTableEmptyExample.tsx similarity index 100% rename from packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewTableEmptyExample.tsx rename to packages/module/patternfly-docs/content/extensions/data-view/examples/Table/DataViewTableEmptyExample.tsx diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewTableErrorExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/Table/DataViewTableErrorExample.tsx similarity index 100% rename from packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewTableErrorExample.tsx rename to packages/module/patternfly-docs/content/extensions/data-view/examples/Table/DataViewTableErrorExample.tsx diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewTableExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/Table/DataViewTableExample.tsx similarity index 100% rename from packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewTableExample.tsx rename to packages/module/patternfly-docs/content/extensions/data-view/examples/Table/DataViewTableExample.tsx diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewTableLoadingExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/Table/DataViewTableLoadingExample.tsx similarity index 100% rename from packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewTableLoadingExample.tsx rename to packages/module/patternfly-docs/content/extensions/data-view/examples/Table/DataViewTableLoadingExample.tsx diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewTableTreeExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/Table/DataViewTableTreeExample.tsx similarity index 100% rename from packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewTableTreeExample.tsx rename to packages/module/patternfly-docs/content/extensions/data-view/examples/Table/DataViewTableTreeExample.tsx diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Functionality/SortingExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/Table/SortingExample.tsx similarity index 100% rename from packages/module/patternfly-docs/content/extensions/data-view/examples/Functionality/SortingExample.tsx rename to packages/module/patternfly-docs/content/extensions/data-view/examples/Table/SortingExample.tsx diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Table/Table.md b/packages/module/patternfly-docs/content/extensions/data-view/examples/Table/Table.md new file mode 100644 index 00000000..19254f94 --- /dev/null +++ b/packages/module/patternfly-docs/content/extensions/data-view/examples/Table/Table.md @@ -0,0 +1,130 @@ +--- +# Sidenav top-level section +# should be the same for all markdown files +section: extensions +subsection: Data view +# Sidenav secondary level section +# should be the same for all markdown files +id: Table +title: Data view table +# Tab (react | react-demos | html | html-demos | design-guidelines | accessibility) +source: react +# If you use typescript, the name of the interface to display props for +# These are found through the sourceProps function provided in patternfly-docs.source.js +sortValue: 3 +propComponents: ['DataViewTableBasic', 'DataViewTableTree', 'DataViewTrTree', 'DataViewTrObject'] +sourceLink: https://github.com/patternfly/react-data-view/blob/main/packages/module/patternfly-docs/content/extensions/data-view/examples/Table/Table.md +--- +import { useMemo } from 'react'; +import { BrowserRouter, useSearchParams } from 'react-router-dom'; +import { Button, EmptyState, EmptyStateActions, EmptyStateBody, EmptyStateFooter } from '@patternfly/react-core'; +import { CubesIcon, FolderIcon, FolderOpenIcon, LeafIcon, ExclamationCircleIcon } from '@patternfly/react-icons'; +import { ErrorState, ResponsiveAction, ResponsiveActions, SkeletonTableHead, SkeletonTableBody } from '@patternfly/react-component-groups'; +import { DataViewToolbar } from '@patternfly/react-data-view/dist/dynamic/DataViewToolbar'; +import { DataViewTable } from '@patternfly/react-data-view/dist/dynamic/DataViewTable'; +import { useDataViewSelection, useDataViewSort } from '@patternfly/react-data-view/dist/dynamic/Hooks'; +import { DataView, DataViewState } from '@patternfly/react-data-view/dist/dynamic/DataView'; + +The **data view table** component renders your data into columns and rows within a [PatternFly table](/components/table) component. You can easily customize and configure the table with these additional [data view components and props](/extensions/data-view/table#props). + +## Configuring rows and columns +To define rows and columns for your table, use these props: +- `columns`: Defines the column heads of the table. Each item in the array can be a `ReactNode` for simple heads, or an object with the following properties: + - `cell`: Content to display in the column head. + - `props` (optional): (`ThProps`) to pass to the `
` component, such as `isHoverable`, `isRowSelected`, and other table row properties. + +It is also possible to disable row selection using the `isSelectDisabled` function, which can be passed to the wrapping `DataView` component through the `selection` prop. + +### Table example +```js file="./DataViewTableExample.tsx" + +``` + +## Tree table + +A tree table includes expandable rows and custom icons for leaf and parent nodes. +To enable a tree table, pass the `isTreeTable` flag to the `` component. + + +Tree table rows have to be defined with following keys: + - `row`: Defines the content for each cell in the row. + - `id`: Unique identifier for the row that's used for matching selected items. + - `children` (optional): Defines the children rows. + +To update a row's icon to reflect its expansion state, pass `collapsedIcon`, `expandedIcon`, and `leafIcon` to ``. + +To disable row selection, pass the `isSelectDisabled` function to `selection` prop of the wrapping `` component . + +### Tree table example + +```js file="./DataViewTableTreeExample.tsx" + +``` + +## Sorting +The following example demonstrates how to enable sorting functionality within a data view. This implementation supports dynamic sorting by column and persists the sort state in the page's URL via [React Router](https://reactrouter.com/). + +### Sorting example +```js file="./SortingExample.tsx" + +``` +### Sorting state + +The `useDataViewSort` hook manages the sorting state of a data view and provides an easy way to handle sorting logic, such as synchronization with URL parameters and the definition of default sorting behavior. + +**Initial values:** +- `initialSort` object to set default `sortBy` and `direction` values: + - `sortBy`: Key of the initial column to sort. + - `direction`: Default sorting direction (`asc` or `desc`). +- `searchParams` (optional): Object to manage URL-based synchronization of sort state. +- `setSearchParams` (optional): Function to update the URL parameters when sorting changes. +- `defaultDirection`: Used to set the default direction when no direction is specified. +- Customizable parameter names for the URL: + - `sortByParam`: Name of the URL parameter for the column key. + - `directionParam`: Name of the URL parameter for the sorting direction. +The `useDataViewSort` hook integrates seamlessly with [React Router](https://reactrouter.com/) to manage the sort state via URL parameters. Alternatively, you can use `URLSearchParams` and `window.history.pushState` APIs, or other routing libraries. If URL synchronization is not configured, the sort state is managed internally within the component. + +**Return values:** +- `sortBy`: Key of the column currently being sorted. +- `direction`: Current sorting direction (`asc` or `desc`). +- `onSort`: Function to handle sorting changes programmatically or via user interaction. + +## States + +The data view table allows you to react to the `activeState` of the data view (such as `empty`, `error`, `loading`). You can use the `headStates` and `bodyStates` props to define the table head and body for a given state. + +### Empty +When there is no data to render in the data view, you can instead display an empty state. + +You can create your empty state by passing a [PatternFly empty state](/components/empty-state) to the `empty` key of `headStates` or `bodyStates`. + +```js file="./DataViewTableEmptyExample.tsx" + +``` + +### Error +When there is a data connection or retrieval error, you can display an error state. + +The error state will be displayed when the data view `activeState` value is `error`. + +You can create your error state by passing either the [component groups extension's error state](/component-groups/error-state) or a [PatternFly empty state](/components/empty-state) to the `error` key of `headStates` or `bodyStates`. + +```js file="./DataViewTableErrorExample.tsx" + +``` + +### Loading +To indicate that data is loading, you can display a loading state. + +The loading state will be displayed when the data view `activeState` value is `loading`. + +You can create your loading state by passing either the [component groups extension's skeleton table](/component-groups/skeleton-table) or a customized [PatternFly empty state](/components/empty-state) to the `loading` key of `headStates` or `bodyStates`. + + +```js file="./DataViewTableLoadingExample.tsx" + +``` diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewToolbarActionsExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/DataViewToolbarActionsExample.tsx similarity index 100% rename from packages/module/patternfly-docs/content/extensions/data-view/examples/Components/DataViewToolbarActionsExample.tsx rename to packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/DataViewToolbarActionsExample.tsx diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/DataViewToolbarExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/DataViewToolbarExample.tsx new file mode 100644 index 00000000..0b65a34e --- /dev/null +++ b/packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/DataViewToolbarExample.tsx @@ -0,0 +1,36 @@ +/* eslint-disable no-console */ +import React from 'react'; +import { Pagination } from '@patternfly/react-core'; +import { BulkSelect } from '@patternfly/react-component-groups'; +import { DataViewToolbar } from '@patternfly/react-data-view/dist/dynamic/DataViewToolbar'; +import { ResponsiveAction, ResponsiveActions } from '@patternfly/react-component-groups'; +import { DataViewFilters } from '@patternfly/react-data-view/dist/dynamic/DataViewFilters'; +import { DataViewTextFilter } from '@patternfly/react-data-view/dist/dynamic/DataViewTextFilter'; + +export const BasicExample: React.FunctionComponent = () => ( + console.log('clearAllFilters called')} + bulkSelect={ + console.log('onSelect called')} + /> + } + filters={ + console.log('onSetFilters calles')} values={{}}> + + + + } + actions={ + + Add repository + Delete repository + + } + pagination={ + + } + /> +) diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Functionality/FiltersExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/FiltersExample.tsx similarity index 100% rename from packages/module/patternfly-docs/content/extensions/data-view/examples/Functionality/FiltersExample.tsx rename to packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/FiltersExample.tsx diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Functionality/PaginationExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/PaginationExample.tsx similarity index 100% rename from packages/module/patternfly-docs/content/extensions/data-view/examples/Functionality/PaginationExample.tsx rename to packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/PaginationExample.tsx diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Functionality/SelectionExample.tsx b/packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/SelectionExample.tsx similarity index 100% rename from packages/module/patternfly-docs/content/extensions/data-view/examples/Functionality/SelectionExample.tsx rename to packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/SelectionExample.tsx diff --git a/packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/Toolbar.md b/packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/Toolbar.md new file mode 100644 index 00000000..1901f424 --- /dev/null +++ b/packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/Toolbar.md @@ -0,0 +1,142 @@ +--- +# Sidenav top-level section +# should be the same for all markdown files +section: extensions +subsection: Data view +# Sidenav secondary level section +# should be the same for all markdown files +id: Toolbar +title: Data view toolbar +# Tab (react | react-demos | html | html-demos | design-guidelines | accessibility) +source: react +# If you use typescript, the name of the interface to display props for +# These are found through the sourceProps function provided in patternfly-docs.source.js +sortValue: 2 +propComponents: ['DataViewToolbar', 'DataViewFilters', 'DataViewTextFilter', 'DataViewCheckboxFilter'] +sourceLink: https://github.com/patternfly/react-data-view/blob/main/packages/module/patternfly-docs/content/extensions/data-view/examples/Toolbar/Toolbar.md +--- +import { useMemo } from 'react'; +import { BrowserRouter, useSearchParams } from 'react-router-dom'; +import { useDataViewPagination, useDataViewSelection, useDataViewFilters } from '@patternfly/react-data-view/dist/dynamic/Hooks'; +import { DataView } from '@patternfly/react-data-view/dist/dynamic/DataView'; +import { BulkSelect, BulkSelectValue, ErrorState, ResponsiveAction, ResponsiveActions, SkeletonTableHead, SkeletonTableBody } from '@patternfly/react-component-groups'; +import { DataViewToolbar } from '@patternfly/react-data-view/dist/dynamic/DataViewToolbar'; +import { DataViewTable } from '@patternfly/react-data-view/dist/dynamic/DataViewTable'; +import { DataViewFilters } from '@patternfly/react-data-view/dist/dynamic/DataViewFilters'; +import { DataViewTextFilter } from '@patternfly/react-data-view/dist/dynamic/DataViewTextFilter'; +import { DataViewCheckboxFilter } from '@patternfly/react-data-view/dist/dynamic/DataViewCheckboxFilter'; + +The **data view toolbar** component renders a default opinionated data view toolbar above or below the data section. + +Data view toolbar can contain pagination, bulk select, filters, actions, or other custom child content. To pass child items to the toolbar, use the [toolbar item](/components/toolbar#toolbar-items) component or predefined `` props for specific use cases. + +You can further customize toolbar interactions by referring to the additional documentation: +- [Actions](#toolbar-actions) +- [Pagination](#pagination) +- [Selection](#selection) +- [Filters](#filters) + +### Toolbar example + +```js file="./DataViewToolbarExample.tsx" + +``` + +## Toolbar actions +To support additional user needs, you can pass relevant actions to the toolbar via `actions`. Add standard PatternFly actions (like buttons) or choose predefined [responsive actions](/component-groups/responsive-actions) which ensure the responsive behavior of multiple actions in 1 toolbar. + +### Actions example + +```js file="./DataViewToolbarActionsExample.tsx" + +``` + +## Pagination + +To help users navigate data records that span multiple pages, add pagination support to your toolbar. + +The data view toolbar can display a pagination using the `pagination` prop. You can also pass a custom `ouiaId` to the toolbar for testing purposes. You can also persist pagination values in the URL to make it easier to share or bookmark specific pages of your data. + +### Pagination state + +The `useDataViewPagination` hook manages the pagination state of the data view. + +**Initial values:** +- `perPage` initial value. +- Optional `page` initial value. +- Optional `searchParams` object. +- Optional `setSearchParams` function. + +While the hook works seamlessly with the [React Router](https://reactrouter.com/) library, you do not need to use it to take advantage of URL persistence. The `searchParams` and `setSearchParams` props can be managed using native browser APIs (`URLSearchParams` and `window.history.pushState`) or any other routing library of your choice. If you don't pass these two props, the pagination state will be stored internally without the URL usage. + +You can also pass custom `pageParam` or `perPageParam` names, renaming the pagination parameters in the URL. + +The retrieved values are named to match the PatternFly pagination component props. + +**Return values:** +- Current `page` number. +- `onSetPage` to modify current page. +- Items `perPage` value. +- `onPerPageSelect` to modify per page value. + +### Pagination example +This example uses the URL to persist the pagination state. + +```js file="./PaginationExample.tsx" + +``` + +## Selection +To allow users to select data records inside the data view, add selection support that displays a row's selection state. + +The data view toolbar can display a bulk selection component by using the predefined [component group extension bulk select](/extensions/component-groups/bulk-select) component. + +### Selection state + +The `useDataViewSelection` hook manages the selection state of the data view. + +**Initial values:** +- Optional `initialSelected` array of record's identifiers selected by default. +- `matchOption` function to check if the record is selected. + - When no `matchOption` is passed, the `Array.prototype.includes()` operation is performed on the `selected` array. + +**Return values:** +- `selected` array of currently selected records. +- `isSelected` function returning the selection state for the record. +- `onSelect` callback to modify the selection state. This accepts the `isSelecting` flag (indicates if records are being selected or deselected) and `items` (affected records). + +### Selection example + +```js file="./SelectionExample.tsx" + +``` + +## Filters +To allow users to filter data records in the data view, add filtering support that displays the applied filter chips. + +The data view toolbar can include a set of filters by passing a React node to the `filters` property. You can use the predefined components ``, ``, and `` to customize and handle filtering directly in the toolbar. The `` component is a wrapper that allows conditional filtering using multiple attributes. If you need just a single filter, you can use ``, ``, or a different filter component alone. Props of these filter components are listed in the [props section of this page](#props). + +You can either pass a `value` and `onChange` event to every filter separately, or you can pass `values` and `onChange` to the `` wrapper, which makes them available to its children. Props directly passed to child filters have a higher priority than the "inherited" ones. + +### Filters state + +The `useDataViewFilters` hook manages the filter state of the data view. It allows you to define default filter values, synchronize filter state with URL parameters, and handle filter changes efficiently. + +**Initial values:** +- `initialFilters` object with default filter values (if the filter param allows multiple values, pass an array). +- Optional `searchParams` object for managing URL-based filter state. +- Optional `setSearchParams` function to update the URL when filters are modified. + +The `useDataViewFilters` hook works well with the [React Router](https://reactrouter.com/) library to support URL-based filtering. Alternatively, you can manage the filter state in the URL using `URLSearchParams` and `window.history.pushState` APIs, or other routing libraries. If no URL parameters are provided, the filter state is managed internally. + +**Return values:** +- `filters` object representing the current filter values. +- `onSetFilters` function to update the filter state. +- `clearAllFilters` function to reset all filters to their initial values. + +### Filtering example +This example demonstrates the setup and usage of filters within the data view. It includes text filters for different attributes, the ability to clear all filters, and persistence of filter state in the URL. + +```js file="./FiltersExample.tsx" + +``` diff --git a/packages/module/src/DataViewToolbar/DataViewToolbar.tsx b/packages/module/src/DataViewToolbar/DataViewToolbar.tsx index 1258528f..5410e706 100644 --- a/packages/module/src/DataViewToolbar/DataViewToolbar.tsx +++ b/packages/module/src/DataViewToolbar/DataViewToolbar.tsx @@ -35,14 +35,14 @@ export const DataViewToolbar: React.FC = ({ className, oui {bulkSelect} )} - {actions && ( + {filters && ( - {actions} + {filters} )} - {filters && ( + {actions && ( - {filters} + {actions} )} {pagination && (
+ + There are no matching data to be displayed. + + + + + + + + + + +
` component, such as `width`, `sort`, and other table head cell properties. +- `rows`: Defines the rows to be displayed in the table. Each item in the array can be either an array of `DataViewTd` for simple rows, or an object with the following properties: + - `row`: Content to display in each cell in the row. + - `id` (optional): Unique identifier for the row that's used for matching selected items. + - `props` (optional): (`TrProps`) to pass to the `