-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathaddresses.jsx
More file actions
418 lines (387 loc) · 16 KB
/
addresses.jsx
File metadata and controls
418 lines (387 loc) · 16 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
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
/*
* Copyright (c) 2021, salesforce.com, 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, {useEffect, useRef, useState} from 'react'
import {defineMessage, FormattedMessage, useIntl} from 'react-intl'
import PropTypes from 'prop-types'
import {
Alert,
Badge,
Box,
Button,
Container,
Heading,
SimpleGrid,
Skeleton,
Stack,
Text
} from '@chakra-ui/react'
import FormActionButtons from '../../components/forms/form-action-buttons'
import {useForm} from 'react-hook-form'
import useToast from '../../hooks/use-toast'
import LoadingSpinner from '../../components/loading-spinner'
import {LocationIcon, PlusIcon} from '../../components/icons'
import ActionCard from '../../components/action-card'
import AddressFields from '../../components/forms/address-fields'
import AddressDisplay from '../../components/address-display'
import PageActionPlaceHolder from '../../components/page-action-placeholder'
import {useCurrentCustomer} from '../../hooks/use-current-customer'
import {useShopperCustomersMutation} from '@salesforce/commerce-sdk-react'
import {nanoid} from 'nanoid'
import {useErrorHandler} from '../../hooks/use-errors'
const DEFAULT_SKELETON_COUNT = 3
const BoxArrow = () => {
return (
<Box
width={4}
height={4}
borderLeft="1px solid"
borderTop="1px solid"
borderColor="blue.600"
position="absolute"
left="50%"
bottom="-23px"
zIndex={1}
background="white"
transform="rotate(45deg)"
/>
)
}
const ShippingAddressForm = ({form, hasAddresses, selectedAddressId, toggleEdit, submitForm}) => {
return (
<Box
border="1px solid"
borderColor="gray.200"
rounded="md"
position="relative"
{...(hasAddresses && {
gridColumn: [1, 'span 2', 'span 2', 'span 2', 'span 3'],
px: [4, 4, 6],
py: 6,
rounded: 'md',
border: '1px solid',
borderColor: 'blue.600'
})}
>
{form.formState.isSubmitting && <LoadingSpinner />}
<Stack gap={6} p={6}>
<Heading as="h3" size="sm">
{selectedAddressId ? (
<FormattedMessage
defaultMessage="Edit Address"
id="shipping_address_form.heading.edit_address"
/>
) : (
<FormattedMessage
defaultMessage="Add New Address"
id="shipping_address_form.heading.new_address"
/>
)}
</Heading>
<Box>
<Container variant="form">
<form onSubmit={form.handleSubmit(submitForm)}>
<Stack gap={6}>
{form.formState.errors?.global && (
<Alert.Root colorPalette="red">
<Alert.Indicator />
<Alert.Content>
<Text fontSize="sm">
{form.formState.errors.global.message}
</Text>
</Alert.Content>
</Alert.Root>
)}
<AddressFields form={form} />
<FormActionButtons onCancel={toggleEdit} />
</Stack>
</form>
</Container>
</Box>
</Stack>
</Box>
)
}
ShippingAddressForm.propTypes = {
form: PropTypes.object,
hasAddresses: PropTypes.bool,
selectedAddressId: PropTypes.string,
toggleEdit: PropTypes.func,
submitForm: PropTypes.func
}
const successfullyAddedAddress = defineMessage({
defaultMessage: 'New address saved',
id: 'account_addresses.info.new_address_saved'
})
const successfullyUpdatedAddress = defineMessage({
defaultMessage: 'Address updated',
id: 'account_addresses.info.address_updated'
})
const successfullyRemovedAddress = defineMessage({
defaultMessage: 'Address removed',
id: 'account_addresses.info.address_removed'
})
const AccountAddresses = () => {
const {formatMessage} = useIntl()
const {data: customer, isLoading} = useCurrentCustomer()
const {isRegistered, addresses, customerId} = customer
const addCustomerAddress = useShopperCustomersMutation('createCustomerAddress')
const updateSavedAddress = useShopperCustomersMutation('updateCustomerAddress')
const removeCustomerAddress = useShopperCustomersMutation('removeCustomerAddress')
const [isEditing, setIsEditing] = useState(false)
const [selectedAddressId, setSelectedAddressId] = useState(false)
const toast = useToast()
const form = useForm()
const showError = useErrorHandler()
const headingRef = useRef()
useEffect(() => {
// Focus the 'Addresses' header when the component mounts for accessibility
headingRef?.current?.focus()
}, [])
// keep track of the edit buttons so we can focus on them later for accessibility
const [editBtnRefs, setEditBtnRefs] = useState({})
useEffect(() => {
const currentRefs = {}
addresses?.forEach(({addressId}) => {
currentRefs[addressId] = React.createRef()
})
setEditBtnRefs(currentRefs)
}, [addresses])
const hasAddresses = addresses?.length > 0
const submitForm = async (address) => {
try {
let data
form.clearErrors()
if (selectedAddressId) {
const body = {
...address,
addressId: selectedAddressId
}
data = await updateSavedAddress.mutateAsync({
body,
parameters: {
customerId,
addressName: selectedAddressId
}
})
} else {
const body = {
addressId: nanoid(),
...address
}
data = await addCustomerAddress.mutateAsync({
body,
parameters: {customerId: customer.customerId}
})
}
if (data) {
toggleEdit()
toast({
title: selectedAddressId
? formatMessage(successfullyUpdatedAddress)
: formatMessage(successfullyAddedAddress),
type: 'success'
})
}
} catch (error) {
form.setError('global', {type: 'manual', message: error.message})
}
}
const removeAddress = async (addressId) => {
try {
if (addressId === selectedAddressId) {
setSelectedAddressId(undefined)
setIsEditing(false)
form.reset({addressId: ''})
}
await removeCustomerAddress.mutateAsync(
{
parameters: {
customerId,
addressName: addressId
}
},
{
onSuccess: () => {
toast({
title: formatMessage(successfullyRemovedAddress),
type: 'success'
})
// Move focus to header after we successfully remove address
headingRef?.current?.focus()
}
}
)
} catch (error) {
showError()
throw error
}
}
const toggleEdit = (address) => {
form.reset({...address})
if (address?.addressId) {
setSelectedAddressId(address.addressId)
setIsEditing(true)
} else {
// Focus on the edit button that opened the form when the form closes
// otherwise focus on the heading if we can't find the button
const focusAfterClose = editBtnRefs[selectedAddressId]?.current ?? headingRef?.current
focusAfterClose?.focus()
setSelectedAddressId(undefined)
setIsEditing(!isEditing)
}
}
return (
<Stack gap={4} data-testid="account-addresses-page">
<Heading as="h1" fontSize="2xl" tabIndex="0" ref={headingRef}>
<FormattedMessage
defaultMessage="Addresses"
id="account_addresses.title.addresses"
/>
</Heading>
{isLoading && (
<SimpleGrid columns={[1, 2, 2, 2, 3]} spacing={4}>
{new Array(DEFAULT_SKELETON_COUNT).fill().map((_, index) => {
return (
<ActionCard key={index}>
<Stack gap={2} mb={7}>
<Skeleton height={6} width={30} />
<Skeleton height={6} width={21} />
<Skeleton height={6} width={26} />
</Stack>
</ActionCard>
)
})}
</SimpleGrid>
)}
{hasAddresses && (
<SimpleGrid columns={[1, 2, 2, 2, 3]} spacing={4} gridAutoFlow="row dense">
{
<Button
variant="outline"
border="1px dashed"
borderColor="gray.200"
color="blue.600"
height={{lg: 'full'}}
minHeight={11}
rounded="md"
fontWeight="medium"
leftIcon={<PlusIcon display="block" boxSize={4} />}
onClick={() => toggleEdit()}
>
<FormattedMessage
defaultMessage="Add Address"
id="account_addresses.button.add_address"
/>
{isEditing && !selectedAddressId && <BoxArrow />}
</Button>
}
{isEditing && !selectedAddressId && (
<>
<ShippingAddressForm
form={form}
hasAddresses={hasAddresses}
submitForm={submitForm}
selectedAddressId={selectedAddressId}
toggleEdit={toggleEdit}
/>
</>
)}
{addresses.map((address) => {
const editLabel = formatMessage(
{
defaultMessage: 'Edit {address}',
id: 'shipping_address.label.edit_button'
},
{address: address.address1}
)
const removeLabel = formatMessage(
{
defaultMessage: 'Remove {address}',
id: 'shipping_address.label.remove_button'
},
{address: address.address1}
)
return (
<React.Fragment key={address.addressId}>
<ActionCard
borderColor="gray.200"
key={address.addressId}
editBtnRef={editBtnRefs[address.addressId]}
onRemove={() => removeAddress(address.addressId)}
onEdit={() => toggleEdit(address)}
editBtnLabel={editLabel}
removeBtnLabel={removeLabel}
>
{address.preferred && (
<Badge
position="absolute"
right={4}
variant="solid"
bg="gray.100"
color="gray.900"
>
<FormattedMessage
defaultMessage="Default"
id="account_addresses.badge.default"
/>
</Badge>
)}
<AddressDisplay address={address} />
{isEditing && address.addressId === selectedAddressId && (
<BoxArrow />
)}
</ActionCard>
{isEditing && address.addressId === selectedAddressId && (
<ShippingAddressForm
form={form}
hasAddresses={hasAddresses}
submitForm={submitForm}
selectedAddressId={selectedAddressId}
toggleEdit={toggleEdit}
/>
)}
</React.Fragment>
)
})}
</SimpleGrid>
)}
{!hasAddresses && !isLoading && (
<>
{!isEditing && isRegistered && (
<PageActionPlaceHolder
icon={<LocationIcon boxSize={8} />}
heading={formatMessage({
defaultMessage: 'No Saved Addresses',
id: 'account_addresses.page_action_placeholder.heading.no_saved_addresses'
})}
text={formatMessage({
defaultMessage: 'Add a new address method for faster checkout.',
id: 'account_addresses.page_action_placeholder.message.add_new_address'
})}
buttonText={formatMessage({
defaultMessage: 'Add Address',
id: 'account_addresses.page_action_placeholder.button.add_address'
})}
onButtonClick={() => toggleEdit()}
/>
)}
{isEditing && !selectedAddressId && (
<ShippingAddressForm
form={form}
hasAddresses={hasAddresses}
submitForm={submitForm}
selectedAddressId={selectedAddressId}
toggleEdit={toggleEdit}
/>
)}
</>
)}
</Stack>
)
}
AccountAddresses.getTemplateName = () => 'account-addresses'
export default AccountAddresses