-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathEarnForm.tsx
More file actions
325 lines (307 loc) · 12.1 KB
/
Copy pathEarnForm.tsx
File metadata and controls
325 lines (307 loc) · 12.1 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
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
import { useId, useMemo } from 'react'
import { yupResolver } from '@hookform/resolvers/yup'
import type { TFunction } from 'i18next'
import { HandshakeIcon, PercentIcon } from 'lucide-react'
import { useForm, useWatch } from 'react-hook-form'
import type { Resolver, SubmitHandler } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import * as yup from 'yup'
import { Button } from '@/components/ui/button'
import { SatSymbol } from '@/components/ui/jam/CurrencySymbol'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Tabs, TabsContent } from '@/components/ui/tabs'
import * as JAM from '@/constants/jam'
import type { OfferType } from '@/constants/jm'
import { cn, factorToPercentage, isValidInteger, isValidNumber } from '@/lib/utils'
import type { AmountSats } from '@/types/global'
import { DevBadge } from '../dev/DevBadge'
import { Card, CardContent, CardHeader } from '../ui/card'
import { Field, FieldDescription, FieldLabel } from '../ui/field'
import { InputGroup, InputGroupAddon, InputGroupInput } from '../ui/input-group'
import { Spinner } from '../ui/spinner'
const FieldPrefixSatSymbol = (
<SatSymbol
width={'18px'}
height={'18px'}
style={{
margin: '5px -1px',
}}
/>
)
const OFFERTYPE_ABS: OfferType = 'sw0absoffer'
const OFFERTYPE_REL: OfferType = 'sw0reloffer'
export interface EarnFormValues {
offerType: OfferType
offerAbsoluteFee?: AmountSats
offerRelativeFeeInPercent?: number
offerMinAmount: AmountSats
}
const FORM_INPUT_DEFAULT_VALUES: Required<EarnFormValues> = {
offerType: OFFERTYPE_ABS,
offerRelativeFeeInPercent: factorToPercentage(JAM.OFFER_FEE_REL_DEFAULT),
offerAbsoluteFee: JAM.OFFER_FEE_ABS_DEFAULT,
offerMinAmount: JAM.OFFER_MINSIZE_DEFAULT,
}
const earnFormBaseSchema = (t: TFunction) => {
const invalidRelativeFeeMessage = t('earn.feedback_invalid_rel_fee', {
feeRelPercentageMin: `${factorToPercentage(JAM.OFFER_FEE_REL_MIN)}%`,
feeRelPercentageMax: `${factorToPercentage(JAM.OFFER_FEE_REL_MAX)}%`,
})
return yup
.object({
offerType: yup.string<OfferType>().default(FORM_INPUT_DEFAULT_VALUES.offerType).required(),
offerAbsoluteFee: yup
.number()
.integer(t('earn.feedback_invalid_abs_fee'))
.transform((value) => (isValidInteger(value) ? value : null))
.when('offerType', {
is: (val: OfferType) => val === OFFERTYPE_ABS,
then: (schema) =>
schema
.min(JAM.OFFER_FEE_ABS_MIN, t('earn.feedback_invalid_abs_fee'))
.required(t('earn.feedback_invalid_abs_fee')),
otherwise: (schema) => schema.nullable().optional(),
}),
offerRelativeFeeInPercent: yup
.number()
.transform((value) => (isValidNumber(value) ? value : null))
.when('offerType', {
is: (val: OfferType) => val === OFFERTYPE_REL,
then: (schema) =>
schema
.min(factorToPercentage(JAM.OFFER_FEE_REL_MIN), invalidRelativeFeeMessage)
.max(factorToPercentage(JAM.OFFER_FEE_REL_MAX), invalidRelativeFeeMessage)
.required(invalidRelativeFeeMessage),
otherwise: (schema) => schema.nullable().optional(),
}),
})
.required()
}
const OfferTypeInput = (props: React.ComponentProps<typeof RadioGroup>) => {
const { t } = useTranslation()
const id = useId()
return (
<RadioGroup className="flex flex-col items-stretch justify-center gap-2 sm:flex-row sm:items-center" {...props}>
<div className="border-input has-data-[state=checked]:border-primary/50 has-data-[state=checked]:border-primary/50 has-data-[state=checked]:ring-primary/20 relative flex w-full cursor-pointer flex-col items-center gap-3 rounded-md border p-4 shadow-xs outline-none has-data-[state=checked]:ring-[2px] sm:max-w-50">
<RadioGroupItem
value={OFFERTYPE_ABS}
id={`${id}-sw0absoffer`}
className="order-1 size-5 cursor-pointer after:absolute after:inset-0 [&_svg]:size-3"
/>
<div className="grid grow justify-items-center gap-2">
<HandshakeIcon />
<Label htmlFor={`${id}-sw0absoffer`} className="justify-center">
{t('earn.radio_abs_offer_label')}
</Label>
</div>
</div>
<div className="border-input has-data-[state=checked]:border-primary/50 has-data-[state=checked]:ring-primary/20 relative flex w-full flex-col items-center gap-3 rounded-md border p-4 shadow-xs outline-none has-data-[state=checked]:ring-[2px] sm:max-w-50">
<RadioGroupItem
value={OFFERTYPE_REL}
id={`${id}-sw0reloffer`}
className="order-1 size-5 cursor-pointer after:absolute after:inset-0 [&_svg]:size-3"
/>
<div className="grid grow justify-items-center gap-2">
<PercentIcon />
<Label htmlFor={`${id}-sw0reloffer`} className="justify-center">
{t('earn.radio_rel_offer_label')}
</Label>
</div>
</div>
</RadioGroup>
)
}
interface EarnFormProps {
className?: string
isWaitingMakerStart: boolean
onSubmit: SubmitHandler<EarnFormValues>
offerMinsizeMax: AmountSats
disabled?: boolean
debug?: boolean
}
export function EarnForm({
className,
isWaitingMakerStart,
onSubmit,
disabled,
offerMinsizeMax,
debug = false,
}: EarnFormProps) {
const { t } = useTranslation()
const schema = useMemo(
() =>
// eslint-disable-next-line unicorn/prefer-spread -- false positive
earnFormBaseSchema(t).concat(
yup.object({
offerMinAmount: yup
.number()
.transform((value) => (isValidInteger(value) ? value : null))
.integer(t('earn.feedback_invalid_min_amount'))
.min(
JAM.OFFER_MINSIZE_MIN,
t('earn.feedback_invalid_min_amount_range', {
minAmountMin: JAM.OFFER_MINSIZE_MIN.toLocaleString(),
minAmountMax: offerMinsizeMax.toLocaleString(),
}),
)
.max(
offerMinsizeMax,
t('earn.feedback_invalid_min_amount_range', {
minAmountMin: JAM.OFFER_MINSIZE_MIN.toLocaleString(),
minAmountMax: offerMinsizeMax.toLocaleString(),
}),
)
.required(t('earn.feedback_invalid_min_amount')),
}),
),
[t, offerMinsizeMax],
)
const {
control,
register,
handleSubmit,
formState: { errors, isSubmitting, isValid },
getValues,
setValue,
} = useForm<EarnFormValues, unknown, EarnFormValues>({
mode: 'onSubmit',
defaultValues: FORM_INPUT_DEFAULT_VALUES,
// force type (see https://github.com/react-hook-form/resolvers/issues/807)
resolver: yupResolver(schema) as Resolver<EarnFormValues, unknown, EarnFormValues>,
})
const values = useWatch({ control })
const watchOfferType = useWatch({ control, name: 'offerType' })
const doOnSubmit = handleSubmit(onSubmit)
return (
<form onSubmit={(event) => void doOnSubmit(event)} className={cn('flex flex-col gap-4', className)} noValidate>
<OfferTypeInput
disabled={disabled}
defaultValue={FORM_INPUT_DEFAULT_VALUES.offerType}
onValueChange={(value) => {
setValue('offerType', value, {
shouldValidate: true, // trigger validation
shouldTouch: true, // update touched fields form state
shouldDirty: true, // update dirty and dirty fields form state
})
}}
/>
<Tabs value={watchOfferType}>
<TabsContent value={OFFERTYPE_ABS}>
<div className="space-y-2">
<Field data-invalid={errors.offerAbsoluteFee !== undefined}>
<FieldLabel htmlFor="offerAbsoluteFee">
{t('earn.label_abs_fee', {
fee: '', // empty on purpose
})}
</FieldLabel>
<FieldDescription className="text-xs">{t('earn.description_abs_fee')}</FieldDescription>
<InputGroup>
<InputGroupInput
id="offerAbsoluteFee"
{...register('offerAbsoluteFee', {
disabled,
})}
type="number"
step={1}
/>
<InputGroupAddon align="inline-start">{FieldPrefixSatSymbol}</InputGroupAddon>
</InputGroup>
</Field>
{errors.offerAbsoluteFee?.message && (
<div className="text-destructive text-xs">{errors.offerAbsoluteFee.message}</div>
)}
</div>
</TabsContent>
<TabsContent value={OFFERTYPE_REL}>
<div className="space-y-2">
<Field data-invalid={errors.offerRelativeFeeInPercent !== undefined}>
<FieldLabel htmlFor="offerRelativeFeeInPercent">
{t('earn.label_rel_fee', {
fee: getValues('offerRelativeFeeInPercent') ? `(${getValues('offerRelativeFeeInPercent')!}%)` : '',
})}
</FieldLabel>
<FieldDescription className="text-xs">{t('earn.description_rel_fee')}</FieldDescription>
<InputGroup>
<InputGroupInput
id="offerRelativeFeeInPercent"
{...register('offerRelativeFeeInPercent', {
disabled,
})}
type="number"
step={factorToPercentage(JAM.OFFER_FEE_REL_STEP)}
/>
<InputGroupAddon align="inline-start">%</InputGroupAddon>
</InputGroup>
</Field>
{errors.offerRelativeFeeInPercent && (
<div className="text-destructive text-xs">{errors.offerRelativeFeeInPercent.message}</div>
)}
</div>
</TabsContent>
</Tabs>
<div className="space-y-2">
<Field data-invalid={errors.offerMinAmount !== undefined}>
<FieldLabel htmlFor="offerMinAmount">{t('earn.label_min_amount_input')}</FieldLabel>
<FieldDescription className="text-xs">{t('earn.description_min_amount_input')}</FieldDescription>
<InputGroup>
<InputGroupInput
id="offerMinAmount"
{...register('offerMinAmount', {
required: true,
disabled,
})}
type="number"
max={offerMinsizeMax}
step={1}
placeholder={t('earn.placeholder_min_amount_input')}
/>
<InputGroupAddon align="inline-start">{FieldPrefixSatSymbol}</InputGroupAddon>
</InputGroup>
</Field>
{errors.offerMinAmount && (
<div className="text-destructive text-xs">
{offerMinsizeMax < JAM.OFFER_MINSIZE_MIN ? (
<>{t('earn.feedback_invalid_min_amount_insufficient_funds')}</>
) : (
<>{errors.offerMinAmount?.message || t('earn.feedback_invalid_min_amount')}</>
)}
</div>
)}
</div>
<Button
type="submit"
variant={disabled && !isWaitingMakerStart ? 'outline' : undefined}
disabled={disabled || isSubmitting || isWaitingMakerStart}
className="w-full"
size="xxl"
>
{isSubmitting || isWaitingMakerStart ? (
<>
<Spinner className="motion-reduce:hidden" />
{t('earn.text_starting')}
</>
) : (
<>{t('earn.button_start')}</>
)}
</Button>
{debug && (
<Card className="mt-8">
<CardHeader className="grid">
<DevBadge className="justify-self-end" />
</CardHeader>
<CardContent className="flex flex-col gap-2">
<div className="overflow-scroll">
<code className="text-destructive">isValid:</code>
<pre className="text-xs">{JSON.stringify(isValid, null, 2)}</pre>
</div>
<div className="overflow-scroll">
<code className="text-destructive">values:</code>
<pre className="text-xs">{JSON.stringify(values, null, 2)}</pre>
</div>
</CardContent>
</Card>
)}
</form>
)
}