Total Complexity | 7 |
Complexity/F | 1.4 |
Lines of Code | 48 |
Function Count | 5 |
Duplicated Lines | 0 |
Ratio | 0 % |
Coverage | 100% |
Changes | 0 |
1 | import {IObserver} from '@enbock/state-value-observer/Observer'; |
||
2 | |||
3 | export interface IPageData { |
||
4 | name: string, |
||
5 | baseUrl: string |
||
6 | currentUrl: string |
||
7 | } |
||
8 | |||
9 | export default class Router { |
||
10 | currentPage: IObserver<IPageData | null>; |
||
11 | history: History; |
||
12 | |||
13 | constructor(pageObserver: IObserver<IPageData | null>, history: History) { |
||
14 | 5 | this.currentPage = pageObserver; |
|
15 | 5 | this.history = history; |
|
16 | } |
||
17 | |||
18 | attachTo(window: Window) { |
||
19 | 2 | window.addEventListener('popstate', this.onHistoryChange.bind(this)); |
|
20 | } |
||
21 | |||
22 | initialize(): void { |
||
23 | 2 | if (this.currentPage.value == null) return; |
|
24 | 1 | const firstPage: IPageData = this.currentPage.value; |
|
25 | 1 | this.history.replaceState(firstPage, firstPage.name, firstPage.baseUrl); |
|
26 | 1 | this.updatePage(firstPage); |
|
27 | } |
||
28 | |||
29 | changePage(newPage: IPageData): void { |
||
30 | 2 | const currentPage: IPageData | null = this.currentPage.value; |
|
31 | 4 | if (currentPage != null && currentPage.name == newPage.name) { |
|
32 | 1 | return; |
|
33 | } |
||
34 | |||
35 | 1 | this.history.replaceState(newPage, newPage.name, newPage.currentUrl); |
|
36 | 1 | this.updatePage(newPage); |
|
37 | } |
||
38 | |||
39 | protected updatePage(page: IPageData): void { |
||
40 | 3 | this.currentPage.value = page; |
|
41 | } |
||
42 | |||
43 | protected onHistoryChange(event: PopStateEvent): void { |
||
44 | 1 | const newPage: IPageData = event.state as IPageData; |
|
45 | 1 | this.updatePage(newPage); |
|
46 | } |
||
47 | } |
||
48 |