| 1 |
import { createContext, forwardRef, useEffect, useRef, useState } from 'react'; |
| 2 |
import styles from '@patternfly/react-styles/css/components/Table/table'; |
| 3 |
import stylesGrid from '@patternfly/react-styles/css/components/Table/table-grid'; |
| 4 |
import stylesTreeView from '@patternfly/react-styles/css/components/Table/table-tree-view'; |
| 5 |
import { css } from '@patternfly/react-styles'; |
| 6 |
import { toCamel } from './utils'; |
| 7 |
import { IVisibility } from './utils/decorators/classNames'; |
| 8 |
import { handleArrows, setTabIndex } from '@patternfly/react-core/dist/esm/helpers/KeyboardHandler'; |
| 9 |
import { KeyTypes } from '@patternfly/react-core/dist/esm/helpers/constants'; |
| 10 |
import { useOUIAProps, OUIAProps } from '@patternfly/react-core/dist/esm/helpers/OUIA/ouia'; |
| 11 |
import { useHasAnimations } from '@patternfly/react-core/dist/esm/helpers'; |
| 12 |
import { TableGridBreakpoint, TableVariant } from './TableTypes'; |
| 13 |
|
| 14 |
export interface BaseCellProps { |
| 15 |
/** Content rendered inside the cell */ |
| 16 |
children?: React.ReactNode; |
| 17 |
/** Additional classes added to the cell */ |
| 18 |
className?: string; |
| 19 |
/** Element to render */ |
| 20 |
component?: React.ReactNode; |
| 21 |
/** Modifies cell to center its contents. */ |
| 22 |
textCenter?: boolean; |
| 23 |
/** Style modifier to apply */ |
| 24 |
modifier?: 'breakWord' | 'fitContent' | 'nowrap' | 'truncate' | 'wrap'; |
| 25 |
/** Width percentage modifier */ |
| 26 |
width?: 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 60 | 70 | 80 | 90 | 100; |
| 27 |
/** Visibility breakpoint modifiers */ |
| 28 |
visibility?: (keyof IVisibility)[]; |
| 29 |
/** @hide Forwarded ref */ |
| 30 |
innerRef?: React.Ref<any>; |
| 31 |
} |
| 32 |
|
| 33 |
export interface TableProps extends React.HTMLProps<HTMLTableElement>, OUIAProps { |
| 34 |
/** Adds an accessible name for the Table */ |
| 35 |
'aria-label'?: string; |
| 36 |
/** Content rendered inside the Table */ |
| 37 |
children?: React.ReactNode; |
| 38 |
/** Additional classes added to the Table */ |
| 39 |
className?: string; |
| 40 |
/** |
| 41 |
* Style variant for the Table |
| 42 |
* compact: Reduces spacing and makes the table more compact |
| 43 |
*/ |
| 44 |
variant?: TableVariant | 'compact'; |
| 45 |
/** Render borders */ |
| 46 |
borders?: boolean; |
| 47 |
/** Specifies the grid breakpoints */ |
| 48 |
gridBreakPoint?: '' | 'grid' | 'grid-md' | 'grid-lg' | 'grid-xl' | 'grid-2xl'; |
| 49 |
/** A valid WAI-ARIA role to be applied to the table element */ |
| 50 |
role?: string; |
| 51 |
/** @beta Flag indicating if the table should have plain styling with a transparent background */ |
| 52 |
isPlain?: boolean; |
| 53 |
/** @beta Flag indicating if the table should not have plain styling when in the glass theme */ |
| 54 |
isNoPlainOnGlass?: boolean; |
| 55 |
/** If set to true, the table header sticks to the top of its container. This property applies both the sticky position and styling. */ |
| 56 |
isStickyHeader?: boolean; |
| 57 |
/** @beta Flag indicating the table header should have sticky positioning to the top of the parent InnerScrollContainer. */ |
| 58 |
isStickyHeaderBase?: boolean; |
| 59 |
/** @beta Flag indicating the table header should have stuck styling, when the header is not at the top of the scroll container. */ |
| 60 |
isStickyHeaderStuck?: boolean; |
| 61 |
/** @hide Forwarded ref */ |
| 62 |
innerRef?: React.RefObject<any>; |
| 63 |
/** Flag indicating table is a tree table */ |
| 64 |
isTreeTable?: boolean; |
| 65 |
/** Flag indicating this table is nested within another table */ |
| 66 |
isNested?: boolean; |
| 67 |
/** Flag indicating this table should be striped. This property works best for a single <tbody> table. Striping may also be done manually by applying this property to Tbody and Tr components. */ |
| 68 |
isStriped?: boolean; |
| 69 |
/** Flag indicating this table contains expandable rows. */ |
| 70 |
isExpandable?: boolean; |
| 71 |
/** @beta Flag indicating whether expandable rows within the table have animations. Expandable rows cannot be dynamically rendered. This prop |
| 72 |
* will be removed in the next breaking change, with the default behavior becoming animations always being enabled. |
| 73 |
*/ |
| 74 |
hasAnimations?: boolean; |
| 75 |
/** Flag indicating this table's rows will not have the inset typically reserved for expanding/collapsing rows in a tree table. Intended for use on tree tables with no visible rows with children. */ |
| 76 |
hasNoInset?: boolean; |
| 77 |
/** Collection of column spans for nested headers. Deprecated: see https://github.com/patternfly/patternfly/issues/4584 */ |
| 78 |
nestedHeaderColumnSpans?: number[]; |
| 79 |
/** Visible text to add alongside the hidden a11y caption for tables with selectable rows. */ |
| 80 |
selectableRowCaptionText?: string; |
| 81 |
/** Value to overwrite the randomly generated data-ouia-component-id.*/ |
| 82 |
ouiaId?: number | string; |
| 83 |
/** Set the value of data-ouia-safe. Only set to true when the component is in a static state, i.e. no animations are occurring. At all other times, this value must be false. */ |
| 84 |
ouiaSafe?: boolean; |
| 85 |
} |
| 86 |
|
| 87 |
interface TableContextProps { |
| 88 |
registerSelectableRow?: () => void; |
| 89 |
hasAnimations?: boolean; |
| 90 |
variant?: TableVariant | 'compact'; |
| 91 |
} |
| 92 |
|
| 93 |
export const TableContext = createContext<TableContextProps>({ |
| 94 |
registerSelectableRow: () => {}, |
| 95 |
hasAnimations: false, |
| 96 |
variant: undefined |
| 97 |
}); |
| 98 |
|
| 99 |
const TableBase: React.FunctionComponent<TableProps> = ({ |
| 100 |
children, |
| 101 |
className, |
| 102 |
variant, |
| 103 |
borders = true, |
| 104 |
isStickyHeader = false, |
| 105 |
isStickyHeaderBase = false, |
| 106 |
isStickyHeaderStuck = false, |
| 107 |
isPlain = false, |
| 108 |
isNoPlainOnGlass = false, |
| 109 |
gridBreakPoint = TableGridBreakpoint.gridMd, |
| 110 |
'aria-label': ariaLabel, |
| 111 |
role = 'grid', |
| 112 |
innerRef, |
| 113 |
ouiaId, |
| 114 |
ouiaSafe = true, |
| 115 |
isTreeTable = false, |
| 116 |
isNested = false, |
| 117 |
isStriped = false, |
| 118 |
isExpandable = false, |
| 119 |
hasAnimations: hasAnimationsProp, |
| 120 |
hasNoInset = false, |
| 121 |
// eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 122 |
nestedHeaderColumnSpans, |
| 123 |
selectableRowCaptionText, |
| 124 |
...props |
| 125 |
}: TableProps) => { |
| 126 |
const hasAnimations = useHasAnimations(hasAnimationsProp); |
| 127 |
const ref = useRef(null); |
| 128 |
const tableRef = innerRef || ref; |
| 129 |
|
| 130 |
const [hasSelectableRows, setHasSelectableRows] = useState(false); |
| 131 |
const [tableCaption, setTableCaption] = useState<React.JSX.Element | undefined>(); |
| 132 |
|
| 133 |
useEffect(() => { |
| 134 |
document.addEventListener('keydown', handleKeys); |
| 135 |
|
| 136 |
// sets up roving tab-index to tree tables only |
| 137 |
if (tableRef && tableRef.current && tableRef.current.classList.contains('pf-m-tree-view')) { |
| 138 |
const tbody = tableRef.current.querySelector('tbody'); |
| 139 |
tbody && setTabIndex(Array.from(tbody.querySelectorAll('button, a, input'))); |
| 140 |
} |
| 141 |
|
| 142 |
return function cleanup() { |
| 143 |
document.removeEventListener('keydown', handleKeys); |
| 144 |
}; |
| 145 |
}, [tableRef, tableRef.current]); |
| 146 |
|
| 147 |
useEffect(() => { |
| 148 |
if (selectableRowCaptionText) { |
| 149 |
setTableCaption( |
| 150 |
<caption> |
| 151 |
{selectableRowCaptionText} |
| 152 |
<div className="pf-v6-screen-reader"> |
| 153 |
This table has selectable rows. It can be navigated by row using tab, and each row can be selected using |
| 154 |
space or enter. |
| 155 |
</div> |
| 156 |
</caption> |
| 157 |
); |
| 158 |
} else { |
| 159 |
setTableCaption( |
| 160 |
<caption className="pf-v6-screen-reader"> |
| 161 |
This table has selectable rows. It can be navigated by row using tab, and each row can be selected using space |
| 162 |
or enter. |
| 163 |
</caption> |
| 164 |
); |
| 165 |
} |
| 166 |
}, [selectableRowCaptionText]); |
| 167 |
|
| 168 |
const ouiaProps = useOUIAProps('Table', ouiaId, ouiaSafe); |
| 169 |
const grid = |
| 170 |
stylesGrid.modifiers?.[ |
| 171 |
toCamel(gridBreakPoint || '').replace(/-?2xl/, '_2xl') as 'grid' | 'gridMd' | 'gridLg' | 'gridXl' | 'grid_2xl' |
| 172 |
]; |
| 173 |
const breakPointPrefix = `treeView${gridBreakPoint.charAt(0).toUpperCase() + gridBreakPoint.slice(1)}`; |
| 174 |
const treeGrid = |
| 175 |
stylesTreeView.modifiers?.[ |
| 176 |
toCamel(breakPointPrefix || '').replace(/-?2xl/, '_2xl') as |
| 177 |
| 'treeViewGrid' |
| 178 |
| 'treeViewGridMd' |
| 179 |
| 'treeViewGridLg' |
| 180 |
| 'treeViewGridXl' |
| 181 |
| 'treeViewGrid_2xl' |
| 182 |
]; |
| 183 |
|
| 184 |
const handleKeys = (event: KeyboardEvent) => { |
| 185 |
if ( |
| 186 |
isNested || |
| 187 |
!(tableRef && tableRef.current && tableRef.current.classList.contains(stylesTreeView.modifiers.treeView)) || // implements roving tab-index to tree tables only |
| 188 |
(tableRef && tableRef.current !== (event.target as HTMLElement).closest(`.${styles.table}:not(.pf-m-nested)`)) |
| 189 |
) { |
| 190 |
return; |
| 191 |
} |
| 192 |
const activeElement = document.activeElement; |
| 193 |
const key = event.key; |
| 194 |
const rows = (Array.from(tableRef.current.querySelectorAll('tbody tr')) as Element[]).filter( |
| 195 |
(el) => !el.classList.contains('pf-m-disabled') && !(el as HTMLElement).hidden |
| 196 |
); |
| 197 |
if (key === KeyTypes.Space || key === KeyTypes.Enter) { |
| 198 |
(activeElement as HTMLElement).click(); |
| 199 |
event.preventDefault(); |
| 200 |
} |
| 201 |
|
| 202 |
const getFocusableElement = (element: Element) => |
| 203 |
element.querySelectorAll('button:not(:disabled), input:not(:disabled), a:not(:disabled)')[0]; |
| 204 |
|
| 205 |
handleArrows( |
| 206 |
event, |
| 207 |
rows, |
| 208 |
(element: Element) => element === activeElement.closest('tr'), |
| 209 |
getFocusableElement, |
| 210 |
['button', 'input', 'a'], |
| 211 |
undefined, |
| 212 |
false, |
| 213 |
true, |
| 214 |
false |
| 215 |
); |
| 216 |
}; |
| 217 |
|
| 218 |
const registerSelectableRow = () => { |
| 219 |
!hasSelectableRows && setHasSelectableRows(true); |
| 220 |
}; |
| 221 |
|
| 222 |
return ( |
| 223 |
<TableContext.Provider value={{ registerSelectableRow, hasAnimations, variant }}> |
| 224 |
<table |
| 225 |
aria-label={ariaLabel} |
| 226 |
role={role} |
| 227 |
className={css( |
| 228 |
className, |
| 229 |
styles.table, |
| 230 |
isTreeTable ? treeGrid : grid, |
| 231 |
styles.modifiers[variant], |
| 232 |
!borders && styles.modifiers.noBorderRows, |
| 233 |
isStickyHeader && styles.modifiers.stickyHeader, |
| 234 |
isStickyHeaderBase && styles.modifiers.stickyHeaderBase, |
| 235 |
isStickyHeaderStuck && styles.modifiers.stickyHeaderStuck, |
| 236 |
isTreeTable && stylesTreeView.modifiers.treeView, |
| 237 |
isStriped && styles.modifiers.striped, |
| 238 |
isExpandable && styles.modifiers.expandable, |
| 239 |
isPlain && styles.modifiers.plain, |
| 240 |
isNoPlainOnGlass && styles.modifiers.noPlainOnGlass, |
| 241 |
hasNoInset && stylesTreeView.modifiers.noInset, |
| 242 |
isNested && 'pf-m-nested', |
| 243 |
hasAnimations && styles.modifiers.animateExpand |
| 244 |
)} |
| 245 |
ref={tableRef} |
| 246 |
{...(isTreeTable && { role: 'treegrid' })} |
| 247 |
{...ouiaProps} |
| 248 |
{...props} |
| 249 |
> |
| 250 |
{hasSelectableRows && tableCaption} |
| 251 |
{children} |
| 252 |
</table> |
| 253 |
</TableContext.Provider> |
| 254 |
); |
| 255 |
}; |
| 256 |
|
| 257 |
export const Table = forwardRef((props: TableProps, ref: React.Ref<HTMLTableElement>) => ( |
| 258 |
<TableBase {...props} innerRef={ref as React.MutableRefObject<any>} /> |
| 259 |
)); |
| 260 |
Table.displayName = 'Table'; |