-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathcredit-card-fields.jsx
More file actions
178 lines (162 loc) · 7.6 KB
/
credit-card-fields.jsx
File metadata and controls
178 lines (162 loc) · 7.6 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
/*
* Copyright (c) 2022, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import React, {useState} from 'react'
import PropTypes from 'prop-types'
import ccValidator from 'card-validator'
import {useIntl} from 'react-intl'
import {Box, Flex, FormLabel, InputRightElement, SimpleGrid, Stack, Tooltip} from '@chakra-ui/react'
import {formatCreditCardNumber, getCreditCardIcon} from '../../utils/cc-utils'
import useCreditCardFields from '../../components/forms/useCreditCardFields'
import Field from '../../components/field'
import {AmexIcon, DiscoverIcon, MastercardIcon, VisaIcon, InfoIcon} from '../../components/icons'
const CreditCardFields = ({form, prefix = ''}) => {
const {formatMessage} = useIntl()
const [isTooltipOpen, setIsTooltipOpen] = useState(false)
const fields = useCreditCardFields({form, prefix})
// Rerender the fields when we `cardType` changes so the detected
// card icon appears while typing the card number.
// https://react-hook-form.com/api#watch
const cardType = form.watch('cardType')
const CardIcon = getCreditCardIcon(form.getValues().cardType)
// Note: The ternary should NOT be placed inside a call to `formatMessage`. The message
// extraction script (`npm run extract-default-translations`) only works when `formatMessage` is
// used with object literals.
const securityCodeTooltipLabel =
cardType === 'american-express'
? formatMessage({
id: 'credit_card_fields.tool_tip.security_code.american_express',
defaultMessage: 'This 4-digit code can be found on the front of your card.',
description: 'American Express security code help text'
})
: formatMessage({
id: 'credit_card_fields.tool_tip.security_code',
defaultMessage: 'This 3-digit code can be found on the back of your card.',
description: 'Generic credit card security code help text'
})
const handleTooltipClose = () => {
setIsTooltipOpen(false)
if (document) {
document.removeEventListener('click', handleTooltipClose)
document.removeEventListener('keydown', handleTooltipClose)
}
}
const handleTooltipOpen = () => {
setIsTooltipOpen(true)
if (document) {
document.addEventListener('click', handleTooltipClose)
document.addEventListener('keydown', handleTooltipClose)
}
}
return (
<Box>
<Stack gap={5}>
<Field
{...fields.number}
formLabel={
<Flex justify="space-between">
<FormLabel>{fields.number.label}</FormLabel>
<Stack direction="row" gap={1}>
<VisaIcon layerStyle="ccIcon" />
<MastercardIcon layerStyle="ccIcon" />
<AmexIcon layerStyle="ccIcon" />
<DiscoverIcon layerStyle="ccIcon" />
</Stack>
</Flex>
}
inputProps={({onChange}) => ({
...fields.number.inputProps,
onChange(evt) {
const number = evt.target.value.replace(/[^0-9 ]+/, '')
const {card} = ccValidator.number(number)
const formattedNumber = card
? formatCreditCardNumber(number, card)
: number
form.setValue('cardType', card?.type || '')
return onChange(formattedNumber)
}
})}
>
{CardIcon && form.getValues().number?.length > 2 && (
<InputRightElement width="60px">
<CardIcon layerStyle="ccIcon" />
</InputRightElement>
)}
</Field>
<Field {...fields.holder} />
<SimpleGrid columns={[2, 2, 3]} gap={5}>
<Field
{...fields.expiry}
inputProps={({onChange}) => ({
...fields.expiry.inputProps,
onChange(evt) {
let value = evt.target.value.replace('/', '')
// We ignore input values other than digits and `/`.
if (value.match(/[^\d|/]/g)) {
return
}
// Ignore input when we already have MM/YY
if (value.length > 4) {
return
}
if (value.length >= 2) {
value = `${value.substr(0, 2)}/${value.substr(2)}`
}
return onChange(value)
},
onKeyDown(evt) {
if (evt.keyCode === 8 || evt.keyCode === 46) {
evt.preventDefault()
return onChange(evt.target.value.slice(0, -1))
}
}
})}
/>
<Field
{...fields.securityCode}
formLabel={
<>
<FormLabel display="inline" mr={1}>
{fields.securityCode.label}
</FormLabel>
<Box
onMouseEnter={handleTooltipOpen}
onFocus={handleTooltipOpen}
as="span"
>
<Tooltip
hasArrow
placement="top"
label={securityCodeTooltipLabel}
shouldWrapChildren={true}
isOpen={isTooltipOpen}
>
<InfoIcon
boxSize={5}
color="gray.700"
aria-label={formatMessage({
id: 'credit_card_fields.tool_tip.security_code_aria_label',
defaultMessage: 'Security code info'
})}
/>
</Tooltip>
</Box>
</>
}
/>
</SimpleGrid>
</Stack>
<Field {...fields.cardType} />
</Box>
)
}
CreditCardFields.propTypes = {
/** Object returned from `useForm` */
form: PropTypes.object.isRequired,
/** Optional prefix for field names */
prefix: PropTypes.string
}
export default CreditCardFields