@patternfly/react-data-view 6.4.0-prerelease.9 → 6.5.0-prerelease.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/cjs/DataViewTextFilter/DataViewTextFilter.d.ts +2 -0
  2. package/dist/cjs/DataViewTextFilter/DataViewTextFilter.js +29 -1
  3. package/dist/cjs/DataViewTextFilter/DataViewTextFilter.test.d.ts +1 -1
  4. package/dist/cjs/DataViewTextFilter/DataViewTextFilter.test.js +83 -0
  5. package/dist/cjs/DataViewTh/DataViewTh.d.ts +4 -4
  6. package/dist/cjs/DataViewTh/DataViewTh.js +8 -1
  7. package/dist/cjs/DataViewToolbar/DataViewToolbar.js +13 -1
  8. package/dist/cjs/DataViewTreeFilter/DataViewTreeFilter.d.ts +26 -0
  9. package/dist/cjs/DataViewTreeFilter/DataViewTreeFilter.js +229 -0
  10. package/dist/cjs/DataViewTreeFilter/DataViewTreeFilter.test.d.ts +1 -0
  11. package/dist/cjs/DataViewTreeFilter/DataViewTreeFilter.test.js +171 -0
  12. package/dist/cjs/DataViewTreeFilter/index.d.ts +2 -0
  13. package/dist/cjs/DataViewTreeFilter/index.js +23 -0
  14. package/dist/cjs/Hooks/selection.d.ts +8 -8
  15. package/dist/cjs/index.d.ts +2 -0
  16. package/dist/cjs/index.js +4 -1
  17. package/dist/dynamic/DataViewTreeFilter/package.json +1 -0
  18. package/dist/dynamic-modules.json +2 -0
  19. package/dist/esm/DataViewTextFilter/DataViewTextFilter.d.ts +2 -0
  20. package/dist/esm/DataViewTextFilter/DataViewTextFilter.js +29 -1
  21. package/dist/esm/DataViewTextFilter/DataViewTextFilter.test.d.ts +1 -1
  22. package/dist/esm/DataViewTextFilter/DataViewTextFilter.test.js +84 -1
  23. package/dist/esm/DataViewTh/DataViewTh.d.ts +4 -4
  24. package/dist/esm/DataViewTh/DataViewTh.js +8 -1
  25. package/dist/esm/DataViewToolbar/DataViewToolbar.js +13 -1
  26. package/dist/esm/DataViewTreeFilter/DataViewTreeFilter.d.ts +26 -0
  27. package/dist/esm/DataViewTreeFilter/DataViewTreeFilter.js +225 -0
  28. package/dist/esm/DataViewTreeFilter/DataViewTreeFilter.test.d.ts +1 -0
  29. package/dist/esm/DataViewTreeFilter/DataViewTreeFilter.test.js +166 -0
  30. package/dist/esm/DataViewTreeFilter/index.d.ts +2 -0
  31. package/dist/esm/DataViewTreeFilter/index.js +2 -0
  32. package/dist/esm/Hooks/selection.d.ts +8 -8
  33. package/dist/esm/index.d.ts +2 -0
  34. package/dist/esm/index.js +2 -0
  35. package/dist/tsconfig.tsbuildinfo +1 -1
  36. package/package.json +1 -1
  37. package/patternfly-docs/content/extensions/data-view/examples/DataView/PredefinedLayoutFullExample.tsx +2 -1
  38. package/patternfly-docs/content/extensions/data-view/examples/Toolbar/FiltersExample.tsx +2 -1
  39. package/patternfly-docs/content/extensions/data-view/examples/Toolbar/PaginationExample.tsx +1 -1
  40. package/patternfly-docs/content/extensions/data-view/examples/Toolbar/Toolbar.md +8 -1
  41. package/patternfly-docs/content/extensions/data-view/examples/Toolbar/TreeFilterExample.tsx +248 -0
  42. package/src/DataViewTextFilter/DataViewTextFilter.test.tsx +129 -0
  43. package/src/DataViewTextFilter/DataViewTextFilter.tsx +58 -22
  44. package/src/DataViewTh/DataViewTh.tsx +15 -7
  45. package/src/DataViewToolbar/DataViewToolbar.tsx +17 -2
  46. package/src/DataViewToolbar/__snapshots__/DataViewToolbar.test.tsx.snap +288 -280
  47. package/src/DataViewTreeFilter/DataViewTreeFilter.test.tsx +222 -0
  48. package/src/DataViewTreeFilter/DataViewTreeFilter.tsx +361 -0
  49. package/src/DataViewTreeFilter/__snapshots__/DataViewTreeFilter.test.tsx.snap +199 -0
  50. package/src/DataViewTreeFilter/index.ts +2 -0
  51. package/src/Hooks/selection.ts +8 -8
  52. package/src/index.ts +3 -0
@@ -16,6 +16,8 @@ export interface DataViewTextFilterProps extends SearchInputProps {
16
16
  trimValue?: boolean;
17
17
  /** Custom OUIA ID */
18
18
  ouiaId?: string;
19
+ /** Enable keyboard shortcut (/) to focus the filter. Defaults to true. */
20
+ enableShortcut?: boolean;
19
21
  }
20
22
  export declare const DataViewTextFilter: FC<DataViewTextFilterProps>;
21
23
  export default DataViewTextFilter;
@@ -13,9 +13,37 @@ var __rest = (this && this.__rest) || function (s, e) {
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
14
  exports.DataViewTextFilter = void 0;
15
15
  const jsx_runtime_1 = require("react/jsx-runtime");
16
+ const react_1 = require("react");
16
17
  const react_core_1 = require("@patternfly/react-core");
17
18
  const DataViewTextFilter = (_a) => {
18
- var { filterId, title, value = '', onChange, onClear = () => onChange === null || onChange === void 0 ? void 0 : onChange(undefined, ''), showToolbarItem, trimValue = true, ouiaId = 'DataViewTextFilter' } = _a, props = __rest(_a, ["filterId", "title", "value", "onChange", "onClear", "showToolbarItem", "trimValue", "ouiaId"]);
19
+ var { filterId, title, value = '', onChange, onClear = () => onChange === null || onChange === void 0 ? void 0 : onChange(undefined, ''), showToolbarItem, trimValue = true, ouiaId = 'DataViewTextFilter', enableShortcut = true } = _a, props = __rest(_a, ["filterId", "title", "value", "onChange", "onClear", "showToolbarItem", "trimValue", "ouiaId", "enableShortcut"]);
20
+ (0, react_1.useEffect)(() => {
21
+ if (!enableShortcut) {
22
+ return;
23
+ }
24
+ const handleKeyDown = (event) => {
25
+ // Only handle "/" key when not typing in an input, textarea, or contenteditable element
26
+ if (event.key === '/' && !event.ctrlKey && !event.metaKey && !event.altKey) {
27
+ const target = event.target;
28
+ const isInputElement = target.tagName === 'INPUT' ||
29
+ target.tagName === 'TEXTAREA' ||
30
+ target.isContentEditable;
31
+ // Only focus if the filter is visible and we're not already in an input field
32
+ if (showToolbarItem && !isInputElement) {
33
+ // Find the input element by its ID (searchInputId prop)
34
+ const inputElement = document.getElementById(filterId);
35
+ if (inputElement) {
36
+ event.preventDefault();
37
+ inputElement.focus();
38
+ }
39
+ }
40
+ }
41
+ };
42
+ window.addEventListener('keydown', handleKeyDown);
43
+ return () => {
44
+ window.removeEventListener('keydown', handleKeyDown);
45
+ };
46
+ }, [showToolbarItem, filterId, enableShortcut]);
19
47
  return ((0, jsx_runtime_1.jsx)(react_core_1.ToolbarFilter, { "data-ouia-component-id": ouiaId, labels: value.length > 0 ? [{ key: title, node: value }] : [], deleteLabel: () => onChange === null || onChange === void 0 ? void 0 : onChange(undefined, ''), categoryName: title, showToolbarItem: showToolbarItem, children: (0, jsx_runtime_1.jsx)(react_core_1.SearchInput, Object.assign({ searchInputId: filterId, value: value, onChange: (e, inputValue) => onChange === null || onChange === void 0 ? void 0 : onChange(e, trimValue ? inputValue.trim() : inputValue), onClear: onClear, placeholder: `Filter by ${title}`, "aria-label": `${title !== null && title !== void 0 ? title : filterId} filter`, "data-ouia-component-id": `${ouiaId}-input` }, props)) }, ouiaId));
20
48
  };
21
49
  exports.DataViewTextFilter = DataViewTextFilter;
@@ -1 +1 @@
1
- export {};
1
+ import '@testing-library/jest-dom';
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const jsx_runtime_1 = require("react/jsx-runtime");
7
7
  const react_1 = require("@testing-library/react");
8
+ require("@testing-library/jest-dom");
8
9
  const DataViewTextFilter_1 = __importDefault(require("./DataViewTextFilter"));
9
10
  const DataViewToolbar_1 = __importDefault(require("../DataViewToolbar"));
10
11
  describe('DataViewTextFilter component', () => {
@@ -19,4 +20,86 @@ describe('DataViewTextFilter component', () => {
19
20
  const { container } = (0, react_1.render)((0, jsx_runtime_1.jsx)(DataViewToolbar_1.default, { filters: (0, jsx_runtime_1.jsx)(DataViewTextFilter_1.default, Object.assign({}, defaultProps)) }));
20
21
  expect(container).toMatchSnapshot();
21
22
  });
23
+ it('should focus the search input when "/" key is pressed and filter is visible', () => {
24
+ (0, react_1.render)((0, jsx_runtime_1.jsx)(DataViewToolbar_1.default, { filters: (0, jsx_runtime_1.jsx)(DataViewTextFilter_1.default, Object.assign({}, defaultProps, { showToolbarItem: true })) }));
25
+ const input = document.getElementById('test-filter');
26
+ expect(input).toBeInTheDocument();
27
+ // Simulate pressing "/" key by creating and dispatching a KeyboardEvent
28
+ const keyEvent = new KeyboardEvent('keydown', {
29
+ key: '/',
30
+ code: 'Slash',
31
+ bubbles: true,
32
+ cancelable: true,
33
+ });
34
+ window.dispatchEvent(keyEvent);
35
+ // Check that the input has focus
36
+ expect(document.activeElement).toBe(input);
37
+ });
38
+ it('should not focus the search input when "/" key is pressed if filter is not visible', () => {
39
+ (0, react_1.render)((0, jsx_runtime_1.jsx)(DataViewToolbar_1.default, { filters: (0, jsx_runtime_1.jsx)(DataViewTextFilter_1.default, Object.assign({}, defaultProps, { showToolbarItem: false })) }));
40
+ const input = document.getElementById('test-filter');
41
+ // Simulate pressing "/" key
42
+ const keyEvent = new KeyboardEvent('keydown', {
43
+ key: '/',
44
+ code: 'Slash',
45
+ bubbles: true,
46
+ cancelable: true,
47
+ });
48
+ window.dispatchEvent(keyEvent);
49
+ if (input) {
50
+ expect(document.activeElement).not.toBe(input);
51
+ }
52
+ });
53
+ it('should not focus the search input when "/" key is pressed while typing in another input', () => {
54
+ const { container } = (0, react_1.render)((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("input", { "data-testid": "other-input" }), (0, jsx_runtime_1.jsx)(DataViewToolbar_1.default, { filters: (0, jsx_runtime_1.jsx)(DataViewTextFilter_1.default, Object.assign({}, defaultProps, { showToolbarItem: true })) })] }));
55
+ const otherInput = container.querySelector('[data-testid="other-input"]');
56
+ // Focus the other input first
57
+ otherInput.focus();
58
+ expect(document.activeElement).toBe(otherInput);
59
+ // Simulate pressing "/" key while focused on the other input
60
+ // The event target should be the input element
61
+ const keyEvent = new KeyboardEvent('keydown', {
62
+ key: '/',
63
+ code: 'Slash',
64
+ bubbles: true,
65
+ cancelable: true,
66
+ });
67
+ Object.defineProperty(keyEvent, 'target', {
68
+ value: otherInput,
69
+ enumerable: true,
70
+ });
71
+ window.dispatchEvent(keyEvent);
72
+ // The search input should not be focused since we're already in an input field
73
+ expect(document.activeElement).toBe(otherInput);
74
+ });
75
+ it('should not focus the search input when enableShortcut is false', () => {
76
+ (0, react_1.render)((0, jsx_runtime_1.jsx)(DataViewToolbar_1.default, { filters: (0, jsx_runtime_1.jsx)(DataViewTextFilter_1.default, Object.assign({}, defaultProps, { showToolbarItem: true, enableShortcut: false })) }));
77
+ const input = document.getElementById('test-filter');
78
+ expect(input).toBeInTheDocument();
79
+ // Simulate pressing "/" key
80
+ const keyEvent = new KeyboardEvent('keydown', {
81
+ key: '/',
82
+ code: 'Slash',
83
+ bubbles: true,
84
+ cancelable: true,
85
+ });
86
+ window.dispatchEvent(keyEvent);
87
+ // The input should not be focused since the shortcut is disabled
88
+ expect(document.activeElement).not.toBe(input);
89
+ });
90
+ it('should focus the search input when enableShortcut is true (default)', () => {
91
+ (0, react_1.render)((0, jsx_runtime_1.jsx)(DataViewToolbar_1.default, { filters: (0, jsx_runtime_1.jsx)(DataViewTextFilter_1.default, Object.assign({}, defaultProps, { showToolbarItem: true })) }));
92
+ const input = document.getElementById('test-filter');
93
+ expect(input).toBeInTheDocument();
94
+ // Simulate pressing "/" key
95
+ const keyEvent = new KeyboardEvent('keydown', {
96
+ key: '/',
97
+ code: 'Slash',
98
+ bubbles: true,
99
+ cancelable: true,
100
+ });
101
+ window.dispatchEvent(keyEvent);
102
+ // The input should be focused since the shortcut is enabled by default
103
+ expect(document.activeElement).toBe(input);
104
+ });
22
105
  });
@@ -5,13 +5,13 @@ export interface DataViewThResizableProps {
5
5
  isResizable?: boolean;
6
6
  /** Callback after the column is resized. Returns the triggering event, the column id passed in via cell props, and the new width of the column. */
7
7
  onResize?: (event: ReactMouseEvent | MouseEvent | ReactKeyboardEvent | KeyboardEvent | TouchEvent, id: string | number | undefined, width: number) => void;
8
- /** Width of the column */
8
+ /** Starting width in pixels of the column */
9
9
  width?: number;
10
- /** Minimum width of the column */
10
+ /** Minimum resize width in pixels of the column */
11
11
  minWidth?: number;
12
- /** Increment for keyboard navigation */
12
+ /** Increment in pixels for keyboard navigation */
13
13
  increment?: number;
14
- /** Increment for keyboard navigation while shift is held */
14
+ /** Increment in pixels for keyboard navigation while shift is held */
15
15
  shiftIncrement?: number;
16
16
  /** Provides an accessible name for the resizable column via a human readable string. */
17
17
  resizeButtonAriaLabel?: string;
@@ -216,7 +216,14 @@ const DataViewTh = (_a) => {
216
216
  onResize && onResize(e, thProps === null || thProps === void 0 ? void 0 : thProps.id, newSize);
217
217
  };
218
218
  const resizableContent = ((0, jsx_runtime_1.jsxs)(react_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("div", { "aria-live": "polite", className: "pf-v6-screen-reader", children: screenReaderText }), (0, jsx_runtime_1.jsx)(react_core_1.Button, { ref: resizeButtonRef, variant: "plain", hasNoPadding: true, icon: (0, jsx_runtime_1.jsx)(ResizeIcon, {}), onMouseDown: handleMousedown, onKeyDown: handleKeys, onTouchStart: handleTouchStart, "aria-label": resizeButtonAriaLabel, className: classes.dataViewResizableButton })] }));
219
- return ((0, jsx_runtime_1.jsx)(react_table_1.Th, Object.assign({}, thProps, props, { style: width > 0 ? { minWidth: width } : undefined, ref: thRef, modifier: "truncate", className: dataViewThClassName }, (isResizable && { additionalContent: resizableContent }), { children: content })));
219
+ const classNames = [];
220
+ if (thProps === null || thProps === void 0 ? void 0 : thProps.className) {
221
+ classNames.push(thProps.className);
222
+ }
223
+ if (dataViewThClassName) {
224
+ classNames.push(dataViewThClassName);
225
+ }
226
+ return ((0, jsx_runtime_1.jsx)(react_table_1.Th, Object.assign({ modifier: "truncate" }, thProps, props, { ref: thRef, style: width > 0 ? Object.assign(Object.assign({}, thProps === null || thProps === void 0 ? void 0 : thProps.style), { minWidth: width }) : thProps === null || thProps === void 0 ? void 0 : thProps.style, className: classNames.length > 0 ? classNames.join(' ') : undefined }, (isResizable && { additionalContent: resizableContent }), { children: content })));
220
227
  };
221
228
  exports.DataViewTh = DataViewTh;
222
229
  exports.default = exports.DataViewTh;
@@ -15,10 +15,22 @@ exports.DataViewToolbar = void 0;
15
15
  const jsx_runtime_1 = require("react/jsx-runtime");
16
16
  const react_1 = require("react");
17
17
  const react_core_1 = require("@patternfly/react-core");
18
+ const react_jss_1 = require("react-jss");
19
+ const useStyles = (0, react_jss_1.createUseStyles)({
20
+ dataViewToolbarPagination: {
21
+ flexBasis: '100%',
22
+ width: '100%'
23
+ },
24
+ dataViewToolbarPaginationWrapper: {
25
+ flexBasis: '100%',
26
+ width: '100%'
27
+ }
28
+ });
18
29
  const DataViewToolbar = (_a) => {
19
30
  var { className, ouiaId = 'DataViewToolbar', bulkSelect, actions, toggleGroup, pagination, filters, customLabelGroupContent, clearAllFilters, children } = _a, props = __rest(_a, ["className", "ouiaId", "bulkSelect", "actions", "toggleGroup", "pagination", "filters", "customLabelGroupContent", "clearAllFilters", "children"]);
31
+ const classes = useStyles();
20
32
  const defaultClearFilters = (0, react_1.useRef)((0, jsx_runtime_1.jsx)(react_core_1.ToolbarItem, { children: (0, jsx_runtime_1.jsx)(react_core_1.Button, { ouiaId: `${ouiaId}-clear-all-filters`, variant: "link", onClick: clearAllFilters, isInline: true, children: "Clear filters" }) }));
21
- return ((0, jsx_runtime_1.jsx)(react_core_1.Toolbar, Object.assign({ ouiaId: ouiaId, className: className, customLabelGroupContent: customLabelGroupContent !== null && customLabelGroupContent !== void 0 ? customLabelGroupContent : defaultClearFilters.current }, props, { children: (0, jsx_runtime_1.jsxs)(react_core_1.ToolbarContent, { children: [bulkSelect && ((0, jsx_runtime_1.jsx)(react_core_1.ToolbarItem, { "data-ouia-component-id": `${ouiaId}-bulk-select`, children: bulkSelect })), filters && ((0, jsx_runtime_1.jsx)(react_core_1.ToolbarItem, { children: filters })), actions && ((0, jsx_runtime_1.jsx)(react_core_1.ToolbarItem, { children: actions })), toggleGroup && ((0, jsx_runtime_1.jsx)(react_core_1.ToolbarItem, { children: toggleGroup })), pagination && ((0, jsx_runtime_1.jsx)(react_core_1.ToolbarItem, { variant: react_core_1.ToolbarItemVariant.pagination, "data-ouia-component-id": `${ouiaId}-pagination`, children: pagination })), children] }) })));
33
+ return ((0, jsx_runtime_1.jsx)(react_core_1.Toolbar, Object.assign({ ouiaId: ouiaId, className: className, customLabelGroupContent: customLabelGroupContent !== null && customLabelGroupContent !== void 0 ? customLabelGroupContent : defaultClearFilters.current }, props, { children: (0, jsx_runtime_1.jsxs)(react_core_1.ToolbarContent, { children: [bulkSelect && ((0, jsx_runtime_1.jsx)(react_core_1.ToolbarItem, { "data-ouia-component-id": `${ouiaId}-bulk-select`, children: bulkSelect })), filters && ((0, jsx_runtime_1.jsx)(react_core_1.ToolbarItem, { children: filters })), actions && ((0, jsx_runtime_1.jsx)(react_core_1.ToolbarItem, { children: actions })), toggleGroup && ((0, jsx_runtime_1.jsx)(react_core_1.ToolbarItem, { children: toggleGroup })), pagination && ((0, jsx_runtime_1.jsx)(react_core_1.ToolbarItem, { variant: react_core_1.ToolbarItemVariant.pagination, "data-ouia-component-id": `${ouiaId}-pagination`, className: classes.dataViewToolbarPagination, children: (0, jsx_runtime_1.jsx)("div", { className: classes.dataViewToolbarPaginationWrapper, children: pagination }) })), children] }) })));
22
34
  };
23
35
  exports.DataViewToolbar = DataViewToolbar;
24
36
  exports.default = exports.DataViewToolbar;
@@ -0,0 +1,26 @@
1
+ import { ToolbarFilterProps, TreeViewDataItem } from '@patternfly/react-core';
2
+ import React, { FC } from 'react';
3
+ export interface DataViewTreeFilterProps {
4
+ /** Unique key for the filter attribute */
5
+ filterId: string;
6
+ /** Array of current filter values */
7
+ value?: string[];
8
+ /** Filter title displayed in the toolbar */
9
+ title: string;
10
+ /** Callback for when the selection changes */
11
+ onChange?: (event?: React.MouseEvent, values?: string[]) => void;
12
+ /** Controls visibility of the filter in the toolbar */
13
+ showToolbarItem?: ToolbarFilterProps['showToolbarItem'];
14
+ /** Custom OUIA ID */
15
+ ouiaId?: string;
16
+ /** Hierarchical data items for the tree structure */
17
+ items?: TreeViewDataItem[];
18
+ /** When true, expands all tree nodes by default */
19
+ defaultExpanded?: boolean;
20
+ /** Callback for when tree items are selected/deselected, provides all currently selected nodes */
21
+ onSelect?: (selectedItems: TreeViewDataItem[]) => void;
22
+ /** Array of pre-selected item id's to be checked on initial render */
23
+ defaultSelected?: string[];
24
+ }
25
+ export declare const DataViewTreeFilter: FC<DataViewTreeFilterProps>;
26
+ export default DataViewTreeFilter;
@@ -0,0 +1,229 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DataViewTreeFilter = void 0;
4
+ const jsx_runtime_1 = require("react/jsx-runtime");
5
+ const react_core_1 = require("@patternfly/react-core");
6
+ const react_1 = require("react");
7
+ const react_jss_1 = require("react-jss");
8
+ /** This style is needed so the tree filter dropdown looks like the basic filter dropdow */
9
+ const useStyles = (0, react_jss_1.createUseStyles)({
10
+ dataViewTreeFilterTreeView: {
11
+ '& .pf-v6-c-tree-view__node::after': {
12
+ borderRadius: 0,
13
+ borderRightStyle: 'none',
14
+ borderLeftStyle: 'none'
15
+ },
16
+ '& .pf-v6-c-tree-view__content': {
17
+ borderRadius: 0
18
+ }
19
+ }
20
+ });
21
+ // Generic helper to collect items from tree based on predicate
22
+ const collectTreeItems = (items, predicate, leafOnly = false) => {
23
+ const collected = [];
24
+ const collect = (item) => {
25
+ var _a;
26
+ const isLeaf = !item.children || item.children.length === 0;
27
+ if (predicate(item) && (!leafOnly || isLeaf)) {
28
+ collected.push(item);
29
+ }
30
+ (_a = item.children) === null || _a === void 0 ? void 0 : _a.forEach(child => collect(child));
31
+ };
32
+ items.forEach(item => collect(item));
33
+ return collected;
34
+ };
35
+ // Helper function to get all checked items (not just leaf nodes)
36
+ const getAllCheckedItems = (items) => collectTreeItems(items, item => { var _a; return ((_a = item.checkProps) === null || _a === void 0 ? void 0 : _a.checked) === true; }, false);
37
+ // Get all checked leaf items (returns array of names)
38
+ const getAllCheckedLeafItems = (items) => collectTreeItems(items, item => { var _a; return ((_a = item.checkProps) === null || _a === void 0 ? void 0 : _a.checked) === true; }, true).map(item => String(item.name));
39
+ // Helper function to expand all nodes in the tree
40
+ const expandAllNodes = (items) => items.map(item => (Object.assign(Object.assign({}, item), { defaultExpanded: true, children: item.children ? expandAllNodes(item.children) : undefined })));
41
+ // Helper function to set pre-selected items
42
+ const setPreSelectedItems = (items, selectedIds) => items.map(item => {
43
+ var _a, _b;
44
+ const isSelected = selectedIds.includes(String(item.id));
45
+ const hasSelectedChildren = (_b = (_a = item.children) === null || _a === void 0 ? void 0 : _a.some(child => selectedIds.includes(String(child.id)))) !== null && _b !== void 0 ? _b : false;
46
+ return Object.assign(Object.assign({}, item), { checkProps: item.checkProps ? Object.assign(Object.assign({}, item.checkProps), { checked: isSelected || hasSelectedChildren }) : undefined, children: item.children ? setPreSelectedItems(item.children, selectedIds) : undefined });
47
+ });
48
+ // Helper function to uncheck all items recursively
49
+ const uncheckRecursive = (items) => items.map(item => (Object.assign(Object.assign({}, item), { checkProps: item.checkProps ? Object.assign(Object.assign({}, item.checkProps), { checked: false }) : undefined, children: item.children ? uncheckRecursive(item.children) : undefined })));
50
+ const DataViewTreeFilter = ({ filterId, title, value = [], onChange, showToolbarItem, ouiaId = 'DataViewTreeFilter', items, defaultExpanded = false, onSelect, defaultSelected = [] }) => {
51
+ const classes = useStyles();
52
+ const [isOpen, setIsOpen] = (0, react_1.useState)(false);
53
+ const [treeData, setTreeData] = (0, react_1.useState)(items || []);
54
+ const menuRef = (0, react_1.useRef)(null);
55
+ const isInitialMount = (0, react_1.useRef)(true);
56
+ const hasCalledInitialOnChange = (0, react_1.useRef)(false);
57
+ // Initialize tree data with defaultExpanded and defaultSelected (only on first mount)
58
+ (0, react_1.useEffect)(() => {
59
+ if (!items) {
60
+ return;
61
+ }
62
+ let initializedData = [...items];
63
+ // Apply default expansion
64
+ if (defaultExpanded) {
65
+ initializedData = expandAllNodes(initializedData);
66
+ }
67
+ // Apply pre-selected items only on initial mount
68
+ if (isInitialMount.current && defaultSelected.length > 0) {
69
+ initializedData = setPreSelectedItems(initializedData, defaultSelected);
70
+ }
71
+ setTreeData(initializedData);
72
+ if (isInitialMount.current) {
73
+ isInitialMount.current = false;
74
+ }
75
+ }, [items, defaultExpanded]);
76
+ // Call onChange and onSelect after tree data is initialized with default selections
77
+ (0, react_1.useEffect)(() => {
78
+ if (!hasCalledInitialOnChange.current && defaultSelected.length > 0 && treeData.length > 0) {
79
+ const selectedValues = getAllCheckedLeafItems(treeData);
80
+ // Only call if there are actually selected values
81
+ if (selectedValues.length > 0) {
82
+ // Calculate both values synchronously before calling callbacks
83
+ const selectedItems = getAllCheckedItems(treeData);
84
+ // useEffect already runs after render, so this is safe
85
+ if (onChange) {
86
+ onChange(undefined, selectedValues);
87
+ }
88
+ if (onSelect) {
89
+ onSelect(selectedItems);
90
+ }
91
+ hasCalledInitialOnChange.current = true;
92
+ }
93
+ }
94
+ }, [treeData, onChange, onSelect, defaultSelected.length]);
95
+ // Sync tree checkboxes when value prop changes (when clearAllFilters is called)
96
+ (0, react_1.useEffect)(() => {
97
+ if (value.length === 0) {
98
+ setTreeData(currentTreeData => {
99
+ if (currentTreeData.length === 0) {
100
+ return currentTreeData;
101
+ }
102
+ const currentCheckedItems = getAllCheckedLeafItems(currentTreeData);
103
+ // Only update if there are checked items that need to be unchecked
104
+ if (currentCheckedItems.length > 0) {
105
+ return uncheckRecursive(currentTreeData);
106
+ }
107
+ return currentTreeData;
108
+ });
109
+ }
110
+ }, [value]);
111
+ // Check if all children are checked (recursive)
112
+ const areAllChildrenChecked = (item) => {
113
+ var _a, _b;
114
+ if (!((_a = item.children) === null || _a === void 0 ? void 0 : _a.length)) {
115
+ return ((_b = item.checkProps) === null || _b === void 0 ? void 0 : _b.checked) === true;
116
+ }
117
+ return item.children.every(child => areAllChildrenChecked(child));
118
+ };
119
+ // Check if some children are checked (recursive)
120
+ const areSomeChildrenChecked = (item) => {
121
+ var _a, _b;
122
+ if (!((_a = item.children) === null || _a === void 0 ? void 0 : _a.length)) {
123
+ return ((_b = item.checkProps) === null || _b === void 0 ? void 0 : _b.checked) === true;
124
+ }
125
+ return item.children.some(child => areSomeChildrenChecked(child));
126
+ };
127
+ // Find tree item by name
128
+ const findItemByName = (items, name) => {
129
+ for (const item of items) {
130
+ if (item.name === name) {
131
+ return item;
132
+ }
133
+ if (item.children) {
134
+ const found = findItemByName(item.children, name);
135
+ if (found) {
136
+ return found;
137
+ }
138
+ }
139
+ }
140
+ return null;
141
+ };
142
+ // Find parent item by child ID
143
+ const findParentById = (items, childId) => {
144
+ var _a;
145
+ for (const item of items) {
146
+ if ((_a = item.children) === null || _a === void 0 ? void 0 : _a.some(child => child.id === childId)) {
147
+ return item;
148
+ }
149
+ if (item.children) {
150
+ const found = findParentById(item.children, childId);
151
+ if (found) {
152
+ return found;
153
+ }
154
+ }
155
+ }
156
+ return null;
157
+ };
158
+ // Update parent checkbox states based on children (recursive)
159
+ const onCheckParentHandle = (childId) => {
160
+ const parent = findParentById(treeData, childId);
161
+ if (!parent) {
162
+ return;
163
+ }
164
+ if (parent.checkProps) {
165
+ const allChildrenChecked = areAllChildrenChecked(parent);
166
+ const someChildrenChecked = areSomeChildrenChecked(parent);
167
+ if (allChildrenChecked) {
168
+ parent.checkProps.checked = true;
169
+ }
170
+ else if (someChildrenChecked) {
171
+ parent.checkProps.checked = null;
172
+ }
173
+ else {
174
+ parent.checkProps.checked = false;
175
+ }
176
+ }
177
+ if (parent.id) {
178
+ onCheckParentHandle(parent.id);
179
+ }
180
+ };
181
+ // Check/uncheck item and all its children (recursive)
182
+ const onCheckHandle = (treeViewItem, checked) => {
183
+ var _a;
184
+ if (treeViewItem.checkProps) {
185
+ treeViewItem.checkProps.checked = checked;
186
+ }
187
+ (_a = treeViewItem.children) === null || _a === void 0 ? void 0 : _a.forEach(child => onCheckHandle(child, checked));
188
+ };
189
+ // Handle checkbox change event
190
+ const onCheck = (event, treeViewItem) => {
191
+ const checked = event.target.checked;
192
+ onCheckHandle(treeViewItem, checked);
193
+ if (treeViewItem.id) {
194
+ onCheckParentHandle(treeViewItem.id);
195
+ }
196
+ setTreeData(prev => [...prev]);
197
+ const selectedValues = getAllCheckedLeafItems(treeData);
198
+ onChange === null || onChange === void 0 ? void 0 : onChange(event, selectedValues);
199
+ if (onSelect) {
200
+ const selectedItems = getAllCheckedItems(treeData);
201
+ onSelect(selectedItems);
202
+ }
203
+ };
204
+ // Clear a specific filter by name (when label chip is removed)
205
+ const onFilterSelectorClear = (itemName) => {
206
+ const treeViewItem = findItemByName(treeData, itemName);
207
+ if (!treeViewItem) {
208
+ return;
209
+ }
210
+ onCheckHandle(treeViewItem, false);
211
+ if (treeViewItem.id) {
212
+ onCheckParentHandle(treeViewItem.id);
213
+ }
214
+ };
215
+ // Uncheck all items in the tree
216
+ const uncheckAllItems = () => {
217
+ const updatedTreeData = uncheckRecursive(treeData);
218
+ setTreeData(updatedTreeData);
219
+ onChange === null || onChange === void 0 ? void 0 : onChange(undefined, []);
220
+ };
221
+ const dropdown = ((0, jsx_runtime_1.jsx)(react_core_1.Dropdown, { ref: menuRef, isOpen: isOpen, onOpenChange: (isOpen) => setIsOpen(isOpen), toggle: (toggleRef) => ((0, jsx_runtime_1.jsx)(react_core_1.MenuToggle, { ref: toggleRef, onClick: () => setIsOpen(!isOpen), isExpanded: isOpen, children: title })), ouiaId: ouiaId, shouldFocusToggleOnSelect: true, children: (0, jsx_runtime_1.jsx)(react_core_1.TreeView, { hasAnimations: true, data: treeData, onCheck: onCheck, hasCheckboxes: true, className: classes.dataViewTreeFilterTreeView }) }));
222
+ return ((0, jsx_runtime_1.jsx)(react_core_1.ToolbarFilter, { "data-ouia-component-id": ouiaId, labels: value.map(item => ({ key: item, node: item })), deleteLabel: (_, label) => {
223
+ const labelKey = typeof label === 'string' ? label : label.key;
224
+ onChange === null || onChange === void 0 ? void 0 : onChange(undefined, value.filter(item => item !== labelKey));
225
+ onFilterSelectorClear(labelKey);
226
+ }, deleteLabelGroup: uncheckAllItems, categoryName: title, showToolbarItem: showToolbarItem, children: dropdown }, filterId));
227
+ };
228
+ exports.DataViewTreeFilter = DataViewTreeFilter;
229
+ exports.default = exports.DataViewTreeFilter;
@@ -0,0 +1 @@
1
+ import '@testing-library/jest-dom';
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const jsx_runtime_1 = require("react/jsx-runtime");
16
+ const react_1 = require("@testing-library/react");
17
+ require("@testing-library/jest-dom");
18
+ const user_event_1 = __importDefault(require("@testing-library/user-event"));
19
+ const DataViewTreeFilter_1 = __importDefault(require("./DataViewTreeFilter"));
20
+ const DataViewToolbar_1 = __importDefault(require("../DataViewToolbar"));
21
+ describe('DataViewTreeFilter component', () => {
22
+ const treeItems = [
23
+ {
24
+ name: 'Linux',
25
+ id: 'os-linux',
26
+ checkProps: { 'aria-label': 'linux-check', checked: false },
27
+ children: [
28
+ {
29
+ name: 'Ubuntu 22.04',
30
+ id: 'os-ubuntu',
31
+ checkProps: { checked: false }
32
+ },
33
+ {
34
+ name: 'RHEL 9',
35
+ id: 'os-rhel',
36
+ checkProps: { checked: false }
37
+ },
38
+ {
39
+ name: 'Debian 12',
40
+ id: 'os-debian',
41
+ checkProps: { checked: false }
42
+ },
43
+ {
44
+ name: 'CentOS 8',
45
+ id: 'os-centos',
46
+ checkProps: { checked: false }
47
+ },
48
+ {
49
+ name: 'Fedora 38',
50
+ id: 'os-fedora',
51
+ checkProps: { checked: false }
52
+ }
53
+ ],
54
+ defaultExpanded: true
55
+ },
56
+ {
57
+ name: 'Windows',
58
+ id: 'os-windows',
59
+ checkProps: { 'aria-label': 'windows-check', checked: false },
60
+ children: [
61
+ {
62
+ name: 'Windows Server 2022',
63
+ id: 'os-windows-2022',
64
+ checkProps: { checked: false }
65
+ }
66
+ ]
67
+ },
68
+ {
69
+ name: 'macOS',
70
+ id: 'os-macos',
71
+ checkProps: { 'aria-label': 'macos-check', checked: false },
72
+ children: [
73
+ {
74
+ name: 'macOS Ventura',
75
+ id: 'os-macos-ventura',
76
+ checkProps: { checked: false }
77
+ },
78
+ {
79
+ name: 'macOS Sonoma',
80
+ id: 'os-macos-sonoma',
81
+ checkProps: { checked: false }
82
+ }
83
+ ]
84
+ }
85
+ ];
86
+ const defaultProps = {
87
+ filterId: 'test-tree-filter',
88
+ title: 'Test Tree Filter',
89
+ value: ['Linux'],
90
+ items: treeItems
91
+ };
92
+ beforeEach(() => {
93
+ jest.clearAllMocks();
94
+ });
95
+ it('should render correctly', () => {
96
+ const { container } = (0, react_1.render)((0, jsx_runtime_1.jsx)(DataViewToolbar_1.default, { filters: (0, jsx_runtime_1.jsx)(DataViewTreeFilter_1.default, Object.assign({}, defaultProps)) }));
97
+ expect(container).toMatchSnapshot();
98
+ });
99
+ describe('defaultExpanded', () => {
100
+ it('should have expanded items by default', () => __awaiter(void 0, void 0, void 0, function* () {
101
+ (0, react_1.render)((0, jsx_runtime_1.jsx)(DataViewToolbar_1.default, { filters: (0, jsx_runtime_1.jsx)(DataViewTreeFilter_1.default, { filterId: "os", title: "Operating System", items: treeItems, defaultExpanded: true }) }));
102
+ const openMenu = react_1.screen.getByRole('button', { name: /operating system/i });
103
+ yield user_event_1.default.click(openMenu);
104
+ yield (0, react_1.waitFor)(() => {
105
+ const node = react_1.screen.getByText('Ubuntu 22.04');
106
+ expect(node).toHaveClass('pf-v6-c-tree-view__node-text');
107
+ expect(node).toBeInTheDocument();
108
+ });
109
+ }));
110
+ });
111
+ describe('onChange callback', () => {
112
+ it('onChange should be called on toggle of node', () => __awaiter(void 0, void 0, void 0, function* () {
113
+ const mockOnChange = jest.fn();
114
+ (0, react_1.render)((0, jsx_runtime_1.jsx)(DataViewToolbar_1.default, { filters: (0, jsx_runtime_1.jsx)(DataViewTreeFilter_1.default, { filterId: "os", title: "Operating System", items: treeItems, defaultExpanded: true, onChange: mockOnChange }) }));
115
+ const openMenu = react_1.screen.getByRole('button', { name: /operating system/i });
116
+ yield user_event_1.default.click(openMenu);
117
+ yield (0, react_1.waitFor)(() => {
118
+ const node = react_1.screen.getByText('Ubuntu 22.04');
119
+ expect(node).toBeInTheDocument();
120
+ });
121
+ const node = react_1.screen.getByText('Ubuntu 22.04');
122
+ yield user_event_1.default.click(node);
123
+ yield (0, react_1.waitFor)(() => {
124
+ expect(mockOnChange).toHaveBeenCalled();
125
+ });
126
+ }));
127
+ });
128
+ describe('onSelect callback', () => {
129
+ it('onSelect should return list of selected items when item is selected', () => __awaiter(void 0, void 0, void 0, function* () {
130
+ const mockOnSelect = jest.fn();
131
+ (0, react_1.render)((0, jsx_runtime_1.jsx)(DataViewToolbar_1.default, { filters: (0, jsx_runtime_1.jsx)(DataViewTreeFilter_1.default, { filterId: "os", title: "Operating System", items: treeItems, defaultExpanded: true, onSelect: mockOnSelect }) }));
132
+ const openMenu = react_1.screen.getByRole('button', { name: /operating system/i });
133
+ yield user_event_1.default.click(openMenu);
134
+ yield (0, react_1.waitFor)(() => {
135
+ const node = react_1.screen.getByText('Ubuntu 22.04');
136
+ expect(node).toBeInTheDocument();
137
+ });
138
+ const node = react_1.screen.getByText('Ubuntu 22.04');
139
+ yield user_event_1.default.click(node);
140
+ yield (0, react_1.waitFor)(() => {
141
+ expect(mockOnSelect).toHaveBeenCalled();
142
+ expect(mockOnSelect).toHaveBeenCalledWith(expect.arrayContaining([
143
+ expect.objectContaining({
144
+ name: 'Ubuntu 22.04',
145
+ id: 'os-ubuntu'
146
+ })
147
+ ]));
148
+ });
149
+ }));
150
+ });
151
+ describe('rendering all items', () => {
152
+ it('all tree items should be rendered', () => __awaiter(void 0, void 0, void 0, function* () {
153
+ (0, react_1.render)((0, jsx_runtime_1.jsx)(DataViewToolbar_1.default, { filters: (0, jsx_runtime_1.jsx)(DataViewTreeFilter_1.default, { filterId: "os", title: "Operating System", items: treeItems, defaultExpanded: true }) }));
154
+ const openMenu = react_1.screen.getByRole('button', { name: /operating system/i });
155
+ yield user_event_1.default.click(openMenu);
156
+ yield (0, react_1.waitFor)(() => {
157
+ expect(react_1.screen.getByText('Linux')).toBeInTheDocument();
158
+ expect(react_1.screen.getByText('Windows')).toBeInTheDocument();
159
+ expect(react_1.screen.getByText('macOS')).toBeInTheDocument();
160
+ expect(react_1.screen.getByText('Ubuntu 22.04')).toBeInTheDocument();
161
+ expect(react_1.screen.getByText('RHEL 9')).toBeInTheDocument();
162
+ expect(react_1.screen.getByText('Debian 12')).toBeInTheDocument();
163
+ expect(react_1.screen.getByText('CentOS 8')).toBeInTheDocument();
164
+ expect(react_1.screen.getByText('Fedora 38')).toBeInTheDocument();
165
+ expect(react_1.screen.getByText('Windows Server 2022')).toBeInTheDocument();
166
+ expect(react_1.screen.getByText('macOS Ventura')).toBeInTheDocument();
167
+ expect(react_1.screen.getByText('macOS Sonoma')).toBeInTheDocument();
168
+ });
169
+ }));
170
+ });
171
+ });
@@ -0,0 +1,2 @@
1
+ export { default } from './DataViewTreeFilter';
2
+ export * from './DataViewTreeFilter';