perf(core): Make PlatformLocation tree-shakable (#32154)

Convert `PlatformLocation` into a tree-shakable provider.

PR Close #32154
This commit is contained in:
Misko Hevery
2019-08-22 19:24:00 -07:00
parent 77c382ccba
commit 1537791f06
29 changed files with 307 additions and 297 deletions

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
let _DOM: DomAdapter = null !;
export function getDOM(): DomAdapter {

View File

@ -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';
@ -62,13 +60,12 @@ 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;
}
@ -76,7 +73,7 @@ export class HashLocationStrategy extends LocationStrategy {
}
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;
}

View File

@ -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';

View File

@ -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 {
@ -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();
@ -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),
@ -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));
}
/**
@ -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);
}
/**
@ -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);
}
/**
@ -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.
@ -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.
@ -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 {

View File

@ -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.
@ -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;
@ -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
@ -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(); }
}

View File

@ -1,97 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
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';
/**
* @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 Location.joinWithSlash(this._baseHref, internal);
}
path(includeHash: boolean = false): string {
const pathname = this._platformLocation.pathname +
Location.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 + Location.normalizeQueryParams(queryParams));
this._platformLocation.pushState(state, title, externalUrl);
}
replaceState(state: any, title: string, url: string, queryParams: string) {
const externalUrl = this.prepareExternalUrl(url + Location.normalizeQueryParams(queryParams));
this._platformLocation.replaceState(state, title, externalUrl);
}
forward(): void { this._platformLocation.forward(); }
back(): void { this._platformLocation.back(); }
}

View File

@ -6,7 +6,10 @@
* found in the LICENSE file at https://angular.io/license
*/
import {InjectionToken} from '@angular/core';
import {Inject, Injectable, InjectionToken, ɵɵinject} from '@angular/core';
import {getDOM} from '../dom_adapter';
import {DOCUMENT} from '../dom_tokens';
/**
* This class should not be used directly by an application developer. Instead, use
* {@link Location}.
@ -29,6 +32,11 @@ import {InjectionToken} from '@angular/core';
*
* @publicApi
*/
@Injectable({
providedIn: 'platform',
// See #23917
useFactory: useBrowserPlatformLocation
})
export abstract class PlatformLocation {
abstract getBaseHrefFromDOM(): string;
abstract getState(): unknown;
@ -52,6 +60,10 @@ export abstract class PlatformLocation {
abstract back(): void;
}
export function useBrowserPlatformLocation() {
return ɵɵinject(BrowserPlatformLocation);
}
/**
* @description
* Indicates when a location is initialized.
@ -75,3 +87,80 @@ export interface LocationChangeEvent {
* @publicApi
*/
export interface LocationChangeListener { (event: LocationChangeEvent): any; }
/**
* `PlatformLocation` encapsulates all of the direct calls to platform APIs.
* This class should not be used directly by an application developer. Instead, use
* {@link Location}.
*/
@Injectable({
providedIn: 'platform',
// See #23917
useFactory: createBrowserPlatformLocation,
})
export class BrowserPlatformLocation extends PlatformLocation {
public readonly location !: Location;
private _history !: History;
constructor(@Inject(DOCUMENT) private _doc: any) {
super();
this._init();
}
// This is moved to its own method so that `MockPlatformLocationStrategy` can overwrite it
/** @internal */
_init() {
(this as{location: Location}).location = getDOM().getLocation();
this._history = getDOM().getHistory();
}
getBaseHrefFromDOM(): string { return getDOM().getBaseHref(this._doc) !; }
onPopState(fn: LocationChangeListener): void {
getDOM().getGlobalEventTarget(this._doc, 'window').addEventListener('popstate', fn, false);
}
onHashChange(fn: LocationChangeListener): void {
getDOM().getGlobalEventTarget(this._doc, 'window').addEventListener('hashchange', fn, false);
}
get href(): string { return this.location.href; }
get protocol(): string { return this.location.protocol; }
get hostname(): string { return this.location.hostname; }
get port(): string { return this.location.port; }
get pathname(): string { return this.location.pathname; }
get search(): string { return this.location.search; }
get hash(): string { return this.location.hash; }
set pathname(newPath: string) { this.location.pathname = newPath; }
pushState(state: any, title: string, url: string): void {
if (supportsState()) {
this._history.pushState(state, title, url);
} else {
this.location.hash = url;
}
}
replaceState(state: any, title: string, url: string): void {
if (supportsState()) {
this._history.replaceState(state, title, url);
} else {
this.location.hash = url;
}
}
forward(): void { this._history.forward(); }
back(): void { this._history.back(); }
getState(): unknown { return this._history.state; }
}
export function supportsState(): boolean {
return !!window.history.pushState;
}
export function createBrowserPlatformLocation() {
return new BrowserPlatformLocation(ɵɵinject(DOCUMENT));
}

View File

@ -0,0 +1,67 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Joins two parts of a URL with a slash if needed.
*
* @param start URL string
* @param end URL string
*
*
* @returns The joined URL string.
*/
export function 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;
}
/**
* Removes a trailing slash from a URL string if needed.
* Looks for the first occurrence of either `#`, `?`, or the end of the
* line as `/` characters and removes the trailing slash if one exists.
*
* @param url URL string.
*
* @returns The URL string, modified if needed.
*/
export function 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);
}
/**
* Normalizes URL parameters by prepending with `?` if needed.
*
* @param params String of URL parameters.
*
* @returns The normalized URL parameters string.
*/
export function normalizeQueryParams(params: string): string {
return params && params[0] !== '?' ? '?' + params : params;
}

View File

@ -11,3 +11,4 @@ export {NgClassImpl as ɵNgClassImpl, NgClassImplProvider__POST_R3__ as ɵNgClas
export {ngStyleDirectiveDef__POST_R3__ as ɵngStyleDirectiveDef__POST_R3__, ngStyleFactoryDef__POST_R3__ as ɵngStyleFactoryDef__POST_R3__} from './directives/ng_style';
export {NgStyleImpl as ɵNgStyleImpl, NgStyleImplProvider__POST_R3__ as ɵNgStyleImplProvider__POST_R3__, NgStyleR2Impl as ɵNgStyleR2Impl} from './directives/ng_style_impl';
export {DomAdapter as ɵDomAdapter, getDOM as ɵgetDOM, setRootDomAdapter as ɵsetRootDomAdapter} from './dom_adapter';
export {BrowserPlatformLocation as ɵBrowserPlatformLocation} from './location/platform_location';