Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(Wizard): add preventNavigation callback function to onStepChange #3924

Merged
merged 10 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,41 @@ const MyForm = () => {
}
```

You can also prevent the user from navigating to the next or previous step, by using the `preventNavigation` callback function found as the third parameter, in the `onStepChange` event.

```tsx
import { Form, Wizard } from '@dnb/eufemia/extensions/forms'

const MyForm = () => {
const { setActiveIndex, activeIndex } = Wizard.useStep('unique-id')

return (
<Form.Handler>
<Wizard.Container
onStepChange={(step, type, { preventNavigation }) => {
if (step === 2 && type === 'next') {
preventNavigation()
}
}}
>
<Wizard.Step title="Step 1">
<P>Step 1</P>
<Wizard.Buttons />
</Wizard.Step>
<Wizard.Step title="Step 2">
<P>Step 2</P>
<Wizard.Buttons />
</Wizard.Step>
<Wizard.Step title="Step 3">
<P>Step 3</P>
<Wizard.Buttons />
</Wizard.Step>
</Wizard.Container>
</Form.Handler>
)
}
```

## Accessibility

The `Wizard.Step` component uses an `aria-label` attribute that matches the title prop value. The step content is enclosed within a section element, which further enhances accessibility.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ function WizardContainer(props: Props) {
const totalStepsRef = useRef<number>(NaN)
const errorOnStepRef = useRef<Record<StepIndex, boolean>>({})
const stepElementRef = useRef<HTMLElement>()
const preventNextStepRef = useRef(false)

// - Handle shared state
const sharedStateRef =
Expand All @@ -141,15 +142,19 @@ function WizardContainer(props: Props) {
// Store the current state of showAllErrors
errorOnStepRef.current[activeIndexRef.current] = showAllErrors

const preventNavigation = useCallback((shouldPrevent = true) => {
preventNextStepRef.current = shouldPrevent
}, [])

const callOnStepChange = useCallback(
async (index: StepIndex, mode: 'previous' | 'next') => {
if (isAsync(onStepChange)) {
return await onStepChange(index, mode)
return await onStepChange(index, mode, { preventNavigation })
}

return onStepChange?.(index, mode)
return onStepChange?.(index, mode, { preventNavigation })
},
[onStepChange]
[onStepChange, preventNavigation]
)

const { setFocus, scrollToTop, isInteractionRef } =
Expand Down Expand Up @@ -182,7 +187,9 @@ function WizardContainer(props: Props) {
enableAsyncBehavior: isAsync(onStepChange),
onSubmit: async () => {
if (!skipStepChangeCallFromHook) {
sharedStateRef.current?.data?.onStepChange?.(index, mode)
sharedStateRef.current?.data?.onStepChange?.(index, mode, {
preventNavigation,
})
}

const result =
Expand All @@ -199,13 +206,15 @@ function WizardContainer(props: Props) {
setShowAllErrors(errorOnStepRef.current[index])
}

if (!(result instanceof Error)) {
if (!preventNextStepRef.current && !(result instanceof Error)) {
handleLayoutEffect()

activeIndexRef.current = index
forceUpdate()
}

preventNextStepRef.current = false

return result
},
})
Expand All @@ -216,6 +225,7 @@ function WizardContainer(props: Props) {
handleSubmitCall,
isInteractionRef,
onStepChange,
preventNavigation,
setFormState,
setShowAllErrors,
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export const WizardContainerProperties: PropertiesTableProps = {

export const WizardContainerEvents: PropertiesTableProps = {
onStepChange: {
doc: 'Will be called when the user navigate to a different step, with step `index` as the first argument and `previous` or `next` (string) as the second argument. When an async function is provided, it will show an indicator on the submit button during the form submission. All form elements will be disabled during the submit. The indicator will be shown for minimum 1 second. Related Form.Handler props: `minimumAsyncBehaviorTime` and `asyncSubmitTimeout`.',
doc: 'Will be called when the user navigate to a different step, with step `index` as the first argument and `previous` or `next` (string) as the second argument, and an options object containing `preventNavigation` function as the third parameter. When an async function is provided, it will show an indicator on the submit button during the form submission. All form elements will be disabled during the submit. The indicator will be shown for minimum 1 second. Related Form.Handler props: `minimumAsyncBehaviorTime` and `asyncSubmitTimeout`.',
type: 'function',
status: 'optional',
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,19 +89,31 @@ describe('Wizard.Container', () => {
await userEvent.click(secondStep.querySelector('.dnb-button'))
expect(output()).toHaveTextContent('Step 2')
expect(onStepChange).toHaveBeenCalledTimes(1)
expect(onStepChange).toHaveBeenLastCalledWith(1, 'next')
expect(onStepChange).toHaveBeenLastCalledWith(
1,
'next',
expect.anything()
)

await userEvent.click(firstStep.querySelector('.dnb-button'))
await wait(1000)
expect(output()).toHaveTextContent('Step 1')
expect(onStepChange).toHaveBeenCalledTimes(2)
expect(onStepChange).toHaveBeenLastCalledWith(0, 'previous')
expect(onStepChange).toHaveBeenLastCalledWith(
0,
'previous',
expect.anything()
)

await userEvent.click(nextButton())
expect(nextButton()).not.toBeDisabled()

expect(onStepChange).toHaveBeenCalledTimes(3)
expect(onStepChange).toHaveBeenLastCalledWith(1, 'next')
expect(onStepChange).toHaveBeenLastCalledWith(
1,
'next',
expect.anything()
)

// Use fireEvent to trigger the event fast
fireEvent.click(previousButton())
Expand All @@ -110,7 +122,11 @@ describe('Wizard.Container', () => {
await waitFor(() => {
expect(previousButton()).toBeNull()
expect(onStepChange).toHaveBeenCalledTimes(4)
expect(onStepChange).toHaveBeenLastCalledWith(0, 'previous')
expect(onStepChange).toHaveBeenLastCalledWith(
0,
'previous',
expect.anything()
)
expect(previousButton()).not.toBeInTheDocument()
})
})
Expand Down Expand Up @@ -1533,6 +1549,110 @@ describe('Wizard.Container', () => {
expect(screen.queryByRole('alert')).toBeInTheDocument()
})

it('should prevent navigation if `preventNavigation` is called', async () => {
render(
<Form.Handler>
<Wizard.Container
onStepChange={(step, mode, { preventNavigation }) => {
// Stop navigation of user presses the next button on step 2 (B)
if (step === 2 && mode === 'next') {
preventNavigation()
}
}}
>
<Wizard.Step title="Step A">
<p>Step A</p>
<Wizard.Buttons />
</Wizard.Step>
<Wizard.Step title="Step B">
<p>Step B</p>
<Wizard.Buttons />
</Wizard.Step>
<Wizard.Step title="Step C">
<p>Step C</p>
<Wizard.Buttons />
</Wizard.Step>
</Wizard.Container>
</Form.Handler>
)

const [stepA, stepB, stepC] = Array.from(
document.querySelectorAll('.dnb-step-indicator__item')
)

expect(stepA).toHaveClass('dnb-step-indicator__item--current')
expect(stepB).not.toHaveClass('dnb-step-indicator__item--current')
expect(stepC).not.toHaveClass('dnb-step-indicator__item--current')

await userEvent.click(screen.getByText('Neste'))

expect(stepA).not.toHaveClass('dnb-step-indicator__item--current')
expect(stepB).toHaveClass('dnb-step-indicator__item--current')
expect(stepC).not.toHaveClass('dnb-step-indicator__item--current')

await userEvent.click(screen.getByText('Neste'))

// Stay on Step B

expect(stepA).not.toHaveClass('dnb-step-indicator__item--current')
expect(stepB).toHaveClass('dnb-step-indicator__item--current')
expect(stepC).not.toHaveClass('dnb-step-indicator__item--current')

await userEvent.click(screen.getByText('Tilbake'))

expect(stepA).toHaveClass('dnb-step-indicator__item--current')
expect(stepB).not.toHaveClass('dnb-step-indicator__item--current')
expect(stepC).not.toHaveClass('dnb-step-indicator__item--current')
})

it('should run validation before `preventNavigation` result is evaluated', async () => {
const onStepChange = jest.fn((step, mode, { preventNavigation }) => {
if (step === 1 && mode === 'next') {
preventNavigation()
}
})

render(
<Form.Handler>
<Wizard.Container onStepChange={onStepChange}>
<Wizard.Step title="Step 1">
<Field.String required />
<output>Step 1</output>
<Wizard.Buttons />
</Wizard.Step>
<Wizard.Step title="Step 2">
<output>Step 2</output>
<Wizard.Buttons />
</Wizard.Step>
</Wizard.Container>
</Form.Handler>
)

expect(output()).toHaveTextContent('Step 1')

await userEvent.click(nextButton())

await waitFor(() => {
expect(screen.queryByRole('alert')).toBeInTheDocument()
})

expect(output()).toHaveTextContent('Step 1')

await userEvent.type(document.querySelector('input'), 'valid')

await waitFor(() => {
expect(screen.queryByRole('alert')).toBeNull()
})

await userEvent.click(nextButton())

expect(output()).toHaveTextContent('Step 1')
expect(onStepChange).toHaveBeenCalledTimes(1)
expect(onStepChange).toHaveBeenLastCalledWith(1, 'next', {
preventNavigation: expect.any(Function),
})
})

describe('prerenderFieldProps and filterData', () => {
it('should keep field props in memory during step change', async () => {
const filterDataHandler = jest.fn(({ props }) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { VisibleWhen } from '../../Form/Visibility'

export type OnStepChange = (
index: StepIndex,
mode: 'previous' | 'next'
mode: 'previous' | 'next',
options: { preventNavigation: (shouldPrevent?: boolean) => void }
) =>
| EventReturnWithStateObject
| void
Expand Down
Loading