-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathebay-progress-stepper.tsx
68 lines (60 loc) · 2.18 KB
/
ebay-progress-stepper.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import React, { Children, cloneElement, FC, Fragment, ReactElement, ReactNode } from 'react'
import classNames from 'classnames'
import { StepperDirection, StepState } from './types'
import { EbayProgressStepProps } from './ebay-progress-step'
type ProgressStepperProps = {
direction?: StepperDirection;
defaultState?: StepState;
className?: string;
children?: ReactNode;
}
const EbayProgressStepper: FC<ProgressStepperProps> = ({
direction = 'row',
defaultState = 'active',
children,
className,
...rest
}) => {
const childrenArray = Children.toArray(children) as ReactElement[]
const currentIndex = currentIndexByDefaultState(childrenArray, defaultState)
return (
<div
{...rest}
className={classNames(className, 'progress-stepper', {
'progress-stepper--vertical': direction === 'column'
})}
>
<div
role="list"
className="progress-stepper__items"
>
{childrenArray.map((child: ReactElement, index) => (
<Fragment key={index}>
{index > 0 && <hr className="progress-stepper__separator" role="presentation" />}
{cloneElement<EbayProgressStepProps>(child, {
state: stepState(index, currentIndex),
...child.props,
current: currentIndex === index
})}
</Fragment>
))}
</div>
</div>
)
}
function currentIndexByDefaultState(steps: ReactElement[], defaultState: StepState): number {
const foundCurrentIndex = steps.findIndex(child => child.props.current)
if (foundCurrentIndex === -1) {
// eslint-disable-next-line default-case
switch (defaultState) {
case 'complete': return steps.length - 1
case 'upcoming': return 0
}
}
return foundCurrentIndex
}
function stepState(stepIndex, currentIndex): StepState {
if (stepIndex <= currentIndex) return 'complete'
if (stepIndex > currentIndex) return 'upcoming'
}
export default EbayProgressStepper