| 222 | }; |
| 223 | |
| 224 | export const recordShellRoute = ( |
| 225 | pathname: string, |
| 226 | key: string, |
| 227 | arrival?: DocumentArrival, |
| 228 | ): void => { |
| 229 | const path = withoutLayoutVariantPrefix(pathname); |
| 230 | const stack = readStack(); |
| 231 | const entry = { key, path }; |
| 232 | const known = stack.routes.findIndex((route) => route.key === key); |
| 233 | |
| 234 | // A replace keeps its key, a back or forward returns to one. |
| 235 | if (known !== -1) { |
| 236 | stack.routes[known] = entry; |
| 237 | writeStack({ routes: stack.routes, pointer: known }); |
| 238 | return; |
| 239 | } |
| 240 | |
| 241 | // A loaded document gets a fresh key from Next, so the kind of load says |
| 242 | // which entry it is: the same one on a reload, a neighbour on a back or |
| 243 | // forward across documents. |
| 244 | if (arrival === 'reload' && stack.routes[stack.pointer]) { |
| 245 | stack.routes[stack.pointer] = entry; |
| 246 | writeStack(stack); |
| 247 | return; |
| 248 | } |
| 249 | if (arrival === 'back_forward') { |
| 250 | const at = |
| 251 | stack.routes[stack.pointer]?.path === path |
| 252 | ? stack.pointer |
| 253 | : nearestWithPath(stack, path); |
| 254 | if (at !== -1) { |
| 255 | stack.routes[at] = entry; |
| 256 | writeStack({ routes: stack.routes, pointer: at }); |
| 257 | return; |
| 258 | } |
| 259 | } |
| 260 | // Arriving from another site starts over: what this tab held before is |
| 261 | // no longer what back leads to. |
| 262 | if (arrival && cameFromOutside()) { |
| 263 | writeStack({ routes: [entry], pointer: 0 }); |
| 264 | return; |
| 265 | } |
| 266 | |
| 267 | const routes = stack.routes |
| 268 | .slice(0, stack.pointer + 1) |
| 269 | .concat(entry) |
| 270 | .slice(-stackLimit); |
| 271 | writeStack({ routes, pointer: routes.length - 1 }); |
| 272 | }; |
| 273 | |
| 274 | const historyKey = (): string => |
| 275 | (globalThis.history?.state as { key?: string } | null)?.key ?? |