-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathindex.jsx
More file actions
472 lines (424 loc) · 20.4 KB
/
index.jsx
File metadata and controls
472 lines (424 loc) · 20.4 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
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
/*
* 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, {useState, useEffect, useMemo} from 'react'
import PropTypes from 'prop-types'
import {useHistory, useLocation} from 'react-router-dom'
import {StorefrontPreview} from '@salesforce/commerce-sdk-react/components'
import {getAssetUrl, getRouterBasePath} from '@salesforce/pwa-kit-react-sdk/ssr/universal/utils'
import useActiveData from '@salesforce/retail-react-app/app/hooks/use-active-data'
import {useQuery} from '@tanstack/react-query'
import {
useAccessToken,
useCategory,
useShopperBasketsMutation
} from '@salesforce/commerce-sdk-react'
import logger from '@salesforce/retail-react-app/app/utils/logger-instance'
import {useAppOrigin} from '@salesforce/retail-react-app/app/hooks/use-app-origin'
import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config'
// Chakra
import {
Box,
Center,
Fade,
Spinner,
useDisclosure,
useStyleConfig
} from '@salesforce/retail-react-app/app/components/shared/ui'
import {SkipNavLink, SkipNavContent} from '@chakra-ui/skip-nav'
// Contexts
import {CurrencyProvider} from '@salesforce/retail-react-app/app/contexts'
// Local Project Components
import Header from '@salesforce/retail-react-app/app/components/header'
import OfflineBanner from '@salesforce/retail-react-app/app/components/offline-banner'
import OfflineBoundary from '@salesforce/retail-react-app/app/components/offline-boundary'
import ScrollToTop from '@salesforce/retail-react-app/app/components/scroll-to-top'
import Footer from '@salesforce/retail-react-app/app/components/footer'
import CheckoutHeader from '@salesforce/retail-react-app/app/pages/checkout/partials/checkout-header'
import CheckoutFooter from '@salesforce/retail-react-app/app/pages/checkout/partials/checkout-footer'
import {DrawerMenu} from '@salesforce/retail-react-app/app/components/drawer-menu'
import {ListMenu, ListMenuContent} from '@salesforce/retail-react-app/app/components/list-menu'
import {HideOnDesktop, HideOnMobile} from '@salesforce/retail-react-app/app/components/responsive'
import AboveHeader from '@salesforce/retail-react-app/app/components/_app/partials/above-header'
import {StoreLocatorModal} from '@salesforce/retail-react-app/app/components/store-locator'
import Island from '@salesforce/retail-react-app/app/components/island'
// Hooks
import {AuthModal, useAuthModal} from '@salesforce/retail-react-app/app/hooks/use-auth-modal'
import {useStoreLocatorModal} from '@salesforce/retail-react-app/app/hooks/use-store-locator'
import {
DntNotification,
useDntNotification
} from '@salesforce/retail-react-app/app/hooks/use-dnt-notification'
import {AddToCartModalProvider} from '@salesforce/retail-react-app/app/hooks/use-add-to-cart-modal'
import {BonusProductSelectionModalProvider} from '@salesforce/retail-react-app/app/hooks/use-bonus-product-selection-modal'
import useMultiSite from '@salesforce/retail-react-app/app/hooks/use-multi-site'
import {useCurrentCustomer} from '@salesforce/retail-react-app/app/hooks/use-current-customer'
import {useCurrentBasket} from '@salesforce/retail-react-app/app/hooks/use-current-basket'
import {useUpdateShopperContext} from '@salesforce/retail-react-app/app/hooks/use-update-shopper-context'
// HOCs
import {withCommerceSdkReact} from '@salesforce/retail-react-app/app/components/with-commerce-sdk-react/with-commerce-sdk-react'
// Localization
import {IntlProvider} from 'react-intl'
// Others
import {watchOnlineStatus, flatten, isServer} from '@salesforce/retail-react-app/app/utils/utils'
import {getTargetLocale, fetchTranslations} from '@salesforce/retail-react-app/app/utils/locale'
import {
DEFAULT_SITE_TITLE,
HOME_HREF,
THEME_COLOR,
CAT_MENU_DEFAULT_NAV_SSR_DEPTH,
CAT_MENU_DEFAULT_ROOT_CATEGORY,
DEFAULT_LOCALE,
STORE_LOCATOR_IS_ENABLED
} from '@salesforce/retail-react-app/app/constants'
import Seo from '@salesforce/retail-react-app/app/components/seo'
import ShopperAgent from '@salesforce/retail-react-app/app/components/shopper-agent'
import {getPathWithLocale} from '@salesforce/retail-react-app/app/utils/url'
import {getCommerceAgentConfig} from '@salesforce/retail-react-app/app/utils/config-utils'
const PlaceholderComponent = () => (
<Center p="2">
<Spinner size="lg" />
</Center>
)
const DrawerMenuItemWithData = withCommerceSdkReact(
({itemComponent: ItemComponent, data, ...rest}) => (
<Fade in={true}>
<ItemComponent {...rest} item={data} itemComponent={DrawerMenuItemWithData} />
</Fade>
),
{
hook: useCategory,
queryOptions: ({item}) => ({
parameters: {
id: item.id
}
}),
placeholder: PlaceholderComponent
}
)
const ListMenuContentWithData = withCommerceSdkReact(
({data, ...rest}) => (
<Fade in={true}>
<ListMenuContent {...rest} item={data} />
</Fade>
),
{
hook: useCategory,
queryOptions: ({item}) => ({
parameters: {
id: item.id,
levels: 2
}
}),
placeholder: PlaceholderComponent
}
)
const App = (props) => {
const {children} = props
const {data: categoriesTree} = useCategory({
parameters: {id: CAT_MENU_DEFAULT_ROOT_CATEGORY, levels: CAT_MENU_DEFAULT_NAV_SSR_DEPTH}
})
const categories = flatten(categoriesTree || {}, 'categories')
const {getTokenWhenReady} = useAccessToken()
const appOrigin = useAppOrigin()
const activeData = useActiveData()
const history = useHistory()
const location = useLocation()
const authModal = useAuthModal()
const dntNotification = useDntNotification()
const {site, locale, buildUrl} = useMultiSite()
const {
isOpen: isStoreLocatorOpen,
onOpen: onOpenStoreLocator,
onClose: onCloseStoreLocator
} = useStoreLocatorModal()
const storeLocatorEnabled = getConfig()?.app?.storeLocatorEnabled ?? STORE_LOCATOR_IS_ENABLED
const [isOnline, setIsOnline] = useState(true)
const styles = useStyleConfig('App')
const {isOpen, onOpen, onClose} = useDisclosure()
const targetLocale = getTargetLocale({
getUserPreferredLocales: () => {
// CONFIG: This function should return an array of preferred locales. They can be
// derived from various sources. Below are some examples of those:
//
// - client side: window.navigator.languages
// - the page URL they're on (example.com/en-GB/home)
// - cookie (if their previous preference is saved there)
//
// If this function returns an empty array (e.g. there isn't locale in the page url),
// then the app would use the default locale as the fallback.
// NOTE: Your implementation may differ, this is just what we did.
return [locale?.id || DEFAULT_LOCALE]
},
l10nConfig: site.l10n
})
// If the translation file exists, it'll be served directly from static folder (and won't reach this code here).
// However, if the file is missing, the App would render a 404 page.
const is404ForMissingTranslationFile = /\/static\/translations\/compiled\/[^.]+\.json$/.test(
location?.pathname
)
// Fetch the translation message data using the target locale.
const {data: messages} = useQuery({
queryKey: ['app', 'translations', 'messages', targetLocale],
queryFn: () => {
if (is404ForMissingTranslationFile) {
// Return early to prevent an infinite loop
// Otherwise, it'll continue to fetch the missing translation file again
return {}
}
return fetchTranslations(targetLocale, appOrigin)
},
enabled: isServer
})
// Used to conditionally render header/footer for checkout page
const isCheckout = /\/checkout$/.test(location?.pathname)
const {l10n} = site
// Get the current currency to be used through out the app
const currency = locale.preferredCurrency || l10n.defaultCurrency
// Handle creating a new basket if there isn't one already assigned to the current
// customer.
const {data: customer} = useCurrentCustomer()
const {data: basket, dataUpdatedAt: basketQueryLastUpdateTime} = useCurrentBasket()
const config = getConfig()
const updateBasket = useShopperBasketsMutation('updateBasket')
const updateCustomerForBasket = useShopperBasketsMutation('updateCustomerForBasket')
useEffect(() => {
// update the basket currency if it doesn't match the current locale currency
if (basket?.currency && basket?.currency !== currency) {
updateBasket.mutate({
parameters: {basketId: basket.basketId},
body: {currency}
})
}
}, [basket?.currency])
const commerceAgentConfiguration = useMemo(() => {
return getCommerceAgentConfig()
}, [config.app.commerceAgent])
useEffect(() => {
// update the basket customer email
if (
basket &&
customer?.isRegistered &&
customer?.email &&
customer?.email !== basket?.customerInfo?.email
) {
updateCustomerForBasket.mutate({
parameters: {basketId: basket.basketId},
body: {
email: customer.email
}
})
}
}, [customer?.isRegistered, customer?.email, basket?.customerInfo?.email])
useEffect(() => {
// Listen for online status changes.
watchOnlineStatus((isOnline) => {
setIsOnline(isOnline)
})
}, [])
// Handle updating the shopper context
useUpdateShopperContext()
useEffect(() => {
// Lets automatically close the mobile navigation when the
// location path is changed.
onClose()
}, [location])
const onLogoClick = () => {
// Goto the home page.
const path = buildUrl(HOME_HREF)
history.push(path)
// Close the drawer.
onClose()
}
const onCartClick = () => {
const path = buildUrl('/cart')
history.push(path)
// Close the drawer.
onClose()
}
const onAccountClick = () => {
// Link to account page if registered; Header component will show auth modal for guest users
const path = buildUrl('/account')
history.push(path)
}
const onWishlistClick = () => {
// Link to wishlist page if registered; Header component will show auth modal for guest users
const path = buildUrl('/account/wishlist')
history.push(path)
}
const trackPage = () => {
activeData.trackPage(site.id, locale.id, currency)
}
useEffect(() => {
trackPage()
}, [location])
const getHrefForLocale = (localeId) =>
`${appOrigin}${getRouterBasePath()}${getPathWithLocale(localeId, buildUrl, {
location: {...location, search: ''}
})}`
return (
<Box className="sf-app" {...styles.container}>
<StorefrontPreview getToken={getTokenWhenReady}>
<IntlProvider
onError={(err) => {
if (!messages) {
// During the ssr prepass phase the messages object has not loaded, so we can suppress
// errors during this time.
return
}
if (err.code === 'MISSING_TRANSLATION') {
// NOTE: Remove the console error for missing translations during development,
// as we knew translations would be added later.
logger.warn('Missing translation', {
namespace: 'App.IntlProvider',
additionalProperties: {
errorMessage: err.message
}
})
return
}
throw err
}}
locale={targetLocale}
messages={messages}
// For react-intl, the _default locale_ refers to the locale that the inline `defaultMessage`s are written for.
// NOTE: if you update this value, please also update the following npm scripts in `template-retail-react-app/package.json`:
// - "extract-default-translations"
// - "compile-translations:pseudo"
defaultLocale={DEFAULT_LOCALE}
>
<CurrencyProvider currency={currency}>
<Seo>
<meta name="theme-color" content={THEME_COLOR} />
<meta name="apple-mobile-web-app-title" content={DEFAULT_SITE_TITLE} />
<link
rel="apple-touch-icon"
href={getAssetUrl('static/img/global/apple-touch-icon.png')}
/>
<link rel="manifest" href={getAssetUrl('static/manifest.json')} />
{/* Urls for all localized versions of this page (including current page)
For more details on hrefLang, see https://developers.google.com/search/docs/advanced/crawling/localized-versions */}
{site.l10n?.supportedLocales.map((locale) => (
<link
rel="alternate"
hrefLang={locale.id.toLowerCase()}
href={getHrefForLocale(locale.id)}
key={locale.id}
/>
))}
{/* A general locale as fallback. For example: "en" if default locale is "en-GB" */}
<link
rel="alternate"
hrefLang={site.l10n.defaultLocale.slice(0, 2)}
href={getHrefForLocale(locale.id)}
/>
{/* A wider fallback for user locales that the app does not support */}
<link rel="alternate" hrefLang="x-default" href={`${appOrigin}/`} />
</Seo>
{commerceAgentConfiguration?.enabled === 'true' && (
<ShopperAgent
commerceAgentConfiguration={commerceAgentConfiguration}
basketDoneLoading={basketQueryLastUpdateTime > 0}
/>
)}
<ScrollToTop />
<Box id="app" display="flex" flexDirection="column" flex={1}>
<SkipNavLink zIndex="skipLink">Skip to Content</SkipNavLink>
{storeLocatorEnabled && (
<StoreLocatorModal
isOpen={isStoreLocatorOpen}
onClose={onCloseStoreLocator}
/>
)}
<Island hydrateOn={'visible'}>
<Box {...styles.headerWrapper}>
{!isCheckout ? (
<>
<AboveHeader />
<Header
onMenuClick={onOpen}
onLogoClick={onLogoClick}
onMyCartClick={onCartClick}
onMyAccountClick={onAccountClick}
onWishlistClick={onWishlistClick}
onStoreLocatorClick={onOpenStoreLocator}
>
<HideOnDesktop>
<DrawerMenu
isOpen={isOpen}
onClose={onClose}
onLogoClick={onLogoClick}
root={
categories?.[
CAT_MENU_DEFAULT_ROOT_CATEGORY
]
}
itemsKey="categories"
itemsCountKey="onlineSubCategoriesCount"
itemComponent={DrawerMenuItemWithData}
/>
</HideOnDesktop>
<HideOnMobile>
<ListMenu
root={
categories?.[
CAT_MENU_DEFAULT_ROOT_CATEGORY
]
}
itemsKey="categories"
itemsCountKey="onlineSubCategoriesCount"
contentComponent={ListMenuContentWithData}
/>
</HideOnMobile>
</Header>
</>
) : (
<CheckoutHeader />
)}
</Box>
</Island>
{!isOnline && <OfflineBanner />}
<AddToCartModalProvider>
<BonusProductSelectionModalProvider>
<SkipNavContent
style={{
display: 'flex',
flexDirection: 'column',
flex: 1,
outline: 0
}}
>
<Box
as="main"
id="app-main"
role="main"
display="flex"
flexDirection="column"
flex="1"
>
<OfflineBoundary isOnline={false}>
{children}
</OfflineBoundary>
</Box>
</SkipNavContent>
<Island hydrateOn={'visible'}>
{!isCheckout ? <Footer /> : <CheckoutFooter />}
</Island>
<AuthModal {...authModal} />
<DntNotification {...dntNotification} />
</BonusProductSelectionModalProvider>
</AddToCartModalProvider>
</Box>
</CurrencyProvider>
</IntlProvider>
</StorefrontPreview>
</Box>
)
}
App.propTypes = {
children: PropTypes.node
}
export default App