|
| 1 | +/* eslint-disable max-classes-per-file */ |
| 2 | + |
| 3 | +class Route { |
| 4 | + url: string; |
| 5 | + |
| 6 | + id: number; |
| 7 | + |
| 8 | + constructor(url: string, id: number) { |
| 9 | + this.url = url; |
| 10 | + this.id = id; |
| 11 | + } |
| 12 | +} |
| 13 | + |
1 | 14 | class Routes {
|
2 |
| - values: string[] = []; |
| 15 | + values: Route[] = [new Route(null, null)]; |
3 | 16 |
|
4 | 17 | id = 0;
|
5 | 18 |
|
6 |
| - current: number | null = null; |
| 19 | + current: number | null = 0; |
7 | 20 |
|
8 |
| - addRoute(url: string): string { |
9 |
| - if (this.values[this.values.length - 1] !== url) { |
10 |
| - if (this.values.includes(url)) { |
11 |
| - this.values.push((url += this.id++)); |
12 |
| - } else { |
13 |
| - this.values.push(url); |
| 21 | + addRoute(url: string): Route { |
| 22 | + let route: Route = this.values[this.current]; |
| 23 | + |
| 24 | + if (this.values[this.current].url !== url) { |
| 25 | + if (this.current !== this.values.length - 1) { |
| 26 | + this.rebuildHistory(url); |
14 | 27 | }
|
| 28 | + |
| 29 | + route = new Route(url, (this.id += 1)); |
| 30 | + this.values.push(route); |
| 31 | + |
| 32 | + this.current = this.values.length - 1; |
| 33 | + } |
| 34 | + |
| 35 | + return route; |
| 36 | + } |
| 37 | + |
| 38 | + rebuildHistory(url: string): void { |
| 39 | + window.history.replaceState('', '', this.values[this.current + 1].url); |
| 40 | + |
| 41 | + for (let i = this.current + 2; i < this.values.length; i += 1) { |
| 42 | + window.history.pushState('', '', this.values[i].url); |
15 | 43 | }
|
16 | 44 |
|
17 |
| - this.current = this.values.length - 1; |
18 |
| - return url; |
| 45 | + window.history.pushState('', '', url); |
19 | 46 | }
|
20 | 47 |
|
21 |
| - navigate(url: string): boolean { |
| 48 | + navigate(route: Route): boolean { |
22 | 49 | let targetIndex: number | null = null;
|
23 |
| - for (let i = 0; i < this.values.length; i++) { |
24 |
| - if (this.values[i] === url) targetIndex = i; |
| 50 | + |
| 51 | + for (let i = 0; i < this.values.length; i += 1) { |
| 52 | + if (this.values[i].url === route.url && this.values[i].id === route.id) { |
| 53 | + targetIndex = i; |
| 54 | + } |
25 | 55 | }
|
26 | 56 |
|
27 | 57 | const delta: number = targetIndex - this.current;
|
|
0 commit comments