Debian Codegraph @

node/@patternfly/react-core/src/deprecated/components/Wizard/Wizard.tsx

raw
1 import { Component, createRef } from 'react';
2 import { KeyTypes } from '../../../helpers/constants';
3 import { css } from '@patternfly/react-styles';
4 import styles from '@patternfly/react-styles/css/components/Wizard/wizard';
5 import { Modal, ModalVariant } from '../Modal';
6 import { WizardFooterInternal } from './WizardFooterInternal';
7 import { WizardToggle } from './WizardToggle';
8 import { WizardNav } from './WizardNav';
9 import { WizardNavItem, WizardNavItemProps } from './WizardNavItem';
10 import { WizardContextProvider } from './WizardContext';
11 import { PickOptional } from '../../../helpers/typeUtils';
12 import { WizardHeader } from './WizardHeader';
13
14 export interface WizardStep {
15 /** Optional identifier */
16 id?: string | number;
17 /** The name of the step */
18 name: React.ReactNode;
19 /** The component to render in the main body */
20 component?: any;
21 /** The content to render in the drawer panel (use when hasDrawer prop is set on the wizard). */
22 drawerPanelContent?: any;
23 /** Custom drawer toggle button that opens the drawer. */
24 drawerToggleButton?: React.ReactNode;
25 /** Setting to true hides the side nav and footer */
26 isFinishedStep?: boolean;
27 /** Enables or disables the step in the navigation. Enabled by default. */
28 canJumpTo?: boolean;
29 /** Sub steps */
30 steps?: WizardStep[];
31 /** Props to pass to the WizardNavItem */
32 stepNavItemProps?: React.HTMLProps<HTMLButtonElement | HTMLAnchorElement> | WizardNavItemProps;
33 /** (Unused if footer is controlled) Can change the Next button text. If nextButtonText is also set for the Wizard, this step specific one overrides it. */
34 nextButtonText?: React.ReactNode;
35 /** (Unused if footer is controlled) The condition needed to enable the Next button */
36 enableNext?: boolean;
37 /** (Unused if footer is controlled) True to hide the Cancel button */
38 hideCancelButton?: boolean;
39 /** (Unused if footer is controlled) True to hide the Back button */
40 hideBackButton?: boolean;
41 /** Flag to disable the step in the navigation */
42 isDisabled?: boolean;
43 }
44
45 export type WizardStepFunctionType = (
46 newStep: { id?: string | number; name: React.ReactNode },
47 prevStep: { prevId?: string | number; prevName: React.ReactNode }
48 ) => void;
49
50 export interface WizardProps extends React.HTMLProps<HTMLDivElement> {
51 /** Custom width of the wizard */
52 width?: number | string;
53 /** Custom height of the wizard */
54 height?: number | string;
55 /** The wizard title to display if header is desired */
56 title?: string;
57 /** An optional id for the title */
58 titleId?: string;
59 /** An optional id for the description */
60 descriptionId?: string;
61 /** The wizard description */
62 description?: React.ReactNode;
63 /** Component type of the description */
64 descriptionComponent?: 'div' | 'p';
65 /** Flag indicating whether the close button should be in the header */
66 hideClose?: boolean;
67 /** Callback function to close the wizard */
68 onClose?: () => void;
69 /** Callback function when a step in the nav is clicked */
70 onGoToStep?: WizardStepFunctionType;
71 /** Additional classes spread to the Wizard */
72 className?: string;
73 /** The wizard steps configuration object */
74 steps: WizardStep[];
75 /** The current step the wizard is on (1 or higher) */
76 startAtStep?: number;
77 /** Aria-label for the Nav */
78 navAriaLabel?: string;
79 /** Sets aria-labelledby on nav element */
80 navAriaLabelledBy?: string;
81 /** Adds an accessible name to the wizard body when the body content overflows and renders
82 * a scrollbar.
83 */
84 mainAriaLabel?: string;
85 /** Adds an accessible name to the wizard body by passing the the id of one or more elements.
86 * The aria-labelledby will only be applied when the body content overflows and renders a scrollbar.
87 */
88 mainAriaLabelledBy?: string;
89 /** Can remove the default padding around the main body content by setting this to true */
90 hasNoBodyPadding?: boolean;
91 /** (Use to control the footer) Passing in a footer component lets you control the buttons yourself */
92 footer?: React.ReactNode;
93 /** (Unused if footer is controlled) Callback function to save at the end of the wizard, if not specified uses onClose */
94 onSave?: () => void;
95 /** (Unused if footer is controlled) Callback function after Next button is clicked */
96 onNext?: WizardStepFunctionType;
97 /** (Unused if footer is controlled) Callback function after Back button is clicked */
98 onBack?: WizardStepFunctionType;
99 /** (Unused if footer is controlled) The Next button text */
100 nextButtonText?: React.ReactNode;
101 /** (Unused if footer is controlled) The Back button text */
102 backButtonText?: React.ReactNode;
103 /** (Unused if footer is controlled) The Cancel button text */
104 cancelButtonText?: React.ReactNode;
105 /** (Unused if footer is controlled) aria-label for the close button */
106 closeButtonAriaLabel?: string;
107 /** The parent container to append the modal to. Defaults to document.body */
108 appendTo?: HTMLElement | (() => HTMLElement);
109 /** Flag indicating Wizard modal is open. Wizard will be placed into a modal if this prop is provided */
110 isOpen?: boolean;
111 /** Flag indicating nav items with sub steps are expandable */
112 isNavExpandable?: boolean;
113 /** Callback function to signal the current step in the wizard */
114 onCurrentStepChanged?: (step: WizardStep) => void;
115 /** Flag indicating the wizard has a drawer for at least one of the wizard steps */
116 hasDrawer?: boolean;
117 /** Flag indicating the wizard drawer is expanded */
118 isDrawerExpanded?: boolean;
119 /** Callback function for when the drawer is toggled. Can be used to set browser focus in the drawer. */
120 onExpandDrawer?: () => void;
121 }
122
123 interface WizardState {
124 currentStep: number;
125 isNavOpen: boolean;
126 }
127
128 class Wizard extends Component<WizardProps, WizardState> {
129 static displayName = 'Wizard';
130 private static currentId = 0;
131 static defaultProps: PickOptional<WizardProps> = {
132 title: null,
133 description: '',
134 descriptionComponent: 'p',
135 className: '',
136 startAtStep: 1,
137 nextButtonText: 'Next',
138 backButtonText: 'Back',
139 cancelButtonText: 'Cancel',
140 hideClose: false,
141 closeButtonAriaLabel: 'Close',
142 navAriaLabel: null,
143 navAriaLabelledBy: null,
144 mainAriaLabel: null,
145 mainAriaLabelledBy: null,
146 hasNoBodyPadding: false,
147 onBack: null as WizardStepFunctionType,
148 onNext: null as WizardStepFunctionType,
149 onGoToStep: null as WizardStepFunctionType,
150 width: null as string,
151 height: null as string,
152 footer: null as React.ReactNode,
153 onClose: () => undefined as any,
154 appendTo: null as HTMLElement,
155 isOpen: undefined,
156 isNavExpandable: false,
157 hasDrawer: false,
158 isDrawerExpanded: false,
159 onExpandDrawer: () => undefined as any
160 };
161 private titleId: string;
162 private descriptionId: string;
163 private drawerRef: React.RefObject<any>;
164
165 constructor(props: WizardProps) {
166 super(props);
167 const newId = Wizard.currentId++;
168 this.titleId = props.titleId || `pf-wizard-title-${newId}`;
169 this.descriptionId = props.descriptionId || `pf-wizard-description-${newId}`;
170
171 this.state = {
172 currentStep: this.props.startAtStep && Number.isInteger(this.props.startAtStep) ? this.props.startAtStep : 1,
173 isNavOpen: false
174 };
175
176 if (props.onCurrentStepChanged) {
177 const flattenedSteps = this.getFlattenedSteps();
178 if (flattenedSteps.length >= this.state.currentStep) {
179 const currentStep = flattenedSteps[this.state.currentStep - 1];
180 props.onCurrentStepChanged(currentStep);
181 }
182 }
183
184 this.drawerRef = createRef();
185 }
186
187 private handleKeyClicks = (event: KeyboardEvent): void => {
188 if (event.key === KeyTypes.Escape) {
189 if (this.state.isNavOpen) {
190 this.setState({ isNavOpen: !this.state.isNavOpen });
191 } else if (this.props.isOpen) {
192 this.props.onClose();
193 }
194 }
195 };
196
197 private onNext = (): void => {
198 const { onNext, onClose, onSave } = this.props;
199 const { currentStep } = this.state;
200 const flattenedSteps = this.getFlattenedSteps();
201 const maxSteps = flattenedSteps.length;
202 if (currentStep >= maxSteps) {
203 // Hit the save button at the end of the wizard
204 if (onSave) {
205 return onSave();
206 }
207 return onClose();
208 } else {
209 let newStep = currentStep;
210
211 for (let nextStep = currentStep; nextStep <= maxSteps; nextStep++) {
212 if (!flattenedSteps[nextStep]) {
213 return;
214 }
215
216 if (!flattenedSteps[nextStep].isDisabled) {
217 newStep = nextStep + 1;
218 break;
219 }
220 }
221
222 this.setCurrentStep(newStep, flattenedSteps[newStep - 1]);
223 const { id: prevId, name: prevName } = flattenedSteps[currentStep - 1];
224 const { id, name } = flattenedSteps[newStep - 1];
225 return onNext && onNext({ id, name }, { prevId, prevName });
226 }
227 };
228
229 private onBack = (): void => {
230 const { onBack } = this.props;
231 const { currentStep } = this.state;
232 const flattenedSteps = this.getFlattenedSteps();
233 if (flattenedSteps.length < currentStep) {
234 // Previous step was removed, just update the currentStep state
235 const adjustedStep = flattenedSteps.length;
236 this.setCurrentStep(adjustedStep, flattenedSteps[adjustedStep - 1]);
237 } else {
238 let newStep = currentStep;
239
240 for (let prevStep = currentStep; prevStep >= 0; prevStep--) {
241 if (!flattenedSteps[prevStep - 2]) {
242 return;
243 }
244
245 if (!flattenedSteps[prevStep - 2].isDisabled) {
246 newStep = prevStep - 1 <= 1 ? 1 : prevStep - 1;
247 break;
248 }
249 }
250
251 this.setCurrentStep(newStep, flattenedSteps[newStep - 1]);
252 const { id: prevId, name: prevName } = flattenedSteps[newStep];
253 const { id, name } = flattenedSteps[newStep - 1];
254 return onBack && onBack({ id, name }, { prevId, prevName });
255 }
256 };
257
258 private goToStep = (step: number): void => {
259 const flattenedSteps = this.getFlattenedSteps();
260
261 if (flattenedSteps[step - 1].isDisabled) {
262 return;
263 }
264
265 const { onGoToStep } = this.props;
266 const { currentStep } = this.state;
267 const maxSteps = flattenedSteps.length;
268 if (step < 1) {
269 step = 1;
270 } else if (step > maxSteps) {
271 step = maxSteps;
272 }
273 this.setCurrentStep(step, flattenedSteps[step - 1]);
274 this.setState({ isNavOpen: false });
275 const { id: prevId, name: prevName } = flattenedSteps[currentStep - 1];
276 const { id, name } = flattenedSteps[step - 1];
277 return onGoToStep && onGoToStep({ id, name }, { prevId, prevName });
278 };
279
280 private goToStepById = (stepId: number | string): void => {
281 const flattenedSteps = this.getFlattenedSteps();
282 let step;
283 for (let i = 0; i < flattenedSteps.length; i++) {
284 if (flattenedSteps[i].id === stepId) {
285 step = i + 1;
286 break;
287 }
288 }
289 if (step) {
290 this.setCurrentStep(step, flattenedSteps[step - 1]);
291 }
292 };
293
294 private goToStepByName = (stepName: string): void => {
295 const flattenedSteps = this.getFlattenedSteps();
296 let step;
297 for (let i = 0; i < flattenedSteps.length; i++) {
298 if (flattenedSteps[i].name === stepName) {
299 step = i + 1;
300 break;
301 }
302 }
303 if (step) {
304 this.setCurrentStep(step, flattenedSteps[step - 1]);
305 }
306 };
307
308 private getFlattenedSteps = (): WizardStep[] => {
309 const { steps } = this.props;
310 const flattenedSteps: WizardStep[] = [];
311 for (const step of steps) {
312 if (step.steps) {
313 for (const childStep of step.steps) {
314 flattenedSteps.push(childStep);
315 }
316 } else {
317 flattenedSteps.push(step);
318 }
319 }
320 return flattenedSteps;
321 };
322
323 private getFlattenedStepsIndex = (flattenedSteps: WizardStep[], stepName: React.ReactNode): number => {
324 for (let i = 0; i < flattenedSteps.length; i++) {
325 if (flattenedSteps[i].name === stepName) {
326 return i + 1;
327 }
328 }
329
330 return 0;
331 };
332
333 private initSteps = (steps: WizardStep[]): WizardStep[] => {
334 // Set default Step values
335 for (let i = 0; i < steps.length; i++) {
336 if (steps[i].steps) {
337 for (let j = 0; j < steps[i].steps.length; j++) {
338 steps[i].steps[j] = Object.assign({ canJumpTo: true }, steps[i].steps[j]);
339 }
340 }
341 steps[i] = Object.assign({ canJumpTo: true }, steps[i]);
342 }
343 return steps;
344 };
345
346 getElement = (appendTo: HTMLElement | (() => HTMLElement)) => {
347 if (typeof appendTo === 'function') {
348 return appendTo();
349 }
350 return appendTo || document.body;
351 };
352
353 private setCurrentStep(currentStep: number, currentStepObject: WizardStep) {
354 this.setState({
355 currentStep
356 });
357
358 if (this.props.onCurrentStepChanged) {
359 this.props.onCurrentStepChanged(currentStepObject);
360 }
361 }
362
363 componentDidMount() {
364 const target = typeof document !== 'undefined' ? document.body : null;
365 if (target) {
366 target.addEventListener('keydown', this.handleKeyClicks, false);
367 }
368 }
369
370 componentWillUnmount() {
371 const target = (typeof document !== 'undefined' && document.body) || null;
372 if (target) {
373 target.removeEventListener('keydown', this.handleKeyClicks, false);
374 }
375 }
376
377 componentDidUpdate(prevProps: Readonly<WizardProps>) {
378 if (prevProps.startAtStep !== this.props.startAtStep) {
379 this.setState({ currentStep: this.props.startAtStep });
380 }
381 }
382
383 render() {
384 const {
385 /* eslint-disable @typescript-eslint/no-unused-vars */
386 width,
387 height,
388 title,
389 description,
390 descriptionComponent,
391 onClose,
392 onSave,
393 onBack,
394 onNext,
395 onGoToStep,
396 className,
397 steps,
398 startAtStep,
399 nextButtonText = 'Next',
400 backButtonText = 'Back',
401 cancelButtonText = 'Cancel',
402 hideClose,
403 closeButtonAriaLabel = 'Close',
404 navAriaLabel,
405 navAriaLabelledBy,
406 mainAriaLabel,
407 mainAriaLabelledBy,
408 hasNoBodyPadding,
409 footer,
410 appendTo,
411 isOpen,
412 titleId,
413 descriptionId,
414 isNavExpandable,
415 onCurrentStepChanged,
416 hasDrawer,
417 isDrawerExpanded,
418 onExpandDrawer,
419 ...rest
420 /* eslint-enable @typescript-eslint/no-unused-vars */
421 } = this.props;
422 const { currentStep } = this.state;
423 const flattenedSteps = this.getFlattenedSteps();
424 const adjustedStep = flattenedSteps.length < currentStep ? flattenedSteps.length : currentStep;
425 const activeStep = flattenedSteps[adjustedStep - 1];
426 const computedSteps: WizardStep[] = this.initSteps(steps);
427 const firstStep = activeStep === flattenedSteps[0];
428 const isValid = activeStep && activeStep.enableNext !== undefined ? activeStep.enableNext : true;
429
430 const nav = (isWizardNavOpen: boolean) => {
431 const wizNavAProps = {
432 isOpen: isWizardNavOpen,
433 'aria-label': navAriaLabel,
434 'aria-labelledby': (title || navAriaLabelledBy) && (navAriaLabelledBy || this.titleId)
435 };
436
437 return (
438 <WizardNav {...wizNavAProps}>
439 {computedSteps.map((step, index) => {
440 if (step.isFinishedStep) {
441 // Don't show finished step in the side nav
442 return;
443 }
444 let enabled;
445 let navItemStep;
446 if (step.steps) {
447 let hasActiveChild = false;
448 let canJumpToParent = false;
449 for (const subStep of step.steps) {
450 if (activeStep.name === subStep.name) {
451 // one of the children matches
452 hasActiveChild = true;
453 }
454 if (subStep.canJumpTo) {
455 canJumpToParent = true;
456 }
457 }
458 navItemStep = this.getFlattenedStepsIndex(flattenedSteps, step.steps[0].name);
459 return (
460 <WizardNavItem
461 key={index}
462 id={step.id}
463 content={step.name}
464 isExpandable={isNavExpandable}
465 isCurrent={hasActiveChild}
466 isDisabled={!canJumpToParent}
467 step={navItemStep}
468 onNavItemClick={this.goToStep}
469 >
470 <WizardNav {...wizNavAProps} returnList>
471 {step.steps.map((childStep: WizardStep, indexChild: number) => {
472 if (childStep.isFinishedStep) {
473 // Don't show finished step in the side nav
474 return;
475 }
476 navItemStep = this.getFlattenedStepsIndex(flattenedSteps, childStep.name);
477 enabled = childStep.canJumpTo && !childStep.isDisabled;
478 return (
479 <WizardNavItem
480 key={`child_${indexChild}`}
481 id={childStep.id}
482 content={childStep.name}
483 isCurrent={activeStep.name === childStep.name}
484 isDisabled={!enabled}
485 step={navItemStep}
486 onNavItemClick={this.goToStep}
487 />
488 );
489 })}
490 </WizardNav>
491 </WizardNavItem>
492 );
493 }
494 navItemStep = this.getFlattenedStepsIndex(flattenedSteps, step.name);
495 enabled = step.canJumpTo && !step.isDisabled;
496
497 return (
498 <WizardNavItem
499 {...step.stepNavItemProps}
500 key={index}
501 id={step.id}
502 content={step.name}
503 isCurrent={activeStep.name === step.name}
504 isDisabled={!enabled}
505 step={navItemStep}
506 onNavItemClick={this.goToStep}
507 />
508 );
509 })}
510 </WizardNav>
511 );
512 };
513
514 const context = {
515 goToStepById: this.goToStepById,
516 goToStepByName: this.goToStepByName,
517 onNext: this.onNext,
518 onBack: this.onBack,
519 onClose,
520 activeStep
521 };
522
523 const divStyles = {
524 ...(height ? { height } : {}),
525 ...(width ? { width } : {})
526 };
527
528 const wizard = (
529 <WizardContextProvider value={context}>
530 <div
531 {...rest}
532 className={css(styles.wizard, activeStep && activeStep.isFinishedStep && 'pf-m-finished', className)}
533 style={Object.keys(divStyles).length ? divStyles : undefined}
534 >
535 {title && (
536 <WizardHeader
537 titleId={this.titleId}
538 descriptionId={this.descriptionId}
539 onClose={onClose}
540 title={title}
541 description={description}
542 descriptionComponent={descriptionComponent}
543 closeButtonAriaLabel={closeButtonAriaLabel}
544 hideClose={hideClose}
545 />
546 )}
547 <WizardToggle
548 hasDrawer={hasDrawer}
549 isDrawerExpanded={isDrawerExpanded}
550 onExpandDrawer={onExpandDrawer}
551 mainAriaLabel={mainAriaLabel}
552 isInPage={isOpen === undefined}
553 mainAriaLabelledBy={(title || mainAriaLabelledBy) && (mainAriaLabelledBy || this.titleId)}
554 isNavOpen={this.state.isNavOpen}
555 onNavToggle={(isNavOpen) => this.setState({ isNavOpen })}
556 nav={nav}
557 steps={steps}
558 activeStep={activeStep}
559 hasNoBodyPadding={hasNoBodyPadding}
560 >
561 {footer || (
562 <WizardFooterInternal
563 onNext={this.onNext}
564 onBack={this.onBack}
565 onClose={onClose}
566 isValid={isValid}
567 firstStep={firstStep}
568 activeStep={activeStep}
569 nextButtonText={(activeStep && activeStep.nextButtonText) || nextButtonText}
570 backButtonText={backButtonText}
571 cancelButtonText={cancelButtonText}
572 />
573 )}
574 </WizardToggle>
575 </div>
576 </WizardContextProvider>
577 );
578
579 if (isOpen !== undefined) {
580 return (
581 <Modal
582 width={width !== null ? width : undefined}
583 isOpen={isOpen}
584 variant={ModalVariant.large}
585 aria-labelledby={this.titleId}
586 aria-describedby={this.descriptionId}
587 showClose={false}
588 hasNoBodyWrapper
589 >
590 {wizard}
591 </Modal>
592 );
593 }
594
595 return wizard;
596 }
597 }
598
599 export { Wizard };