Passed
Push — master ( 71527a...9c3746 )
by Endre
47s queued 11s
created

Registry.getPages   A

Complexity

Conditions 1

Size

Total Lines 10
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 9
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 1
rs 9.95
c 0
b 0
f 0
1
import ListenerAdapter from '@enbock/state-value-observer/ListenerAdapter';
2
import {IObserver} from '@enbock/state-value-observer/Observer';
3
import {IPageData} from './Router';
4
5
export interface IPageDictionary<T> {
6
  [index: string]: T
7
}
8
9 1
export default class Registry {
10
  dictionary: IPageDictionary<IPageData>;
11
  observer: IObserver<IPageData | null>;
12
13
  constructor(observer: IObserver<IPageData | null>) {
14 4
    this.observer = observer;
15 4
    this.dictionary = {};
16
  }
17
18 1
  attachAdapter(adapter: ListenerAdapter<IPageData | null>): void {
19 2
    adapter.addListener(this.updatePageData.bind(this));
20
  }
21
22 2
  getPages(): IPageData[] {
23 2
    const pages: IPageData[] = [];
24
25 2
    Object.keys(this.dictionary).forEach((pageName: string) => {
26 2
      const page: IPageData = this.dictionary[pageName];
27 2
      pages.push(page);
28
    });
29
30 2
    return pages;
31
  }
32
33 1
  registerPage(page: IPageData) {
34 6
    if (this.observer.value != null) {
35 5
      this.updatePageUrlByDepth(this.observer.value, page);
36
    }
37 6
    this.dictionary[page.name] = page;
38
  }
39
40 3
  protected updatePageData(newValue: IPageData | null): void {
41 3
    if (newValue == null) return;
42 2
    Object.keys(this.dictionary).forEach(
43
      (pageName: string) => {
44 6
        this.updatePageUrlByDepth(newValue, this.dictionary[pageName]);
45
      }
46
    );
47
  }
48
49 1
  protected updatePageUrlByDepth(currentPage:IPageData, registeredPage: IPageData): void {
50 11
    let relativeBack: string = '', index: number = 0, newUrl: string;
51
52 11
    if (registeredPage == currentPage) {
53 4
      newUrl = registeredPage.baseUrl.replace(/.*\//, './');
54
    } else {
55 7
      const depth: number = currentPage.baseUrl.replace(/[^\/]*/g, '').length - 1;
56 7
      for (index = 0; index < depth; index++) {
57 13
        relativeBack += '../';
58
      }
59 7
      newUrl = (relativeBack + registeredPage.baseUrl).replace('.././', '../');
60
    }
61
62 11
    registeredPage.currentUrl = newUrl;
63
  }
64
}
65