-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.jsx
238 lines (202 loc) · 6.33 KB
/
index.jsx
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
import "./style.css";
import React, { useCallback, useEffect, useRef, useState } from "react";
let renderPage = () => {};
let currentPosition = history.state?.position || 1;
let checkIsBrowserNavigate = () => {};
let isProgramGoBack = false;
const ANIMATION_DURATION = 200;
export const navigateTo = (to) => {
if (isUrlChanged(to)) {
currentPosition++;
window.history.pushState({ position: currentPosition }, "", to);
checkIsBrowserNavigate(false);
isProgramGoBack = false;
renderPage("forward", to);
}
};
export const replaceTo = (to) => {
if (isUrlChanged(to)) {
window.history.replaceState({ position: currentPosition }, "", to);
checkIsBrowserNavigate(false);
isProgramGoBack = false;
renderPage("replace", to);
}
};
export const goBack = () => {
checkIsBrowserNavigate(false);
isProgramGoBack = true;
window.history.back();
};
// Navigate with component
export const BabyLink = React.memo(({ to, children }) => {
const handleClick = useCallback(
(e) => {
e.preventDefault();
navigateTo(to);
},
[to]
);
return (
<a href={to} onClick={handleClick}>
{children}
</a>
);
});
export const BabyRoutes = React.memo(
({
routes,
defaultRoute = "/",
enableAnimation = true,
bgColor = "white",
maxWidth = "none",
}) => {
const [pageStack, setPageStack] = useState(initPageStack(routes));
const [isBrowserNavigate, setIsBrowserNavigate] = useState(false);
const [animationState, setAnimationState] = useState("none"); // 'none', 'enter', 'active'
const timeoutRef = useRef(null);
renderPage = (newDirection, newPath) => {
if (newDirection === "forward") {
setAnimationState("enter");
setPageStack([
...pageStack,
{ key: newPath, component: getPageComponent(routes, newPath) },
]);
// Use requestAnimationFrame to ensure the 'enter' class is applied before 'active'
requestAnimationFrame(() => {
requestAnimationFrame(() => {
setAnimationState("active");
});
});
} else if (newDirection === "replace") {
setPageStack([
...pageStack.slice(0, pageStack.length - 1),
{ key: newPath, component: getPageComponent(routes, newPath) },
]);
} else {
setPageStack(pageStack.slice(0, pageStack.length - 1));
}
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
useEffect(() => {
const handlePopState = (event) => {
if (!isProgramGoBack) {
setIsBrowserNavigate(true);
}
const newPosition = event.state?.position ?? 0;
renderPage(
newPosition > currentPosition ? "forward" : "backward",
`${window.location.pathname}${window.location.search}`
);
};
window.addEventListener("popstate", handlePopState);
checkIsBrowserNavigate = setIsBrowserNavigate;
setPageStack(initPageStack(routes));
return () => {
window.removeEventListener("popstate", handlePopState);
};
}, [routes]);
useEffect(() => {
if (!pageStack[0]) {
const newStack = initPageStack(routes);
if (newStack.length) {
setPageStack(newStack);
} else {
replaceTo(defaultRoute);
}
}
}, [defaultRoute, pageStack, routes]);
const isAnimationEnabled =
enableAnimation && !(isBrowserNavigate && isIOSBrowser());
return (
<div className="page-container">
{pageStack.map((page, index) => {
const isLast = index === pageStack.length - 1;
const isSecondLast = index === pageStack.length - 2;
let className = "page";
if (isAnimationEnabled) {
if (isLast && animationState !== "none") {
className +=
animationState === "enter"
? " page-enter"
: " page-enter page-enter-active";
} else if (isSecondLast && animationState !== "none") {
className += " page-exit page-exit-active";
}
}
return (
<div
key={page.key}
className={className}
style={{
...(bgColor ? { "--baby-routes-background": bgColor } : {}),
...(maxWidth ? { "--baby-routes-max-width": maxWidth } : {}),
zIndex: index,
display: isLast || isSecondLast ? "block" : "none",
transition: isAnimationEnabled
? `transform ${ANIMATION_DURATION}ms ease`
: "none",
}}
>
<div className="page-content">{page.component}</div>
</div>
);
})}
</div>
);
}
);
function initPageStack(routes) {
return routes[window.location.pathname]
? [
{
key: `${window.location.pathname}${window.location.search}`,
component: getPageComponent(
routes,
`${window.location.pathname}${window.location.search}`
),
},
]
: [];
}
function getPageComponent(routes) {
const { pathname, search } = window.location;
if (routes[pathname]) {
const Component = routes[pathname];
const queryParams = parseSearch(search);
return <Component queryParams={queryParams} />;
}
return null;
}
function parseSearch(search) {
const obj = {};
if (search) {
const searchParams = new URLSearchParams(search);
searchParams.forEach((value, key) => {
obj[key] = value;
});
}
return obj;
}
function isUrlChanged(to) {
const current = `${window.location.pathname}${window.location.search}`;
return current !== to;
}
function isIOSBrowser() {
const userAgent = window.navigator.userAgent.toLowerCase();
const iOS_devices = /iphone|ipad|ipod/;
// Check if it's an iOS device
if (iOS_devices.test(userAgent)) {
return true;
}
// Special check for iPad on iOS 13+ (which reports as Mac)
if (
userAgent.includes("mac") &&
navigator.maxTouchPoints &&
navigator.maxTouchPoints > 2
) {
return true;
}
return false;
}