-
Notifications
You must be signed in to change notification settings - Fork 192
/
DonationAmountCurrencySwitcherMessage.tsx
78 lines (65 loc) · 2.24 KB
/
DonationAmountCurrencySwitcherMessage.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
import {CurrencySwitcherSetting} from '@givewp/forms/types';
import {__} from '@wordpress/i18n';
/**
* @since 3.0.0
*/
type CurrencySwitcherMessageProps = {
message: string;
baseCurrency: string;
newCurrencyRate: string;
newCurrency: string;
};
/**
* @since 3.0.0
*/
type DonationAmountCurrencySwitcherMessageProps = {
currencySettings: CurrencySwitcherSetting[];
message: string;
};
/**
* @since 3.0.0
*/
const CurrencySwitcherMessage = ({
message,
baseCurrency,
newCurrencyRate,
newCurrency,
}: CurrencySwitcherMessageProps) => {
if (baseCurrency === newCurrency) {
return;
}
const templateTags = {
base_currency: baseCurrency,
new_currency_rate: newCurrencyRate,
new_currency: newCurrency,
};
Object.keys(templateTags).forEach((key) => {
message = message.replace(`{${key}}`, templateTags[key]);
});
return <div className="givewp-fields-amount__currency-switcher-message">{__(message, 'give')}</div>;
};
/**
* @since 3.0.0
*/
export default function DonationAmountCurrencySwitcherMessage({
currencySettings,
message,
}: DonationAmountCurrencySwitcherMessageProps) {
const {useWatch, useCurrencyFormatter} = window.givewp.form.hooks;
const currency = useWatch({name: 'currency'});
const baseCurrency = currencySettings.find((setting) => setting.exchangeRate === 0)?.id ?? 'USD';
const baseCurrencyFormatter = useCurrencyFormatter(baseCurrency);
const newCurrencySetting = currencySettings.find((setting) => setting.id === currency);
const newCurrencyRate = newCurrencySetting?.exchangeRate ?? Number('1.00');
const newCurrencyRateFormatter = useCurrencyFormatter(currency, {
minimumFractionDigits: newCurrencySetting.exchangeRateFractionDigits,
});
return (
<CurrencySwitcherMessage
baseCurrency={baseCurrency}
message={message.replace('1.00', baseCurrencyFormatter.format(1))}
newCurrency={currency}
newCurrencyRate={newCurrencyRateFormatter.format(newCurrencyRate)}
/>
);
}