forked from CredenceOrg/Credence-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfirmDialog.tsx
More file actions
248 lines (228 loc) · 7.67 KB
/
Copy pathConfirmDialog.tsx
File metadata and controls
248 lines (228 loc) · 7.67 KB
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
import { useCallback, useEffect, useId, useRef, useState, type RefObject } from 'react'
import { useTranslation, Trans } from 'react-i18next'
import { createPortal } from 'react-dom'
import { useFocusTrap } from '../hooks/useFocusTrap'
import { useScrollPreserver } from '../hooks/useScrollPreserver'
import Button from './Button'
import './ConfirmDialog.css'
const DEFAULT_CONFIRM_PHRASE = 'CONFIRM'
const DEFAULT_CONFIRM_HINT =
'This action cannot be undone. Funds will be sent to your connected wallet.'
export interface ConfirmDialogPenaltyBreakdown {
bondAmount: string
penaltyAmount: string
penaltyPercent: number
resultingBalance: string
}
export interface ConfirmDialogProps {
open: boolean
title: string
subtitle?: string
/**
* Financial breakdown to display. When omitted, the `description` slot or
* `children` is rendered instead.
*/
breakdown?: ConfirmDialogPenaltyBreakdown
/**
* Arbitrary content shown in the body when `breakdown` is not provided.
*/
description?: React.ReactNode
/**
* React children slot for custom content in the dialog body.
*/
children?: React.ReactNode
onConfirm: () => void
onCancel: () => void
returnFocusRef?: RefObject<HTMLElement | null>
confirmLabel?: string
confirmInputLabel?: React.ReactNode
confirmInputHint?: React.ReactNode
variant?: 'danger' | 'info'
/**
* Word the user must type exactly to unlock the confirm button.
* Defaults to `'CONFIRM'`.
*/
confirmPhrase?: string
/**
* Small print shown below the type-to-confirm input.
* Defaults to the wallet/funds hint used for bond withdrawals.
*/
confirmHint?: string
/**
* When `true`, the dialog is mid-submission: the confirm button enters its
* loading state, the cancel button is disabled, and backdrop-click is ignored.
* Reset to `false` once the async operation settles (success or error).
*/
isSubmitting?: boolean
}
export default function ConfirmDialog({
open,
title,
subtitle,
breakdown,
description,
children,
onConfirm,
onCancel,
returnFocusRef,
confirmLabel = 'Withdraw bond',
confirmInputLabel,
confirmInputHint,
variant = 'danger',
confirmPhrase = DEFAULT_CONFIRM_PHRASE,
confirmHint = DEFAULT_CONFIRM_HINT,
isSubmitting = false,
}: ConfirmDialogProps) {
const { t } = useTranslation()
const titleId = useId()
const descId = useId()
const announcementId = useId()
const dialogRef = useRef<HTMLDivElement>(null)
const cancelRef = useRef<HTMLButtonElement>(null)
const confirmRef = useRef<HTMLButtonElement>(null)
const [confirmText, setConfirmText] = useState('')
const [announcement, setAnnouncement] = useState('')
const [prevConfirmEnabled, setPrevConfirmEnabled] = useState(false)
const handleCancel = useCallback(() => {
onCancel()
}, [onCancel])
useScrollPreserver({ isActive: open })
useFocusTrap({
containerRef: dialogRef,
isActive: open,
initialFocusRef: cancelRef,
returnFocusRef,
onEscape: handleCancel,
})
useEffect(() => {
if (!open) {
setConfirmText('')
setAnnouncement('')
setPrevConfirmEnabled(false)
return
}
const message = subtitle ? `${title}. ${subtitle}` : title
setAnnouncement(message)
}, [open, title, subtitle])
const isConfirmEnabled = confirmText === confirmPhrase
useEffect(() => {
if (isConfirmEnabled !== prevConfirmEnabled) {
if (isConfirmEnabled) {
setAnnouncement(t('confirmDialog.announcements.actionEnabled', { phrase: confirmPhrase }))
requestAnimationFrame(() => {
confirmRef.current?.focus()
})
} else {
setAnnouncement(t('confirmDialog.announcements.actionDisabled', { phrase: confirmPhrase }))
requestAnimationFrame(() => cancelRef.current?.focus())
}
setPrevConfirmEnabled(isConfirmEnabled)
}
}, [isConfirmEnabled, prevConfirmEnabled, confirmPhrase, t])
const handleConfirm = () => {
if (!isConfirmEnabled) return
onConfirm()
}
const handleBackdropClick = (event: React.MouseEvent<HTMLDivElement>) => {
if (isSubmitting) return
if (event.target === event.currentTarget) {
handleCancel()
}
}
if (!open) return null
return createPortal(
<div className="confirm-dialog__backdrop" onClick={handleBackdropClick} aria-hidden={false}>
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
aria-describedby={descId}
className={`confirm-dialog confirm-dialog--${variant}`}
onClick={(e) => e.stopPropagation()}
>
<div id={announcementId} className="sr-only" aria-live="assertive" aria-atomic="true">
{announcement}
</div>
<header className="confirm-dialog__header">
<h2 id={titleId} className="confirm-dialog__title">
{title}
</h2>
{subtitle && <p className="confirm-dialog__subtitle">{subtitle}</p>}
</header>
<div id={descId} className="confirm-dialog__body">
{breakdown ? (
<dl className="confirm-dialog__breakdown">
<div className="confirm-dialog__breakdown-row">
<dt>{t('confirmDialog.breakdown.bondAmount')}</dt>
<dd>{breakdown.bondAmount}</dd>
</div>
<div className="confirm-dialog__breakdown-row confirm-dialog__breakdown-row--penalty">
<dt>
{t('confirmDialog.breakdown.slashPenalty', { percent: breakdown.penaltyPercent })}
</dt>
<dd>−{breakdown.penaltyAmount}</dd>
</div>
<div className="confirm-dialog__breakdown-row confirm-dialog__breakdown-row--total">
<dt>{t('confirmDialog.breakdown.youReceive')}</dt>
<dd>{breakdown.resultingBalance}</dd>
</div>
</dl>
) : description ? (
<div className="confirm-dialog__description">{description}</div>
) : null}
{children}
<div className="confirm-dialog__confirm-field">
<label htmlFor={`${titleId}-confirm-input`}>
{confirmInputLabel || (
<Trans
i18nKey="confirmDialog.typeToConfirm"
values={{
phrase: confirmPhrase,
action:
confirmLabel !== 'Withdraw bond' ? confirmLabel.toLowerCase() : 'withdrawal',
}}
components={{ strong: <strong /> }}
/>
)}
</label>
<input
id={`${titleId}-confirm-input`}
type="text"
value={confirmText}
onChange={(e) => setConfirmText(e.target.value)}
autoComplete="off"
spellCheck={false}
aria-required="true"
placeholder={confirmPhrase}
/>
<p className="confirm-dialog__confirm-hint">{confirmInputHint || confirmHint}</p>
</div>
</div>
<footer className="confirm-dialog__footer">
<Button
ref={cancelRef}
type="button"
variant="secondary"
onClick={handleCancel}
disabled={isSubmitting}
>
Cancel
</Button>
<Button
ref={confirmRef}
type="button"
variant={variant === 'danger' ? 'danger' : 'primary'}
disabled={!isConfirmEnabled || isSubmitting}
isLoading={isSubmitting}
onClick={handleConfirm}
aria-disabled={!isConfirmEnabled || isSubmitting}
>
{confirmLabel}
</Button>
</footer>
</div>
</div>,
document.body
)
}