Skip to content

Add drag and drop column component #763

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
# Sidenav top-level section
# should be the same for all markdown files
section: Component groups
subsection: Helpers
# Sidenav secondary level section
# should be the same for all markdown files
id: Column management
# 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
propComponents: ['ColumnManagement']
sourceLink: https://github.com/patternfly/react-component-groups/blob/main/packages/module/patternfly-docs/content/extensions/component-groups/examples/ColumnManagement/ColumnManagement.md
---

import ColumnManagement from '@patternfly/react-component-groups/dist/dynamic/ColumnManagement';
import { FunctionComponent, useState } from 'react';

The **column management** component can be used to implement customizable table columns. Columns can be configured to be enabled or disabled by default or be unhidable.

## Examples

### Basic column list

The order of the columns can be changed by dragging and dropping the columns themselves. This list can be used within a page or within a modal. Always make sure to set `isShownByDefault` and `isShown` to the same boolean value in the initial state.

```js file="./ColumnManagementExample.tsx"
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { FunctionComponent, useState } from 'react';
import { Column, ColumnManagement } from '@patternfly/react-component-groups';

const DEFAULT_COLUMNS: Column[] = [
{
title: 'ID',
key: 'id',
isShownByDefault: true,
isShown: true,
isUntoggleable: true
},
{
title: 'Publish date',
key: 'publishDate',
isShownByDefault: true,
isShown: true
},
{
title: 'Impact',
key: 'impact',
isShownByDefault: true,
isShown: true
},
{
title: 'Score',
key: 'score',
isShownByDefault: false,
isShown: false
}
];

export const ColumnExample: FunctionComponent = () => {
const [ columns, setColumns ] = useState(DEFAULT_COLUMNS);

return (
<ColumnManagement
title="Manage columns"
description="Select the columns to display in the table."
columns={columns}
onOrderChange={setColumns}
onSelect={(col) => {
const newColumns = [...columns];
const changedColumn = newColumns.find(c => c.key === col.key);
if (changedColumn) {
changedColumn.isShown = col.isShown;
}
setColumns(newColumns);
}}
onSelectAll={(newColumns) => setColumns(newColumns)}
onSave={(newColumns) => {
setColumns(newColumns);
alert('Changes saved!');
}}
onCancel={() => alert('Changes cancelled!')}
/>
);
};
77 changes: 77 additions & 0 deletions packages/module/src/ColumnManagement/ColumnManagement.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';
import ColumnManagement from './ColumnManagement';

const mockColumns = [
{ key: 'name', title: 'Name', isShown: true, isShownByDefault: true },
{ key: 'status', title: 'Status', isShown: true, isShownByDefault: true },
{ key: 'version', title: 'Version', isShown: false, isShownByDefault: false },
];

describe('Column', () => {
it('renders with initial columns', () => {
render(<ColumnManagement columns={mockColumns} />);
expect(screen.getByTestId('column-check-name')).toBeChecked();
expect(screen.getByTestId('column-check-status')).toBeChecked();
expect(screen.getByTestId('column-check-version')).not.toBeChecked();
});

it('renders title and description', () => {
render(<ColumnManagement columns={mockColumns} title="Test Title" description="Test Description" />);
expect(screen.getByText('Test Title')).toBeInTheDocument();
expect(screen.getByText('Test Description')).toBeInTheDocument();
});

it('renders a cancel button', async () => {
const onCancel = jest.fn();
render(<ColumnManagement columns={mockColumns} onCancel={onCancel} />);
const cancelButton = screen.getByText('Cancel');
expect(cancelButton).toBeInTheDocument();
await userEvent.click(cancelButton);
expect(onCancel).toHaveBeenCalled();
});

it('toggles a column', async () => {
const onSelect = jest.fn();
render(<ColumnManagement columns={mockColumns} onSelect={onSelect} />);
const nameCheckbox = screen.getByTestId('column-check-name');
await userEvent.click(nameCheckbox);
expect(nameCheckbox).not.toBeChecked();
expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ key: 'name', isShown: false }));
});

it('selects all columns', async () => {
render(<ColumnManagement columns={mockColumns} />);
const menuToggle = screen.getByLabelText('Select all').closest('button');
if (menuToggle) {
await userEvent.click(menuToggle);
}
const selectAllButton = screen.getByText('Select all');
await userEvent.click(selectAllButton);
expect(screen.getByTestId('column-check-name')).toBeChecked();
expect(screen.getByTestId('column-check-status')).toBeChecked();
expect(screen.getByTestId('column-check-version')).toBeChecked();
});

it('selects no columns', async () => {
render(<ColumnManagement columns={mockColumns} />);
const menuToggle = screen.getByLabelText('Select all').closest('button');
if (menuToggle) {
await userEvent.click(menuToggle);
}
const selectNoneButton = screen.getByText('Select none');
await userEvent.click(selectNoneButton);
expect(screen.getByTestId('column-check-name')).not.toBeChecked();
expect(screen.getByTestId('column-check-status')).not.toBeChecked();
expect(screen.getByTestId('column-check-version')).not.toBeChecked();
});

it('saves changes', async () => {
const onSave = jest.fn();
render(<ColumnManagement columns={mockColumns} onSave={onSave} />);
const saveButton = screen.getByText('Save');
await userEvent.click(saveButton);
expect(onSave).toHaveBeenCalledWith(expect.any(Array));
});
});
196 changes: 196 additions & 0 deletions packages/module/src/ColumnManagement/ColumnManagement.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
import type { FunctionComponent } from 'react';
import { useState, useEffect } from 'react';
import {
DataListItem,
DataList,
DataListItemRow,
DataListCheck,
DataListCell,
DataListItemCells,
DataListControl,
DataListDragButton,
Button,
ButtonVariant,
Title,
Checkbox,
Dropdown,
DropdownItem,
MenuToggle
} from '@patternfly/react-core';
import {
DragDrop,
Droppable,
Draggable
} from '@patternfly/react-core/deprecated';

export interface Column {
/** Internal identifier of a column by which table displayed columns are filtered. */
key: string;
/** The actual display name of the column possibly with a tooltip or icon. */
title: React.ReactNode;
/** If user changes checkboxes, the component will send back column array with this property altered. */
isShown?: boolean;
/** Set to false if the column should be hidden initially */
isShownByDefault: boolean;
/** The checkbox will be disabled, this is applicable to columns which should not be toggleable by user */
isUntoggleable?: boolean;
}

export interface ColumnProps {
/** Current column state */
columns: Column[];
/* Column description text */
description?: string;
/* Column title text */
title?: string;
/** Custom OUIA ID */
ouiaId?: string | number;
/** Callback when a column is selected or deselected */
onSelect?: (column: Column) => void;
/** Callback when all columns are selected or deselected */
onSelectAll?: (columns: Column[]) => void;
/** Callback when the column order changes */
onOrderChange?: (columns: Column[]) => void;
/** Callback to save the column state */
onSave?: (columns: Column[]) => void;
/** Callback to close the modal */
onCancel?: () => void;
}

const ColumnManagement: FunctionComponent<ColumnProps> = (
{ columns,
description,
title,
ouiaId = 'Column',
onSelect,
onSelectAll,
onOrderChange,
onSave,
onCancel }: ColumnProps) => {

const [ isDropdownOpen, setIsDropdownOpen ] = useState(false);
const [ currentColumns, setCurrentColumns ] = useState(
() => columns.map(column => ({ ...column, isShown: column.isShown ?? column.isShownByDefault, id: column.key }))
);

useEffect(() => {
setCurrentColumns(columns.map(column => ({ ...column, isShown: column.isShown ?? column.isShownByDefault, id: column.key })));
}, [ columns ]);

const handleChange = index => {
const newColumns = [ ...currentColumns ];
const changedColumn = { ...newColumns[index] };

changedColumn.isShown = !changedColumn.isShown;
newColumns[index] = changedColumn;

setCurrentColumns(newColumns);
onSelect?.(changedColumn);
};

const onDrag = (source, dest) => {
if (dest) {
const newColumns = [ ...currentColumns ];
const [ removed ] = newColumns.splice(source.index, 1);
newColumns.splice(dest.index, 0, removed);
setCurrentColumns(newColumns);
onOrderChange?.(newColumns);
return true;
}
return false;
};

const handleSave = () => {
onSave?.(currentColumns);
}

const handleSelectAll = (select = true) => {
const newColumns = currentColumns.map(c => ({ ...c, isShown: c.isUntoggleable ? c.isShown : select }));
setCurrentColumns(newColumns);
onSelectAll?.(newColumns);
}

const isAllSelected = () => currentColumns.every(c => c.isShown || c.isUntoggleable);
const isSomeSelected = () => currentColumns.some(c => c.isShown);

const dropdownItems = [
<DropdownItem key="select-all" onClick={() => handleSelectAll(true)}>Select all</DropdownItem>,
<DropdownItem key="deselect-all" onClick={() => handleSelectAll(false)}>Select none</DropdownItem>
];

return (
<>
<Title headingLevel="h3">{title}</Title>
{description && <div style={{ paddingBottom: '1rem' }}><p>{description}</p></div>}
<div style={{ paddingBottom: '1rem' }}>
<Dropdown
onSelect={() => setIsDropdownOpen(false)}
toggle={(toggleRef) => (
<MenuToggle
ref={toggleRef}
onClick={() => setIsDropdownOpen(!isDropdownOpen)}
isExpanded={isDropdownOpen}
>
<Checkbox
aria-label="Select all"
isChecked={isAllSelected() ? true : isSomeSelected() ? null : false}
id={`${ouiaId}-select-all-checkbox`}
/>
</MenuToggle>
)}
isOpen={isDropdownOpen}
>
{dropdownItems}
</Dropdown>
</div>
<DragDrop onDrop={onDrag}>
<Droppable droppableId="draggable-datalist">
<DataList aria-label="Selected columns" isCompact data-ouia-component-id={`${ouiaId}-column-list`}>
{currentColumns.map((column, index) =>
<Draggable key={column.key} id={column.key}>
<DataListItem key={column.key} data-testid={`column-item-${column.key}`}>
<DataListItemRow>
<DataListControl>
<DataListDragButton
aria-label="Reorder"
aria-labelledby={`${ouiaId}-column-${index}-label`}
/>
</DataListControl>
<DataListCheck
data-testid={`column-check-${column.key}`}
isChecked={column.isShown}
onChange={() => handleChange(index)}
isDisabled={column.isUntoggleable}
aria-labelledby={`${ouiaId}-column-${index}-label`}
ouiaId={`${ouiaId}-column-${index}-checkbox`}
id={`${ouiaId}-column-${index}-checkbox`}
/>
<DataListItemCells
dataListCells={[
<DataListCell key={column.key} data-ouia-component-id={`${ouiaId}-column-${index}-label`}>
<label htmlFor={`${ouiaId}-column-${index}-checkbox`} id={`${ouiaId}-column-${index}-label`}>
{column.title}
</label>
</DataListCell>
]}
/>
</DataListItemRow>
</DataListItem>
</Draggable>
)}
</DataList>
</Droppable>
</DragDrop>
<div style={{ display: 'flex', justifyContent: 'normal', paddingTop: '1rem' }}>
<Button key="save" variant={ButtonVariant.primary} onClick={handleSave} ouiaId={`${ouiaId}-save-button`}>
Save
</Button>
<Button key="cancel" variant={ButtonVariant.link} onClick={onCancel} ouiaId={`${ouiaId}-cancel-button`}>
Cancel
</Button>
</div>
</>
);
}

export default ColumnManagement;
2 changes: 2 additions & 0 deletions packages/module/src/ColumnManagement/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { default } from './ColumnManagement';
export * from './ColumnManagement';
3 changes: 3 additions & 0 deletions packages/module/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ export * from './ErrorBoundary';
export { default as ColumnManagementModal } from './ColumnManagementModal';
export * from './ColumnManagementModal';

export { default as ColumnManagement } from './ColumnManagement';
export * from './ColumnManagement';

export { default as CloseButton } from './CloseButton';
export * from './CloseButton';

Expand Down
Loading