Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion goldens/public-api/common/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ export class LowerCasePipe implements PipeTransform {

// @public
export class NgClass implements DoCheck {
constructor(_iterableDiffers: IterableDiffers, _keyValueDiffers: KeyValueDiffers, _ngEl: ElementRef, _renderer: Renderer2);
constructor(_renderer: Renderer2, _ngEl: ElementRef);
// (undocumented)
set klass(value: string);
// (undocumented)
Expand Down
125 changes: 43 additions & 82 deletions packages/common/src/directives/ng_class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@
* 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, ElementRef, Input, IterableChanges, IterableDiffer, IterableDiffers, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer2, ɵisListLikeIterable as isListLikeIterable, ɵstringify as stringify} from '@angular/core';
import {Directive, DoCheck, ElementRef, Input, Renderer2, ɵstringify as stringify} from '@angular/core';

type NgClassSupportedTypes = string[]|Set<string>|{[klass: string]: any}|null|undefined;

const SPLIT_BY_WS_REGEXP = /\s+/;

const EMPTY_SET = new Set<string>();

/**
* @ngModule CommonModule
*
Expand Down Expand Up @@ -42,108 +46,65 @@ type NgClassSupportedTypes = string[]|Set<string>|{[klass: string]: any}|null|un
standalone: true,
})
export class NgClass implements DoCheck {
private _iterableDiffer: IterableDiffer<string>|null = null;
private _keyValueDiffer: KeyValueDiffer<string, any>|null = null;
private _initialClasses: string[] = [];
private _rawClass: NgClassSupportedTypes = null;
private _initialClasses = EMPTY_SET;
private _rawClass: NgClassSupportedTypes;

constructor(
private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers,
private _ngEl: ElementRef, private _renderer: Renderer2) {}
private _prevSet = EMPTY_SET;

constructor(private _renderer: Renderer2, private _ngEl: ElementRef) {}

@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);
this._initialClasses = new Set(value.trim().split(SPLIT_BY_WS_REGEXP));
}

@Input('ngClass')
set ngClass(value: string|string[]|Set<string>|{[klass: string]: any}|null|undefined) {
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._rawClass = typeof value === 'string' ? value.trim().split(SPLIT_BY_WS_REGEXP) : value;
}

ngDoCheck() {
if (this._iterableDiffer) {
const iterableChanges = this._iterableDiffer.diff(this._rawClass as string[]);
if (iterableChanges) {
this._applyIterableChanges(iterableChanges);
ngDoCheck(): void {
const nextSet = new Set(this._initialClasses);

const rawClass = this._rawClass;
if (Array.isArray(rawClass) || rawClass instanceof Set) {
for (const classNames of rawClass) {
nextSet.add(classNames);
}
} else if (this._keyValueDiffer) {
const keyValueChanges = this._keyValueDiffer.diff(this._rawClass as {[k: string]: any});
if (keyValueChanges) {
this._applyKeyValueChanges(keyValueChanges);
} else if (rawClass != null) {
for (const classNames of Object.keys(rawClass)) {
const toggle = rawClass[classNames];
if (toggle) {
nextSet.add(classNames);
} else {
nextSet.delete(classNames);
}
}
}
}

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);
}
});
this._diff(nextSet);
this._prevSet = nextSet;
}

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));
}
private _diff(next: Set<string>) {
const prev = this._prevSet;

/**
* 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: NgClassSupportedTypes) {
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]));
// detect deleted items
for (const prevClass of prev) {
if (!next.has(prevClass)) {
this._toggleClass(prevClass, false);
}
}
}

/**
* Removes a collection of CSS classes from the DOM element. This is mostly useful for cleanup
* purposes.
*/
private _removeClasses(rawClassVal: NgClassSupportedTypes) {
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));
// detect added items
for (const nextClass of next) {
if (!prev.has(nextClass)) {
// TODO: dev mode only
if (typeof nextClass !== 'string') {
throw new Error(`NgClass can only toggle CSS classes expressed as strings, got ${
stringify(nextClass)}`);
}
this._toggleClass(nextClass, true);
}
}
}
Expand Down
Loading