feat(ivy): convert [ngStyle] and [ngClass] to use ivy styling bindings (#28711)
Prior to this fix, both the `NgStyle` and `NgClass` directives made use of `Renderer2` and this dependency raised issues for future versions of Angular that cannot inject it. This patch ensures that there are two versions of both directives: one for the VE and another for Ivy. Jira Issue: FW-882 PR Close #28711
This commit is contained in:

committed by
Igor Minar

parent
d0e81eb593
commit
cfb2d176f8
@ -7,18 +7,18 @@
|
||||
*/
|
||||
|
||||
import {Provider} from '@angular/core';
|
||||
|
||||
import {NgClass} from './ng_class';
|
||||
import {NgClass, NgClassBase} from './ng_class';
|
||||
import {NgComponentOutlet} from './ng_component_outlet';
|
||||
import {NgForOf, NgForOfContext} from './ng_for_of';
|
||||
import {NgIf, NgIfContext} from './ng_if';
|
||||
import {NgPlural, NgPluralCase} from './ng_plural';
|
||||
import {NgStyle} from './ng_style';
|
||||
import {NgStyle, NgStyleBase} from './ng_style';
|
||||
import {NgSwitch, NgSwitchCase, NgSwitchDefault} from './ng_switch';
|
||||
import {NgTemplateOutlet} from './ng_template_outlet';
|
||||
|
||||
export {
|
||||
NgClass,
|
||||
NgClassBase,
|
||||
NgComponentOutlet,
|
||||
NgForOf,
|
||||
NgForOfContext,
|
||||
@ -27,10 +27,11 @@ export {
|
||||
NgPlural,
|
||||
NgPluralCase,
|
||||
NgStyle,
|
||||
NgStyleBase,
|
||||
NgSwitch,
|
||||
NgSwitchCase,
|
||||
NgSwitchDefault,
|
||||
NgTemplateOutlet
|
||||
NgTemplateOutlet,
|
||||
};
|
||||
|
||||
|
||||
|
@ -5,8 +5,68 @@
|
||||
* 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 {Directive, DoCheck, Input, ɵRenderFlags, ɵdefineDirective, ɵelementStyling, ɵelementStylingApply, ɵelementStylingMap} from '@angular/core';
|
||||
|
||||
import {Directive, DoCheck, ElementRef, Input, IterableChanges, IterableDiffer, IterableDiffers, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer2, ɵisListLikeIterable as isListLikeIterable, ɵstringify as stringify} from '@angular/core';
|
||||
import {NgClassImpl, NgClassImplProvider} from './ng_class_impl';
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* NgClass (as well as NgStyle) behaves differently when loaded in the VE and when not.
|
||||
*
|
||||
* If the VE is present (which is for older versions of Angular) then NgClass will inject
|
||||
* the legacy diffing algorithm as a service and delegate all styling changes to that.
|
||||
*
|
||||
* If the VE is not present then NgStyle will normalize (through the injected service) and
|
||||
* then write all styling changes to the `[style]` binding directly (through a host binding).
|
||||
* Then Angular will notice the host binding change and treat the changes as styling
|
||||
* changes and apply them via the core styling instructions that exist within Angular.
|
||||
*/
|
||||
|
||||
// used when the VE is present
|
||||
export const ngClassDirectiveDef__PRE_R3__ = undefined;
|
||||
|
||||
// used when the VE is not present (note the directive will
|
||||
// never be instantiated normally because it is apart of a
|
||||
// base class)
|
||||
export const ngClassDirectiveDef__POST_R3__ = ɵdefineDirective({
|
||||
type: function() {} as any,
|
||||
selectors: null as any,
|
||||
factory: () => {},
|
||||
hostBindings: function(rf: ɵRenderFlags, ctx: any, elIndex: number) {
|
||||
if (rf & ɵRenderFlags.Create) {
|
||||
ɵelementStyling(null, null, null, ctx);
|
||||
}
|
||||
if (rf & ɵRenderFlags.Update) {
|
||||
ɵelementStylingMap(elIndex, ctx.getValue(), null, ctx);
|
||||
ɵelementStylingApply(elIndex, ctx);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export const ngClassDirectiveDef = ngClassDirectiveDef__PRE_R3__;
|
||||
|
||||
/**
|
||||
* Serves as the base non-VE container for NgClass.
|
||||
*
|
||||
* While this is a base class that NgClass extends from, the
|
||||
* class itself acts as a container for non-VE code to setup
|
||||
* a link to the `[class]` host binding (via the static
|
||||
* `ngDirectiveDef` property on the class).
|
||||
*
|
||||
* Note that the `ngDirectiveDef` property's code is switched
|
||||
* depending if VE is present or not (this allows for the
|
||||
* binding code to be set only for newer versions of Angular).
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
export class NgClassBase {
|
||||
static ngDirectiveDef: any = ngClassDirectiveDef;
|
||||
|
||||
constructor(protected _delegate: NgClassImpl) {}
|
||||
|
||||
getValue() { return this._delegate.getValue(); }
|
||||
}
|
||||
|
||||
/**
|
||||
* @ngModule CommonModule
|
||||
@ -36,126 +96,17 @@ import {Directive, DoCheck, ElementRef, Input, IterableChanges, IterableDiffer,
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
@Directive({selector: '[ngClass]'})
|
||||
export class NgClass implements DoCheck {
|
||||
// TODO(issue/24571): remove '!'.
|
||||
private _iterableDiffer !: IterableDiffer<string>| null;
|
||||
// TODO(issue/24571): remove '!'.
|
||||
private _keyValueDiffer !: KeyValueDiffer<string, any>| null;
|
||||
private _initialClasses: string[] = [];
|
||||
// TODO(issue/24571): remove '!'.
|
||||
private _rawClass !: string[] | Set<string>| {[klass: string]: any};
|
||||
|
||||
constructor(
|
||||
private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers,
|
||||
private _ngEl: ElementRef, private _renderer: Renderer2) {}
|
||||
@Directive({selector: '[ngClass]', providers: [NgClassImplProvider]})
|
||||
export class NgClass extends NgClassBase implements DoCheck {
|
||||
constructor(delegate: NgClassImpl) { super(delegate); }
|
||||
|
||||
@Input('class')
|
||||
set klass(value: string) {
|
||||
this._removeClasses(this._initialClasses);
|
||||
this._initialClasses = typeof value === 'string' ? value.split(/\s+/) : [];
|
||||
this._applyClasses(this._initialClasses);
|
||||
this._applyClasses(this._rawClass);
|
||||
}
|
||||
set klass(value: string) { this._delegate.setClass(value); }
|
||||
|
||||
@Input()
|
||||
@Input('ngClass')
|
||||
set ngClass(value: string|string[]|Set<string>|{[klass: string]: any}) {
|
||||
this._removeClasses(this._rawClass);
|
||||
this._applyClasses(this._initialClasses);
|
||||
|
||||
this._iterableDiffer = null;
|
||||
this._keyValueDiffer = null;
|
||||
|
||||
this._rawClass = typeof value === 'string' ? value.split(/\s+/) : value;
|
||||
|
||||
if (this._rawClass) {
|
||||
if (isListLikeIterable(this._rawClass)) {
|
||||
this._iterableDiffer = this._iterableDiffers.find(this._rawClass).create();
|
||||
} else {
|
||||
this._keyValueDiffer = this._keyValueDiffers.find(this._rawClass).create();
|
||||
}
|
||||
}
|
||||
this._delegate.setNgClass(value);
|
||||
}
|
||||
|
||||
ngDoCheck(): void {
|
||||
if (this._iterableDiffer) {
|
||||
const iterableChanges = this._iterableDiffer.diff(this._rawClass as string[]);
|
||||
if (iterableChanges) {
|
||||
this._applyIterableChanges(iterableChanges);
|
||||
}
|
||||
} else if (this._keyValueDiffer) {
|
||||
const keyValueChanges = this._keyValueDiffer.diff(this._rawClass as{[k: string]: any});
|
||||
if (keyValueChanges) {
|
||||
this._applyKeyValueChanges(keyValueChanges);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _applyKeyValueChanges(changes: KeyValueChanges<string, any>): void {
|
||||
changes.forEachAddedItem((record) => this._toggleClass(record.key, record.currentValue));
|
||||
changes.forEachChangedItem((record) => this._toggleClass(record.key, record.currentValue));
|
||||
changes.forEachRemovedItem((record) => {
|
||||
if (record.previousValue) {
|
||||
this._toggleClass(record.key, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private _applyIterableChanges(changes: IterableChanges<string>): void {
|
||||
changes.forEachAddedItem((record) => {
|
||||
if (typeof record.item === 'string') {
|
||||
this._toggleClass(record.item, true);
|
||||
} else {
|
||||
throw new Error(
|
||||
`NgClass can only toggle CSS classes expressed as strings, got ${stringify(record.item)}`);
|
||||
}
|
||||
});
|
||||
|
||||
changes.forEachRemovedItem((record) => this._toggleClass(record.item, false));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a collection of CSS classes to the DOM element.
|
||||
*
|
||||
* For argument of type Set and Array CSS class names contained in those collections are always
|
||||
* added.
|
||||
* For argument of type Map CSS class name in the map's key is toggled based on the value (added
|
||||
* for truthy and removed for falsy).
|
||||
*/
|
||||
private _applyClasses(rawClassVal: string[]|Set<string>|{[klass: string]: any}) {
|
||||
if (rawClassVal) {
|
||||
if (Array.isArray(rawClassVal) || rawClassVal instanceof Set) {
|
||||
(<any>rawClassVal).forEach((klass: string) => this._toggleClass(klass, true));
|
||||
} else {
|
||||
Object.keys(rawClassVal).forEach(klass => this._toggleClass(klass, !!rawClassVal[klass]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a collection of CSS classes from the DOM element. This is mostly useful for cleanup
|
||||
* purposes.
|
||||
*/
|
||||
private _removeClasses(rawClassVal: string[]|Set<string>|{[klass: string]: any}) {
|
||||
if (rawClassVal) {
|
||||
if (Array.isArray(rawClassVal) || rawClassVal instanceof Set) {
|
||||
(<any>rawClassVal).forEach((klass: string) => this._toggleClass(klass, false));
|
||||
} else {
|
||||
Object.keys(rawClassVal).forEach(klass => this._toggleClass(klass, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _toggleClass(klass: string, enabled: boolean): void {
|
||||
klass = klass.trim();
|
||||
if (klass) {
|
||||
klass.split(/\s+/g).forEach(klass => {
|
||||
if (enabled) {
|
||||
this._renderer.addClass(this._ngEl.nativeElement, klass);
|
||||
} else {
|
||||
this._renderer.removeClass(this._ngEl.nativeElement, klass);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
ngDoCheck() { this._delegate.applyChanges(); }
|
||||
}
|
||||
|
208
packages/common/src/directives/ng_class_impl.ts
Normal file
208
packages/common/src/directives/ng_class_impl.ts
Normal file
@ -0,0 +1,208 @@
|
||||
/**
|
||||
* @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 {ElementRef, Injectable, IterableChanges, IterableDiffer, IterableDiffers, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer2, ɵisListLikeIterable as isListLikeIterable, ɵstringify as stringify} from '@angular/core';
|
||||
|
||||
import {StylingDiffer, StylingDifferOptions} from './styling_differ';
|
||||
|
||||
/**
|
||||
* Used as a token for an injected service within the NgClass directive.
|
||||
*
|
||||
* NgClass behaves differenly whether or not VE is being used or not. If
|
||||
* present then the legacy ngClass diffing algorithm will be used as an
|
||||
* injected service. Otherwise the new diffing algorithm (which delegates
|
||||
* to the `[class]` binding) will be used. This toggle behavior is done so
|
||||
* via the ivy_switch mechanism.
|
||||
*/
|
||||
export abstract class NgClassImpl {
|
||||
abstract setClass(value: string): void;
|
||||
abstract setNgClass(value: string|string[]|Set<string>|{[klass: string]: any}): void;
|
||||
abstract applyChanges(): void;
|
||||
abstract getValue(): {[key: string]: any}|null;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class NgClassR2Impl implements NgClassImpl {
|
||||
// TODO(issue/24571): remove '!'.
|
||||
private _iterableDiffer !: IterableDiffer<string>| null;
|
||||
// TODO(issue/24571): remove '!'.
|
||||
private _keyValueDiffer !: KeyValueDiffer<string, any>| null;
|
||||
private _initialClasses: string[] = [];
|
||||
// TODO(issue/24571): remove '!'.
|
||||
private _rawClass !: string[] | Set<string>| {[klass: string]: any};
|
||||
|
||||
constructor(
|
||||
private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers,
|
||||
private _ngEl: ElementRef, private _renderer: Renderer2) {}
|
||||
|
||||
getValue() { return null; }
|
||||
|
||||
setClass(value: string) {
|
||||
this._removeClasses(this._initialClasses);
|
||||
this._initialClasses = typeof value === 'string' ? value.split(/\s+/) : [];
|
||||
this._applyClasses(this._initialClasses);
|
||||
this._applyClasses(this._rawClass);
|
||||
}
|
||||
|
||||
setNgClass(value: string) {
|
||||
this._removeClasses(this._rawClass);
|
||||
this._applyClasses(this._initialClasses);
|
||||
|
||||
this._iterableDiffer = null;
|
||||
this._keyValueDiffer = null;
|
||||
|
||||
this._rawClass = typeof value === 'string' ? value.split(/\s+/) : value;
|
||||
|
||||
if (this._rawClass) {
|
||||
if (isListLikeIterable(this._rawClass)) {
|
||||
this._iterableDiffer = this._iterableDiffers.find(this._rawClass).create();
|
||||
} else {
|
||||
this._keyValueDiffer = this._keyValueDiffers.find(this._rawClass).create();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
applyChanges() {
|
||||
if (this._iterableDiffer) {
|
||||
const iterableChanges = this._iterableDiffer.diff(this._rawClass as string[]);
|
||||
if (iterableChanges) {
|
||||
this._applyIterableChanges(iterableChanges);
|
||||
}
|
||||
} else if (this._keyValueDiffer) {
|
||||
const keyValueChanges = this._keyValueDiffer.diff(this._rawClass as{[k: string]: any});
|
||||
if (keyValueChanges) {
|
||||
this._applyKeyValueChanges(keyValueChanges);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _applyKeyValueChanges(changes: KeyValueChanges<string, any>): void {
|
||||
changes.forEachAddedItem((record) => this._toggleClass(record.key, record.currentValue));
|
||||
changes.forEachChangedItem((record) => this._toggleClass(record.key, record.currentValue));
|
||||
changes.forEachRemovedItem((record) => {
|
||||
if (record.previousValue) {
|
||||
this._toggleClass(record.key, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private _applyIterableChanges(changes: IterableChanges<string>): void {
|
||||
changes.forEachAddedItem((record) => {
|
||||
if (typeof record.item === 'string') {
|
||||
this._toggleClass(record.item, true);
|
||||
} else {
|
||||
throw new Error(
|
||||
`NgClass can only toggle CSS classes expressed as strings, got ${stringify(record.item)}`);
|
||||
}
|
||||
});
|
||||
|
||||
changes.forEachRemovedItem((record) => this._toggleClass(record.item, false));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a collection of CSS classes to the DOM element.
|
||||
*
|
||||
* For argument of type Set and Array CSS class names contained in those collections are always
|
||||
* added.
|
||||
* For argument of type Map CSS class name in the map's key is toggled based on the value (added
|
||||
* for truthy and removed for falsy).
|
||||
*/
|
||||
private _applyClasses(rawClassVal: string[]|Set<string>|{[klass: string]: any}) {
|
||||
if (rawClassVal) {
|
||||
if (Array.isArray(rawClassVal) || rawClassVal instanceof Set) {
|
||||
(<any>rawClassVal).forEach((klass: string) => this._toggleClass(klass, true));
|
||||
} else {
|
||||
Object.keys(rawClassVal).forEach(klass => this._toggleClass(klass, !!rawClassVal[klass]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a collection of CSS classes from the DOM element. This is mostly useful for cleanup
|
||||
* purposes.
|
||||
*/
|
||||
private _removeClasses(rawClassVal: string[]|Set<string>|{[klass: string]: any}) {
|
||||
if (rawClassVal) {
|
||||
if (Array.isArray(rawClassVal) || rawClassVal instanceof Set) {
|
||||
(<any>rawClassVal).forEach((klass: string) => this._toggleClass(klass, false));
|
||||
} else {
|
||||
Object.keys(rawClassVal).forEach(klass => this._toggleClass(klass, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _toggleClass(klass: string, enabled: boolean): void {
|
||||
klass = klass.trim();
|
||||
if (klass) {
|
||||
klass.split(/\s+/g).forEach(klass => {
|
||||
if (enabled) {
|
||||
this._renderer.addClass(this._ngEl.nativeElement, klass);
|
||||
} else {
|
||||
this._renderer.removeClass(this._ngEl.nativeElement, klass);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class NgClassR3Impl implements NgClassImpl {
|
||||
private _value: {[key: string]: boolean}|null = null;
|
||||
private _ngClassDiffer = new StylingDiffer<{[key: string]: boolean}|null>(
|
||||
'NgClass', StylingDifferOptions.TrimProperties|
|
||||
StylingDifferOptions.AllowSubKeys|
|
||||
StylingDifferOptions.AllowStringValue|StylingDifferOptions.ForceAsMap);
|
||||
private _classStringDiffer: StylingDiffer<{[key: string]: boolean}>|null = null;
|
||||
|
||||
getValue() { return this._value; }
|
||||
|
||||
setClass(value: string) {
|
||||
// early exit incase the binding gets emitted as an empty value which
|
||||
// means there is no reason to instantiate and diff the values...
|
||||
if (!value && !this._classStringDiffer) return;
|
||||
|
||||
this._classStringDiffer = this._classStringDiffer ||
|
||||
new StylingDiffer('class',
|
||||
StylingDifferOptions.AllowStringValue | StylingDifferOptions.ForceAsMap);
|
||||
this._classStringDiffer.setValue(value);
|
||||
}
|
||||
|
||||
setNgClass(value: string|string[]|Set<string>|{[klass: string]: any}) {
|
||||
this._ngClassDiffer.setValue(value);
|
||||
}
|
||||
|
||||
applyChanges() {
|
||||
const classChanged =
|
||||
this._classStringDiffer ? this._classStringDiffer.hasValueChanged() : false;
|
||||
const ngClassChanged = this._ngClassDiffer.hasValueChanged();
|
||||
if (classChanged || ngClassChanged) {
|
||||
let value = this._ngClassDiffer.value;
|
||||
if (this._classStringDiffer) {
|
||||
let classValue = this._classStringDiffer.value;
|
||||
if (classValue) {
|
||||
value = value ? {...classValue, ...value} : classValue;
|
||||
}
|
||||
}
|
||||
this._value = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// the implementation for both NgStyleR2Impl and NgStyleR3Impl are
|
||||
// not ivy_switch'd away, instead they are only hooked up into the
|
||||
// DI via NgStyle's directive's provider property.
|
||||
export const NgClassImplProvider__PRE_R3__ = {
|
||||
provide: NgClassImpl,
|
||||
useClass: NgClassR2Impl
|
||||
};
|
||||
|
||||
export const NgClassImplProvider__POST_R3__ = {
|
||||
provide: NgClassImpl,
|
||||
useClass: NgClassR3Impl
|
||||
};
|
||||
|
||||
export const NgClassImplProvider = NgClassImplProvider__PRE_R3__;
|
@ -5,8 +5,68 @@
|
||||
* 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 {Directive, DoCheck, Input, ɵRenderFlags, ɵdefineDirective, ɵelementStyling, ɵelementStylingApply, ɵelementStylingMap} from '@angular/core';
|
||||
|
||||
import {Directive, DoCheck, ElementRef, Input, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer2} from '@angular/core';
|
||||
import {NgStyleImpl, NgStyleImplProvider} from './ng_style_impl';
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* NgStyle (as well as NgClass) behaves differently when loaded in the VE and when not.
|
||||
*
|
||||
* If the VE is present (which is for older versions of Angular) then NgStyle will inject
|
||||
* the legacy diffing algorithm as a service and delegate all styling changes to that.
|
||||
*
|
||||
* If the VE is not present then NgStyle will normalize (through the injected service) and
|
||||
* then write all styling changes to the `[style]` binding directly (through a host binding).
|
||||
* Then Angular will notice the host binding change and treat the changes as styling
|
||||
* changes and apply them via the core styling instructions that exist within Angular.
|
||||
*/
|
||||
|
||||
// used when the VE is present
|
||||
export const ngStyleDirectiveDef__PRE_R3__ = undefined;
|
||||
|
||||
// used when the VE is not present (note the directive will
|
||||
// never be instantiated normally because it is apart of a
|
||||
// base class)
|
||||
export const ngStyleDirectiveDef__POST_R3__ = ɵdefineDirective({
|
||||
type: function() {} as any,
|
||||
selectors: null as any,
|
||||
factory: () => {},
|
||||
hostBindings: function(rf: ɵRenderFlags, ctx: any, elIndex: number) {
|
||||
if (rf & ɵRenderFlags.Create) {
|
||||
ɵelementStyling(null, null, null, ctx);
|
||||
}
|
||||
if (rf & ɵRenderFlags.Update) {
|
||||
ɵelementStylingMap(elIndex, null, ctx.getValue(), ctx);
|
||||
ɵelementStylingApply(elIndex, ctx);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export const ngStyleDirectiveDef = ngStyleDirectiveDef__PRE_R3__;
|
||||
|
||||
/**
|
||||
* Serves as the base non-VE container for NgStyle.
|
||||
*
|
||||
* While this is a base class that NgStyle extends from, the
|
||||
* class itself acts as a container for non-VE code to setup
|
||||
* a link to the `[style]` host binding (via the static
|
||||
* `ngDirectiveDef` property on the class).
|
||||
*
|
||||
* Note that the `ngDirectiveDef` property's code is switched
|
||||
* depending if VE is present or not (this allows for the
|
||||
* binding code to be set only for newer versions of Angular).
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
export class NgStyleBase {
|
||||
static ngDirectiveDef: any = ngStyleDirectiveDef;
|
||||
|
||||
constructor(protected _delegate: NgStyleImpl) {}
|
||||
|
||||
getValue() { return this._delegate.getValue(); }
|
||||
}
|
||||
|
||||
/**
|
||||
* @ngModule CommonModule
|
||||
@ -44,58 +104,12 @@ import {Directive, DoCheck, ElementRef, Input, KeyValueChanges, KeyValueDiffer,
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
@Directive({selector: '[ngStyle]'})
|
||||
export class NgStyle implements DoCheck {
|
||||
// TODO(issue/24571): remove '!'.
|
||||
private _ngStyle !: {[key: string]: string};
|
||||
// TODO(issue/24571): remove '!'.
|
||||
private _differ !: KeyValueDiffer<string, string|number>;
|
||||
@Directive({selector: '[ngStyle]', providers: [NgStyleImplProvider]})
|
||||
export class NgStyle extends NgStyleBase implements DoCheck {
|
||||
constructor(delegate: NgStyleImpl) { super(delegate); }
|
||||
|
||||
constructor(
|
||||
private _differs: KeyValueDiffers, private _ngEl: ElementRef, private _renderer: Renderer2) {}
|
||||
@Input('ngStyle')
|
||||
set ngStyle(value: {[klass: string]: any}|null) { this._delegate.setNgStyle(value); }
|
||||
|
||||
@Input()
|
||||
set ngStyle(
|
||||
/**
|
||||
* A map of style properties, specified as colon-separated
|
||||
* key-value pairs.
|
||||
* * The key is a style name, with an optional `.<unit>` suffix
|
||||
* (such as 'top.px', 'font-style.em').
|
||||
* * The value is an expression to be evaluated.
|
||||
*/
|
||||
values: {[key: string]: string}) {
|
||||
this._ngStyle = values;
|
||||
if (!this._differ && values) {
|
||||
this._differ = this._differs.find(values).create();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the new styles if needed.
|
||||
*/
|
||||
ngDoCheck() {
|
||||
if (this._differ) {
|
||||
const changes = this._differ.diff(this._ngStyle);
|
||||
if (changes) {
|
||||
this._applyChanges(changes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _applyChanges(changes: KeyValueChanges<string, string|number>): void {
|
||||
changes.forEachRemovedItem((record) => this._setStyle(record.key, null));
|
||||
changes.forEachAddedItem((record) => this._setStyle(record.key, record.currentValue));
|
||||
changes.forEachChangedItem((record) => this._setStyle(record.key, record.currentValue));
|
||||
}
|
||||
|
||||
private _setStyle(nameAndUnit: string, value: string|number|null|undefined): void {
|
||||
const [name, unit] = nameAndUnit.split('.');
|
||||
value = value != null && unit ? `${value}${unit}` : value;
|
||||
|
||||
if (value != null) {
|
||||
this._renderer.setStyle(this._ngEl.nativeElement, name, value as string);
|
||||
} else {
|
||||
this._renderer.removeStyle(this._ngEl.nativeElement, name);
|
||||
}
|
||||
}
|
||||
ngDoCheck() { this._delegate.applyChanges(); }
|
||||
}
|
||||
|
114
packages/common/src/directives/ng_style_impl.ts
Normal file
114
packages/common/src/directives/ng_style_impl.ts
Normal file
@ -0,0 +1,114 @@
|
||||
/**
|
||||
* @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 {ElementRef, Injectable, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer2} from '@angular/core';
|
||||
|
||||
import {StylingDiffer, StylingDifferOptions} from './styling_differ';
|
||||
|
||||
/**
|
||||
* Used as a token for an injected service within the NgStyle directive.
|
||||
*
|
||||
* NgStyle behaves differenly whether or not VE is being used or not. If
|
||||
* present then the legacy ngClass diffing algorithm will be used as an
|
||||
* injected service. Otherwise the new diffing algorithm (which delegates
|
||||
* to the `[style]` binding) will be used. This toggle behavior is done so
|
||||
* via the ivy_switch mechanism.
|
||||
*/
|
||||
export abstract class NgStyleImpl {
|
||||
abstract getValue(): {[key: string]: any}|null;
|
||||
abstract setNgStyle(value: {[key: string]: any}|null): void;
|
||||
abstract applyChanges(): void;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class NgStyleR2Impl implements NgStyleImpl {
|
||||
// TODO(issue/24571): remove '!'.
|
||||
private _ngStyle !: {[key: string]: string};
|
||||
// TODO(issue/24571): remove '!'.
|
||||
private _differ !: KeyValueDiffer<string, string|number>;
|
||||
|
||||
constructor(
|
||||
private _ngEl: ElementRef, private _differs: KeyValueDiffers, private _renderer: Renderer2) {}
|
||||
|
||||
getValue() { return null; }
|
||||
|
||||
/**
|
||||
* A map of style properties, specified as colon-separated
|
||||
* key-value pairs.
|
||||
* * The key is a style name, with an optional `.<unit>` suffix
|
||||
* (such as 'top.px', 'font-style.em').
|
||||
* * The value is an expression to be evaluated.
|
||||
*/
|
||||
setNgStyle(values: {[key: string]: string}) {
|
||||
this._ngStyle = values;
|
||||
if (!this._differ && values) {
|
||||
this._differ = this._differs.find(values).create();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the new styles if needed.
|
||||
*/
|
||||
applyChanges() {
|
||||
if (this._differ) {
|
||||
const changes = this._differ.diff(this._ngStyle);
|
||||
if (changes) {
|
||||
this._applyChanges(changes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _applyChanges(changes: KeyValueChanges<string, string|number>): void {
|
||||
changes.forEachRemovedItem((record) => this._setStyle(record.key, null));
|
||||
changes.forEachAddedItem((record) => this._setStyle(record.key, record.currentValue));
|
||||
changes.forEachChangedItem((record) => this._setStyle(record.key, record.currentValue));
|
||||
}
|
||||
|
||||
private _setStyle(nameAndUnit: string, value: string|number|null|undefined): void {
|
||||
const [name, unit] = nameAndUnit.split('.');
|
||||
value = value != null && unit ? `${value}${unit}` : value;
|
||||
|
||||
if (value != null) {
|
||||
this._renderer.setStyle(this._ngEl.nativeElement, name, value as string);
|
||||
} else {
|
||||
this._renderer.removeStyle(this._ngEl.nativeElement, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class NgStyleR3Impl implements NgStyleImpl {
|
||||
private _differ =
|
||||
new StylingDiffer<{[key: string]: any}|null>('NgStyle', StylingDifferOptions.AllowUnits);
|
||||
|
||||
private _value: {[key: string]: any}|null = null;
|
||||
|
||||
getValue() { return this._value; }
|
||||
|
||||
setNgStyle(value: {[key: string]: any}|null) { this._differ.setValue(value); }
|
||||
|
||||
applyChanges() {
|
||||
if (this._differ.hasValueChanged()) {
|
||||
this._value = this._differ.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// the implementation for both NgClassR2Impl and NgClassR3Impl are
|
||||
// not ivy_switch'd away, instead they are only hooked up into the
|
||||
// DI via NgStyle's directive's provider property.
|
||||
export const NgStyleImplProvider__PRE_R3__ = {
|
||||
provide: NgStyleImpl,
|
||||
useClass: NgStyleR2Impl
|
||||
};
|
||||
|
||||
export const NgStyleImplProvider__POST_R3__ = {
|
||||
provide: NgStyleImpl,
|
||||
useClass: NgStyleR3Impl
|
||||
};
|
||||
|
||||
export const NgStyleImplProvider = NgStyleImplProvider__PRE_R3__;
|
302
packages/common/src/directives/styling_differ.ts
Normal file
302
packages/common/src/directives/styling_differ.ts
Normal file
@ -0,0 +1,302 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Used to diff and convert ngStyle/ngClass instructions into [style] and [class] bindings.
|
||||
*
|
||||
* ngStyle and ngClass both accept various forms of input and behave differently than that
|
||||
* of how [style] and [class] behave in Angular.
|
||||
*
|
||||
* The differences are:
|
||||
* - ngStyle and ngClass both **watch** their binding values for changes each time CD runs
|
||||
* while [style] and [class] bindings do not (they check for identity changes)
|
||||
* - ngStyle allows for unit-based keys (e.g. `{'max-width.px':value}`) and [style] does not
|
||||
* - ngClass supports arrays of class values and [class] only accepts map and string values
|
||||
* - ngClass allows for multiple className keys (space-separated) within an array or map
|
||||
* (as the * key) while [class] only accepts a simple key/value map object
|
||||
*
|
||||
* Having Angular understand and adapt to all the different forms of behavior is complicated
|
||||
* and unnecessary. Instead, ngClass and ngStyle should have their input values be converted
|
||||
* into something that the core-level [style] and [class] bindings understand.
|
||||
*
|
||||
* This [StylingDiffer] class handles this conversion by creating a new input value each time
|
||||
* the inner representation of the binding value have changed.
|
||||
*
|
||||
* ## Why do we care about ngStyle/ngClass?
|
||||
* The styling algorithm code (documented inside of `render3/interfaces/styling.ts`) needs to
|
||||
* respect and understand the styling values emitted through ngStyle and ngClass (when they
|
||||
* are present and used in a template).
|
||||
*
|
||||
* Instead of having these directives manage styling on their own, they should be included
|
||||
* into the Angular styling algorithm that exists for [style] and [class] bindings.
|
||||
*
|
||||
* Here's why:
|
||||
*
|
||||
* - If ngStyle/ngClass is used in combination with [style]/[class] bindings then the
|
||||
* styles and classes would fall out of sync and be applied and updated at
|
||||
* inconsistent times
|
||||
* - Both ngClass/ngStyle do not respect [class.name] and [style.prop] bindings
|
||||
* (they will write over them given the right combination of events)
|
||||
*
|
||||
* ```
|
||||
* <!-- if `w1` is updated then it will always override `w2`
|
||||
* if `w2` is updated then it will always override `w1`
|
||||
* if both are updated at the same time then `w1` wins -->
|
||||
* <div [ngStyle]="{width:w1}" [style.width]="w2">...</div>
|
||||
*
|
||||
* <!-- if `w1` is updated then it will always lose to `w2`
|
||||
* if `w2` is updated then it will always override `w1`
|
||||
* if both are updated at the same time then `w2` wins -->
|
||||
* <div [style]="{width:w1}" [style.width]="w2">...</div>
|
||||
* ```
|
||||
* - ngClass/ngStyle were written as a directives and made use of maps, closures and other
|
||||
* expensive data structures which were evaluated each time CD runs
|
||||
*/
|
||||
export class StylingDiffer<T> {
|
||||
public readonly value: T|null = null;
|
||||
|
||||
private _lastSetValue: {[key: string]: any}|string|string[]|null = null;
|
||||
private _lastSetValueType: StylingDifferValueTypes = StylingDifferValueTypes.Null;
|
||||
private _lastSetValueIdentityChange = false;
|
||||
|
||||
constructor(private _name: string, private _options: StylingDifferOptions) {}
|
||||
|
||||
/**
|
||||
* Sets (updates) the styling value within the differ.
|
||||
*
|
||||
* Only when `hasValueChanged` is called then this new value will be evaluted
|
||||
* and checked against the previous value.
|
||||
*
|
||||
* @param value the new styling value provided from the ngClass/ngStyle binding
|
||||
*/
|
||||
setValue(value: {[key: string]: any}|string[]|string|null) {
|
||||
if (Array.isArray(value)) {
|
||||
this._lastSetValueType = StylingDifferValueTypes.Array;
|
||||
} else if (value instanceof Set) {
|
||||
this._lastSetValueType = StylingDifferValueTypes.Set;
|
||||
} else if (value && typeof value === 'string') {
|
||||
if (!(this._options & StylingDifferOptions.AllowStringValue)) {
|
||||
throw new Error(this._name + ' string values are not allowed');
|
||||
}
|
||||
this._lastSetValueType = StylingDifferValueTypes.String;
|
||||
} else {
|
||||
this._lastSetValueType = value ? StylingDifferValueTypes.Map : StylingDifferValueTypes.Null;
|
||||
}
|
||||
|
||||
this._lastSetValueIdentityChange = true;
|
||||
this._lastSetValue = value || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether or not the value has changed.
|
||||
*
|
||||
* This function can be called right after `setValue()` is called, but it can also be
|
||||
* called incase the existing value (if it's a collection) changes internally. If the
|
||||
* value is indeed a collection it will do the necessary diffing work and produce a
|
||||
* new object value as assign that to `value`.
|
||||
*
|
||||
* @returns whether or not the value has changed in some way.
|
||||
*/
|
||||
hasValueChanged(): boolean {
|
||||
let valueHasChanged = this._lastSetValueIdentityChange;
|
||||
if (!valueHasChanged && !(this._lastSetValueType & StylingDifferValueTypes.Collection))
|
||||
return false;
|
||||
|
||||
let finalValue: {[key: string]: any}|string|null = null;
|
||||
const trimValues = (this._options & StylingDifferOptions.TrimProperties) ? true : false;
|
||||
const parseOutUnits = (this._options & StylingDifferOptions.AllowUnits) ? true : false;
|
||||
const allowSubKeys = (this._options & StylingDifferOptions.AllowSubKeys) ? true : false;
|
||||
|
||||
switch (this._lastSetValueType) {
|
||||
// case 1: [input]="string"
|
||||
case StylingDifferValueTypes.String:
|
||||
const tokens = (this._lastSetValue as string).split(/\s+/g);
|
||||
if (this._options & StylingDifferOptions.ForceAsMap) {
|
||||
finalValue = {};
|
||||
tokens.forEach((token, i) => (finalValue as{[key: string]: any})[token] = true);
|
||||
} else {
|
||||
finalValue = tokens.reduce((str, token, i) => str + (i ? ' ' : '') + token);
|
||||
}
|
||||
break;
|
||||
|
||||
// case 2: [input]="{key:value}"
|
||||
case StylingDifferValueTypes.Map:
|
||||
const map: {[key: string]: any} = this._lastSetValue as{[key: string]: any};
|
||||
const keys = Object.keys(map);
|
||||
if (!valueHasChanged) {
|
||||
if (this.value) {
|
||||
// we know that the classExp value exists and that it is
|
||||
// a map (otherwise an identity change would have occurred)
|
||||
valueHasChanged = mapHasChanged(keys, this.value as{[key: string]: any}, map);
|
||||
} else {
|
||||
valueHasChanged = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (valueHasChanged) {
|
||||
finalValue =
|
||||
bulidMapFromValues(this._name, trimValues, parseOutUnits, allowSubKeys, map, keys);
|
||||
}
|
||||
break;
|
||||
|
||||
// case 3a: [input]="[str1, str2, ...]"
|
||||
// case 3b: [input]="Set"
|
||||
case StylingDifferValueTypes.Array:
|
||||
case StylingDifferValueTypes.Set:
|
||||
const values = Array.from(this._lastSetValue as string[] | Set<string>);
|
||||
if (!valueHasChanged) {
|
||||
const keys = Object.keys(this.value !);
|
||||
valueHasChanged = !arrayEqualsArray(keys, values);
|
||||
}
|
||||
if (valueHasChanged) {
|
||||
finalValue =
|
||||
bulidMapFromValues(this._name, trimValues, parseOutUnits, allowSubKeys, values);
|
||||
}
|
||||
break;
|
||||
|
||||
// case 4: [input]="null|undefined"
|
||||
default:
|
||||
finalValue = null;
|
||||
break;
|
||||
}
|
||||
|
||||
if (valueHasChanged) {
|
||||
(this as any).value = finalValue !;
|
||||
}
|
||||
|
||||
return valueHasChanged;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Various options that are consumed by the [StylingDiffer] class.
|
||||
*/
|
||||
export const enum StylingDifferOptions {
|
||||
None = 0b00000,
|
||||
TrimProperties = 0b00001,
|
||||
AllowSubKeys = 0b00010,
|
||||
AllowStringValue = 0b00100,
|
||||
AllowUnits = 0b01000,
|
||||
ForceAsMap = 0b10000,
|
||||
}
|
||||
|
||||
/**
|
||||
* The different types of inputs that the [StylingDiffer] can deal with
|
||||
*/
|
||||
const enum StylingDifferValueTypes {
|
||||
Null = 0b0000,
|
||||
String = 0b0001,
|
||||
Map = 0b0010,
|
||||
Array = 0b0100,
|
||||
Set = 0b1000,
|
||||
Collection = 0b1110,
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* builds and returns a map based on the values input value
|
||||
*
|
||||
* If the `keys` param is provided then the `values` param is treated as a
|
||||
* string map. Otherwise `values` is treated as a string array.
|
||||
*/
|
||||
function bulidMapFromValues(
|
||||
errorPrefix: string, trim: boolean, parseOutUnits: boolean, allowSubKeys: boolean,
|
||||
values: {[key: string]: any} | string[], keys?: string[]) {
|
||||
const map: {[key: string]: any} = {};
|
||||
if (keys) {
|
||||
// case 1: map
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
let key = keys[i];
|
||||
key = trim ? key.trim() : key;
|
||||
const value = (values as{[key: string]: any})[key];
|
||||
setMapValues(map, key, value, parseOutUnits, allowSubKeys);
|
||||
}
|
||||
} else {
|
||||
// case 2: array
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
let value = (values as string[])[i];
|
||||
assertValidValue(errorPrefix, value);
|
||||
value = trim ? value.trim() : value;
|
||||
setMapValues(map, value, true, false, allowSubKeys);
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
function assertValidValue(errorPrefix: string, value: any) {
|
||||
if (typeof value !== 'string') {
|
||||
throw new Error(
|
||||
`${errorPrefix} can only toggle CSS classes expressed as strings, got ${value}`);
|
||||
}
|
||||
}
|
||||
|
||||
function setMapValues(
|
||||
map: {[key: string]: any}, key: string, value: any, parseOutUnits: boolean,
|
||||
allowSubKeys: boolean) {
|
||||
if (allowSubKeys && key.indexOf(' ') > 0) {
|
||||
const innerKeys = key.split(/\s+/g);
|
||||
for (let j = 0; j < innerKeys.length; j++) {
|
||||
setIndividualMapValue(map, innerKeys[j], value, parseOutUnits);
|
||||
}
|
||||
} else {
|
||||
setIndividualMapValue(map, key, value, parseOutUnits);
|
||||
}
|
||||
}
|
||||
|
||||
function setIndividualMapValue(
|
||||
map: {[key: string]: any}, key: string, value: any, parseOutUnits: boolean) {
|
||||
if (parseOutUnits) {
|
||||
const values = normalizeStyleKeyAndValue(key, value);
|
||||
value = values.value;
|
||||
key = values.key;
|
||||
}
|
||||
map[key] = value;
|
||||
}
|
||||
|
||||
function normalizeStyleKeyAndValue(key: string, value: string | null) {
|
||||
const index = key.indexOf('.');
|
||||
if (index > 0) {
|
||||
const unit = key.substr(index + 1); // ignore the . ([width.px]="'40'" => "40px")
|
||||
key = key.substring(0, index);
|
||||
if (value != null) { // we should not convert null values to string
|
||||
value += unit;
|
||||
}
|
||||
}
|
||||
return {key, value};
|
||||
}
|
||||
|
||||
function mapHasChanged(keys: string[], a: {[key: string]: any}, b: {[key: string]: any}) {
|
||||
const oldKeys = Object.keys(a);
|
||||
const newKeys = keys;
|
||||
|
||||
// the keys are different which means the map changed
|
||||
if (!arrayEqualsArray(oldKeys, newKeys)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
for (let i = 0; i < newKeys.length; i++) {
|
||||
const key = newKeys[i];
|
||||
if (a[key] !== b[key]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function arrayEqualsArray(a: any[] | null, b: any[] | null) {
|
||||
if (a && b) {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (b.indexOf(a[i]) === -1) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
Reference in New Issue
Block a user