-
-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathDonateForm.tsx
494 lines (448 loc) · 19.2 KB
/
DonateForm.tsx
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
import * as React from "react"
import ReactDOM from "react-dom"
import * as Sentry from "@sentry/react"
import cx from "classnames"
import { observable, action, computed } from "mobx"
import { observer } from "mobx-react"
import { bind } from "decko"
import Recaptcha from "react-recaptcha"
import {
DONATE_API_URL,
BAKED_BASE_URL,
RECAPTCHA_SITE_KEY,
} from "../settings/clientSettings.js"
import {
Tippy,
stringifyUnknownError,
titleCase,
DonationCurrencyCode,
DonationInterval,
DonationRequest,
getErrorMessageDonation,
SUPPORTED_CURRENCY_CODES,
getCurrencySymbol,
DonateSessionResponse,
PLEASE_TRY_AGAIN,
} from "@ourworldindata/utils"
import { Checkbox } from "@ourworldindata/components"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome/index.js"
import { faArrowRight, faInfoCircle } from "@fortawesome/free-solid-svg-icons"
import { SiteAnalytics } from "./SiteAnalytics.js"
const ONETIME_DONATION_AMOUNTS = [20, 50, 100, 500, 1000]
const MONTHLY_DONATION_AMOUNTS = [5, 10, 25, 50, 100]
const ONETIME_DEFAULT_INDEX = 2
const MONTHLY_DEFAULT_INDEX = 2
const analytics = new SiteAnalytics()
@observer
export class DonateForm extends React.Component {
@observable interval: DonationInterval = "once"
@observable presetAmount?: number =
ONETIME_DONATION_AMOUNTS[ONETIME_DEFAULT_INDEX]
@observable customAmount: string = ""
@observable name: string = ""
@observable showOnList: boolean = true
@observable errorMessage?: string
@observable isSubmitting: boolean = false
@observable isLoading: boolean = true
@observable currencyCode: DonationCurrencyCode = "GBP"
captchaInstance?: Recaptcha | null
@observable.ref captchaPromiseHandlers?: {
resolve: (value: any) => void
reject: (value: any) => void
}
@action.bound setInterval(interval: DonationInterval) {
this.interval = interval
this.presetAmount =
this.intervalAmounts[
interval === "monthly"
? MONTHLY_DEFAULT_INDEX
: ONETIME_DEFAULT_INDEX
]
}
@action.bound setPresetAmount(amount?: number) {
this.presetAmount = amount
this.customAmount = ""
this.errorMessage = undefined
}
@action.bound setCustomAmount(amount: string) {
this.customAmount = amount
this.presetAmount = undefined
this.errorMessage = undefined
}
@action.bound setName(name: string) {
// capitalize first letter of each word. Words can be separated by
// spaces or hyphens.
this.name = titleCase(name)
this.errorMessage = undefined
}
@action.bound toggleShowOnList() {
this.showOnList = !this.showOnList
this.errorMessage = undefined
}
@action.bound setErrorMessage(message?: string) {
this.errorMessage = message
}
@action.bound setIsSubmitting(isSubmitting: boolean) {
this.isSubmitting = isSubmitting
}
@action.bound setCurrency(currency: DonationCurrencyCode) {
this.currencyCode = currency
}
@computed get amount(): number | undefined {
return this.customAmount
? parseFloat(this.customAmount)
: this.presetAmount
}
@computed get intervalAmounts(): number[] {
return this.interval === "monthly"
? MONTHLY_DONATION_AMOUNTS
: ONETIME_DONATION_AMOUNTS
}
@computed get currencySymbol(): string {
return getCurrencySymbol(this.currencyCode)
}
async submitDonation(): Promise<void> {
const requestBodyForClientSideValidation: DonationRequest = {
// Don't send the name if the reader doesn't want to appear on the
// list of supporters, but keep it in the form in case they change
// their mind.
name: this.showOnList ? this.name : "",
showOnList: this.showOnList,
currency: this.currencyCode,
amount: this.amount,
interval: this.interval,
successUrl: `${BAKED_BASE_URL}/thank-you`,
cancelUrl: `${BAKED_BASE_URL}/donate`,
captchaToken: "",
}
// Validate the request body before requesting the CAPTCHA token for
// faster feedback in case of form errors (e.g. invalid amount).
const errorMessage = getErrorMessageDonation(
requestBodyForClientSideValidation
)
if (errorMessage) throw new Error(errorMessage)
// Get the CAPTCHA token once the request body is validated.
const captchaToken = await this.getCaptchaToken()
const requestBody: DonationRequest = {
...requestBodyForClientSideValidation,
captchaToken,
}
// Send the request to the server, along with the CAPTCHA token.
const response = await fetch(DONATE_API_URL, {
method: "POST",
headers: {
Accept: "application/json", // expect JSON in response
"Content-Type": "application/json", // send JSON in request
},
body: JSON.stringify(requestBody),
})
const session: DonateSessionResponse = await response.json()
if (!response.ok || !session.url) {
throw new Error(
session.error || `Something went wrong. ${PLEASE_TRY_AGAIN}`
)
}
analytics.logSiteFormSubmit("donate")
window.location.href = session.url
}
@bind async getCaptchaToken(): Promise<string> {
return new Promise((resolve, reject) => {
if (!this.captchaInstance)
return reject(
new Error(`Could not load reCAPTCHA. ${PLEASE_TRY_AGAIN}`)
)
this.captchaPromiseHandlers = { resolve, reject }
this.captchaInstance.reset()
this.captchaInstance.execute()
})
}
@bind onCaptchaLoad() {
this.isLoading = false
}
@bind onCaptchaVerify(token: string) {
if (this.captchaPromiseHandlers)
this.captchaPromiseHandlers.resolve(token)
}
@bind async onSubmit(event: React.FormEvent) {
event.preventDefault()
this.setIsSubmitting(true)
this.setErrorMessage(undefined)
try {
await this.submitDonation()
} catch (error) {
this.setIsSubmitting(false)
const prefixedErrorMessage = stringifyUnknownError(error)
// Send all errors to Sentry. This will help surface issues
// with our aging reCAPTCHA setup, and pull the trigger on a
// (hook-based?) rewrite if it starts failing. This reporting
// also includes form validation errors, which are useful to
// identify possible UX improvements or validate UX experiments
// (such as the combination of the name field and the "include
// my name on the list" checkbox).
Sentry.captureException(
error instanceof Error ? error : new Error(prefixedErrorMessage)
)
if (!prefixedErrorMessage) {
this.setErrorMessage(
`Something went wrong. ${PLEASE_TRY_AGAIN}`
)
return
}
const rawErrorMessage = prefixedErrorMessage.match(/^Error: (.*)$/)
this.setErrorMessage(rawErrorMessage?.[1] || prefixedErrorMessage)
}
}
render() {
return (
<form className="donate-form" onSubmit={this.onSubmit}>
<fieldset>
<legend className="overline-black-caps">Frequency</legend>
<div className="donation-options">
<input
type="button"
value="Give once"
onClick={() => this.setInterval("once")}
className={cx("donation-options__button", {
active: this.interval === "once",
})}
/>
<input
type="button"
value="Monthly"
onClick={() => this.setInterval("monthly")}
className={cx("donation-options__button", {
active: this.interval === "monthly",
})}
/>
</div>
</fieldset>
<fieldset>
<legend>Currency</legend>
<div className="donation-options">
{SUPPORTED_CURRENCY_CODES.map((code) => (
<input
type="button"
value={`${code} (${getCurrencySymbol(code)})`}
onClick={() => this.setCurrency(code)}
className={cx("donation-options__button", {
active: this.currencyCode === code,
})}
key={code}
/>
))}
</div>
</fieldset>
<fieldset>
<legend>Amount</legend>
<div className="donation-options donation-options--grid">
{this.intervalAmounts.map((amount) => (
<input
type="button"
value={`${this.currencySymbol}${amount}`}
onClick={() => this.setPresetAmount(amount)}
className={cx("donation-options__button", {
active:
amount === this.presetAmount &&
!this.customAmount,
})}
key={`${amount}-${this.interval}`}
/>
))}
<div
className={cx("donation-custom-amount", {
active: !!this.customAmount,
})}
>
<label htmlFor="donation-custom-amount__input">
{this.currencySymbol}
</label>
<input
type="text"
placeholder="Other"
id="donation-custom-amount__input"
className="donation-custom-amount__input"
onChange={(event) =>
this.setCustomAmount(event.target.value)
}
value={this.customAmount}
/>
</div>
</div>
</fieldset>
<fieldset className="donation-public-checkbox">
<Checkbox
label={
<span className="donation-public-checkbox__label">
Include my name on our{" "}
<a href="/funding" target="_blank">
public list of donors
</a>
</span>
}
checked={this.showOnList}
onChange={() => this.toggleShowOnList()}
/>
</fieldset>
{this.showOnList && (
<fieldset>
<label
className="donation-name__label"
htmlFor="donation-name__input"
>
Full name (required if ticked)
</label>
<input
id="donation-name__input"
type="text"
className="donation-name__input sentry-mask"
value={this.name}
onChange={(event) =>
this.setName(event.target.value)
}
/>
</fieldset>
)}
{this.errorMessage && (
<p className="error">{this.errorMessage}</p>
)}
<Recaptcha
ref={(inst) => (this.captchaInstance = inst)}
sitekey={RECAPTCHA_SITE_KEY}
size="invisible"
badge="bottomleft"
render="explicit"
onloadCallback={this.onCaptchaLoad}
verifyCallback={this.onCaptchaVerify}
/>
<div className="donation-payment">
<button
aria-label="Submit donation"
type="submit"
className="donation-submit"
disabled={this.isLoading || this.isSubmitting}
onClick={() => analytics.logSiteClick("donate-now")}
>
Donate now
<FontAwesomeIcon
icon={faArrowRight}
className="donation-submit__icon"
/>
</button>
<ul className="donation-payment-benefits">
<li className="donation-payment-benefits__item">
🇬🇧 Your donation qualifies for Gift Aid in the UK{" "}
<Tippy
appendTo={() => document.body}
content={
<div>
<p>
Your donation qualifies for Gift Aid
if you pay tax in the UK, and have
signed the Gift Aid declaration.
</p>
<p>
Every £1 that you donate with Gift
Aid is worth £1.25 to us, at no
extra cost to you.
</p>
</div>
}
interactive
placement="bottom"
theme="owid-footnote"
trigger="mouseenter focus click"
>
<FontAwesomeIcon icon={faInfoCircle} />
</Tippy>
</li>
<li className="donation-payment-benefits__item">
You can donate using credit card, debit card, SEPA,
iDEAL and more
</li>
</ul>
</div>
<div className="donation-payment">
<p className="donation-payment__or">
For US donors, our partner every.org facilitates
tax-deductible giving and offers more payment options.
</p>
<a
href="https://www.every.org/ourworldindata?donateTo=ourworldindata#/donate/card"
className="donation-submit donation-submit--light"
>
Donate via every.org
<FontAwesomeIcon
icon={faArrowRight}
className="donation-submit__icon"
/>
</a>
<ul className="donation-payment-benefits">
<li className="donation-payment-benefits__item">
🇺🇸 Your donation is tax-deductible in the US{" "}
<Tippy
appendTo={() => document.body}
content={
<div>
<p>
Your donation is made to Every.org,
a tax-exempt US 501(c)(3) charity
that grants unrestricted funds to
Our World in Data on your behalf.
This means that if you are a US
taxpayer, 100% of your donation is
tax-deductible to the extent allowed
by US law.
</p>
<p>
After your donation payment is
confirmed by Every.org, you will
immediately get a tax-deductible
receipt emailed to you.
</p>
</div>
}
interactive
placement="bottom"
theme="owid-footnote"
trigger="mouseenter focus click"
>
<FontAwesomeIcon icon={faInfoCircle} />
</Tippy>
</li>
<li className="donation-payment-benefits__item">
You can donate in US dollars using PayPal, Venmo,
direct US bank transfer (ACH), credit card and more
</li>
<li className="donation-payment-benefits__item">
You can use this option for donor-advised fund (DAF)
grants
</li>
</ul>
</div>
<p className="donation-note">
This site is protected by reCAPTCHA and the Google{" "}
<a href="https://policies.google.com/privacy">
Privacy Policy
</a>{" "}
and{" "}
<a href="https://policies.google.com/terms">
Terms of Service
</a>{" "}
apply.
</p>
</form>
)
}
}
export class DonateFormRunner {
async run() {
ReactDOM.render(
<DonateForm />,
document.querySelector(".donate-form-container")
)
}
}
export async function runDonateForm() {
const donateForm = new DonateFormRunner()
await donateForm.run()
}