-
-
Notifications
You must be signed in to change notification settings - Fork 158
/
multiStepPlugin.ts
745 lines (682 loc) · 21.4 KB
/
multiStepPlugin.ts
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
import {
FormKitNode,
FormKitPlugin,
createMessage,
FormKitFrameworkContext,
isPlaceholder,
} from '@formkit/core'
import { whenAvailable } from '@formkit/utils'
import type { FormKitSlotData, FormKitInputs } from '@formkit/inputs'
import { multiStep, step } from './schema'
/* <declare> */
/**
* Extend FormKitNode with Multi-step helper functions.
*/
declare module '@formkit/core' {
interface FormKitNodeExtensions {
next(): void
previous(): void
goTo(step: number | string): void
}
}
/* </declare> */
/* <declare> */
declare module '@formkit/inputs' {
interface FormKitInputProps<Props extends FormKitInputs<Props>> {
'multi-step': {
type: 'multi-step'
value?: Record<string, any>
allowIncomplete?: boolean
tabStyle?: 'tab' | 'progress'
hideProgressLabels?: boolean
validStepIcon?: string
beforeStepChange?: BeforeStepChange
}
step: {
beforeStepChange?: BeforeStepChange
nextAttrs?: Record<string, any>
nextLabel?: string
previousAttrs?: Record<string, any>
previousLabel?: string
type: 'step'
validStepIcon?: string
value?: Record<string, any>
}
}
interface FormKitInputSlots<Props extends FormKitInputs<Props>> {
'multi-step': FormKitMultiStepSlots<Props>
step: FormKitStepSlots<Props>
}
}
/**
* The node type that is augmented with next and previous and goTo functions.
*
* @public
*/
export type FormKitMultiStepNode = FormKitNode & MultiStepNodeAdditions
/**
* Additional arguments that are added to the FormKitNode of a multistep input.
*
* @public
*/
export interface MultiStepNodeAdditions {
next: () => void
previous: () => void
goTo: (target: number | string) => void
}
/**
* @public
*/
export interface MultiStepSlotData {
steps: Array<FormKitMultiStepSlotData>
allowIncomplete?: boolean
tabStyle: 'tab' | 'progress'
hideProgressLabels: boolean
validStepIcon: string | undefined
activeStep: string
beforeStepChange?: BeforeStepChange
node: FormKitMultiStepNode
handlers: FormKitFrameworkContext['handlers'] & MultiStepHandlers
}
export interface MultiStepHandlers {
incrementStep: (
delta: number,
currentStep: FormKitFrameworkContext | undefined
) => () => void
triggerStepValidations: (step: FormKitFrameworkContext) => void
showStepErrors: (step: FormKitFrameworkContext) => boolean | undefined
setActiveStep: (step: FormKitFrameworkContext) => (e?: Event) => void
}
/**
* Slot data unique to the step input.
*
* @public
*/
export interface StepSlotData {
beforeStepChange?: BeforeStepChange
makeActive: () => void
blockingCount: number
errorCount: number
hasBeenVisited: true | undefined
isActiveStep: boolean
isFirstStep: boolean
isLastStep: boolean
isValid: boolean
nextAttrs?: Record<string, any>
nextLabel?: string
ordered: boolean
previousAttrs?: Record<string, any>
previousLabel?: string
showStepErrors: boolean
stepName: string
steps: Array<FormKitMultiStepSlotData>
stepIndex: number
totalErrorCount: number
validStepIcon?: string
handlers: FormKitFrameworkContext['handlers'] & StepHandlers
}
export interface StepHandlers {
incrementStep: (delta: number) => () => void
next: () => void
previous: () => void
}
/**
* @public
*/
export interface FormKitMultiStepSlots<Props extends FormKitInputs<Props>> {
multiStepOuter: FormKitSlotData<Props, MultiStepSlotData>
wrapper: FormKitSlotData<Props, MultiStepSlotData>
tabs: FormKitSlotData<Props, MultiStepSlotData>
tab: FormKitSlotData<Props, MultiStepSlotData>
tabLabel: FormKitSlotData<
Props,
MultiStepSlotData & {
step: FormKitFrameworkContext
index: number
}
>
badge: FormKitSlotData<
Props,
MultiStepSlotData & {
step: FormKitFrameworkContext
index: number
}
>
validStepIcon: FormKitSlotData<
Props,
MultiStepSlotData & {
step: FormKitFrameworkContext
index: number
}
>
steps: FormKitSlotData<Props, MultiStepSlotData>
default: FormKitSlotData<Props, MultiStepSlotData>
}
/**
* @public
*/
export interface FormKitStepSlots<Props extends FormKitInputs<Props>> {
stepInner: FormKitSlotData<Props, StepSlotData>
stepActions: FormKitSlotData<Props, StepSlotData>
stepNext: FormKitSlotData<Props, StepSlotData>
stepPrevious: FormKitSlotData<Props, StepSlotData>
default: FormKitSlotData<Props, StepSlotData>
}
/* </declare> */
const isBrowser = typeof window !== 'undefined'
/**
* The typing for the beforeStepChange function.
*
* @public
*/
export interface BeforeStepChange {
(data: StepChangeData): any
}
export interface StepChangeData<T = unknown> {
currentStep: FormKitFrameworkContext<T>
targetStep: FormKitFrameworkContext<T>
delta: number
}
/**
* The typing for the slot data for a FormKit multi-step input.
* @public
*/
export type FormKitMultiStepSlotData = FormKitFrameworkContext<
Record<string, any>
> &
StepSlotData
/**
* The options to be passed to {@link createMultiStepPlugin | createMultiStepPlugin}
*
* @public
*/
export interface MultiStepOptions {
allowIncomplete?: boolean
hideProgressLabels?: boolean
tabStyle?: 'tab' | 'progress'
}
/**
* Coverts a camelCase string to a title case string
*
* @param str - The string to convert
* @returns string
*/
const camel2title = (str: string) => {
if (!str) return str
return str
.replace(/([A-Z])/g, (match: string) => ` ${match}`)
.replace(/^./, (match: string) => match.toUpperCase())
.trim()
}
/**
* Compares steps to DOM order and reorders steps if needed
*/
function orderSteps(node: FormKitNode, steps: FormKitFrameworkContext[]) {
if (!isBrowser || !steps) return steps
const orderedSteps = [...steps]
orderedSteps.sort((a, b) => {
const aEl = node.props.__root?.getElementById(a.id)
const bEl = node.props.__root?.getElementById(b.id)
if (!aEl || !bEl) return 0
return aEl.compareDocumentPosition(bEl) === 2 ? 1 : -1
})
orderedSteps.map((step) => {
step.ordered = true
})
return orderedSteps
}
/**
* Iterates through each step and sets props to help
* determine step positioning within the multi-step.
*
* @param steps - The steps to iterate through
*/
function setNodePositionProps(steps: FormKitFrameworkContext[]) {
if (!steps) return
steps.forEach((step: FormKitFrameworkContext, index: number) => {
step.isFirstStep = index === 0
step.isLastStep = index === steps.length - 1
step.stepIndex = index
step.steps = steps
})
}
function showStepErrors(step: FormKitFrameworkContext) {
if (!step.showStepErrors) return
return (
parseInt(step.blockingCount as string) +
parseInt(step.errorCount as string) >
0
)
}
/**
* Determines if the target step can be navigated to based on current
* configuration options and the state of the current step.
*
* @param currentStep - The current step
* @param targetStep - The target step
*/
async function isTargetStepAllowed(
currentStep: FormKitFrameworkContext,
targetStep: FormKitFrameworkContext
): Promise<boolean> {
if (currentStep === targetStep) return true
const { allowIncomplete } = currentStep.node.parent?.props || {}
const parentNode = currentStep.node.parent
const currentStepIndex = parentNode?.props.steps.indexOf(currentStep)
const targetStepIndex = parentNode?.props.steps.indexOf(targetStep)
// show the current step errors because this step has
// been visited.
const currentStepIsValid = triggerStepValidations(currentStep)
currentStep.showStepErrors = true
// if we are navigating forward, check our current step is complete
if (targetStepIndex >= currentStepIndex) {
// if the current step is invalid and we do not allow incomplete
// then prevent navigation
if (!currentStepIsValid && !allowIncomplete) {
return false
}
}
// check how many steps we need to step forward
// and then check that each intermediate step is valid
const delta = targetStepIndex - currentStepIndex
for (let i = 0; i < delta; i++) {
const intermediateStep = parentNode?.props.steps[currentStepIndex + i]
const stepIsAllowed = allowIncomplete || intermediateStep.state?.valid
if (!stepIsAllowed) {
return false
}
}
// check if there is a function for the stepChange guard
const beforeStepChange =
currentStep.node.props.beforeStepChange ||
currentStep.node.parent?.props.beforeStepChange
if (beforeStepChange && typeof beforeStepChange === 'function') {
if (parentNode) {
parentNode?.store.set(
createMessage({
key: 'loading',
value: true,
visible: false,
})
)
parentNode.props.disabled = true
currentStep.disabled = true
}
const result = await beforeStepChange({
currentStep,
targetStep,
delta: targetStepIndex - currentStepIndex,
})
if (parentNode) {
parentNode?.store.remove('loading')
parentNode.props.disabled = false
currentStep.disabled = false
}
if (typeof result === 'boolean' && !result) return false
}
return true
}
/**
* Changes the active step to the target step if the target step is allowed.
*
* @param targetStep - The target step
*/
async function setActiveStep(targetStep: FormKitFrameworkContext, e?: Event) {
if (e) {
e.preventDefault()
}
if (targetStep && targetStep.node.name && targetStep.node.parent) {
const currentStep = targetStep.node.parent.props.steps.find(
(step: FormKitFrameworkContext) =>
step.node.name === targetStep.node.parent?.props.activeStep
)
const stepIsAllowed = await isTargetStepAllowed(currentStep, targetStep)
if (stepIsAllowed && targetStep.node.parent.context) {
targetStep.node.parent.props.activeStep = targetStep.node.name
}
}
}
/**
* Changes the current step by the delta value if the target step is allowed.
*
* @param delta - The number of steps to increment or decrement
* @param step - The current step
*/
async function incrementStep(
delta: number,
currentStep: FormKitFrameworkContext
) {
if (currentStep && currentStep.node.name && currentStep.node.parent) {
const steps = currentStep.node.parent.props.steps
const stepIndex = currentStep.stepIndex
const targetStep = steps[(stepIndex as number) + delta]
if (!targetStep) return
const stepIsAllowed = await isTargetStepAllowed(currentStep, targetStep)
if (targetStep && stepIsAllowed) {
currentStep.node.parent.props.activeStep = targetStep.node.name
}
}
}
/**
* Causes the display of any validation errors on the target step.
*
* @param step - The current step
* @returns Boolean
*/
function triggerStepValidations(step: FormKitFrameworkContext) {
step.node.walk((n) => {
n.store.set(
createMessage({
key: 'submitted',
value: true,
visible: false,
})
)
})
return (
step.node.context?.state.valid || step.node.parent?.props.allowIncomplete
)
}
function initEvents(node: FormKitNode, el: Element) {
if (!(el instanceof HTMLElement)) return
el.addEventListener('keydown', (event: KeyboardEvent) => {
if (event.target instanceof HTMLButtonElement) {
if (
event.key === 'Tab' &&
'data-next' in event.target?.attributes &&
!event.shiftKey
) {
event.preventDefault()
const activeStepContext = node.children.find(
(step) => !isPlaceholder(step) && step.name === node.props.activeStep
) as FormKitNode | undefined
if (activeStepContext && activeStepContext.context) {
incrementStep(1, activeStepContext.context)
}
}
}
})
}
function createSSRStepsFromTabs(tabs: Record<string, any>[]) {
if (!tabs || !tabs.length) return []
// if our tabs object is a fragment, then loop over the children
// otherwise loop directly
const tabsToRender =
tabs[0].type == Symbol.for('v-fgt') && tabs[0].children
? tabs[0].children
: tabs
const placeholderTabs = tabsToRender.map(
(tab: Record<string, any>, index: number) => {
return {
__isPlaceholder: true,
stepName: tab.props?.label || camel2title(tab.props?.name),
isFirstStep: index === 0,
isLastStep: index === tabs.length - 1,
isActiveStep: index === 0,
node: {
name: tab.props?.name,
},
}
}
)
return placeholderTabs
}
function createPreRenderStepsFunction(node: FormKitNode) {
return () => {
if (!node.context || node.props.steps) return
// call the default slot to pre-render child steps
// for SSR support
let tabs = []
if (
node.context.slots &&
(node.context.slots as Record<string, () => any>).default
) {
tabs = (node.context.slots as Record<string, () => any>).default()
}
node.props.steps = node.props.steps || createSSRStepsFromTabs(tabs)
node.context.stepCount = node.props.steps.length
}
}
/**
* Creates a new multi-step plugin.
*
* @param options - The options of {@link MultiStepOptions | MultiStepOptions} to pass to the plugin
*
* @returns A {@link @formkit/core#FormKitPlugin | FormKitPlugin}
*
* @public
*/
export function createMultiStepPlugin(
options?: MultiStepOptions
): FormKitPlugin {
let isFirstStep = true
const multiStepPlugin = (node: FormKitNode) => {
if (node.props.type === 'multi-step') {
if (!node.context) return
isFirstStep = true // reset variable, next step will be first step in multistep
node.addProps(['steps', 'tabs', 'activeStep'])
node.context.fns.preRenderSteps = createPreRenderStepsFunction(node)
node.context.fns.getStepCount = () => {
if (!node.context) return
return node.context.stepCount
}
node.context.fns.getSteps = () => {
if (!node.context) return
return node.context.steps
}
node.props.allowIncomplete =
typeof node.props.allowIncomplete === 'boolean'
? node.props.allowIncomplete
: typeof options?.allowIncomplete === 'boolean'
? options?.allowIncomplete
: true
node.props.hideProgressLabels =
typeof node.props.hideProgressLabels === 'boolean'
? node.props.hideProgressLabels
: options?.hideProgressLabels || false
node.props.tabStyle = node.props.tabStyle || options?.tabStyle || 'tab'
node.context.handlers.triggerStepValidations = triggerStepValidations
node.context.handlers.showStepErrors = showStepErrors
node.on('created', () => {
if (!node.context) return
node.extend('next', {
get: (node) => () => {
incrementStep(
1,
node?.props?.steps.find(
(step: Record<string, any>) => step.isActiveStep
)
)
},
set: false,
})
node.extend('previous', {
get: (node) => () => {
incrementStep(
-1,
node?.props?.steps.find(
(step: Record<string, any>) => step.isActiveStep
)
)
},
set: false,
})
node.extend('goTo', {
get: (node) => (target: number | string) => {
if (typeof target === 'number') {
const targetStep = node.props.steps[target]
setActiveStep(targetStep)
} else if (typeof target === 'string') {
const targetStep = node.props.steps.find(
(step: Record<string, any>) => step.node.name === target
)
setActiveStep(targetStep)
}
},
set: false,
})
whenAvailable(
`${node.props.id}`,
(el) => {
initEvents(node, el)
},
node.props.__root
)
})
node.on('child', ({ payload: childNode }) => {
// remove placeholder steps
if (node.props.steps && node.props.steps.length) {
node.props.steps = node.props.steps.filter(
(step: Record<string, any>) => !step.__isPlaceholder
)
}
node.props.steps =
Array.isArray(node.props.steps) && node.props.steps.length > 0
? [...node.props.steps, childNode.context]
: [childNode.context]
node.props.steps = orderSteps(node, node.props.steps)
setNodePositionProps(node.props.steps)
childNode.props.stepName =
childNode.props.label || camel2title(childNode.name)
childNode.props.errorCount = 0
childNode.props.blockingCount = 0
childNode.props.isActiveStep = isFirstStep
isFirstStep = false
node.props.activeStep = node.props.activeStep
? node.props.activeStep
: node.props.steps[0]
? node.props.steps[0].node.name
: ''
})
node.on('prop:activeStep', ({ payload }) => {
node.children.forEach((child) => {
if (isPlaceholder(child)) return
child.props.isActiveStep = child.name === payload
if (isBrowser && child.name === payload) {
const el = node.props.__root?.querySelector(
`[aria-controls="${child.props.id}"]`
)
if (el instanceof HTMLButtonElement) {
el.focus()
}
}
})
})
node.on('childRemoved', ({ payload: childNode }) => {
let removedStepIndex = -1
childNode.props.ordered = false
node.props.steps = node.props.steps.filter(
(step: FormKitFrameworkContext, index: number) => {
if (step.node.name !== childNode.name) {
return true
}
removedStepIndex = index
return false
}
)
setNodePositionProps(node.props.steps)
// if the child that was removed was the active step
// then fallback to the next available step
if (node.props.activeStep === childNode.name) {
const targetIndex = removedStepIndex > 0 ? removedStepIndex - 1 : 0
node.props.activeStep = node.props.steps[targetIndex]
? node.props.steps[targetIndex].node.name
: ''
}
})
} else if (
node.props.type === 'step' &&
node.parent?.props.type === 'multi-step'
) {
if (!node.context || !node.parent || !node.parent.context) return
node.addProps([
'isActiveStep',
'isFirstStep',
'isLastStep',
'stepName',
'errorCount',
'blockingCount',
'totalErrorCount',
'showStepErrors',
'isValid',
'hasBeenVisited',
'ordered',
])
const parentNode = node.parent
node.on('created', () => {
if (!node.context || !parentNode.context) return
whenAvailable(
`${node.props.id}`,
() => {
parentNode.props.steps = orderSteps(node, parentNode.props.steps)
setNodePositionProps(parentNode.props.steps)
},
node.props.__root
)
})
if (node.context && parentNode.context) {
parentNode.context.handlers.setActiveStep = (
stepNode: FormKitFrameworkContext
) => setActiveStep.bind(null, stepNode)
node.context.handlers.incrementStep = (delta: number) => () =>
incrementStep(delta, node.context!)
node.context.makeActive = () => {
setActiveStep(node.context as FormKitFrameworkContext)
}
node.context.handlers.next = () =>
incrementStep(1, node.context as FormKitFrameworkContext)
node.context.handlers.previous = () =>
incrementStep(-1, node.context as FormKitFrameworkContext)
}
node.on('count:errors', ({ payload: count }) => {
node.props.errorCount = count
})
node.on('count:blocking', ({ payload: count }) => {
node.props.blockingCount = count
})
function updateTotalErrorCount(node: FormKitNode) {
node.props.totalErrorCount =
node.props.errorCount + node.props.blockingCount
}
node.on('prop:errorCount', () => updateTotalErrorCount(node))
node.on('prop:blockingCount', () => updateTotalErrorCount(node))
node.on('prop:totalErrorCount', () => {
node.props.isValid = node.props.totalErrorCount <= 0
})
node.on('message-added', ({ payload }) => {
if (payload.key === 'submitted') {
updateTotalErrorCount(node)
if (node.context) {
triggerStepValidations(node.context)
node.props.showStepErrors = true
}
}
})
node.on('prop:isActiveStep', () => {
if (!node.props.hasBeenVisited && node.props.isActiveStep) {
node.props.hasBeenVisited = true
}
})
} else if (node.parent?.props.type === 'multi-step') {
console.warn(
'Invalid FormKit input location. <FormKit type="multi-step"> should only have <FormKit type="step"> inputs as immediate children. Failure to wrap child inputs in <FormKit type="step"> can lead to undesired behaviors.'
)
}
}
multiStepPlugin.library = (node: FormKitNode) => {
switch (node.props.type) {
case 'multi-step':
return node.define(multiStep)
case 'step':
const isInvalid =
!node.parent || node.parent.props.type !== 'multi-step'
if (isInvalid) {
console.warn(
'Invalid use of <FormKit type="step">. <FormKit type="step"> must be an immediate child of a <FormKit type="multi-step"> component.'
)
}
return node.define(step)
}
}
return multiStepPlugin
}