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