@onewelcome/react-lib-components 0.1.5-alpha → 0.1.8-alpha

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 (105) hide show
  1. package/dist/Button/IconButton.d.ts +2 -1
  2. package/dist/ContextMenu/ContextMenu.d.ts +2 -3
  3. package/dist/ContextMenu/ContextMenuItem.d.ts +10 -3
  4. package/dist/DataGrid/DataGrid.d.ts +30 -0
  5. package/dist/DataGrid/DataGridActions/DataGridActions.d.ts +14 -0
  6. package/dist/DataGrid/DataGridActions/DataGridColumnsToggle.d.ts +13 -0
  7. package/dist/DataGrid/DataGridBody/DataGridBody.d.ts +16 -0
  8. package/dist/DataGrid/DataGridBody/DataGridCell.d.ts +6 -0
  9. package/dist/DataGrid/DataGridBody/DataGridRow.d.ts +7 -0
  10. package/dist/DataGrid/DataGridHeader/DataGridHeader.d.ts +10 -0
  11. package/dist/DataGrid/DataGridHeader/DataGridHeaderCell.d.ts +10 -0
  12. package/dist/DataGrid/datagrid.interfaces.d.ts +13 -0
  13. package/dist/Form/Checkbox/Checkbox.d.ts +2 -2
  14. package/dist/Form/Select/Option.d.ts +9 -4
  15. package/dist/Form/Select/Select.d.ts +8 -2
  16. package/dist/Form/Toggle/Toggle.d.ts +1 -1
  17. package/dist/Form/Wrapper/SelectWrapper/SelectWrapper.d.ts +1 -1
  18. package/dist/Icon/Icon.d.ts +1 -0
  19. package/dist/Link/Link.d.ts +4 -3
  20. package/dist/Notifications/BaseModal/BaseModal.d.ts +4 -2
  21. package/dist/Notifications/SlideInModal/SlideInModal.d.ts +4 -0
  22. package/dist/StatusIndicator/StatusIndicator.d.ts +9 -0
  23. package/dist/_BaseStyling_/BaseStyling.d.ts +4 -0
  24. package/dist/hooks/useSpacing.d.ts +1 -1
  25. package/dist/hooks/useWrapper.d.ts +1 -1
  26. package/dist/index.d.ts +48 -43
  27. package/dist/react-lib-components.cjs.development.js +2900 -2049
  28. package/dist/react-lib-components.cjs.development.js.map +1 -1
  29. package/dist/react-lib-components.cjs.production.min.js +1 -1
  30. package/dist/react-lib-components.cjs.production.min.js.map +1 -1
  31. package/dist/react-lib-components.esm.js +2897 -2050
  32. package/dist/react-lib-components.esm.js.map +1 -1
  33. package/dist/util/helper.d.ts +1 -1
  34. package/package.json +11 -11
  35. package/src/Button/BaseButton.module.scss +3 -18
  36. package/src/Button/Button.module.scss +4 -311
  37. package/src/Button/IconButton.module.scss +21 -128
  38. package/src/Button/IconButton.test.tsx +24 -0
  39. package/src/Button/IconButton.tsx +6 -1
  40. package/src/ContextMenu/ContextMenu.test.tsx +121 -6
  41. package/src/ContextMenu/ContextMenu.tsx +99 -6
  42. package/src/ContextMenu/ContextMenuItem.tsx +57 -9
  43. package/src/DataGrid/DataGrid.module.scss +21 -0
  44. package/src/DataGrid/DataGrid.test.tsx +276 -0
  45. package/src/DataGrid/DataGrid.tsx +101 -0
  46. package/src/DataGrid/DataGridActions/DataGridActions.module.scss +35 -0
  47. package/src/DataGrid/DataGridActions/DataGridActions.test.tsx +184 -0
  48. package/src/DataGrid/DataGridActions/DataGridActions.tsx +109 -0
  49. package/src/DataGrid/DataGridActions/DataGridColumnsToggle.module.scss +41 -0
  50. package/src/DataGrid/DataGridActions/DataGridColumnsToggle.test.tsx +83 -0
  51. package/src/DataGrid/DataGridActions/DataGridColumnsToggle.tsx +88 -0
  52. package/src/DataGrid/DataGridBody/DataGridBody.module.scss +10 -0
  53. package/src/DataGrid/DataGridBody/DataGridBody.test.tsx +123 -0
  54. package/src/DataGrid/DataGridBody/DataGridBody.tsx +64 -0
  55. package/src/DataGrid/DataGridBody/DataGridCell.module.scss +33 -0
  56. package/src/DataGrid/DataGridBody/DataGridCell.test.tsx +74 -0
  57. package/src/DataGrid/DataGridBody/DataGridCell.tsx +25 -0
  58. package/src/DataGrid/DataGridBody/DataGridRow.module.scss +7 -0
  59. package/src/DataGrid/DataGridBody/DataGridRow.test.tsx +101 -0
  60. package/src/DataGrid/DataGridBody/DataGridRow.tsx +27 -0
  61. package/src/DataGrid/DataGridBody/__snapshots__/DataGridBody.test.tsx.snap +258 -0
  62. package/src/DataGrid/DataGridHeader/DataGridHeader.module.scss +26 -0
  63. package/src/DataGrid/DataGridHeader/DataGridHeader.test.tsx +255 -0
  64. package/src/DataGrid/DataGridHeader/DataGridHeader.tsx +80 -0
  65. package/src/DataGrid/DataGridHeader/DataGridHeaderCell.module.scss +68 -0
  66. package/src/DataGrid/DataGridHeader/DataGridHeaderCell.test.tsx +128 -0
  67. package/src/DataGrid/DataGridHeader/DataGridHeaderCell.tsx +72 -0
  68. package/src/DataGrid/datagrid.interfaces.ts +14 -0
  69. package/src/Form/Checkbox/Checkbox.test.tsx +144 -8
  70. package/src/Form/Checkbox/Checkbox.tsx +8 -8
  71. package/src/Form/Select/Option.tsx +39 -21
  72. package/src/Form/Select/Select.module.scss +1 -1
  73. package/src/Form/Select/Select.test.tsx +235 -56
  74. package/src/Form/Select/Select.tsx +194 -34
  75. package/src/Form/Toggle/Toggle.module.scss +1 -0
  76. package/src/Form/Toggle/Toggle.test.tsx +45 -19
  77. package/src/Form/Toggle/Toggle.tsx +3 -3
  78. package/src/Form/Wrapper/CheckboxWrapper/CheckboxWrapper.test.tsx +1 -1
  79. package/src/Form/Wrapper/SelectWrapper/SelectWrapper.test.tsx +44 -0
  80. package/src/Form/Wrapper/SelectWrapper/SelectWrapper.tsx +4 -2
  81. package/src/Icon/Icon.module.scss +4 -0
  82. package/src/Icon/Icon.tsx +1 -0
  83. package/src/Link/Link.module.scss +20 -0
  84. package/src/Link/Link.test.tsx +33 -0
  85. package/src/Link/Link.tsx +8 -2
  86. package/src/Notifications/BaseModal/BaseModal.module.scss +1 -1
  87. package/src/Notifications/BaseModal/BaseModal.test.tsx +77 -12
  88. package/src/Notifications/BaseModal/BaseModal.tsx +27 -6
  89. package/src/Notifications/Dialog/Dialog.module.scss +1 -1
  90. package/src/Notifications/Dialog/Dialog.tsx +1 -1
  91. package/src/Notifications/SlideInModal/SlideInModal.module.scss +36 -0
  92. package/src/Notifications/SlideInModal/SlideInModal.test.tsx +69 -0
  93. package/src/Notifications/SlideInModal/SlideInModal.tsx +31 -0
  94. package/src/Notifications/Snackbar/SnackbarContainer/SnackbarContainer.module.scss +1 -1
  95. package/src/Notifications/Snackbar/SnackbarItem/SnackbarItem.module.scss +1 -1
  96. package/src/Pagination/Pagination.module.scss +74 -74
  97. package/src/StatusIndicator/StatusIndicator.module.scss +27 -0
  98. package/src/StatusIndicator/StatusIndicator.test.tsx +127 -0
  99. package/src/StatusIndicator/StatusIndicator.tsx +25 -0
  100. package/src/Tiles/Tile.module.scss +1 -1
  101. package/src/Tiles/Tile.test.tsx +4 -4
  102. package/src/_BaseStyling_/BaseStyling.tsx +14 -6
  103. package/src/index.ts +85 -48
  104. package/src/mixins.module.scss +171 -0
  105. package/src/readyclasses.module.scss +0 -30
@@ -1,6 +1,6 @@
1
1
  import React, { useEffect, useRef } from 'react';
2
2
  import { ContextMenu, Props } from './ContextMenu';
3
- import { render, getByRole } from '@testing-library/react';
3
+ import { render } from '@testing-library/react';
4
4
  import { Button } from '../Button/Button';
5
5
  import { ContextMenuItem } from './ContextMenuItem';
6
6
  import userEvent from '@testing-library/user-event';
@@ -15,8 +15,12 @@ const defaultParams: Props = {
15
15
  <ContextMenuItem onClick={onClick} data-testid="contextmenuitem" key="1">
16
16
  Example item 1
17
17
  </ContextMenuItem>,
18
- <ContextMenuItem key="2">Example item 2</ContextMenuItem>,
19
- <ContextMenuItem key="3">Example item 3</ContextMenuItem>,
18
+ <ContextMenuItem onClick={onClick} data-testid="contextmenuitem2" key="2">
19
+ Example item 2
20
+ </ContextMenuItem>,
21
+ <ContextMenuItem onClick={onClick} data-testid="contextmenuitem3" key="3">
22
+ Example item 3
23
+ </ContextMenuItem>,
20
24
  ],
21
25
  show: false,
22
26
  onShow: onShow,
@@ -61,12 +65,10 @@ describe('ContextMenu should render', () => {
61
65
  show: true,
62
66
  }));
63
67
 
64
- const contextmenuitem = getByTestId('contextmenuitem');
65
- const button = getByRole(contextmenuitem, 'button');
68
+ const button = getByTestId('contextmenuitem');
66
69
 
67
70
  userEvent.click(button);
68
71
 
69
- expect(contextmenuitem).toBeTruthy();
70
72
  expect(onClick).toHaveBeenCalled();
71
73
  });
72
74
 
@@ -117,3 +119,116 @@ describe('ref should work', () => {
117
119
  render(<ExampleComponent propagateRef={refCheck} />);
118
120
  });
119
121
  });
122
+
123
+ describe('accessibility controls', () => {
124
+ it('opening works correctly with arrow key down, then navigation should work with arrow keys', () => {
125
+ const { getByTestId, trigger } = createContextMenu();
126
+ const firstContextMenuItem = getByTestId('contextmenuitem');
127
+ const secondContextMenuItem = getByTestId('contextmenuitem2');
128
+ const thirdContextMenuItem = getByTestId('contextmenuitem3');
129
+
130
+ userEvent.keyboard('{arrowdown}');
131
+ userEvent.keyboard('{arrowdown}');
132
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
133
+ expect(firstContextMenuItem).toHaveFocus();
134
+
135
+ userEvent.keyboard('{arrowdown}');
136
+ expect(secondContextMenuItem).toHaveFocus();
137
+
138
+ userEvent.keyboard('{arrowdown}');
139
+ expect(thirdContextMenuItem).toHaveFocus();
140
+
141
+ userEvent.keyboard('{arrowdown}');
142
+ expect(firstContextMenuItem).toHaveFocus();
143
+
144
+ userEvent.keyboard('{arrowup}');
145
+ expect(thirdContextMenuItem).toHaveFocus();
146
+
147
+ userEvent.keyboard('{arrowup}');
148
+ expect(secondContextMenuItem).toHaveFocus();
149
+ });
150
+
151
+ it('opens correctly with enter key, closing works with escape key.', async () => {
152
+ const { trigger } = createContextMenu();
153
+
154
+ userEvent.keyboard('{enter}');
155
+
156
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
157
+
158
+ userEvent.keyboard('{escape}');
159
+
160
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
161
+ });
162
+
163
+ it('opens correctly with space, home and end buttons work', () => {
164
+ const { trigger, getByTestId } = createContextMenu();
165
+ const firstContextMenuItem = getByTestId('contextmenuitem');
166
+ const thirdContextMenuItem = getByTestId('contextmenuitem3');
167
+
168
+ userEvent.keyboard('{space}');
169
+
170
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
171
+
172
+ userEvent.keyboard('{end}');
173
+
174
+ expect(thirdContextMenuItem).toHaveFocus();
175
+
176
+ userEvent.keyboard('{home}');
177
+
178
+ expect(firstContextMenuItem).toHaveFocus();
179
+ });
180
+
181
+ it('opens correctly with space, navigate with arrow keys, select with enter', () => {
182
+ onClick.mockImplementation((e) => {
183
+ expect(e.target.getAttribute('data-testid')).toBe('contextmenuitem3');
184
+ });
185
+
186
+ const { trigger, getByTestId } = createContextMenu((defaultParams) => ({
187
+ ...defaultParams,
188
+ }));
189
+ const thirdContextMenuItem = getByTestId('contextmenuitem3');
190
+
191
+ userEvent.keyboard('{space}');
192
+
193
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
194
+
195
+ userEvent.keyboard('{arrowdown}');
196
+ userEvent.keyboard('{arrowdown}');
197
+ userEvent.keyboard('{arrowdown}');
198
+
199
+ expect(thirdContextMenuItem).toHaveFocus();
200
+
201
+ userEvent.keyboard('{enter}');
202
+
203
+ expect(onClick).toHaveBeenCalled();
204
+ });
205
+
206
+ it('opens correctly with enter, navigate with arrow keys, select with space', () => {
207
+ onClick.mockImplementation((e) => {
208
+ expect(e.target.getAttribute('data-testid')).toBe('contextmenuitem3');
209
+ });
210
+
211
+ const { trigger, getByTestId } = createContextMenu((defaultParams) => ({
212
+ ...defaultParams,
213
+ }));
214
+ const thirdContextMenuItem = getByTestId('contextmenuitem3');
215
+
216
+ userEvent.keyboard('{enter}');
217
+
218
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
219
+
220
+ userEvent.keyboard('{arrowdown}');
221
+ userEvent.keyboard('{arrowdown}');
222
+ userEvent.keyboard('{arrowdown}');
223
+
224
+ expect(thirdContextMenuItem).toHaveFocus();
225
+
226
+ userEvent.keyboard('{space}');
227
+
228
+ expect(onClick).toHaveBeenCalled();
229
+
230
+ userEvent.keyboard('{space}');
231
+
232
+ expect(thirdContextMenuItem).toHaveFocus();
233
+ });
234
+ });
@@ -1,16 +1,22 @@
1
- import React, { ComponentPropsWithRef, ReactElement, useEffect, useRef, useState } from 'react';
1
+ import React, {
2
+ ComponentPropsWithRef,
3
+ ReactElement,
4
+ ReactNode,
5
+ useEffect,
6
+ useRef,
7
+ useState,
8
+ } from 'react';
2
9
  import { Props as ButtonProps } from '../Button/Button';
3
10
  import { Props as IconButtonProps } from '../Button/IconButton';
4
11
  import { Popover } from '../Popover/Popover';
5
12
  import { Placement, Offset } from '../hooks/usePosition';
6
- import { Props as ContextMenuItemProps } from './ContextMenuItem';
7
13
  import classes from './ContextMenu.module.scss';
8
14
  import { useBodyClick } from '../hooks/useBodyClick';
9
15
  import { createPortal } from 'react-dom';
10
16
 
11
17
  export interface Props extends ComponentPropsWithRef<'div'> {
12
18
  trigger: ReactElement<ButtonProps> | ReactElement<IconButtonProps>;
13
- children: ReactElement<ContextMenuItemProps> | ReactElement<ContextMenuItemProps>[];
19
+ children: ReactNode;
14
20
  placement?: Placement;
15
21
  transformOrigin?: Placement;
16
22
  offset?: Offset;
@@ -40,11 +46,78 @@ export const ContextMenu = React.forwardRef<HTMLDivElement, Props>(
40
46
  ) => {
41
47
  const anchorEl = useRef<HTMLButtonElement>(null);
42
48
  const [showContextMenu, setShowContextMenu] = useState(show);
49
+ const [selectedContextMenuItem, setSelectedContextMenuItem] = useState(-1);
50
+ const [focusedContextMenuItem, setFocusedContextMenuItem] = useState(-1);
51
+ const [shouldClick, setShouldClick] =
52
+ useState(
53
+ false
54
+ ); /** We need this, because whenever we use the arrow keys to select the contextmenu item, and we focus the currently selected item it fires the "click" listener in ContextMenuItem component. Instead, we only want this to fire if we press "enter" or "spacebar" so we set this to true whenever that is the case, and back to false when it has been executed. */
55
+ const [childrenCount] = useState(React.Children.count(children));
43
56
 
44
57
  if (!id) {
45
58
  throw new Error('You need to provide an ID to the context menu');
46
59
  }
47
60
 
61
+ const onArrowNavigation = (event: React.KeyboardEvent) => {
62
+ if (focusedContextMenuItem === -1 && selectedContextMenuItem !== -1) {
63
+ setFocusedContextMenuItem(selectedContextMenuItem);
64
+ }
65
+
66
+ const codesToPrevenDefault = [
67
+ 'ArrowDown',
68
+ 'ArrowUp',
69
+ 'ArrowLeft',
70
+ 'ArrowRight',
71
+ 'Enter',
72
+ 'Space',
73
+ 'Escape',
74
+ 'End',
75
+ 'Home',
76
+ ];
77
+
78
+ if (codesToPrevenDefault.includes(event.code)) {
79
+ event.preventDefault();
80
+ }
81
+
82
+ switch (event.code) {
83
+ case 'ArrowDown':
84
+ if (!showContextMenu) {
85
+ setShowContextMenu(true);
86
+ return;
87
+ }
88
+ setFocusedContextMenuItem((prevState) => {
89
+ return prevState + 1 > childrenCount - 1 ? 0 : prevState + 1;
90
+ });
91
+ return;
92
+ case 'ArrowUp':
93
+ setFocusedContextMenuItem((prevState) => {
94
+ return prevState - 1 < 0 ? childrenCount - 1 : prevState - 1;
95
+ });
96
+ return;
97
+ case 'Enter':
98
+ case 'Space':
99
+ if (!showContextMenu) {
100
+ setShowContextMenu(true);
101
+ return;
102
+ }
103
+
104
+ setShouldClick(true);
105
+ setSelectedContextMenuItem(focusedContextMenuItem);
106
+ setShowContextMenu(false);
107
+ return;
108
+ case 'Tab':
109
+ case 'Escape':
110
+ setShowContextMenu(false);
111
+ return;
112
+ case 'End':
113
+ setFocusedContextMenuItem(childrenCount - 1);
114
+ return;
115
+ case 'Home':
116
+ setFocusedContextMenuItem(0);
117
+ return;
118
+ }
119
+ };
120
+
48
121
  useBodyClick(
49
122
  (event) => {
50
123
  return showContextMenu && anchorEl.current !== event.target;
@@ -60,6 +133,8 @@ export const ContextMenu = React.forwardRef<HTMLDivElement, Props>(
60
133
  onShow && onShow();
61
134
  } else {
62
135
  onClose && onClose();
136
+ setFocusedContextMenuItem(-1);
137
+ anchorEl.current && anchorEl.current.focus();
63
138
  }
64
139
  }, [showContextMenu]);
65
140
 
@@ -68,13 +143,31 @@ export const ContextMenu = React.forwardRef<HTMLDivElement, Props>(
68
143
  id: id,
69
144
  'aria-haspopup': 'true',
70
145
  'aria-controls': `${id}-menu`,
71
- 'aria-expanded': show,
146
+ 'aria-expanded': showContextMenu,
72
147
  onClick: () => setShowContextMenu(!showContextMenu),
148
+ tabIndex: 0,
73
149
  ref: anchorEl,
74
150
  });
75
151
 
152
+ const renderChildren = () => {
153
+ return React.Children.map(children, (child, index) => {
154
+ return React.cloneElement(child as ReactElement, {
155
+ onFocusChange: (childIndex: number) => setFocusedContextMenuItem(childIndex),
156
+ onSelectedChange: (childIndex: number) => {
157
+ setSelectedContextMenuItem(childIndex);
158
+ setShouldClick(false);
159
+ },
160
+ childIndex: index,
161
+ hasFocus: focusedContextMenuItem === index,
162
+ isSelected: selectedContextMenuItem === index,
163
+ contextMenuOpened: showContextMenu,
164
+ shouldClick: shouldClick,
165
+ });
166
+ });
167
+ };
168
+
76
169
  return (
77
- <div {...rest} ref={ref} className={classes['context-menu']}>
170
+ <div {...rest} ref={ref} onKeyDown={onArrowNavigation} className={classes['context-menu']}>
78
171
  {renderTrigger()}
79
172
  {createPortal(
80
173
  <Popover
@@ -85,7 +178,7 @@ export const ContextMenu = React.forwardRef<HTMLDivElement, Props>(
85
178
  show={showContextMenu}
86
179
  >
87
180
  <ul className={classes.menu} id={`${id}-menu`} aria-describedby={id} role="menu">
88
- {children}
181
+ {renderChildren()}
89
182
  </ul>
90
183
  </Popover>,
91
184
  domRoot
@@ -1,15 +1,63 @@
1
- import React, { HTMLProps } from 'react';
1
+ import React, { ComponentPropsWithRef, createRef, RefObject, useEffect } from 'react';
2
2
  import classes from './ContextMenuItem.module.scss';
3
3
 
4
- export interface Props extends Omit<HTMLProps<HTMLLIElement>, 'onClick'> {
4
+ export interface Props extends Omit<ComponentPropsWithRef<'button'>, 'onClick'> {
5
5
  children?: string;
6
+ hasFocus?: boolean;
7
+ isSelected?: boolean;
8
+ childIndex?: number;
9
+ shouldClick?: boolean;
10
+ contextMenuOpened?: boolean;
6
11
  onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
12
+ onFocusChange?: (childIndex: number) => void;
13
+ onSelectedChange?: (childIndex: number) => void;
7
14
  }
8
15
 
9
- export const ContextMenuItem = ({ children, onClick, ...rest }: Props) => {
10
- return (
11
- <li {...rest} role="menuitem" className={classes['context-menu-item']}>
12
- <button onClick={(event) => onClick && onClick(event)}>{children}</button>
13
- </li>
14
- );
15
- };
16
+ export const ContextMenuItem = React.forwardRef<HTMLButtonElement, Props>(
17
+ (
18
+ {
19
+ children,
20
+ onClick,
21
+ onFocusChange,
22
+ onSelectedChange,
23
+ hasFocus,
24
+ isSelected,
25
+ childIndex,
26
+ contextMenuOpened,
27
+ shouldClick,
28
+ ...rest
29
+ }: Props,
30
+ ref
31
+ ) => {
32
+ let innerButtonRef = (ref as RefObject<HTMLButtonElement>) || createRef<HTMLButtonElement>();
33
+
34
+ useEffect(() => {
35
+ if (isSelected && innerButtonRef.current && shouldClick) {
36
+ innerButtonRef.current.click();
37
+ }
38
+ }, [isSelected, shouldClick]);
39
+
40
+ useEffect(() => {
41
+ if (innerButtonRef.current && hasFocus && contextMenuOpened) {
42
+ onFocusChange && childIndex && onFocusChange(childIndex);
43
+ innerButtonRef.current.focus();
44
+ }
45
+ }, [hasFocus, innerButtonRef, contextMenuOpened]);
46
+
47
+ return (
48
+ <li role="menuitem" className={classes['context-menu-item']}>
49
+ <button
50
+ {...rest}
51
+ ref={innerButtonRef}
52
+ data-focus={hasFocus}
53
+ onClick={(event) => {
54
+ onClick && onClick(event);
55
+ onSelectedChange && childIndex && onSelectedChange(childIndex);
56
+ }}
57
+ >
58
+ {children}
59
+ </button>
60
+ </li>
61
+ );
62
+ }
63
+ );
@@ -0,0 +1,21 @@
1
+ .table-wrapper {
2
+ overflow-x: auto;
3
+ }
4
+
5
+ .table {
6
+ border-collapse: collapse;
7
+ padding-top: 0.5rem;
8
+ width: 100%;
9
+ position: relative;
10
+ }
11
+
12
+ .pagination {
13
+ margin-top: 1rem;
14
+ padding: 0 1rem;
15
+ }
16
+
17
+ @media only screen and (min-width: 50em) {
18
+ .pagination {
19
+ padding: 0 1.25rem;
20
+ }
21
+ }
@@ -0,0 +1,276 @@
1
+ import React, { useEffect, useRef } from 'react';
2
+ import { DataGrid, Props } from './DataGrid';
3
+ import { getAllByRole, render, queryAllByRole, getByRole } from '@testing-library/react';
4
+ import { DataGridRow } from './DataGridBody/DataGridRow';
5
+ import { DataGridCell } from './DataGridBody/DataGridCell';
6
+ import { ContextMenu } from '../ContextMenu/ContextMenu';
7
+ import { IconButton } from '../Button/IconButton';
8
+ import { Icon, Icons } from '../Icon/Icon';
9
+ import { ContextMenuItem } from '../ContextMenu/ContextMenuItem';
10
+ import userEvent from '@testing-library/user-event';
11
+
12
+ type DataType = { firstName: string; lastName: string; date: string };
13
+
14
+ const defaultParams: Props<DataType> = {
15
+ children: ({ item }) => (
16
+ <DataGridRow key={item.firstName}>
17
+ <DataGridCell>{item.firstName}</DataGridCell>
18
+ <DataGridCell>{item.lastName}</DataGridCell>
19
+ <DataGridCell>{item.date}</DataGridCell>
20
+ <DataGridCell>
21
+ <ContextMenu
22
+ id={`consent_menu_${item.firstName}`}
23
+ trigger={
24
+ <IconButton title={`Actions for ${item.firstName}`} color="default">
25
+ <Icon icon={Icons.EllipsisAlt} />
26
+ </IconButton>
27
+ }
28
+ >
29
+ <ContextMenuItem>Item 1</ContextMenuItem>
30
+ </ContextMenu>
31
+ </DataGridCell>
32
+ </DataGridRow>
33
+ ),
34
+ headers: [
35
+ { name: 'firstName', headline: 'First name' },
36
+ { name: 'lastName', headline: 'Last name' },
37
+ { name: 'date', headline: 'Date' },
38
+ ],
39
+ enableMultiSorting: true,
40
+ data: [
41
+ { firstName: 'Paweł', lastName: 'Napieracz', date: '12.12.1990' },
42
+ { firstName: 'Michał', lastName: 'Górski', date: '12.12.1994' },
43
+ { firstName: 'Daniel', lastName: 'Velden', date: '12.12.199x' },
44
+ { firstName: 'Jasha', lastName: 'Joachimsthal', date: '12.12.198x' },
45
+ ],
46
+ };
47
+
48
+ const createDataGrid = (params?: (defaultParams: Props<DataType>) => Props<DataType>) => {
49
+ let parameters = defaultParams;
50
+ if (params) {
51
+ parameters = params(defaultParams);
52
+ }
53
+ const queries = render(<DataGrid {...parameters} data-testid="dataGrid" />);
54
+ const dataGrid = queries.getByTestId('dataGrid');
55
+
56
+ return {
57
+ ...queries,
58
+ dataGrid,
59
+ };
60
+ };
61
+
62
+ describe('DataGrid should render', () => {
63
+ it('renders without crashing', () => {
64
+ const rowsCount = defaultParams.data?.length!;
65
+ const colsCount = defaultParams.headers?.length!;
66
+ const contextMenuCellCount = 1;
67
+ const { dataGrid, ...queries } = createDataGrid();
68
+
69
+ expect(dataGrid).toBeDefined();
70
+
71
+ expect(dataGrid.querySelector('.actions')).toBeNull();
72
+
73
+ const [thead, tbody] = queries.getAllByRole('rowgroup');
74
+
75
+ expect(queryAllByRole(thead, 'columnheader')).toHaveLength(3);
76
+ expect(queryAllByRole(thead, 'cell')).toHaveLength(contextMenuCellCount);
77
+ expect(queryAllByRole(thead, 'button')).toHaveLength(0); //sorting should be disabled by default
78
+
79
+ expect(queryAllByRole(tbody, 'cell')).toHaveLength(
80
+ rowsCount * (colsCount + contextMenuCellCount)
81
+ );
82
+ });
83
+
84
+ it('renders actions buttons', () => {
85
+ const { dataGrid } = createDataGrid((params) => ({
86
+ ...params,
87
+ actions: {
88
+ enableAddBtn: true,
89
+ enableColumnsBtn: true,
90
+ enableSearchBtn: true,
91
+ },
92
+ }));
93
+ const [addBtn, desktopColumnsBtn, mobileColumnsBtn, desktopSearchBtn, mobileSearchBtn] =
94
+ getAllByRole(dataGrid.querySelector('.actions')!, 'button');
95
+ expect(addBtn).toHaveTextContent('Add item');
96
+ expect(desktopColumnsBtn).toHaveTextContent('Columns');
97
+ expect(mobileColumnsBtn).toHaveTextContent('Show/hide columns');
98
+ expect(desktopSearchBtn).toHaveTextContent('Search');
99
+ expect(mobileSearchBtn).toHaveTextContent('Search');
100
+ });
101
+
102
+ it('renders table with initialized sorting indicators', () => {
103
+ const { getAllByRole } = createDataGrid((params) => ({
104
+ ...params,
105
+ onSort: jest.fn(),
106
+ initialSort: [
107
+ { name: defaultParams.headers[0].name, direction: 'DESC' },
108
+ { name: defaultParams.headers[2].name, direction: 'ASC' },
109
+ ],
110
+ }));
111
+
112
+ const [firstNameHeader, lastNameHeader, dateHeader] = getAllByRole('columnheader');
113
+ expect(firstNameHeader).toHaveAttribute('aria-sort', 'descending');
114
+ expect(lastNameHeader).not.toHaveAttribute('aria-sort');
115
+ expect(dateHeader).toHaveAttribute('aria-sort', 'ascending');
116
+ });
117
+
118
+ it('renders table without context menu', () => {
119
+ const rowsCount = defaultParams.data?.length!;
120
+ const colsCount = defaultParams.headers?.length!;
121
+ const { getAllByRole } = createDataGrid((params) => ({
122
+ ...params,
123
+ disableContextMenuColumn: true,
124
+ children: ({ item }) => (
125
+ <DataGridRow key={item.firstName}>
126
+ <DataGridCell>{item.firstName}</DataGridCell>
127
+ <DataGridCell>{item.lastName}</DataGridCell>
128
+ <DataGridCell>{item.date}</DataGridCell>
129
+ </DataGridRow>
130
+ ),
131
+ }));
132
+
133
+ expect(getAllByRole('columnheader')).toHaveLength(3);
134
+ expect(getAllByRole('cell')).toHaveLength(rowsCount * colsCount);
135
+ });
136
+
137
+ it('renders loading state with skeleton loading animation on data cells and empty row on content menu cells', () => {
138
+ const { ...queries } = createDataGrid((params) => ({ ...params, isLoading: true }));
139
+
140
+ const [_thead, tbody] = queries.getAllByRole('rowgroup');
141
+ expect(
142
+ getAllByRole(tbody, 'cell').find((cell, index) => {
143
+ const contextMenuCell = index % 4 === 3;
144
+ return (
145
+ !contextMenuCell && (cell.firstChild as HTMLElement).getAttribute('class') !== 'loading'
146
+ );
147
+ })
148
+ ).toBeUndefined();
149
+ });
150
+
151
+ it('renders empty state', () => {
152
+ const emptyLabel = 'emptyLabel';
153
+ const { ...queries } = createDataGrid((params) => ({ ...params, emptyLabel, data: [] }));
154
+
155
+ const [_thead, tbody] = queries.getAllByRole('rowgroup');
156
+ const rows = getAllByRole(tbody, 'row');
157
+ const firstRowCells = getAllByRole(rows[0], 'cell');
158
+ expect(firstRowCells).toHaveLength(1);
159
+ expect(firstRowCells[0]).toHaveAttribute('colspan', `${defaultParams.headers.length + 1}`);
160
+ expect(firstRowCells[0]).toHaveTextContent(emptyLabel);
161
+ });
162
+
163
+ it('renders pagination', () => {
164
+ const { getByRole } = createDataGrid((params) => ({
165
+ ...params,
166
+ paginationProps: {
167
+ totalElements: 105,
168
+ pageSize: 10,
169
+ currentPage: 2,
170
+ onPageChange: jest.fn(),
171
+ onPageSizeChange: jest.fn(),
172
+ },
173
+ }));
174
+
175
+ expect(getByRole('button', { name: 'previous' })).toBeDefined();
176
+ expect(getByRole('button', { name: 'next' })).toBeDefined();
177
+ expect(getByRole('button', { name: 'last' })).toBeDefined();
178
+ });
179
+ });
180
+
181
+ describe('DataGrid should have interactive table header', () => {
182
+ it('clicking table headers should call sort callback', () => {
183
+ const onSort = jest.fn();
184
+ const { getAllByRole } = createDataGrid((params) => ({
185
+ ...params,
186
+ onSort,
187
+ }));
188
+
189
+ const [firstNameHeader, lastNameHeader, dateHeader] = getAllByRole('columnheader');
190
+
191
+ userEvent.click(getByRole(firstNameHeader, 'button'));
192
+ expect(onSort).toBeCalledWith([{ name: defaultParams.headers[0].name, direction: 'ASC' }]);
193
+
194
+ userEvent.click(getByRole(lastNameHeader, 'button'));
195
+ userEvent.click(getByRole(dateHeader, 'button'));
196
+ expect(onSort).toBeCalledWith([
197
+ { name: defaultParams.headers[2].name, direction: 'ASC' },
198
+ { name: defaultParams.headers[1].name, direction: 'ASC' },
199
+ { name: defaultParams.headers[0].name, direction: 'ASC' },
200
+ ]);
201
+
202
+ userEvent.click(getByRole(firstNameHeader, 'button'));
203
+ expect(onSort).toBeCalledWith([
204
+ { name: defaultParams.headers[0].name, direction: 'DESC' },
205
+ { name: defaultParams.headers[2].name, direction: 'ASC' },
206
+ { name: defaultParams.headers[1].name, direction: 'ASC' },
207
+ ]);
208
+
209
+ userEvent.click(getByRole(dateHeader, 'button'));
210
+ expect(onSort).toBeCalledWith([
211
+ { name: defaultParams.headers[2].name, direction: 'DESC' },
212
+ { name: defaultParams.headers[0].name, direction: 'DESC' },
213
+ { name: defaultParams.headers[1].name, direction: 'ASC' },
214
+ ]);
215
+
216
+ userEvent.click(getByRole(dateHeader, 'button'));
217
+ userEvent.click(getByRole(firstNameHeader, 'button'));
218
+ userEvent.click(getByRole(lastNameHeader, 'button'));
219
+ expect(onSort).toBeCalledWith([{ name: defaultParams.headers[1].name, direction: 'DESC' }]);
220
+ expect(onSort).toBeCalledTimes(8);
221
+ });
222
+
223
+ it('clicking on show/hide columns popover should show/hide columns', async () => {
224
+ const { getByRole, findByLabelText, ...queries } = createDataGrid((params) => ({
225
+ ...params,
226
+ actions: { enableColumnsBtn: true },
227
+ }));
228
+ expect(queries.getAllByRole('columnheader')).toHaveLength(3);
229
+
230
+ userEvent.click(getByRole('button', { name: 'Columns' }));
231
+
232
+ const nameToggle = await findByLabelText(defaultParams.headers[1].headline);
233
+ expect(nameToggle).toBeChecked();
234
+ userEvent.click(nameToggle);
235
+ expect(nameToggle).not.toBeChecked();
236
+ expect(getByRole('button', { name: 'Close show columns dialog' })).toBeDefined();
237
+
238
+ const columns = queries.getAllByRole('columnheader');
239
+ expect(columns).toHaveLength(2);
240
+ expect(columns[0]).toHaveTextContent(defaultParams.headers[0].headline);
241
+ expect(columns[1]).toHaveTextContent(defaultParams.headers[2].headline);
242
+
243
+ const rowsCount = defaultParams.data?.length!;
244
+ const colsCount = defaultParams.headers.length;
245
+ const hiddenColsCount = defaultParams.headers.length;
246
+ const contextMenuColsCount = defaultParams.headers.length;
247
+ const [_thead, tbody] = queries.getAllByRole('rowgroup');
248
+ expect(getAllByRole(tbody, 'cell')).toHaveLength(
249
+ rowsCount * (colsCount - hiddenColsCount + contextMenuColsCount)
250
+ );
251
+ });
252
+ });
253
+
254
+ describe('ref should work', () => {
255
+ it('should give back the proper data prop, this also checks if the component propagates ...rest properly', () => {
256
+ const ExampleComponent = ({
257
+ propagateRef,
258
+ }: {
259
+ propagateRef: (ref: React.RefObject<HTMLElement>) => void;
260
+ }) => {
261
+ const ref = useRef(null);
262
+
263
+ useEffect(() => {
264
+ propagateRef(ref);
265
+ }, [ref]);
266
+
267
+ return <DataGrid {...defaultParams} data-ref="testing" ref={ref} />;
268
+ };
269
+
270
+ const refCheck = (ref: React.RefObject<HTMLElement>) => {
271
+ expect(ref.current).toHaveAttribute('data-ref', 'testing');
272
+ };
273
+
274
+ render(<ExampleComponent propagateRef={refCheck} />);
275
+ });
276
+ });