-
Notifications
You must be signed in to change notification settings - Fork 285
/
Copy path($locale).account.tsx
287 lines (258 loc) · 6.74 KB
/
($locale).account.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
import {
Await,
Form,
Outlet,
useLoaderData,
useMatches,
useOutlet,
} from '@remix-run/react';
import {Suspense} from 'react';
import {
json,
defer,
redirect,
type LoaderArgs,
type AppLoadContext,
} from '@shopify/remix-oxygen';
import {flattenConnection} from '@shopify/hydrogen';
import type {
CustomerDetailsFragment,
OrderCardFragment,
} from 'storefrontapi.generated';
import {
Button,
OrderCard,
PageHeader,
Text,
AccountDetails,
AccountAddressBook,
Modal,
ProductSwimlane,
} from '~/components';
import {FeaturedCollections} from '~/components/FeaturedCollections';
import {usePrefixPathWithLocale} from '~/lib/utils';
import {CACHE_NONE, routeHeaders} from '~/data/cache';
import {ORDER_CARD_FRAGMENT} from '~/components/OrderCard';
import {
getFeaturedData,
type FeaturedData,
} from './($locale).featured-products';
import {doLogout} from './($locale).account.logout';
// Combining json + Response + defer in a loader breaks the
// types returned by useLoaderData. This is a temporary fix.
type TmpRemixFix = ReturnType<typeof defer<{isAuthenticated: false}>>;
export const headers = routeHeaders;
export async function loader({request, context, params}: LoaderArgs) {
const {pathname} = new URL(request.url);
const locale = params.locale;
const customerAccessToken = await context.session.get('customerAccessToken');
const isAuthenticated = Boolean(customerAccessToken);
const loginPath = locale ? `/${locale}/account/login` : '/account/login';
const isAccountPage = /^\/account\/?$/.test(pathname);
if (!isAuthenticated) {
if (isAccountPage) {
return redirect(loginPath) as unknown as TmpRemixFix;
}
// pass through to public routes
return json({isAuthenticated: false}) as unknown as TmpRemixFix;
}
const customer = await getCustomer(context, customerAccessToken);
const heading = customer
? customer.firstName
? `Welcome, ${customer.firstName}.`
: `Welcome to your account.`
: 'Account Details';
return defer(
{
isAuthenticated,
customer,
heading,
featuredData: getFeaturedData(context.storefront),
},
{
headers: {
'Cache-Control': CACHE_NONE,
},
},
);
}
export default function Authenticated() {
const data = useLoaderData<typeof loader>();
const outlet = useOutlet();
const matches = useMatches();
// routes that export handle { renderInModal: true }
const renderOutletInModal = matches.some((match) => {
return match?.handle?.renderInModal;
});
// Public routes
if (!data.isAuthenticated) {
return <Outlet />;
}
// Authenticated routes
if (outlet) {
if (renderOutletInModal) {
return (
<>
<Modal cancelLink="/account">
<Outlet context={{customer: data.customer}} />
</Modal>
<Account {...data} />
</>
);
} else {
return <Outlet context={{customer: data.customer}} />;
}
}
return <Account {...data} />;
}
interface AccountType {
customer: CustomerDetailsFragment;
featuredData: Promise<FeaturedData>;
heading: string;
}
function Account({customer, heading, featuredData}: AccountType) {
const orders = flattenConnection(customer.orders);
const addresses = flattenConnection(customer.addresses);
return (
<>
<PageHeader heading={heading}>
<Form method="post" action={usePrefixPathWithLocale('/account/logout')}>
<button type="submit" className="text-primary/50">
Sign out
</button>
</Form>
</PageHeader>
{orders && <AccountOrderHistory orders={orders} />}
<AccountDetails customer={customer} />
<AccountAddressBook addresses={addresses} customer={customer} />
{!orders.length && (
<Suspense>
<Await
resolve={featuredData}
errorElement="There was a problem loading featured products."
>
{(data) => (
<>
<FeaturedCollections
title="Popular Collections"
collections={data.featuredCollections}
/>
<ProductSwimlane products={data.featuredProducts} />
</>
)}
</Await>
</Suspense>
)}
</>
);
}
type OrderCardsProps = {
orders: OrderCardFragment[];
};
function AccountOrderHistory({orders}: OrderCardsProps) {
return (
<div className="mt-6">
<div className="grid w-full gap-4 p-4 py-6 md:gap-8 md:p-8 lg:p-12">
<h2 className="font-bold text-lead">Order History</h2>
{orders?.length ? <Orders orders={orders} /> : <EmptyOrders />}
</div>
</div>
);
}
function EmptyOrders() {
return (
<div>
<Text className="mb-1" size="fine" width="narrow" as="p">
You haven't placed any orders yet.
</Text>
<div className="w-48">
<Button
className="w-full mt-2 text-sm"
variant="secondary"
to={usePrefixPathWithLocale('/')}
>
Start Shopping
</Button>
</div>
</div>
);
}
function Orders({orders}: OrderCardsProps) {
return (
<ul className="grid grid-flow-row grid-cols-1 gap-2 gap-y-6 md:gap-4 lg:gap-6 false sm:grid-cols-3">
{orders.map((order) => (
<OrderCard order={order} key={order.id} />
))}
</ul>
);
}
const CUSTOMER_QUERY = `#graphql
query CustomerDetails(
$customerAccessToken: String!
$country: CountryCode
$language: LanguageCode
) @inContext(country: $country, language: $language) {
customer(customerAccessToken: $customerAccessToken) {
...CustomerDetails
}
}
fragment AddressPartial on MailingAddress {
id
formatted
firstName
lastName
company
address1
address2
country
province
city
zip
phone
}
fragment CustomerDetails on Customer {
firstName
lastName
phone
email
defaultAddress {
...AddressPartial
}
addresses(first: 6) {
edges {
node {
...AddressPartial
}
}
}
orders(first: 250, sortKey: PROCESSED_AT, reverse: true) {
edges {
node {
...OrderCard
}
}
}
}
${ORDER_CARD_FRAGMENT}
` as const;
export async function getCustomer(
context: AppLoadContext,
customerAccessToken: string,
) {
const {storefront} = context;
const data = await storefront.query(CUSTOMER_QUERY, {
variables: {
customerAccessToken,
country: context.storefront.i18n.country,
language: context.storefront.i18n.language,
},
cache: storefront.CacheNone(),
});
/**
* If the customer failed to load, we assume their access token is invalid.
*/
if (!data || !data.customer) {
throw await doLogout(context);
}
return data.customer;
}