-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathApp.tsx
More file actions
407 lines (370 loc) · 15.5 KB
/
App.tsx
File metadata and controls
407 lines (370 loc) · 15.5 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
import '@ionic/react/css/core.css'
/* Basic CSS for apps built with Ionic */
import '@ionic/react/css/normalize.css'
import '@ionic/react/css/structure.css'
import '@ionic/react/css/typography.css'
/* Optional CSS utils that can be commented out */
import '@ionic/react/css/padding.css'
import '@ionic/react/css/float-elements.css'
import '@ionic/react/css/text-alignment.css'
import '@ionic/react/css/text-transformation.css'
import '@ionic/react/css/flex-utils.css'
import '@ionic/react/css/display.css'
import '@ionic/react/css/palettes/dark.class.css'
import { AnimatePresence } from 'framer-motion'
import { ConfigContext } from './providers/config'
import { IonApp, IonPage, IonTab, IonTabBar, IonTabButton, IonTabs, setupIonicReact } from '@ionic/react'
import { NavigationContext, pageComponent, Pages, Tabs, type NavigationDirection } from './providers/navigation'
import { useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { isInAppBrowser } from './lib/browser'
import { detectJSCapabilities } from './lib/jsCapabilities'
import { OptionsContext } from './providers/options'
import { WalletContext } from './providers/wallet'
import { FlowContext } from './providers/flow'
import { SettingsOptions } from './lib/types'
import { AspContext } from './providers/asp'
import { hapticLight } from './lib/haptics'
import { setBootAnimActive as syncBootAnimFlag } from './lib/logoAnchor'
import { PageTransition } from './components/PageTransition'
import SettingsIcon from './icons/Settings'
import BootError from './components/BootError'
import LoadingLogo from './components/LoadingLogo'
import PillNavbarOverlay from './components/PillNavbarOverlay'
import FlexCol from './components/FlexCol'
import WalletIcon from './icons/Wallet'
import AppsIcon from './icons/Apps'
import Focusable from './components/Focusable'
import { useReducedMotion } from './hooks/useReducedMotion'
import { useLoadingStatus } from './hooks/useLoadingStatus'
import { defaultPassword } from './lib/constants'
import { consoleError } from './lib/logs'
setupIonicReact()
const PASSWORDLESS_AUTO_RELOAD_KEY = 'passwordless-auto-reload-attempted'
export const appReloader = {
reload: () => window.location.reload(),
}
function PageAnimWrapper({
children,
animated,
direction,
}: {
children: ReactNode
animated: boolean
direction: NavigationDirection | 'none'
}) {
if (!animated) return <>{children}</>
return (
<AnimatePresence mode='sync' initial={false} custom={direction}>
{children}
</AnimatePresence>
)
}
const animClass = 'tab-anim-pop'
function AnimatedTabIcon({ children, animating }: { children: React.ReactNode; animating: boolean }) {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
if (!animating || !ref.current) return
const el = ref.current
el.classList.remove(animClass)
void el.offsetWidth // Force reflow so removing + re-adding the class triggers the animation
el.classList.add(animClass)
const handleEnd = () => el.classList.remove(animClass)
el.addEventListener('animationend', handleEnd)
return () => el.removeEventListener('animationend', handleEnd)
}, [animating])
return (
<div ref={ref} className='tab-icon-animated'>
{children}
</div>
)
}
export default function App() {
const { aspInfo } = useContext(AspContext)
const { configLoaded } = useContext(ConfigContext)
const { direction, navigate, screen, tab } = useContext(NavigationContext)
const { initInfo } = useContext(FlowContext)
const { option, setOption } = useContext(OptionsContext)
const { authState, unlockWallet, walletLoaded, initialized, wallet, dataReady, loadError } = useContext(WalletContext)
const loadingStatus = useLoadingStatus()
const isIAB = useMemo(() => isInAppBrowser(), [])
const [isCapable, setIsCapable] = useState(false)
const [jsCapabilitiesChecked, setJsCapabilitiesChecked] = useState(false)
const [animatingTab, setAnimatingTab] = useState<string | null>(null)
const [bootAnimActive, setBootAnimActive] = useState(false)
// Syncs the external store before React re-renders, so Wallet reads
// the correct value on the same frame LoadingLogo unmounts.
const updateBootAnim = useCallback((active: boolean) => {
syncBootAnimFlag(active)
setBootAnimActive(active)
}, [])
const [bootAnimDone, setBootAnimDone] = useState(false)
const [bootExitMode, setBootExitMode] = useState<'fly-to-target' | 'fly-up'>('fly-up')
// refs for the tabs to be able to programmatically activate them
const appsRef = useRef<HTMLIonTabElement>(null)
const walletRef = useRef<HTMLIonTabElement>(null)
const settingsRef = useRef<HTMLIonTabElement>(null)
const passwordlessBootAttempted = useRef(false)
const passwordlessReloadTimer = useRef<ReturnType<typeof setTimeout>>()
// lock screen orientation to portrait
// this is a workaround for the issue with the screen orientation API
// not being supported in some browsers
const orientation = window.screen.orientation as any
if (orientation && typeof orientation.lock === 'function') {
orientation.lock('portrait').catch(() => {})
}
// Check JavaScript capabilities on mount
useEffect(() => {
detectJSCapabilities()
.then((res) => setIsCapable(res.isSupported))
.catch(() => setIsCapable(false))
.finally(() => setJsCapabilitiesChecked(true))
}, [])
// Global escape key to go back to wallet
useEffect(() => {
if (!navigate) return
const handleGlobalDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') navigate(Pages.Wallet)
}
window.addEventListener('keydown', handleGlobalDown)
return () => window.removeEventListener('keydown', handleGlobalDown)
}, [navigate])
useEffect(() => {
if (isIAB) return navigate(Pages.InAppBrowser)
if (aspInfo.unreachable) return navigate(Pages.Unavailable)
if (jsCapabilitiesChecked && !isCapable) return navigate(Pages.Unavailable)
// avoid redirect if the user is still setting up the wallet
if (initInfo.password || initInfo.privateKey) return
if (!walletLoaded) return navigate(Pages.Loading)
// dev auto-init: stay on loading screen while VITE_DEV_NSEC initializes the wallet
if (import.meta.env.DEV && import.meta.env.VITE_DEV_NSEC && !initialized) return
if (!wallet.pubkey) return navigate(Pages.Init)
if (authState === 'locked') return navigate(Pages.Unlock)
}, [walletLoaded, wallet.pubkey, authState, initInfo, aspInfo.unreachable, jsCapabilitiesChecked, isCapable])
// for some reason you need to manually set the active tab
// if you are coming from a page in a different tab
useEffect(() => {
switch (tab) {
case Tabs.Wallet:
walletRef.current?.setActive()
walletRef.current?.classList.remove('tab-hidden')
appsRef.current?.classList.add('tab-hidden')
settingsRef.current?.classList.add('tab-hidden')
break
case Tabs.Apps:
appsRef.current?.setActive()
appsRef.current?.classList.remove('tab-hidden')
walletRef.current?.classList.add('tab-hidden')
settingsRef.current?.classList.add('tab-hidden')
break
case Tabs.Settings:
settingsRef.current?.setActive()
settingsRef.current?.classList.remove('tab-hidden')
walletRef.current?.classList.add('tab-hidden')
appsRef.current?.classList.add('tab-hidden')
break
default:
break
}
}, [tab])
const triggerTabAnim = useCallback((tabName: string) => {
setAnimatingTab(null)
requestAnimationFrame(() => setAnimatingTab(tabName))
}, [])
const handleWallet = () => {
triggerTabAnim('wallet')
hapticLight()
navigate(Pages.Wallet)
}
const handleApps = () => {
triggerTabAnim('apps')
hapticLight()
navigate(Pages.Apps)
}
const handleSettings = () => {
triggerTabAnim('settings')
hapticLight()
setOption(SettingsOptions.Menu)
navigate(Pages.Settings)
}
const prefersReduced = useReducedMotion()
const effectiveDirection = prefersReduced ? 'none' : direction
// New users (no wallet in storage) skip straight to Init — the logo morph animation
// serves as the intro visual while ASP and JS capability checks resolve in the background.
// Init doesn't need ASP or crypto until "Create wallet" is clicked.
const aspReady = aspInfo.signerPubkey || aspInfo.unreachable
const isNewUser = walletLoaded && !wallet.pubkey
const allChecksReady = jsCapabilitiesChecked && configLoaded && aspReady
const hasStoredWallet = walletLoaded && !!wallet.pubkey
const shouldShowUnlock = hasStoredWallet && authState === 'locked'
// Hold the loading screen during boot until wallet data is ready.
// Skip during the init/connect flow (creating or restoring a wallet) so the
// Connect component stays mounted and can run swap recovery before navigating.
const isInInitFlow = !!(initInfo.password || initInfo.privateKey)
const shouldHoldOnLoading = hasStoredWallet && (!initialized || !dataReady) && authState !== 'locked' && !isInInitFlow
useEffect(() => {
passwordlessBootAttempted.current = false
}, [wallet.pubkey, authState])
useEffect(() => {
return () => {
if (passwordlessReloadTimer.current) clearTimeout(passwordlessReloadTimer.current)
}
}, [])
useEffect(() => {
if (!allChecksReady) return
if (!wallet.pubkey || initialized) return
if (authState !== 'passwordless') return
if (passwordlessBootAttempted.current) return
passwordlessBootAttempted.current = true
unlockWallet(defaultPassword).catch((err) => {
consoleError(err, 'error auto-initializing passwordless wallet')
try {
if (sessionStorage.getItem(PASSWORDLESS_AUTO_RELOAD_KEY)) return
sessionStorage.setItem(PASSWORDLESS_AUTO_RELOAD_KEY, 'true')
passwordlessReloadTimer.current = setTimeout(() => appReloader.reload(), 1_000)
} catch {
// ignore session storage errors; keep the app on loading instead of retry-looping
}
})
}, [allChecksReady, wallet.pubkey, initialized, authState, unlockWallet])
const page = !(allChecksReady || isNewUser)
? Pages.Loading
: shouldHoldOnLoading
? Pages.Loading
: shouldShowUnlock
? Pages.Unlock
: screen
// Boot animation: persists on Loading, then flies to the LogoIcon position when
// Wallet is reached. For any other destination (Unlock, Init, etc.), exits with fly-up.
// Skip in dev with VITE_DEV_NSEC — the fast auto-init races with the animation.
useEffect(() => {
if (import.meta.env.DEV && import.meta.env.VITE_DEV_NSEC) return
if (page === Pages.Loading && !bootAnimActive) {
setBootAnimDone(false)
setBootExitMode('fly-up')
updateBootAnim(true)
return
}
if (!bootAnimActive || bootAnimDone) return
if (page === Pages.Wallet) {
setBootExitMode('fly-to-target')
setBootAnimDone(true)
return
}
if (page !== Pages.Loading) {
setBootExitMode('fly-up')
setBootAnimDone(true)
}
}, [page, bootAnimActive, bootAnimDone])
const handleBootAnimComplete = useCallback(() => {
updateBootAnim(false)
}, [updateBootAnim])
const comp = page === Pages.Loading ? null : pageComponent(page)
const isSettingsRoot = screen === Pages.Settings && option === SettingsOptions.Menu
const showNavbar = page === screen && (screen === Pages.Wallet || screen === Pages.Apps || isSettingsRoot)
return (
<IonApp className={showNavbar ? 'has-pill-navbar' : undefined}>
<IonPage>
{tab === Tabs.None ? (
<div className='page-transition-container'>
<PageAnimWrapper animated={!prefersReduced} direction={effectiveDirection}>
<PageTransition key={String(page)} direction={direction} pageKey={String(page)}>
{comp}
</PageTransition>
</PageAnimWrapper>
</div>
) : (
<>
<IonTabs>
<IonTab ref={walletRef} tab={Tabs.Wallet}>
<div className='page-transition-container'>
<PageAnimWrapper animated={!prefersReduced} direction={effectiveDirection}>
{tab === Tabs.Wallet && (
<PageTransition key={String(page)} direction={direction} pageKey={String(page)}>
{comp}
</PageTransition>
)}
</PageAnimWrapper>
</div>
</IonTab>
<IonTab ref={appsRef} tab={Tabs.Apps}>
<div className='page-transition-container'>
<PageAnimWrapper animated={!prefersReduced} direction={effectiveDirection}>
{tab === Tabs.Apps && (
<PageTransition key={String(page)} direction={direction} pageKey={String(page)}>
{comp}
</PageTransition>
)}
</PageAnimWrapper>
</div>
</IonTab>
<IonTab ref={settingsRef} tab={Tabs.Settings}>
<div className='page-transition-container'>
<PageAnimWrapper animated={!prefersReduced} direction={effectiveDirection}>
{tab === Tabs.Settings && (
<PageTransition key={String(page)} direction={direction} pageKey={String(page)}>
{comp}
</PageTransition>
)}
</PageAnimWrapper>
</div>
</IonTab>
<IonTabBar slot='bottom'>
<IonTabButton tab={Tabs.Wallet} onClick={handleWallet} selected={tab === Tabs.Wallet}>
<Focusable>
<FlexCol centered gap='6px' padding='5px'>
<AnimatedTabIcon animating={animatingTab === 'wallet'}>
<WalletIcon />
</AnimatedTabIcon>
Wallet
</FlexCol>
</Focusable>
</IonTabButton>
<IonTabButton tab={Tabs.Apps} onClick={handleApps} selected={tab === Tabs.Apps}>
<Focusable>
<FlexCol centered gap='6px' padding='5px'>
<AnimatedTabIcon animating={animatingTab === 'apps'}>
<AppsIcon />
</AnimatedTabIcon>
Apps
</FlexCol>
</Focusable>
</IonTabButton>
<IonTabButton tab={Tabs.Settings} onClick={handleSettings} selected={tab === Tabs.Settings}>
<Focusable>
<FlexCol centered gap='6px' padding='5px'>
<AnimatedTabIcon animating={animatingTab === 'settings'}>
<SettingsIcon />
</AnimatedTabIcon>
Settings
</FlexCol>
</Focusable>
</IonTabButton>
</IonTabBar>
</IonTabs>
</>
)}
</IonPage>
{tab !== Tabs.None && !bootAnimActive && (
<PillNavbarOverlay
visible={showNavbar}
activeTab={tab}
onWalletClick={handleWallet}
onAppsClick={handleApps}
onSettingsClick={handleSettings}
/>
)}
{bootAnimActive ? (
loadError ? (
<BootError />
) : (
<LoadingLogo
text={loadingStatus}
exitMode={bootExitMode}
done={bootAnimDone}
onExitComplete={handleBootAnimComplete}
/>
)
) : null}
</IonApp>
)
}