ActionBar.tsx105 lines · main
1import { noop } from 'lodash'
2import { PropsWithChildren, useCallback, useState } from 'react'
3import { Button, KeyboardShortcut } from 'ui'
4
5import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
6import { useShortcut } from '@/state/shortcuts/useShortcut'
7
8interface ActionBarProps {
9 loading?: boolean
10 disableApply?: boolean
11 hideApply?: boolean
12 applyButtonLabel?: string
13 backButtonLabel?: string
14 applyFunction?: (resolve: any) => void
15 closePanel: () => void
16 formId?: string
17 visible?: boolean
18}
19
20export const ActionBar = ({
21 loading = false,
22 disableApply = false,
23 hideApply = false,
24 children = undefined,
25 applyButtonLabel = 'Apply',
26 backButtonLabel = 'Back',
27 applyFunction = undefined,
28 closePanel = noop,
29 formId,
30 visible = true,
31}: PropsWithChildren<ActionBarProps>) => {
32 const [isRunning, setIsRunning] = useState(false)
33
34 const onSelectApply = useCallback(async () => {
35 const applyCallback = () => new Promise((resolve) => applyFunction?.(resolve))
36 setIsRunning(true)
37 await applyCallback()
38 setIsRunning(false)
39 }, [applyFunction])
40
41 const handleSave = useCallback(() => {
42 if (isRunning || loading || disableApply || hideApply) return
43
44 if (formId) {
45 const form = document.getElementById(formId) as HTMLFormElement | null
46 if (form) {
47 form.requestSubmit()
48 }
49 } else if (applyFunction) {
50 onSelectApply()
51 }
52 }, [isRunning, loading, disableApply, hideApply, formId, applyFunction, onSelectApply])
53
54 useShortcut(SHORTCUT_IDS.ACTION_BAR_SAVE, handleSave, { enabled: visible })
55
56 return (
57 <div className="flex w-full items-center gap-3 border-t border-default px-3 py-4">
58 {children}
59
60 <div className="flex items-center gap-3 ml-auto">
61 <Button
62 type="default"
63 htmlType="button"
64 onClick={closePanel}
65 disabled={isRunning || loading}
66 >
67 {backButtonLabel}
68 </Button>
69
70 {applyFunction !== undefined ? (
71 // Old solution, necessary when loading is handled by this component itself
72 <Button
73 onClick={onSelectApply}
74 disabled={disableApply || isRunning || loading}
75 loading={isRunning || loading}
76 iconRight={
77 isRunning || loading ? undefined : (
78 <KeyboardShortcut keys={['Meta', 'Enter']} variant="inline" />
79 )
80 }
81 >
82 {applyButtonLabel}
83 </Button>
84 ) : !hideApply ? (
85 // New solution, when using the Form component, loading is handled by the Form itself
86 // Does not require applyFunction() callback
87 <Button
88 disabled={loading || disableApply}
89 loading={loading}
90 data-testid="action-bar-save-row"
91 htmlType="submit"
92 form={formId}
93 iconRight={
94 loading ? undefined : <KeyboardShortcut keys={['Meta', 'Enter']} variant="inline" />
95 }
96 >
97 {applyButtonLabel}
98 </Button>
99 ) : (
100 <div />
101 )}
102 </div>
103 </div>
104 )
105}