|
| 1 | +import {HashLocationStrategy, PlatformLocation, LocationStrategy} from "@angular/common"; |
| 2 | +import {Injectable} from "@angular/core"; |
| 3 | + |
| 4 | +import {services} from "../common/coreservices"; |
| 5 | +import {isDefined} from "../common/predicates"; |
| 6 | +import {applyPairs} from "../common/common"; |
| 7 | +import {beforeAfterSubstr} from "../common/strings"; |
| 8 | + |
| 9 | +const splitOnHash = beforeAfterSubstr("#"); |
| 10 | +const splitOnEquals = beforeAfterSubstr("="); |
| 11 | +const splitOnQuestionMark = beforeAfterSubstr("?"); |
| 12 | + |
| 13 | +@Injectable() |
| 14 | +export class UIRouterLocation { |
| 15 | + isHashBang: boolean; |
| 16 | + hashPrefix: string = ""; |
| 17 | + |
| 18 | + constructor( |
| 19 | + public locationStrategy: LocationStrategy, |
| 20 | + public platformLocation: PlatformLocation |
| 21 | + ) { |
| 22 | + this.isHashBang = locationStrategy instanceof HashLocationStrategy; |
| 23 | + } |
| 24 | + |
| 25 | + init() { |
| 26 | + let loc = <any> services.location; |
| 27 | + let locSt = this.locationStrategy; |
| 28 | + |
| 29 | + if (this.isHashBang) { |
| 30 | + loc.hash = () => |
| 31 | + splitOnHash(splitOnHash(this.platformLocation.hash)[1])[1]; |
| 32 | + } else { |
| 33 | + loc.hash = () => |
| 34 | + splitOnHash(this.platformLocation.hash)[1]; |
| 35 | + } |
| 36 | + |
| 37 | + loc.path = () => |
| 38 | + splitOnHash(splitOnQuestionMark(locSt.path())[0])[0]; |
| 39 | + |
| 40 | + loc.search = () => { |
| 41 | + let queryString = splitOnHash(splitOnQuestionMark(locSt.path())[1])[0]; |
| 42 | + return queryString.split("&").map(kv => splitOnEquals(kv)).reduce(applyPairs, {}); |
| 43 | + }; |
| 44 | + |
| 45 | + loc.url = (url) => { |
| 46 | + if(isDefined(url)) { |
| 47 | + let split = splitOnQuestionMark(url); |
| 48 | + locSt.pushState(null, null, split[0], split[1]); |
| 49 | + } |
| 50 | + return locSt.path() |
| 51 | + }; |
| 52 | + |
| 53 | + loc.replace = () => { |
| 54 | + console.log(new Error('$location.replace() not impl')) |
| 55 | + }; |
| 56 | + |
| 57 | + loc.onChange = cb => locSt.onPopState(cb); |
| 58 | + |
| 59 | + let locCfg = <any> services.locationConfig; |
| 60 | + |
| 61 | + locCfg.port = () => null; |
| 62 | + locCfg.protocol = () => null; |
| 63 | + locCfg.host = () => null; |
| 64 | + locCfg.baseHref = () => locSt.getBaseHref(); |
| 65 | + locCfg.html5Mode = () => !this.isHashBang; |
| 66 | + locCfg.hashPrefix = (newprefix: string): string => { |
| 67 | + if(isDefined(newprefix)) { |
| 68 | + this.hashPrefix = newprefix; |
| 69 | + } |
| 70 | + return this.hashPrefix; |
| 71 | + }; |
| 72 | + } |
| 73 | +} |
| 74 | + |
0 commit comments