-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy path__root.tsx
More file actions
485 lines (441 loc) · 13.6 KB
/
Copy path__root.tsx
File metadata and controls
485 lines (441 loc) · 13.6 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
473
474
475
476
477
478
479
480
481
482
483
484
485
import { Env, UserAgent } from '@porto/apps'
import { Button } from '@porto/apps/components'
import * as UI from '@porto/ui'
import {
createRootRoute,
HeadContent,
Outlet,
useLocation,
} from '@tanstack/react-router'
import { Actions, Hooks } from 'porto/remote'
import * as React from 'react'
import * as Dialog from '~/lib/Dialog'
import { EnsureVisibility } from '~/lib/IntersectionObserver'
import { porto } from '~/lib/Porto'
import * as Referrer from '~/lib/Referrer'
import LucideCircleAlert from '~icons/lucide/circle-alert'
import { Layout } from './-components/Layout'
export const Route = createRootRoute({
component: RouteComponent,
head: () => ({
meta: [
{
content: __APP_VERSION__,
name: 'x-app-version',
},
],
}),
})
const env = (
{
anvil: 'anvil',
prod: undefined,
stg: 'staging',
} satisfies Record<Env.Env, string | undefined>
)[Env.get()]
function RouteComponent() {
React.useEffect(() => {
// Note: we already call `porto.ready()` optimistically in `main.tsx`, but
// we should call it here incase it didn't resolve due to a race condition.
porto.ready()
}, [])
const mode = Dialog.useStore((state) => state.mode)
const referrer = Dialog.useStore((state) => state.referrer)
const customTheme = Dialog.useStore((state) => state.customTheme)
const display = Dialog.useStore((state) => state.display)
const verifyStatus = Referrer.useVerify()
const trusted = Referrer.useTrusted(['allow-safari-iframe'])
const { domain, subdomain, icon, url } = React.useMemo(() => {
const hostnameParts = referrer?.url?.hostname.split('.').slice(-3)
const domain = hostnameParts?.slice(-2).join('.')
const subdomain = hostnameParts?.at(-3)
return {
domain,
icon: referrer?.icon,
subdomain,
url: referrer?.url?.toString(),
}
}, [referrer])
const location = useLocation()
const request = Hooks.useRequest(porto)
const [controlledSize, setControlledSize] = React.useState(mode === 'popup')
const heightUpdateCheckTimer =
React.useRef<ReturnType<typeof setTimeout>>(undefined)
const onNextResize = React.useRef<() => void>(() => {})
React.useEffect(() => {
setControlledSize(mode === 'popup')
}, [mode])
const enableEnsureVisibility = mode.includes('iframe') && !trusted
if (!request) return null
return (
<>
<HeadContent />
<style>{customTheme?.tailwindCss}</style>
<UI.Frame
// the color scheme is set from here rather than at the :root level,
// this is because a mismatch between the color scheme of an iframe
// and its parent would make the iframe opaque [1][2]. So the strategy
// is to set the same color scheme at the :root level than outside the
// iframe, and then restoring the color scheme we actually want here.
// [1] https://fvsch.com/transparent-iframes#toc-3
// [2] https://github.com/w3c/csswg-drafts/issues/4772
colorScheme={customTheme?.colorScheme}
mode={
display === 'full'
? {
name: 'full',
variant: controlledSize ? 'content-height' : 'auto',
}
: {
name: 'dialog',
variant: display === 'drawer' ? 'drawer' : 'floating',
}
}
onClose={
mode === 'inline-iframe' || mode === 'popup-standalone'
? undefined
: () => Actions.rejectAll(porto)
}
onHeight={(height) => {
if (controlledSize) {
clearTimeout(heightUpdateCheckTimer.current)
window.removeEventListener('resize', onNextResize.current)
const outerWindowHeight = window.outerHeight - window.innerHeight
const height_ = Math.ceil(height)
heightUpdateCheckTimer.current = setTimeout(() => {
window.removeEventListener('resize', onNextResize.current)
onNextResize.current = () => {
if (height_ !== window.innerHeight) setControlledSize(false)
}
window.addEventListener('resize', onNextResize.current, {
once: true,
})
window.resizeTo(window.outerWidth, height_ + outerWindowHeight)
}, 100) // chrome might be resizing and give us a wrong height on the next resize, so we wait a bit
}
if (
mode !== 'inline-iframe' &&
mode !== 'popup-standalone' &&
mode !== 'page'
)
porto.messenger.send('__internal', {
height: Math.ceil(height),
type: 'resize',
})
}}
screenKey={`${location.pathname}${request?.id}`}
site={{
icon: typeof icon === 'object' ? [icon.light, icon.dark] : icon,
label: (
<div className="mr-auto flex shrink items-center gap-1 overflow-hidden whitespace-nowrap font-normal text-[14px] text-th_frame leading-[22px]">
{url?.startsWith('cli') ? (
referrer?.title
) : url ? (
<div className="flex overflow-hidden" title={url}>
{subdomain && (
<>
<div className="truncate">{subdomain}</div>
<div>.</div>
</>
)}
<div>{domain}</div>
</div>
) : (
'Porto'
)}
</div>
),
tag: env,
verified: verifyStatus.data?.status === 'whitelisted',
}}
visible
>
<CheckError>
<CheckUnsupportedBrowser>
<CheckReferrer>
<EnsureVisibility enabled={enableEnsureVisibility}>
<div
className="flex h-full w-full flex-col"
key={
import.meta.env.MODE !== 'test' ? request?.id : undefined
}
>
<Outlet />
</div>
</EnsureVisibility>
</CheckReferrer>
</CheckUnsupportedBrowser>
</CheckError>
</UI.Frame>
<React.Suspense>
<TanStackRouterDevtools position="bottom-right" />
<TanStackQueryDevtools
buttonPosition="bottom-left"
initialIsOpen={false}
position="left"
/>
</React.Suspense>
</>
)
}
function CheckError(props: CheckError.Props) {
const { children } = props
const error = Dialog.useStore((state) => state.error)
if (!error) return children
const mainAction =
error.action === 'retry-in-popup'
? {
label: 'Try in popup',
onClick: () => {
// clear error state and switch to popup mode
porto.messenger.send('__internal', {
mode: 'popup',
type: 'switch',
})
// prevents screen change while the popup opens
setTimeout(() => {
Dialog.store.setState({ error: null })
}, 100)
},
}
: {
label: 'Close',
onClick: () => Actions.rejectAll(porto),
}
const secondaryAction = error.action !== 'close' && {
label: 'Cancel',
onClick: () => Actions.rejectAll(porto),
}
return (
<Layout>
<Layout.Header className="flex-grow">
<Layout.Header.Default
content={
<div className="space-y-2">
<div>{error.message}</div>
{error.secondaryMessage && (
<div className="text-th_base-secondary">
{error.secondaryMessage}
</div>
)}
</div>
}
icon={LucideCircleAlert}
title={error.title}
variant="warning"
/>
</Layout.Header>
<Layout.Footer>
<Layout.Footer.Actions>
{secondaryAction && (
<UI.Button
data-testid="secondary-action"
onClick={secondaryAction.onClick}
>
{secondaryAction.label}
</UI.Button>
)}
<UI.Button
data-testid="primary-action"
onClick={mainAction.onClick}
variant="primary"
width="grow"
>
{mainAction.label}
</UI.Button>
</Layout.Footer.Actions>
</Layout.Footer>
</Layout>
)
}
declare namespace CheckError {
type Props = {
children: React.ReactNode
}
}
function CheckReferrer(props: CheckReferrer.Props) {
const { children } = props
const [proceed, setProceed] = React.useState(false)
const hostname = Dialog.useStore((state) => state.referrer?.url?.hostname)
const verifyStatus = Referrer.useVerify()
if (proceed) return children
if (verifyStatus.data?.status !== 'blacklisted') return children
return (
<Layout>
<Layout.Header>
<Layout.Header.Default
content={
<>
<span className="font-medium">{hostname}</span> has been flagged
as potentially malicious, and may trick you into signing actions
that may take all your assets.
</>
}
icon={LucideCircleAlert}
title="Malicious website detected"
variant="destructive"
/>
</Layout.Header>
<Layout.Footer>
<Layout.Footer.Actions>
<Button
className="flex-1"
onClick={() => setProceed(true)}
variant="destructive"
>
Proceed anyway
</Button>
<Button className="flex-1" onClick={() => Actions.rejectAll(porto)}>
Close
</Button>
</Layout.Footer.Actions>
</Layout.Footer>
</Layout>
)
}
declare namespace CheckReferrer {
type Props = {
children: React.ReactNode
}
}
const isInAppBrowser = UserAgent.isInAppBrowser()
const isUnsupportedBrowser = UserAgent.isUnsupportedBrowser()
const isUnsupportedCliBrowser = UserAgent.isUnsupportedCliBrowser()
function CheckUnsupportedBrowser(props: CheckUnsupportedBrowser.Props) {
const { children } = props
const cli = Dialog.useStore((state) =>
state.referrer?.url?.toString().startsWith('cli'),
)
const [proceed, setProceed] = React.useState(false)
if (
(!cli || !isUnsupportedCliBrowser) &&
!isInAppBrowser &&
!isUnsupportedBrowser
)
return children
if (proceed) return children
const type = React.useMemo(() => {
if (cli) return 'cli'
if (isInAppBrowser) return 'in-app'
return 'browser'
}, [cli])
const browserName = UserAgent.getInAppBrowserName()
const message = (
<>
{browserName ? (
<>
<span className="font-medium">{browserName}</span>'s in-app
</>
) : (
'In-app'
)}
</>
)
const action = (
<p>
Please switch to a{' '}
<a
className="text-th_base underline"
href="https://porto.sh/sdk/faq#which-browsers-are-supported"
rel="noreferrer"
target="_blank"
>
supported browser
</a>
.
</p>
)
const content = React.useMemo(() => {
if (type === 'cli')
return (
<>
Support for the Porto CLI in this browser is coming soon. <br />
For now, please open this page in{' '}
<span className="font-medium">Chrome</span>,{' '}
<span className="font-medium">Firefox</span>, or{' '}
<span className="font-medium">Edge</span> to continue.
</>
)
if (type === 'in-app')
return (
<>
{message} browser does not support Porto. Please open this page in
your device's browser.
<br />
{action}
</>
)
if (type === 'browser')
return (
<>
This browser does not support Porto. Please switch to a supported
browser.
<br />
{action}
</>
)
}, [message, type])
return (
<Layout>
<Layout.Header>
<Layout.Header.Default
content={content}
icon={LucideCircleAlert}
title="Unsupported browser"
variant="destructive"
/>
</Layout.Header>
{type === 'cli' && (
<Layout.Footer>
<Layout.Footer.Actions>
<Button
className="flex-1"
onClick={() => {
navigator.clipboard.writeText(window.location.href)
}}
>
Copy page link
</Button>
</Layout.Footer.Actions>
</Layout.Footer>
)}
{type !== 'cli' && (
<Layout.Footer>
<Layout.Footer.Actions>
<Button
className="flex-1"
onClick={() => setProceed(true)}
variant="destructive"
>
Proceed anyway
</Button>
<Button className="flex-1" onClick={() => Actions.rejectAll(porto)}>
Close
</Button>
</Layout.Footer.Actions>
</Layout.Footer>
)}
</Layout>
)
}
declare namespace CheckUnsupportedBrowser {
type Props = {
children: React.ReactNode
}
}
const TanStackRouterDevtools =
import.meta.env.PROD || window !== window.parent || Boolean(window.opener)
? () => null
: React.lazy(() =>
import('@tanstack/react-router-devtools').then((res) => ({
default: res.TanStackRouterDevtools,
})),
)
const TanStackQueryDevtools =
import.meta.env.PROD || window !== window.parent || Boolean(window.opener)
? () => null
: React.lazy(() =>
import('@tanstack/react-query-devtools').then((res) => ({
default: res.ReactQueryDevtools,
})),
)