-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathwith-layout.tsx
More file actions
376 lines (337 loc) · 14.7 KB
/
with-layout.tsx
File metadata and controls
376 lines (337 loc) · 14.7 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
/*
* Copyright (c) 2024, 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
*/
// Third-Party Imports
import React, {useState, useEffect} from 'react'
import {useHistory, useLocation} from 'react-router-dom'
import {Helmet} from 'react-helmet'
// Removes focus for non-keyboard interactions for the whole application
import 'focus-visible/dist/focus-visible'
// Platform Imports
import {getStaticAssetUrl} from '@salesforce/pwa-kit-react-sdk/ssr/universal/utils'
import {getAppOrigin} from '@salesforce/pwa-kit-react-sdk/utils/url'
import {useCategory, useShopperBasketsMutation} from '@salesforce/commerce-sdk-react'
// Chakra
import {
Box,
Center,
Button,
Flex,
Heading,
Spinner,
useDisclosure,
useSlotRecipe,
useToken
} from '@chakra-ui/react'
// Local Project Components
import {DrawerMenu} from '../drawer-menu'
import {SkipNavLink, SkipNavContent} from '../skip-nav'
import {getPathWithLocale} from '../../utils/url'
import {HideOnDesktop, HideOnMobile} from '../responsive'
import {ListMenu, ListMenuContent} from '../list-menu'
import {withCommerceSdkReactHookData} from '../with-commerce-sdk-react-hook-data'
import AboveHeader from '../above-header'
import CheckoutHeader from '../../pages/checkout/partials/checkout-header'
import CheckoutFooter from '../../pages/checkout/partials/checkout-footer'
import Footer from '../footer'
import Header from '../header'
import OfflineBanner from '../offline-banner'
import OfflineBoundary from '../offline-boundary'
import Seo from '../seo'
import ScrollToTop from '../scroll-to-top'
import Fade from '../fade'
// Local Project Hooks
import {AuthModal, useAuthModal} from '../../hooks/use-auth-modal'
import {AddToCartModalProvider} from '../../hooks/use-add-to-cart-modal'
import {useExtensionConfig, useCurrentCustomer, useCurrentBasket} from '../../hooks'
import {watchOnlineStatus, flatten} from '../../utils/utils'
import useActiveData from '../../hooks/use-active-data'
import useMultiSite from '../../hooks/use-multi-site'
// import {DntNotification, useDntNotification} from '../../hooks/use-dnt-notification'
import {UserConfig} from '../../types/config'
// Define a type for the HOC props
type WithAppLayoutProps = React.ComponentPropsWithoutRef<any>
const PlaceholderComponent: React.FC = () => (
<Center p="2">
<Spinner size="lg" />
</Center>
)
const DrawerMenuItemWithData = withCommerceSdkReactHookData(
({itemComponent: ItemComponent, data, ...rest}: any) => (
<Fade in={true}>
<ItemComponent {...rest} item={data} itemComponent={DrawerMenuItemWithData} />
</Fade>
),
{
hook: useCategory,
queryOptions: ({item}: {item: {id: string}}) => ({
parameters: {
id: item.id
}
}),
placeholder: PlaceholderComponent
}
)
const ListMenuContentWithData = withCommerceSdkReactHookData(
({data, ...rest}: any) => <ListMenuContent {...rest} item={data} />,
{
hook: useCategory,
queryOptions: ({item}: {item: {id: string}}) => ({
parameters: {
id: item.id,
levels: 2
}
}),
placeholder: PlaceholderComponent
}
)
// Define the HOC function
const withLayout = <P extends object>(WrappedComponent: React.ComponentType<P>) => {
const WithLayout: React.FC<P> = (props: WithAppLayoutProps) => {
const config = useExtensionConfig() as UserConfig
const CAT_MENU_DEFAULT_ROOT_CATEGORY = String(config.categoryNav.defaultRootCategory)
const CAT_MENU_DEFAULT_NAV_SSR_DEPTH = config.categoryNav.defaultNavSsrDepth
const {data: categoriesTree} = useCategory({
parameters: {
id: CAT_MENU_DEFAULT_ROOT_CATEGORY,
levels: CAT_MENU_DEFAULT_NAV_SSR_DEPTH
}
})
const categories = flatten(categoriesTree || {}, 'categories')
const appOrigin = getAppOrigin()
const activeData = useActiveData()
const history = useHistory()
const location = useLocation()
const authModal = useAuthModal()
// const dntNotification = useDntNotification()
const {site, locale, buildUrl} = useMultiSite()
const [isOnline, setIsOnline] = useState<boolean>(true)
// https://www.chakra-ui.com/docs/theming/overview#tokens-1
const [themeColor] = useToken('colors.blue', '600')
const {open, onOpen, onClose} = useDisclosure()
// 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} = useCurrentBasket()
const basketId = basket?.basketId || ''
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},
body: {currency}
})
}
}, [basket?.currency])
useEffect(() => {
// update the basket customer email
if (
basket &&
customer?.isRegistered &&
customer?.email &&
customer?.email !== basket?.customerInfo?.email
) {
updateCustomerForBasket.mutate({
parameters: {basketId},
body: {
email: customer.email
}
})
}
}, [customer?.isRegistered, customer?.email, basket?.customerInfo?.email])
useEffect(() => {
// Listen for online status changes.
watchOnlineStatus((isOnline: boolean) => {
setIsOnline(isOnline)
})
}, [])
useEffect(() => {
// Lets automatically close the mobile navigation when the
// location path is changed.
onClose()
}, [location])
const onLogoClick = () => {
// Goto the home page.
const path = config.pages?.Home
? buildUrl(config.pages.Home.path, site.id, locale.id)
: '/'
history.push(path)
// Close the drawer.
onClose()
}
const onCartClick = () => {
const path = buildUrl('/cart', site.id, locale.id)
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', site.id, locale.id)
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', site.id, locale.id)
history.push(path)
}
const trackPage = () => {
void activeData.trackPage(site.id, locale.id, currency)
}
useEffect(() => {
trackPage()
}, [location])
// Apply styles from the theme
const recipe = useSlotRecipe({key: 'app'})
const styles = recipe()
return (
<Box className="sf-app" css={styles.container}>
<Helmet>
{config.activeDataEnabled && (
<script
src={getStaticAssetUrl('libs/head-active_data.js', {
appExtensionPackageName: '@salesforce/extension-chakra-storefront'
})}
id="headActiveData"
type="text/javascript"
></script>
)}
</Helmet>
<Seo>
<meta name="theme-color" content={themeColor} />
<meta name="apple-mobile-web-app-title" content={config.defaultSiteTitle} />
{/* 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={`${appOrigin}${getPathWithLocale(locale.id, buildUrl, {
location: {
...location,
search: ''
}
})}`}
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={`${appOrigin}${getPathWithLocale(locale.id, buildUrl, {
location: {
...location,
search: ''
}
})}`}
/>
{/* A wider fallback for user locales that the app does not support */}
<link rel="alternate" hrefLang="x-default" href={`${appOrigin}/`} />
</Seo>
<ScrollToTop />
<Box id="app" display="flex" flexDirection="column" flex={1}>
<SkipNavLink>Skip to Content</SkipNavLink>
<Box css={styles.headerWrapper}>
{!isCheckout ? (
<>
<AboveHeader />
<Header
onMenuClick={onOpen}
onLogoClick={onLogoClick}
onMyCartClick={onCartClick}
onMyAccountClick={onAccountClick}
onWishlistClick={onWishlistClick}
>
{/* TODO: mobile menu */}
<HideOnDesktop>
<DrawerMenu
isOpen={open}
onClose={onClose}
onLogoClick={onLogoClick}
root={categories?.[CAT_MENU_DEFAULT_ROOT_CATEGORY]}
itemsKey="categories"
itemsCountKey="onlineSubCategoriesCount"
itemComponent={DrawerMenuItemWithData}
/>
</HideOnDesktop>
{/*TODO: Fix menu to load children lazily.*/}
<HideOnMobile>
<ListMenu
root={categories?.[CAT_MENU_DEFAULT_ROOT_CATEGORY]}
itemsKey="categories"
itemsCountKey="onlineSubCategoriesCount"
contentComponent={ListMenuContentWithData}
/>
</HideOnMobile>
</Header>
</>
) : (
<CheckoutHeader />
)}
</Box>
{!isOnline && <OfflineBanner />}
<AddToCartModalProvider>
<SkipNavContent
css={{
display: 'flex',
flexDirection: 'column',
flex: 1,
outline: 0
}}
>
<Box
as="main"
id="app-main"
role="main"
display="flex"
flexDirection="column"
flex="1"
>
<OfflineBoundary isOnline={isOnline}>
<WrappedComponent {...(props as P)} />
</OfflineBoundary>
</Box>
</SkipNavContent>
{!isCheckout ? <Footer /> : <CheckoutFooter />}
<AuthModal {...(authModal as any)} />
{/*<DntNotification {...dntNotification} />*/}
</AddToCartModalProvider>
</Box>
{(config.activeDataEnabled as boolean) && (
<script
type="text/javascript"
src={getStaticAssetUrl('libs/dwanalytics-22.2.js', {
appExtensionPackageName: '@salesforce/extension-chakra-storefront'
})}
id="dwanalytics"
async={true}
onLoad={trackPage}
></script>
)}
{config.activeDataEnabled && (
<script
src={getStaticAssetUrl('libs/dwac-21.7.js', {
appExtensionPackageName: '@salesforce/extension-chakra-storefront'
})}
type="text/javascript"
id="dwac"
async={true}
></script>
)}
</Box>
)
}
return WithLayout
}
export default withLayout