-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.tsx
292 lines (251 loc) · 9.11 KB
/
index.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
import React, { useState, useEffect, cloneElement } from 'react'
import { Animated, View, BackHandler, TouchableOpacity } from 'react-native'
import { styles } from './styles'
import startTransition, { initialPosition, connect, isTransitioning, isTransitionValid } from './transition'
import { CustomTransition } from './animations'
import { Transition, Screen, State, TransitionInput, type ScreenProps } from './types'
export { Transition, CustomTransition, type ScreenProps }
// All the registered screens.
const screens: { [key: string]: Screen } = {}
// History of the screens visited.
export const history: Screen[] = []
// Useful for tests when rerendering, but not back on first screen.
export const reset = () => history.splice(0, history.length, history[0])
// React hook: const screen = useCurrentScreen()
const currentScreenHookListeners: ((screen: string) => void)[] = []
const updateCurrentScreenHookListeners = (screen: string) =>
currentScreenHookListeners.forEach((listener) => listener(screen))
export const useCurrentScreen = () => {
const initialScreenName = history[history.length - 1].name
const [currentScreen, setCurrentScreen] = useState(initialScreenName)
useEffect(() => {
currentScreenHookListeners.push(setCurrentScreen)
// Clear up old listeners.
return () => {
const index = currentScreenHookListeners.findIndex((listener) => listener === setCurrentScreen)
if (index !== -1) {
currentScreenHookListeners.splice(index, 1)
}
}
}, [])
return currentScreen
}
// Register a screen.
export const register = (
Component: JSX.Element,
name: string,
configuration: { transition?: TransitionInput; background?: string; initial?: boolean } = {
transition: Transition.regular,
background: 'white',
initial: false,
},
) => {
const { transition = Transition.regular, background = 'white', initial } = configuration
const screen: Screen = { Component, transition, background, name }
if (!name) {
return console.error('Reactigation: Trying to register a Component without a name as the second argument.')
}
if (!isTransitionValid(transition, 'register')) {
return
}
// First registered screen will initially be shown.
if (!history.length) {
history.push(screen)
}
if (initial) {
history[0] = screen
}
if (name in screens) {
return console.warn(`Reactigation: Screen "${name}" has already been registered.`)
}
screens[name] = screen
}
export const initial = (name: string) => {
if (!screens[name]) {
return console.warn(`Reactigation: Trying to set initial screen "${name}" which hasn't been registered yet.`)
}
if (history.length === 0) {
return console.error('Reactigation: Trying to set initial screen before any screens have been registered.')
}
history[0] = screens[name]
}
// TODO logs only in development mode.
// Go to certain screen.
export const go = (name: string, transition?: TransitionInput, props?: object) => {
if (isTransitioning()) {
return console.warn('Reactigation: Transition already in progress.')
}
const currentScreen = screens[name]
if (!currentScreen) {
return console.warn(`Reactigation: Screen ${name} wasn't registered.`)
}
if (!transition) {
transition = currentScreen.transition ?? Transition.regular
}
if (!isTransitionValid(transition, 'go')) {
return
}
const previousScreen = history[history.length - 1]
if (previousScreen.name === name) {
return console.warn(`Reactigation: Already on screen ${name}.`)
}
// Make a copy to reuse transition when going back.
const nextScreen = Object.assign({}, currentScreen, {
transition: transition || currentScreen.transition,
props,
})
history.push(nextScreen)
startTransition(nextScreen, previousScreen, nextScreen.transition)
updateCurrentScreenHookListeners(name)
}
// Go back to previous screen.
export const back = (transition?: TransitionInput) => {
if (isTransitioning()) {
return console.warn('Reactigation: Transition already in progress.')
}
if (history.length === 1) {
return console.warn('Reactigation: Only one screen left, cannot go back.')
}
if (transition && !isTransitionValid(transition, 'back')) {
return
}
const lastScreen = history.pop() as Screen
const backTransition = transition || lastScreen.transition // Use reverse of go transition if none specified.
const currentScreen = history[history.length - 1]
startTransition(lastScreen, currentScreen, backTransition, true)
updateCurrentScreenHookListeners(currentScreen.name)
}
export const currentScreen = () => history[history.length - 1].name
// Clear navigation state.
export const destroy = () => {
history.length = 0
for (const key in screens) {
delete screens[key]
}
}
// Go back when the android back button gets pressed.
BackHandler.addEventListener('hardwareBackPress', () => {
back()
// Ignore other registered back handlers.
return true
})
function addHistoryProps(screen: Screen) {
// TODO are those clones truly necessary?
const props = { ...screen.props }
const [bottomScreen, topScreen] = history.slice(-2)
// topScreen missing for history.length === 1
if (topScreen && topScreen.name === screen.name) {
Object.assign(props, topScreen.props ?? {})
}
if (bottomScreen.name === screen.name) {
Object.assign(props, bottomScreen.props ?? {})
}
return props
}
const updateScreenView = (screen: Screen, state: State, isNextScreen: boolean) => {
const newProps = {
backPossible: history.length > 1,
title: screen.name,
...addHistoryProps(screen),
}
if (screen.name in state.renderedScreens) {
const propsChanged = JSON.stringify(newProps) !== JSON.stringify(state.renderedScreens[screen.name].props)
if (isNextScreen && propsChanged) {
// Update rendered screen.
state.renderedScreens[screen.name] = {
screen,
props: newProps,
view: cloneElement(screen.Component, newProps),
}
}
} else {
// Initially render screen.
state.renderedScreens[screen.name] = {
screen,
props: newProps,
view: cloneElement(screen.Component, newProps),
}
}
}
function getScreenPosition(name: string, state: State) {
return {
isTopOrBottomScreen: name === state.Top.name || name === state.Bottom?.name,
isTop: name === state.Top.name,
isBottom: name === state.Bottom?.name,
}
}
const renderScreen = (screen: Screen, state: State) => {
const position = getScreenPosition(screen.name, state)
const isNextScreen = !!((position.isTop && !state.reverse) || (position.isBottom && state.reverse))
if (!(screen.name in state.renderedScreens) && !position.isTopOrBottomScreen) {
// Screen doesn't need to be rendered yet.
return
}
if (position.isTopOrBottomScreen) {
// Only top or bottom screen needs to be added or updated.
updateScreenView(screen, state, isNextScreen)
}
return (
<Animated.View
aria-label={screen.name}
key={screen.name}
style={[
styles.screen,
{ backgroundColor: screen.background },
position.isTop && { left: state.left, top: state.top, opacity: state.opacity },
]}
>
{state.renderedScreens[screen.name].view}
</Animated.View>
)
}
function orderScreens(existingScreens: JSX.Element[], state: State) {
existingScreens.sort((firstScreen, secondScreen) => {
const firstName = firstScreen.props['aria-label']
const secondName = secondScreen.props['aria-label']
const firstPosition = getScreenPosition(firstName, state)
const secondPosition = getScreenPosition(secondName, state)
const getSortPriority = (position: { isTopOrBottomScreen: boolean; isTop: boolean; isBottom: boolean }) => {
if (position.isTop) {
return 3
}
if (position.isBottom) {
return 2
}
return 1
}
return getSortPriority(firstPosition) - getSortPriority(secondPosition)
})
}
// Disable transitions and render only top screen, useful for programmatic tests.
export default ({ headless = process.env.NODE_ENV === 'test' }) => {
const [state, setState] = useState<State>(initialPosition(history[0]))
const afterRender = connect({ setState, state }, headless)
useEffect(afterRender, [afterRender])
if (headless) {
return (
<View style={styles.stretch}>
<View style={[styles.screen, { backgroundColor: state.Top.background }]}>
{cloneElement(state.Top.Component, {
backPossible: history.length > 1,
title: state.Top.name,
...state.Top.props,
})}
</View>
</View>
)
}
const existingScreens = Object.values(screens)
.map((screen) => renderScreen(screen, state))
.filter((screen): screen is NonNullable<typeof screen> => screen !== null && screen !== undefined)
orderScreens(existingScreens, state)
// Add to second last position, to be between top and bottom.
existingScreens.splice(
existingScreens.length - 1,
0,
<View key="backdrop" style={[styles.stretch, state.backdrop ? styles.backdrop : styles.hideBackdrop]}>
<TouchableOpacity style={styles.stretch} onPress={() => back()} />
</View>,
)
return <View style={styles.stretch}>{existingScreens}</View>
}