| 576 | * @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types |
| 577 | */ |
| 578 | export function createMemoryHistory( |
| 579 | opts: { |
| 580 | initialEntries: Array<string> |
| 581 | initialIndex?: number |
| 582 | } = { |
| 583 | initialEntries: ['/'], |
| 584 | }, |
| 585 | ): RouterHistory { |
| 586 | const entries = opts.initialEntries |
| 587 | let index = opts.initialIndex |
| 588 | ? Math.min(Math.max(opts.initialIndex, 0), entries.length - 1) |
| 589 | : entries.length - 1 |
| 590 | const states = entries.map((_entry, index) => |
| 591 | assignKeyAndIndex(index, undefined), |
| 592 | ) |
| 593 | |
| 594 | const getLocation = () => parseHref(entries[index]!, states[index]) |
| 595 | |
| 596 | let blockers: Array<NavigationBlocker> = [] |
| 597 | const _getBlockers = () => blockers |
| 598 | const _setBlockers = (newBlockers: Array<NavigationBlocker>) => |
| 599 | (blockers = newBlockers) |
| 600 | |
| 601 | return createHistory({ |
| 602 | getLocation, |
| 603 | getLength: () => entries.length, |
| 604 | pushState: (path, state) => { |
| 605 | // Removes all subsequent entries after the current index to start a new branch |
| 606 | if (index < entries.length - 1) { |
| 607 | entries.splice(index + 1) |
| 608 | states.splice(index + 1) |
| 609 | } |
| 610 | states.push(state) |
| 611 | entries.push(path) |
| 612 | index = Math.max(entries.length - 1, 0) |
| 613 | }, |
| 614 | replaceState: (path, state) => { |
| 615 | states[index] = state |
| 616 | entries[index] = path |
| 617 | }, |
| 618 | back: () => { |
| 619 | index = Math.max(index - 1, 0) |
| 620 | }, |
| 621 | forward: () => { |
| 622 | index = Math.min(index + 1, entries.length - 1) |
| 623 | }, |
| 624 | go: (n) => { |
| 625 | index = Math.min(Math.max(index + n, 0), entries.length - 1) |
| 626 | }, |
| 627 | createHref: (path) => path, |
| 628 | getBlockers: _getBlockers, |
| 629 | setBlockers: _setBlockers, |
| 630 | }) |
| 631 | } |
| 632 | |
| 633 | /** |
| 634 | * Sanitize a path to prevent open redirect vulnerabilities. |