Passed
Push — develop ( 588e30...c592f3 )
by Endre
04:05
created

src/Router/Router.ts   A

Complexity

Total Complexity 6
Complexity/F 1.2

Size

Lines of Code 48
Function Count 5

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 57.14%

Importance

Changes 0
Metric Value
eloc 37
dl 0
loc 48
ccs 8
cts 14
cp 0.5714
rs 10
c 0
b 0
f 0
wmc 6
mnd 1
bc 1
fnc 5
bpm 0.2
cpm 1.2
noi 0

5 Functions

Rating   Name   Duplication   Size   Complexity  
A Router.attachTo 0 3 1
A Router.updatePage 0 3 1
A Router.changePage 0 10 2
A Router.onHistoryChange 0 4 1
A Router.initialize 0 5 1
1
import {IObserver} from '../Observer/Observer';
2
3
export interface IPageData {
4
  name: string,
5
  url: string,
6
  depth: number
7
}
8
9
export default class Router {
10
  currentPage: IObserver<IPageData>;
11
  history: History;
12
13
  constructor(pageObserver: IObserver<IPageData>, history: History) {
14 1
    this.currentPage = pageObserver;
15 1
    this.history = history;
16
  }
17
18
  attachTo(window: Window) {
19 1
    window.addEventListener('popstate', this.onHistoryChange.bind(this));
20
  }
21
22
  initialize(): void {
23 1
    const firstPage: IPageData = this.currentPage.value;
24 1
    this.history.replaceState(firstPage, firstPage.name, firstPage.url);
25 1
    this.updatePage(firstPage);
26
  }
27
28
  changePage(newPage: IPageData): void {
29
    const currentPage = this.currentPage.value;
30 2
    if (currentPage.name == newPage.name) {
31
      return;
32
    }
33
34
    this.history.replaceState(newPage, newPage.name, newPage.url);
35
36
    this.updatePage(newPage);
37
  }
38
39
  updatePage(page: IPageData): void {
40 1
    this.currentPage.value = page;
41
  }
42
43
  onHistoryChange(event: PopStateEvent) {
44
    const newPage: IPageData = event.state as IPageData;
45
    this.updatePage(newPage);
46
  }
47
}
48