-
Notifications
You must be signed in to change notification settings - Fork 0
/
root.tsx
522 lines (477 loc) · 12.1 KB
/
root.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
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
import {
defer,
type LinksFunction,
type LoaderArgs,
type AppLoadContext,
SerializeFrom,
} from '@shopify/remix-oxygen';
import {
Links,
Meta,
Outlet,
Scripts,
LiveReload,
ScrollRestoration,
useLoaderData,
type ShouldRevalidateFunction,
useLocation,
useRouteError,
useRouteLoaderData,
isRouteErrorResponse,
useMatches,
} from '@remix-run/react';
import styles from './styles/tailwind.css';
import favicon from '../public/favicon.png';
import {Layout} from './components/Layout';
import {seoPayload} from '~/lib/seo.server';
//from shopify demo-store templates
import invariant from 'tiny-invariant';
import {DEFAULT_LOCALE, getCartId, parseMenu} from './lib/utils';
import {
ShopifySalesChannel,
Seo,
useNonce,
parseGid,
Script,
} from '@shopify/hydrogen';
import {useAnalytics} from './hooks/useAnalytics';
import {cssBundleHref} from '@remix-run/css-bundle';
//SLEDGE PACKAGE
import {SledgeProvider} from '@sledge-app/core';
import sledgeCss from '@sledge-app/core/style.css';
//Sledge Custom Css
import sledgeDarkCss from '~/styles/sledge-dark.css';
import {useEffect} from 'react';
import * as gtag from '~/lib/gtags.client';
import {GenericError} from './components/Pages/GenericError';
import {NotFound} from './components/Pages/NotFound';
// This is important to avoid re-fetching root queries on sub-navigations
export const shouldRevalidate: ShouldRevalidateFunction = ({
formMethod,
currentUrl,
nextUrl,
}) => {
// revalidate when a mutation is performed e.g add to cart, login...
if (formMethod && formMethod !== 'GET') {
return true;
}
// revalidate when manually revalidating via useRevalidator
if (currentUrl.toString() === nextUrl.toString()) {
return true;
}
return false;
};
export const links: LinksFunction = () => {
return [
{rel: 'stylesheet', href: styles},
...(cssBundleHref ? [{rel: 'stylesheet', href: cssBundleHref}] : []),
{rel: 'stylesheet', href: sledgeCss},
{rel: 'stylesheet', href: sledgeDarkCss},
{
rel: 'preconnect',
href: 'https://cdn.shopify.com',
},
{
rel: 'preconnect',
href: 'https://shop.app',
},
{rel: 'icon', type: 'image/svg+xml', href: favicon},
];
};
export const useRootLoaderData = () => {
const [root] = useMatches();
return root?.data as SerializeFrom<typeof loader>;
};
export async function loader({request, context}: LoaderArgs) {
const {session, storefront, cart} = context;
const cartId = getCartId(request);
const [customerAccessToken, layout] = await Promise.all([
session.get('customerAccessToken'),
getLayoutData(context),
]);
const seo = seoPayload.root({shop: layout.shop, url: request.url});
const {customer} = await storefront.query(CUSTOMER_QUERY, {
variables: {
customerAccessToken: customerAccessToken ? customerAccessToken : '',
country: context.storefront.i18n.country,
language: context.storefront.i18n.language,
},
cache: storefront.CacheNone(),
});
const gaTrackingId = context.env.GA_TRACKING_ID;
return defer({
isLoggedIn: Boolean(customerAccessToken),
customer,
layout,
sledgeApiKey: context.env.SLEDGE_API_KEY,
sledgeInstantSearchApiKey: context.env.SLEDGE_INSTANT_SEARCH_API_KEY,
selectedLocale: storefront.i18n,
cart: cartId ? getCart(context, cartId) : undefined,
analytics: {
shopifySalesChannel: ShopifySalesChannel.hydrogen,
shopId: layout.shop.id,
},
seo,
gaTrackingId,
});
}
export default function App() {
const nonce = useNonce();
const {
selectedLocale,
layout,
customer,
sledgeApiKey,
sledgeInstantSearchApiKey,
} = useLoaderData<typeof loader>();
const locale = selectedLocale ?? DEFAULT_LOCALE;
const hasUserConsent = true;
const {pathname} = useLocation();
let productClass = '';
if (pathname.split('/').length && pathname.split('/')[1] === 'products')
productClass = 'template-product';
useAnalytics(hasUserConsent);
return (
<html lang={locale.language}>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<Seo />
<Meta />
<Links />
</head>
<body className={`bg-dark text-white antialiased ${productClass}`}>
<GoogleAnalyticsScript />
<script src="https://cdn.jsdelivr.net/npm/tsparticles-confetti@2.12.0/tsparticles.confetti.bundle.min.js" />
<SledgeProvider
apiKey={sledgeApiKey}
instantSearchApiKey={sledgeInstantSearchApiKey}
userId={parseGid(customer?.id).id}
userEmail={customer?.email}
userFullname={
customer?.firstName || customer?.lastName
? (customer?.firstName ? customer?.firstName + ' ' : '') +
(customer?.lastName ? customer?.lastName : '')
: ''
}
>
<Layout key={`${locale.language}-${locale.country}`} layout={layout}>
<Outlet />
</Layout>
<ScrollRestoration nonce={nonce} />
<Scripts nonce={nonce} />
<LiveReload nonce={nonce} />
</SledgeProvider>
</body>
</html>
);
}
export function ErrorBoundary({error}: {error: Error}) {
const nonce = useNonce();
const routeError = useRouteError();
const rootData = useRootLoaderData();
const locale = rootData?.selectedLocale ?? DEFAULT_LOCALE;
const isRouteError = isRouteErrorResponse(routeError);
let title = 'Whoops! Something Wrong.';
let pageType = 'page';
if (isRouteError) {
title = 'Not found';
if (routeError.status === 404) pageType = routeError.data || pageType;
}
return (
<html className="h-full" lang={locale.language}>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>{title}</title>
<Meta />
<Links />
</head>
<body className="bg-dark h-full">
<div className="min-h-screen h-full lg:h-fit">
{isRouteError ? (
<>
{routeError.status === 404 ? (
<NotFound type={pageType} />
) : (
<GenericError
error={{message: `${routeError.status} ${routeError.data}`}}
/>
)}
</>
) : (
<GenericError error={error instanceof Error ? error : undefined} />
)}
</div>
<ScrollRestoration nonce={nonce} />
<Scripts nonce={nonce} />
<LiveReload nonce={nonce} />
</body>
</html>
);
}
export function GoogleAnalyticsScript() {
const {gaTrackingId} = useLoaderData<typeof loader>();
const location = useLocation();
useEffect(() => {
if (gaTrackingId?.length) {
gtag.pageview(location.pathname, gaTrackingId);
}
}, [location.pathname, gaTrackingId]);
return !gaTrackingId ? null : (
<>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${gaTrackingId}`}
/>
<Script
async
id="gtag-init"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${gaTrackingId}', {
page_path: window.location.pathname,
});
`,
}}
/>
</>
);
}
async function getLayoutData({storefront, env}: AppLoadContext) {
const data = await storefront.query(LAYOUT_QUERY, {
variables: {
headerMenuHandle: 'main-menu',
footerMenuHandle: 'footer',
language: storefront.i18n.language,
},
});
invariant(data, 'No data returned from Shopify API');
/*
Modify specific links/routes (optional)
@see: https://shopify.dev/api/storefront/unstable/enums/MenuItemType
e.g here we map:
- /blogs/news -> /news
- /blog/news/blog-post -> /news/blog-post
- /collections/all -> /products
*/
const customPrefixes = {BLOG: '', CATALOG: 'products'};
const headerMenu = data?.headerMenu
? parseMenu(
data.headerMenu,
data.shop.primaryDomain.url,
env,
customPrefixes,
)
: undefined;
const footerMenu = data?.footerMenu
? parseMenu(
data.footerMenu,
data.shop.primaryDomain.url,
env,
customPrefixes,
)
: undefined;
return {shop: data.shop, headerMenu, footerMenu};
}
export async function getCart({storefront}: AppLoadContext, cartId: string) {
invariant(storefront, 'missing storefront client in cart query');
const {cart} = await storefront.query(CART_QUERY, {
variables: {
cartId,
country: storefront.i18n.country,
language: storefront.i18n.language,
},
cache: storefront.CacheNone(),
});
return cart;
}
const LAYOUT_QUERY = `#graphql
query layout(
$language: LanguageCode
$headerMenuHandle: String!
$footerMenuHandle: String!
) @inContext(language: $language) {
shop {
...Shop
}
headerMenu: menu(handle: $headerMenuHandle) {
...Menu
}
footerMenu: menu(handle: $footerMenuHandle) {
...Menu
}
}
fragment Shop on Shop {
id
name
description
primaryDomain {
url
}
brand {
logo {
image {
url
}
}
}
}
fragment MenuItem on MenuItem {
id
resourceId
tags
title
type
url
}
fragment ChildMenuItem on MenuItem {
...MenuItem
}
fragment ParentMenuItem on MenuItem {
...MenuItem
items {
...ChildMenuItem
}
}
fragment Menu on Menu {
id
items {
...ParentMenuItem
}
}
` as const;
const CART_QUERY = `#graphql
query cartQuery($cartId: ID!, $country: CountryCode, $language: LanguageCode)
@inContext(country: $country, language: $language) {
cart(id: $cartId) {
...CartFragment
}
}
fragment CartFragment on Cart {
id
checkoutUrl
totalQuantity
buyerIdentity {
countryCode
customer {
id
email
firstName
lastName
displayName
}
email
phone
}
lines(first: 100) {
edges {
node {
id
quantity
attributes {
key
value
}
cost {
totalAmount {
amount
currencyCode
}
amountPerQuantity {
amount
currencyCode
}
compareAtAmountPerQuantity {
amount
currencyCode
}
}
merchandise {
... on ProductVariant {
id
availableForSale
sku
quantityAvailable
compareAtPrice {
...MoneyFragment
}
price {
...MoneyFragment
}
requiresShipping
title
image {
...ImageFragment
}
product {
handle
vendor
title
id
}
selectedOptions {
name
value
}
}
}
}
}
}
cost {
subtotalAmount {
...MoneyFragment
}
totalAmount {
...MoneyFragment
}
totalDutyAmount {
...MoneyFragment
}
totalTaxAmount {
...MoneyFragment
}
}
note
attributes {
key
value
}
discountCodes {
code
}
}
fragment MoneyFragment on MoneyV2 {
currencyCode
amount
}
fragment ImageFragment on Image {
id
url
altText
width
height
}
` as const;
const CUSTOMER_QUERY = `#graphql
query CustomerDetails(
$customerAccessToken: String!
$country: CountryCode
$language: LanguageCode
) @inContext(country: $country, language: $language) {
customer(customerAccessToken: $customerAccessToken) {
...CustomerDetails
}
}
fragment CustomerDetails on Customer {
id
firstName
lastName
phone
email
}
` as const;