Debian Codegraph @

node/@patternfly/react-core/src/components/ExpandableSection/ExpandableSection.tsx

raw
1 import { Component, createRef } from 'react';
2 import styles from '@patternfly/react-styles/css/components/ExpandableSection/expandable-section';
3 import { css } from '@patternfly/react-styles';
4 import lineClamp from '@patternfly/react-tokens/dist/esm/c_expandable_section_m_truncate__content_LineClamp';
5 import RhMicronsCaretDownIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-caret-down-icon';
6 import { PickOptional } from '../../helpers/typeUtils';
7 import { debounce } from '../../helpers/util';
8 import { getResizeObserver } from '../../helpers/resizeObserver';
9 import { GenerateId } from '../../helpers';
10 import { Button } from '../Button';
11
12 export enum ExpandableSectionVariant {
13 default = 'default',
14 truncate = 'truncate'
15 }
16
17 /** The main expandable section component. */
18
19 export interface ExpandableSectionProps extends Omit<React.HTMLProps<HTMLDivElement>, 'onToggle'> {
20 /** Content rendered inside the expandable section. */
21 children?: React.ReactNode;
22 /** Additional classes added to the expandable section. */
23 className?: string;
24 /** Id of the content of the expandable section. When passing in the isDetached property, this
25 * property's value should match the contentId property of the expandable section toggle sub-component.
26 */
27 contentId?: string;
28 /** Id of the toggle of the expandable section, which provides an accessible name to the
29 * expandable section content via the aria-labelledby attribute. When the isDetached property
30 * is also passed in, the value of this property must match the toggleId property of the
31 * expandable section toggle sub-component.
32 */
33 toggleId?: string;
34 /** Display size variant. Set to "lg" for disclosure styling. */
35 displaySize?: 'default' | 'lg';
36 /** Flag indicating that the expandable section and expandable toggle are detached from one another. */
37 isDetached?: boolean;
38 /** Flag to indicate if the content is expanded. */
39 isExpanded?: boolean;
40 /** Flag to indicate if the content is indented. */
41 isIndented?: boolean;
42 /** Flag to indicate the width of the component is limited. Set to "true" for disclosure styling. */
43 isWidthLimited?: boolean;
44 /** Callback function to toggle the expandable section. Detached expandable sections should
45 * use the onToggle property of the expandable section toggle sub-component.
46 */
47 onToggle?: (event: React.MouseEvent, isExpanded: boolean) => void;
48 /** React node that appears in the attached toggle in place of the toggleText property.
49 * Can also be a function that receives the expanded state and returns a React node.
50 */
51 toggleContent?: React.ReactNode | ((isExpanded: boolean) => React.ReactNode);
52 /** Text that appears in the attached toggle. */
53 toggleText?: string;
54 /** Text that appears in the attached toggle when collapsed (will override toggleText if
55 * both are specified; used for uncontrolled expandable with dynamic toggle text).
56 */
57 toggleTextCollapsed?: string;
58 /** Text that appears in the attached toggle when expanded (will override toggleText if
59 * both are specified; used for uncontrolled expandable with dynamic toggle text).
60 */
61 toggleTextExpanded?: string;
62 /** Accessible name via human readable string for the expandable section toggle. */
63 toggleAriaLabel?: string;
64 /** Accessible name via space delimtted list of IDs for the expandable section toggle. */
65 toggleAriaLabelledBy?: string;
66 /** Icon shown in toggle when variant is not truncated. */
67 toggleIcon?: React.ReactNode;
68 /** Whether to show a toggle icon when variant is not truncated. If omitted, it is important to ensure the current state of the ExpandableSection is conveyed, most likely by having dynamic toggle text. */
69 hasToggleIcon?: boolean;
70 /** Truncates the expandable content to the specified number of lines when using the
71 * "truncate" variant.
72 */
73 truncateMaxLines?: number;
74 /** Determines the variant of the expandable section. When passing in "truncate" as the
75 * variant, the expandable content will be truncated after 3 lines by default.
76 */
77 variant?: 'default' | 'truncate';
78 /** Sets the direction of the expandable animation when isDetached is true. If this prop is not passed,
79 * animation will not occur.
80 */
81 direction?: 'up' | 'down';
82 /** The HTML element to use for the toggle wrapper. Can be 'div' (default) or any heading level.
83 * When using heading elements, the button will be rendered inside the heading for proper semantics.
84 * This is useful when the toggle text should function as a heading in the document structure.
85 */
86 toggleWrapper?: 'div' | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
87 }
88
89 interface ExpandableSectionState {
90 isExpanded: boolean;
91 hasToggle: boolean;
92 previousWidth: number;
93 }
94
95 const directionClassMap = {
96 up: styles.modifiers.expandTop,
97 down: styles.modifiers.expandBottom
98 };
99
100 const setLineClamp = (lines: number, element: HTMLDivElement) => {
101 if (!element || lines < 1) {
102 return;
103 }
104
105 element.style.setProperty(lineClamp.name, lines.toString());
106 };
107
108 class ExpandableSection extends Component<ExpandableSectionProps, ExpandableSectionState> {
109 static displayName = 'ExpandableSection';
110
111 constructor(props: ExpandableSectionProps) {
112 super(props);
113
114 this.state = {
115 isExpanded: props.isExpanded,
116 hasToggle: true,
117 previousWidth: undefined
118 };
119 }
120
121 expandableContentRef = createRef<HTMLDivElement>();
122 observer: any = () => {};
123
124 static defaultProps: PickOptional<ExpandableSectionProps> = {
125 className: '',
126 toggleText: '',
127 toggleTextExpanded: '',
128 toggleTextCollapsed: '',
129 toggleAriaLabel: undefined,
130 toggleAriaLabelledBy: undefined,
131 // eslint-disable-next-line @typescript-eslint/no-unused-vars
132 onToggle: (event, isExpanded): void => undefined,
133 isDetached: false,
134 displaySize: 'default',
135 isWidthLimited: false,
136 isIndented: false,
137 variant: 'default'
138 };
139
140 private calculateToggleText(
141 toggleText: string,
142 toggleTextExpanded: string,
143 toggleTextCollapsed: string,
144 propOrStateIsExpanded: boolean
145 ) {
146 if (propOrStateIsExpanded && toggleTextExpanded !== '') {
147 return toggleTextExpanded;
148 }
149 if (!propOrStateIsExpanded && toggleTextCollapsed !== '') {
150 return toggleTextCollapsed;
151 }
152 return toggleText;
153 }
154
155 componentDidMount() {
156 if (this.props.variant === ExpandableSectionVariant.truncate) {
157 const expandableContent = this.expandableContentRef.current;
158 this.setState({ previousWidth: expandableContent.offsetWidth });
159 this.observer = getResizeObserver(expandableContent, this.handleResize, false);
160
161 if (this.props.truncateMaxLines) {
162 setLineClamp(this.props.truncateMaxLines, expandableContent);
163 }
164
165 this.checkToggleVisibility();
166 }
167 }
168
169 componentDidUpdate(prevProps: ExpandableSectionProps) {
170 if (
171 this.props.variant === ExpandableSectionVariant.truncate &&
172 (prevProps.truncateMaxLines !== this.props.truncateMaxLines || prevProps.children !== this.props.children)
173 ) {
174 const expandableContent = this.expandableContentRef.current;
175 setLineClamp(this.props.truncateMaxLines, expandableContent);
176 this.checkToggleVisibility();
177 }
178 }
179
180 componentWillUnmount() {
181 if (this.props.variant === ExpandableSectionVariant.truncate) {
182 this.observer();
183 }
184 }
185
186 checkToggleVisibility = () => {
187 if (this.expandableContentRef?.current) {
188 const maxLines = this.props.truncateMaxLines || parseInt(lineClamp.value);
189 const totalLines =
190 this.expandableContentRef.current.scrollHeight /
191 parseInt(getComputedStyle(this.expandableContentRef.current).lineHeight);
192
193 this.setState({
194 hasToggle: totalLines > maxLines
195 });
196 }
197 };
198
199 resize = () => {
200 if (this.expandableContentRef.current) {
201 const { offsetWidth } = this.expandableContentRef.current;
202 if (this.state.previousWidth !== offsetWidth) {
203 this.setState({ previousWidth: offsetWidth });
204 this.checkToggleVisibility();
205 }
206 }
207 };
208 handleResize = debounce(this.resize, 250);
209
210 render() {
211 const {
212 onToggle: onToggleProp,
213 className,
214 toggleText,
215 toggleTextExpanded,
216 toggleTextCollapsed,
217 toggleContent,
218 toggleAriaLabel,
219 toggleAriaLabelledBy,
220 toggleIcon = <RhMicronsCaretDownIcon />,
221 hasToggleIcon = true,
222 children,
223 isExpanded,
224 isDetached,
225 displaySize,
226 isWidthLimited,
227 isIndented,
228 contentId,
229 toggleId,
230 variant,
231 // eslint-disable-next-line @typescript-eslint/no-unused-vars
232 truncateMaxLines,
233 direction,
234 toggleWrapper = 'div',
235 ...props
236 } = this.props;
237
238 if (isDetached && !toggleId) {
239 /* eslint-disable no-console */
240 console.warn(
241 'ExpandableSection: The toggleId value must be passed in and must match the toggleId of the ExpandableSectionToggle.'
242 );
243 }
244
245 let onToggle = onToggleProp;
246 let propOrStateIsExpanded = isExpanded;
247
248 // uncontrolled
249 if (isExpanded === undefined) {
250 propOrStateIsExpanded = this.state.isExpanded;
251 onToggle = (event, isOpen) => {
252 this.setState({ isExpanded: isOpen }, () => onToggleProp(event, this.state.isExpanded));
253 };
254 }
255
256 const computedToggleText = this.calculateToggleText(
257 toggleText,
258 toggleTextExpanded,
259 toggleTextCollapsed,
260 propOrStateIsExpanded
261 );
262
263 const computedToggleContent =
264 typeof toggleContent === 'function' ? toggleContent(propOrStateIsExpanded) : toggleContent;
265 const ToggleWrapper = toggleWrapper as any;
266
267 return (
268 <GenerateId prefix="expandable-section-content-">
269 {(genContentId) => (
270 <GenerateId prefix="expandable-section-toggle-">
271 {(genToggleId) => {
272 const uniqueContentId = contentId || genContentId;
273 const uniqueToggleId = toggleId || genToggleId;
274
275 const expandableToggle = !isDetached && (
276 <ToggleWrapper className={`${styles.expandableSection}__toggle`}>
277 <Button
278 variant="link"
279 {...(variant === ExpandableSectionVariant.truncate && { isInline: true })}
280 aria-expanded={propOrStateIsExpanded}
281 aria-controls={uniqueContentId}
282 id={uniqueToggleId}
283 onClick={(event) => onToggle(event, !propOrStateIsExpanded)}
284 {...(variant !== ExpandableSectionVariant.truncate &&
285 hasToggleIcon && {
286 icon: <span className={css(styles.expandableSectionToggleIcon)}>{toggleIcon}</span>
287 })}
288 aria-label={toggleAriaLabel}
289 aria-labelledby={toggleAriaLabelledBy}
290 >
291 {computedToggleContent || computedToggleText}
292 </Button>
293 </ToggleWrapper>
294 );
295
296 return (
297 <div
298 className={css(
299 styles.expandableSection,
300 propOrStateIsExpanded && styles.modifiers.expanded,
301 displaySize === 'lg' && styles.modifiers.displayLg,
302 isWidthLimited && styles.modifiers.limitWidth,
303 isIndented && styles.modifiers.indented,
304 isDetached && direction && directionClassMap[direction],
305 isDetached && direction && 'pf-m-detached',
306 variant === ExpandableSectionVariant.truncate && styles.modifiers.truncate,
307 className
308 )}
309 {...props}
310 >
311 {variant === ExpandableSectionVariant.default && expandableToggle}
312 <div
313 ref={this.expandableContentRef}
314 className={css(styles.expandableSectionContent)}
315 hidden={variant !== ExpandableSectionVariant.truncate && !propOrStateIsExpanded}
316 id={uniqueContentId}
317 aria-labelledby={uniqueToggleId}
318 role="region"
319 >
320 {children}
321 </div>
322 {variant === ExpandableSectionVariant.truncate && this.state.hasToggle && expandableToggle}
323 </div>
324 );
325 }}
326 </GenerateId>
327 )}
328 </GenerateId>
329 );
330 }
331 }
332
333 export { ExpandableSection };