Debian Codegraph @

node/@patternfly/react-table/src/components/Table/Th.tsx

raw
1 import { createRef, forwardRef, useEffect, useState, useContext } from 'react';
2 import { css } from '@patternfly/react-styles';
3 import styles from '@patternfly/react-styles/css/components/Table/table';
4 import scrollStyles from '@patternfly/react-styles/css/components/Table/table-scrollable';
5 import accessibilityStyles from '@patternfly/react-styles/css/utilities/Accessibility/accessibility';
6 import { info, sortable, sortableFavorites, selectable, collapsible, cellWidth, Visibility, classNames } from './utils';
7 import { ThInfoType, ThSelectType, ThExpandType, ThSortType, formatterValueType } from './base/types';
8 import { mergeProps } from './base/merge-props';
9 import { IVisibility } from './utils/decorators/classNames';
10 import { Tooltip, TooltipProps } from '@patternfly/react-core/dist/esm/components/Tooltip';
11 import { BaseCellProps, TableContext } from './Table';
12 import { IFormatterValueType, IColumn } from './TableTypes';
13 import cssStickyCellMinWidth from '@patternfly/react-tokens/dist/esm/c_table__sticky_cell_MinWidth';
14 import cssStickyCellInlineStart from '@patternfly/react-tokens/dist/esm/c_table__sticky_cell_InsetInlineStart';
15 import cssStickyCellInlineEnd from '@patternfly/react-tokens/dist/esm/c_table__sticky_cell_InsetInlineEnd';
16
17 export interface ThProps
18 extends BaseCellProps, Omit<React.HTMLProps<HTMLTableHeaderCellElement>, 'onSelect' | 'width'> {
19 /**
20 * The column header the cell corresponds to. Applicable when this component is used as a direct child to <Tr>.
21 * This attribute replaces table header in mobile viewport. It is rendered by ::before pseudo element.
22 */
23 dataLabel?: string;
24 /** Renders a checkbox select so that all row checkboxes can be selected/deselected */
25 select?: ThSelectType;
26 /** Renders a chevron so that all row chevrons can be expanded/collapsed */
27 expand?: ThExpandType;
28 /** Formats the header so that its column will be sortable */
29 sort?: ThSortType;
30 /**
31 * Tooltip to show on the header cell.
32 * Note: If the header cell is truncated and has simple string content, it will already attempt to display the header text.
33 * If you want to show a tooltip that differs from the header text, you can set it here.
34 * To disable it completely you can set it to null.
35 */
36 tooltip?: React.ReactNode;
37 /** other props to pass to the tooltip */
38 tooltipProps?: Omit<TooltipProps, 'content'>;
39 /** Callback on mouse enter */
40 onMouseEnter?: (event: any) => void;
41 /** Adds tooltip/popover info button */
42 info?: ThInfoType;
43 /** Adds scope to the column to associate header cells with data cells*/
44 scope?: string;
45 /** Indicates the header column should be sticky */
46 isStickyColumn?: boolean;
47 /** Adds a border to the right side of the cell */
48 hasRightBorder?: boolean;
49 /** Adds a border to the left side of the cell */
50 hasLeftBorder?: boolean;
51 /** Minimum width for a sticky column */
52 stickyMinWidth?: string;
53 /** Left offset of a sticky column. This will typically be equal to the combined value set by stickyMinWidth of any sticky columns that precede the current sticky column. */
54 stickyLeftOffset?: string;
55 /** Right offset of a sticky column. This will typically be equal to the combined value set by stickyMinWidth of any sticky columns that come after the current sticky column. */
56 stickyRightOffset?: string;
57 /** Indicates the <th> is part of a subheader of a nested header */
58 isSubheader?: boolean;
59 /** Visually hidden text accessible only via assistive technologies. This must be passed in if the
60 * th is intended to be visually empty, and must be conveyed as a column header text.
61 */
62 screenReaderText?: string;
63 /** Provides an accessible name to the th. This should only be passed in when the th contains only non-text
64 * content, such as a "select all" checkbox or "expand all" toggle.
65 */
66 'aria-label'?: string;
67 /** @hide Beta prop, internal use only. Additional content to render in the column header, appended to the end of the header content. */
68 additionalContent?: React.ReactNode;
69 }
70
71 const ThBase: React.FunctionComponent<ThProps> = ({
72 children,
73 className,
74 component = 'th',
75 dataLabel,
76 scope = 'col',
77 textCenter = false,
78 sort = null,
79 modifier,
80 select = null,
81 expand: collapse = null,
82 tooltip = '',
83 tooltipProps,
84 onMouseEnter: onMouseEnterProp = () => {},
85 width,
86 visibility,
87 innerRef,
88 info: infoProps,
89 isStickyColumn = false,
90 hasRightBorder = false,
91 hasLeftBorder = false,
92 stickyMinWidth = '120px',
93 stickyLeftOffset,
94 stickyRightOffset,
95 isSubheader = false,
96 screenReaderText,
97 'aria-label': ariaLabel,
98 additionalContent,
99 ...props
100 }: ThProps) => {
101 const { variant } = useContext(TableContext);
102
103 if (!children && !screenReaderText && !ariaLabel) {
104 // eslint-disable-next-line no-console
105 console.warn(
106 'Th: Table headers must have an accessible name. If the Th is intended to be visually empty, pass in screenReaderText. If the Th contains only non-text, interactive content such as a checkbox or expand toggle, pass in an aria-label.'
107 );
108 }
109
110 const [showTooltip, setShowTooltip] = useState(false);
111 const [truncated, setTruncated] = useState(false);
112 const cellRef = innerRef ? innerRef : createRef();
113 const onMouseEnter = (event: any) => {
114 if (event.target.offsetWidth < event.target.scrollWidth) {
115 !showTooltip && setShowTooltip(true);
116 } else {
117 showTooltip && setShowTooltip(false);
118 }
119 onMouseEnterProp(event);
120 };
121
122 let sortParams = null;
123 if (sort) {
124 if (sort.isFavorites) {
125 sortParams = sortableFavorites({
126 onSort: sort.onSort,
127 columnIndex: sort.columnIndex,
128 sortBy: sort.sortBy,
129 tooltip: tooltip as string,
130 tooltipProps,
131 ariaLabel: sort['aria-label'],
132 favoriteButtonProps: sort.favoriteButtonProps
133 })();
134 } else {
135 sortParams = sortable(children as IFormatterValueType, {
136 columnIndex: sort.columnIndex,
137 column: {
138 extraParams: {
139 sortBy: sort.sortBy,
140 onSort: sort?.onSort
141 }
142 } as IColumn,
143 tooltip: tooltip as string,
144 tooltipProps
145 });
146 }
147 }
148
149 const selectParams = select
150 ? selectable(children as IFormatterValueType, {
151 rowData: {
152 selected: select.isSelected,
153 disableSelection: select?.isDisabled,
154 props: select?.props
155 },
156 column: {
157 extraParams: {
158 onSelect: select?.onSelect,
159 selectVariant: 'checkbox',
160 allRowsSelected: select.isSelected,
161 isHeaderSelectDisabled: !!select.isHeaderSelectDisabled,
162 isIndeterminate: select?.isIndeterminate
163 }
164 },
165 tooltip: tooltip as string,
166 tooltipProps
167 })
168 : null;
169 const collapseParams = collapse
170 ? collapsible(children as IFormatterValueType, {
171 column: {
172 extraParams: {
173 onCollapse: collapse?.onToggle,
174 allRowsExpanded: !collapse.areAllExpanded,
175 collapseAllAriaLabel: '',
176 variant
177 }
178 }
179 })
180 : null;
181 const widthParams = width ? cellWidth(width)() : null;
182 const visibilityParams = visibility
183 ? classNames(...visibility.map((vis: keyof IVisibility) => Visibility[vis]))()
184 : null;
185 let transformedChildren = sortParams?.children || selectParams?.children || collapseParams?.children || children;
186 // info can wrap other transformedChildren
187 let infoParams = null;
188 if (infoProps) {
189 infoParams = info(infoProps)(transformedChildren as formatterValueType);
190 transformedChildren = infoParams.children;
191 }
192 const merged = mergeProps(sortParams, selectParams, collapseParams, widthParams, visibilityParams, infoParams);
193 const {
194 // ignore the merged children since we transform them ourselves so we can wrap it with info
195 // eslint-disable-next-line @typescript-eslint/no-unused-vars
196 children: mergedChildren = null,
197 // selectable adds this but we don't want it
198 // eslint-disable-next-line @typescript-eslint/no-unused-vars
199 isVisible = null,
200 className: mergedClassName = '',
201 component: MergedComponent = component,
202 ...mergedProps
203 } = merged;
204
205 useEffect(() => {
206 setTruncated(
207 (cellRef as React.RefObject<HTMLElement | null>).current.offsetWidth <
208 (cellRef as React.RefObject<HTMLElement | null>).current.scrollWidth
209 );
210 }, [cellRef]);
211
212 const cell = (
213 <MergedComponent
214 tabIndex={sort || select || !truncated ? -1 : 0}
215 onFocus={tooltip !== null ? onMouseEnter : onMouseEnterProp}
216 onBlur={() => setShowTooltip(false)}
217 data-label={dataLabel}
218 onMouseEnter={tooltip !== null ? onMouseEnter : onMouseEnterProp}
219 scope={component === 'th' ? scope : null}
220 ref={cellRef}
221 aria-label={ariaLabel}
222 className={css(
223 styles.tableTh,
224 className,
225 textCenter && styles.modifiers.center,
226 isSubheader && styles.tableSubhead,
227 isStickyColumn && scrollStyles.tableStickyCell,
228 hasRightBorder && scrollStyles.modifiers.borderRight,
229 hasLeftBorder && scrollStyles.modifiers.borderLeft,
230 modifier && styles.modifiers[modifier as 'breakWord' | 'fitContent' | 'nowrap' | 'truncate' | 'wrap'],
231 sort?.favoriteButtonProps?.favorited && styles.modifiers.favorited,
232 mergedClassName
233 )}
234 {...mergedProps}
235 {...props}
236 {...(isStickyColumn && {
237 style: {
238 [cssStickyCellMinWidth.name]: stickyMinWidth ? stickyMinWidth : undefined,
239 [cssStickyCellInlineStart.name]: stickyLeftOffset ? stickyLeftOffset : 0,
240 [cssStickyCellInlineEnd.name]: stickyRightOffset ? stickyRightOffset : 0,
241 ...props.style
242 } as React.CSSProperties
243 })}
244 >
245 {transformedChildren ||
246 (screenReaderText && <span className={accessibilityStyles.screenReader}>{screenReaderText}</span>)}
247 {additionalContent && additionalContent}
248 </MergedComponent>
249 );
250
251 const canMakeDefaultTooltip = tooltip === '' ? typeof transformedChildren === 'string' : true;
252 const childControlsTooltip = sortParams || selectParams;
253 return tooltip !== null && canMakeDefaultTooltip && !childControlsTooltip && showTooltip ? (
254 <>
255 {cell}
256 <Tooltip
257 triggerRef={cellRef as React.RefObject<any>}
258 content={tooltip || (tooltip === '' && children)}
259 isVisible
260 {...tooltipProps}
261 />
262 </>
263 ) : (
264 cell
265 );
266 };
267
268 export const Th = forwardRef((props: ThProps, ref: React.Ref<HTMLTableHeaderCellElement>) => (
269 <ThBase {...props} innerRef={ref} />
270 ));
271 Th.displayName = 'Th';