Skip to content

Commit

Permalink
perf(core): Make PlatformLocation tree-shakable
Browse files Browse the repository at this point in the history
Convert `PlatformLocation` into a tree-shakable provider.
  • Loading branch information
mhevery committed Aug 29, 2019
1 parent 7833fa8 commit c5b76ae
Show file tree
Hide file tree
Showing 32 changed files with 312 additions and 304 deletions.
4 changes: 2 additions & 2 deletions integration/_payload-limits.json
Expand Up @@ -3,7 +3,7 @@
"master": {
"uncompressed": {
"runtime": 1497,
"main": 161490,
"main": 159016,
"polyfills": 45399
}
}
Expand Down Expand Up @@ -34,4 +34,4 @@
}
}
}
}
}
2 changes: 1 addition & 1 deletion integration/ngcc/test.sh
Expand Up @@ -68,7 +68,7 @@ grep "_MatMenuBase.ngBaseDef = ɵngcc0.ɵɵdefineBase({ inputs: {" node_modules/
if [[ $? != 0 ]]; then exit 1; fi

# Did it handle namespace imported decorators in UMD using `__decorate` syntax?
grep "type: core.Injectable" node_modules/@angular/common/bundles/common.umd.js
grep "type: i0.Injectable" node_modules/@angular/common/bundles/common.umd.js
# (and ensure the @angular/common package is indeed using `__decorate` syntax)
grep "JsonPipe = __decorate(" node_modules/@angular/common/bundles/common.umd.js.__ivy_ngcc_bak

Expand Down
4 changes: 2 additions & 2 deletions integration/side-effects/snapshots/common/esm5.js
@@ -1,3 +1,3 @@
import "@angular/core";

import "tslib";

import "@angular/core";
2 changes: 1 addition & 1 deletion integration/side-effects/snapshots/forms/esm2015.js
@@ -1,6 +1,6 @@
import "@angular/core";

import "@angular/platform-browser";
import "@angular/common";

import "rxjs";

Expand Down
2 changes: 1 addition & 1 deletion integration/side-effects/snapshots/forms/esm5.js
Expand Up @@ -2,7 +2,7 @@ import "tslib";

import "@angular/core";

import "@angular/platform-browser";
import "@angular/common";

import "rxjs";

Expand Down
2 changes: 0 additions & 2 deletions integration/side-effects/snapshots/router/esm2015.js
Expand Up @@ -5,5 +5,3 @@ import "@angular/core";
import "rxjs";

import "rxjs/operators";

import "@angular/platform-browser";
2 changes: 0 additions & 2 deletions integration/side-effects/snapshots/router/esm5.js
Expand Up @@ -7,5 +7,3 @@ import "@angular/core";
import "rxjs";

import "rxjs/operators";

import "@angular/platform-browser";
1 change: 0 additions & 1 deletion packages/common/src/dom_adapter.ts
Expand Up @@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/


let _DOM: DomAdapter = null !;

export function getDOM(): DomAdapter {
Expand Down
11 changes: 4 additions & 7 deletions packages/common/src/location/hash_location_strategy.ts
Expand Up @@ -7,11 +7,9 @@
*/

import {Inject, Injectable, Optional} from '@angular/core';


import {Location} from './location';
import {APP_BASE_HREF, LocationStrategy} from './location_strategy';
import {LocationChangeListener, PlatformLocation} from './platform_location';
import {joinWithSlash, normalizeQueryParams} from './util';



Expand Down Expand Up @@ -62,21 +60,20 @@ export class HashLocationStrategy extends LocationStrategy {
}

prepareExternalUrl(internal: string): string {
const url = Location.joinWithSlash(this._baseHref, internal);
const url = joinWithSlash(this._baseHref, internal);
return url.length > 0 ? ('#' + url) : url;
}

pushState(state: any, title: string, path: string, queryParams: string) {
let url: string|null =
this.prepareExternalUrl(path + Location.normalizeQueryParams(queryParams));
let url: string|null = this.prepareExternalUrl(path + normalizeQueryParams(queryParams));
if (url.length == 0) {
url = this._platformLocation.pathname;
}
this._platformLocation.pushState(state, title, url);
}

replaceState(state: any, title: string, path: string, queryParams: string) {
let url = this.prepareExternalUrl(path + Location.normalizeQueryParams(queryParams));
let url = this.prepareExternalUrl(path + normalizeQueryParams(queryParams));
if (url.length == 0) {
url = this._platformLocation.pathname;
}
Expand Down
9 changes: 4 additions & 5 deletions packages/common/src/location/index.ts
Expand Up @@ -6,8 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/

export * from './platform_location';
export * from './location_strategy';
export * from './hash_location_strategy';
export * from './path_location_strategy';
export * from './location';
export {HashLocationStrategy} from './hash_location_strategy';
export {Location, PopStateEvent} from './location';
export {APP_BASE_HREF, LocationStrategy, PathLocationStrategy} from './location_strategy';
export {LOCATION_INITIALIZED, LocationChangeEvent, LocationChangeListener, PlatformLocation} from './platform_location';
56 changes: 18 additions & 38 deletions packages/common/src/location/location.ts
Expand Up @@ -6,11 +6,11 @@
* found in the LICENSE file at https://angular.io/license
*/

import {EventEmitter, Injectable} from '@angular/core';
import {EventEmitter, Injectable, ɵɵinject} from '@angular/core';
import {SubscriptionLike} from 'rxjs';

import {LocationStrategy} from './location_strategy';
import {PlatformLocation} from './platform_location';
import {joinWithSlash, normalizeQueryParams, stripTrailingSlash} from './util';

/** @publicApi */
export interface PopStateEvent {
Expand Down Expand Up @@ -48,7 +48,11 @@ export interface PopStateEvent {
*
* @publicApi
*/
@Injectable()
@Injectable({
providedIn: 'root',
// See #23917
useFactory: createLocation,
})
export class Location {
/** @internal */
_subject: EventEmitter<any> = new EventEmitter();
Expand All @@ -65,7 +69,7 @@ export class Location {
this._platformStrategy = platformStrategy;
const browserBaseHref = this._platformStrategy.getBaseHref();
this._platformLocation = platformLocation;
this._baseHref = Location.stripTrailingSlash(_stripIndexHtml(browserBaseHref));
this._baseHref = stripTrailingSlash(_stripIndexHtml(browserBaseHref));
this._platformStrategy.onPopState((ev) => {
this._subject.emit({
'url': this.path(true),
Expand Down Expand Up @@ -105,7 +109,7 @@ export class Location {
* otherwise.
*/
isCurrentPathEqualTo(path: string, query: string = ''): boolean {
return this.path() == this.normalize(path + Location.normalizeQueryParams(query));
return this.path() == this.normalize(path + normalizeQueryParams(query));
}

/**
Expand Down Expand Up @@ -149,7 +153,7 @@ export class Location {
go(path: string, query: string = '', state: any = null): void {
this._platformStrategy.pushState(state, '', path, query);
this._notifyUrlChangeListeners(
this.prepareExternalUrl(path + Location.normalizeQueryParams(query)), state);
this.prepareExternalUrl(path + normalizeQueryParams(query)), state);
}

/**
Expand All @@ -163,7 +167,7 @@ export class Location {
replaceState(path: string, query: string = '', state: any = null): void {
this._platformStrategy.replaceState(state, '', path, query);
this._notifyUrlChangeListeners(
this.prepareExternalUrl(path + Location.normalizeQueryParams(query)), state);
this.prepareExternalUrl(path + normalizeQueryParams(query)), state);
}

/**
Expand Down Expand Up @@ -213,9 +217,7 @@ export class Location {
*
* @returns The normalized URL parameters string.
*/
public static normalizeQueryParams(params: string): string {
return params && params[0] !== '?' ? '?' + params : params;
}
public static normalizeQueryParams: (params: string) => string = normalizeQueryParams;

/**
* Joins two parts of a URL with a slash if needed.
Expand All @@ -226,28 +228,7 @@ export class Location {
*
* @returns The joined URL string.
*/
public static joinWithSlash(start: string, end: string): string {
if (start.length == 0) {
return end;
}
if (end.length == 0) {
return start;
}
let slashes = 0;
if (start.endsWith('/')) {
slashes++;
}
if (end.startsWith('/')) {
slashes++;
}
if (slashes == 2) {
return start + end.substring(1);
}
if (slashes == 1) {
return start + end;
}
return start + '/' + end;
}
public static joinWithSlash: (start: string, end: string) => string = joinWithSlash;

/**
* Removes a trailing slash from a URL string if needed.
Expand All @@ -258,12 +239,11 @@ export class Location {
*
* @returns The URL string, modified if needed.
*/
public static stripTrailingSlash(url: string): string {
const match = url.match(/#|\?|$/);
const pathEndIdx = match && match.index || url.length;
const droppedSlashIdx = pathEndIdx - (url[pathEndIdx - 1] === '/' ? 1 : 0);
return url.slice(0, droppedSlashIdx) + url.slice(pathEndIdx);
}
public static stripTrailingSlash: (url: string) => string = stripTrailingSlash;
}

export function createLocation() {
return new Location(ɵɵinject(LocationStrategy as any), ɵɵinject(PlatformLocation as any));
}

function _stripBaseHref(baseHref: string, url: string): string {
Expand Down
93 changes: 91 additions & 2 deletions packages/common/src/location/location_strategy.ts
Expand Up @@ -6,8 +6,10 @@
* found in the LICENSE file at https://angular.io/license
*/

import {InjectionToken} from '@angular/core';
import {LocationChangeListener} from './platform_location';
import {Inject, Injectable, InjectionToken, Optional, ɵɵinject} from '@angular/core';
import {DOCUMENT} from '../dom_tokens';
import {LocationChangeListener, PlatformLocation} from './platform_location';
import {joinWithSlash, normalizeQueryParams} from './util';

/**
* Enables the `Location` service to read route state from the browser's URL.
Expand All @@ -26,6 +28,7 @@ import {LocationChangeListener} from './platform_location';
*
* @publicApi
*/
@Injectable({providedIn: 'root', useFactory: provideLocationStrategy})
export abstract class LocationStrategy {
abstract path(includeHash?: boolean): string;
abstract prepareExternalUrl(internal: string): string;
Expand All @@ -37,6 +40,13 @@ export abstract class LocationStrategy {
abstract getBaseHref(): string;
}

export function provideLocationStrategy(platformLocation: PlatformLocation) {
// See #23917
const location = ɵɵinject(DOCUMENT).location;
return new PathLocationStrategy(
ɵɵinject(PlatformLocation as any), location && location.origin || '');
}


/**
* A predefined [DI token](guide/glossary#di-token) for the base href
Expand All @@ -62,3 +72,82 @@ export abstract class LocationStrategy {
* @publicApi
*/
export const APP_BASE_HREF = new InjectionToken<string>('appBaseHref');

/**
* @description
* A {@link LocationStrategy} used to configure the {@link Location} service to
* represent its state in the
* [path](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) of the
* browser's URL.
*
* If you're using `PathLocationStrategy`, you must provide a {@link APP_BASE_HREF}
* or add a base element to the document. This URL prefix that will be preserved
* when generating and recognizing URLs.
*
* For instance, if you provide an `APP_BASE_HREF` of `'/my/app'` and call
* `location.go('/foo')`, the browser's URL will become
* `example.com/my/app/foo`.
*
* Similarly, if you add `<base href='/my/app'/>` to the document and call
* `location.go('/foo')`, the browser's URL will become
* `example.com/my/app/foo`.
*
* @usageNotes
*
* ### Example
*
* {@example common/location/ts/path_location_component.ts region='LocationComponent'}
*
* @publicApi
*/
@Injectable()
export class PathLocationStrategy extends LocationStrategy {
private _baseHref: string;

constructor(
private _platformLocation: PlatformLocation,
@Optional() @Inject(APP_BASE_HREF) href?: string) {
super();

if (href == null) {
href = this._platformLocation.getBaseHrefFromDOM();
}

if (href == null) {
throw new Error(
`No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.`);
}

this._baseHref = href;
}

onPopState(fn: LocationChangeListener): void {
this._platformLocation.onPopState(fn);
this._platformLocation.onHashChange(fn);
}

getBaseHref(): string { return this._baseHref; }

prepareExternalUrl(internal: string): string { return joinWithSlash(this._baseHref, internal); }

path(includeHash: boolean = false): string {
const pathname =
this._platformLocation.pathname + normalizeQueryParams(this._platformLocation.search);
const hash = this._platformLocation.hash;
return hash && includeHash ? `${pathname}${hash}` : pathname;
}

pushState(state: any, title: string, url: string, queryParams: string) {
const externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams));
this._platformLocation.pushState(state, title, externalUrl);
}

replaceState(state: any, title: string, url: string, queryParams: string) {
const externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams));
this._platformLocation.replaceState(state, title, externalUrl);
}

forward(): void { this._platformLocation.forward(); }

back(): void { this._platformLocation.back(); }
}

0 comments on commit c5b76ae

Please sign in to comment.